title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python program to copy odd lines of one file to other | 23 Aug, 2018
Write a python program to read contents of a file and copy only the content of odd lines into new file.
Examples:
Input : Hello
World
Python
Language
Output : Hello
Python
Input : Python
Language
Is
Easy
Output : Python
Is
1) Open file name bcd.txt in read mode and assign it to fn.2) Open file name nfile.txt in write mode and assign it to fn1.3) Read the content line by line of the file fn and assign it to cont.4) Access each element from 0 to length of cont.5) Check if i is not divisible by 2 then write the content in fn1 else pass.6) Close the file fn1.7) Now open nfile.txt in read mode and assign it to fn1.8) Read the content of the file and assign it to cont1.9) Print the content of the file and then close the file fn and fn1 .
# open file in read modefn = open('bcd.txt', 'r') # open other file in write modefn1 = open('nfile.txt', 'w') # read the content of the file line by linecont = fn.readlines()type(cont)for i in range(0, len(cont)): if(i % 2 ! = 0): fn1.write(cont[i]) else: pass # close the filefn1.close() # open file in read modefn1 = open('nfile.txt', 'r') # read the content of the filecont1 = fn1.read() # print the content of the fileprint(cont1) # close all filesfn.close()fn1.close()
Output : Python
Is
python-file-handling
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2018"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "Write a python program to read contents of a file and copy only the content of odd lines into new file."
},
{
"code": null,
"e": 142,
"s": 132,
"text": "Examples:"
},
{
"code": null,
"e": 319,
"s": 142,
"text": "Input : Hello\n World\n Python\n Language\nOutput : Hello\n Python\n\nInput : Python\n Language\n Is\n Easy\nOutput : Python\n Is\n"
},
{
"code": null,
"e": 838,
"s": 319,
"text": "1) Open file name bcd.txt in read mode and assign it to fn.2) Open file name nfile.txt in write mode and assign it to fn1.3) Read the content line by line of the file fn and assign it to cont.4) Access each element from 0 to length of cont.5) Check if i is not divisible by 2 then write the content in fn1 else pass.6) Close the file fn1.7) Now open nfile.txt in read mode and assign it to fn1.8) Read the content of the file and assign it to cont1.9) Print the content of the file and then close the file fn and fn1 ."
},
{
"code": "# open file in read modefn = open('bcd.txt', 'r') # open other file in write modefn1 = open('nfile.txt', 'w') # read the content of the file line by linecont = fn.readlines()type(cont)for i in range(0, len(cont)): if(i % 2 ! = 0): fn1.write(cont[i]) else: pass # close the filefn1.close() # open file in read modefn1 = open('nfile.txt', 'r') # read the content of the filecont1 = fn1.read() # print the content of the fileprint(cont1) # close all filesfn.close()fn1.close()",
"e": 1339,
"s": 838,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1339,
"text": "Output : Python\n Is\n"
},
{
"code": null,
"e": 1389,
"s": 1368,
"text": "python-file-handling"
},
{
"code": null,
"e": 1405,
"s": 1389,
"text": "Python Programs"
}
] |
How to write address in an HTML document ? | 04 Jan, 2022
The <address> tag in HTML is used to write contact information of a person or an organization. If <address> tag is used inside the <body> tag then it represents the contact information of the document and if the <address> tag is used inside the <article> tag, then it represents the contact information of the article. The text inside the <address> tag will display in italic format. Some browser adding a line break before and after the address element.
Syntax:
<address> Contact Information... </address>
Example:
HTML
<!DOCTYPE html><html> <head> <title> What is the correct way to write address in an HTML document? </title></head> <body> <h1 style="color:green;">GeeksforGeeks</h1> <h3> Correct way to write address in HTML document </h3> <!-- address tag starts from here --> <address> Organization Name: GeeksforGeeks <br> Web Site: <a href="https://www.geeksforgeeks.org/about/contact-us/"> GeeksforGeeks</a><br> visit us: GeeksforGeeks<br> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <!-- address tag ends here --> </body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
varshagumber28
HTML-Misc
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 483,
"s": 28,
"text": "The <address> tag in HTML is used to write contact information of a person or an organization. If <address> tag is used inside the <body> tag then it represents the contact information of the document and if the <address> tag is used inside the <article> tag, then it represents the contact information of the article. The text inside the <address> tag will display in italic format. Some browser adding a line break before and after the address element."
},
{
"code": null,
"e": 491,
"s": 483,
"text": "Syntax:"
},
{
"code": null,
"e": 535,
"s": 491,
"text": "<address> Contact Information... </address>"
},
{
"code": null,
"e": 544,
"s": 535,
"text": "Example:"
},
{
"code": null,
"e": 549,
"s": 544,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is the correct way to write address in an HTML document? </title></head> <body> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3> Correct way to write address in HTML document </h3> <!-- address tag starts from here --> <address> Organization Name: GeeksforGeeks <br> Web Site: <a href=\"https://www.geeksforgeeks.org/about/contact-us/\"> GeeksforGeeks</a><br> visit us: GeeksforGeeks<br> 5th Floor, A-118, Sector-136, Noida, Uttar Pradesh - 201305 </address> <!-- address tag ends here --> </body> </html>",
"e": 1211,
"s": 549,
"text": null
},
{
"code": null,
"e": 1219,
"s": 1211,
"text": "Output:"
},
{
"code": null,
"e": 1239,
"s": 1219,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1253,
"s": 1239,
"text": "Google Chrome"
},
{
"code": null,
"e": 1271,
"s": 1253,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1279,
"s": 1271,
"text": "Firefox"
},
{
"code": null,
"e": 1285,
"s": 1279,
"text": "Opera"
},
{
"code": null,
"e": 1292,
"s": 1285,
"text": "Safari"
},
{
"code": null,
"e": 1307,
"s": 1292,
"text": "varshagumber28"
},
{
"code": null,
"e": 1317,
"s": 1307,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1322,
"s": 1317,
"text": "HTML"
},
{
"code": null,
"e": 1339,
"s": 1322,
"text": "Web Technologies"
},
{
"code": null,
"e": 1366,
"s": 1339,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1371,
"s": 1366,
"text": "HTML"
},
{
"code": null,
"e": 1469,
"s": 1371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1493,
"s": 1469,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1532,
"s": 1493,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1571,
"s": 1532,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1608,
"s": 1571,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1628,
"s": 1608,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1661,
"s": 1628,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1722,
"s": 1661,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1765,
"s": 1722,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1837,
"s": 1765,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to set a String as a key for an object - JavaScript? | Let’s say the following is our string −
const keyName = 'username';
To set a string as a key for an object, use the [] and pass the string name −
const stringToObject = {
[keyName]: 'David Miller'
};
Following is the complete code −
const keyName = 'username';
const stringToObject = {
[keyName]: 'David Miller'
};
console.log("Your String Value="+keyName);
console.log("Your Object Value=")
console.log(stringToObject);
To run the above program, use the following command −
node fileName.js.
Here, my file name is demo238.js.
The output is as follows −
PS C:\Users\Amit\javascript-code> node demo238.js
Your String Value=username
Your Object Value=
{ username: 'David Miller' } | [
{
"code": null,
"e": 1227,
"s": 1187,
"text": "Let’s say the following is our string −"
},
{
"code": null,
"e": 1255,
"s": 1227,
"text": "const keyName = 'username';"
},
{
"code": null,
"e": 1333,
"s": 1255,
"text": "To set a string as a key for an object, use the [] and pass the string name −"
},
{
"code": null,
"e": 1389,
"s": 1333,
"text": "const stringToObject = {\n [keyName]: 'David Miller'\n};"
},
{
"code": null,
"e": 1422,
"s": 1389,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 1614,
"s": 1422,
"text": "const keyName = 'username';\nconst stringToObject = {\n [keyName]: 'David Miller'\n}; \nconsole.log(\"Your String Value=\"+keyName);\nconsole.log(\"Your Object Value=\")\nconsole.log(stringToObject);"
},
{
"code": null,
"e": 1668,
"s": 1614,
"text": "To run the above program, use the following command −"
},
{
"code": null,
"e": 1686,
"s": 1668,
"text": "node fileName.js."
},
{
"code": null,
"e": 1720,
"s": 1686,
"text": "Here, my file name is demo238.js."
},
{
"code": null,
"e": 1747,
"s": 1720,
"text": "The output is as follows −"
},
{
"code": null,
"e": 1872,
"s": 1747,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo238.js\nYour String Value=username\nYour Object Value=\n{ username: 'David Miller' }"
}
] |
Underscore.js _.uniq() Function | 24 Nov, 2021
The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.uniq() function returns the array which does not contain duplicate elements. The first occurrence of element is included in the resultant array. The operation of checking whether the array is duplicate or not. It is done by the ‘===’ operation.
Syntax:
_.uniq( array, [isSorted], [iteratee] )
Parameters: This function accepts three parameters which are listed below:
array: This parameter is used to hold the array of elements.
isSorted: It is optional parameter. This parameter is used to hold true for sorted array.
iteratee: It is optional parameter which is used ho hold iteratee function.
Return value: It returns an array of unique elements.
Passing a list of numbers to _.uniq() function: The ._uniq() function takes the element from the list one by one and checks whether it is in the resultant array (which is initially empty) by the ‘===’ operator. If it is present then it ignores it and checks the next element. Otherwise since it is the first occurrence of the element so it is included in the resultant array.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.uniq([1, 2, 3, 4, 5, 4, 3, 2, 1])); </script> </body></html>
Output:
Passing the second parameter as false to the _.uniq() function: If pass the second parameter as false along with the array then the _.uniq() function will work in the similar manner as in the first example. All the unique elements will be present in the resultant array.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.uniq([10, 0, 5, 1, 6, 10, 2, 1, 2], false)); </script> </body></html>
Output:
Passing the second parameter as true to the _.uniq() function: If pass the second parameter as true along with the array then the _.uniq() function will not work in the similar manner rather it will perform any operation on the array. Hence, the resultant array will contain all the elements of the array passed in the same order in which it appeared in the passed array.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.uniq([10, 0, 5, 1, 6, 10, 2, 1, 2], true)); </script> </body></html>
Output:
Passing words to the _.uniq() function: If pass the set of strings to the _.uniq() function then it will work in the similar manner as it will work with numbers etc. Therefore, the resultant array will contain only the first occurrence of all the repeated elements in the resultant array.
Example:
<!DOCTYPE html><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> console.log(_.uniq(["HTML", "CSS", "JS", "AJAX", "CSS", "JS", "CSS"])); </script> </body></html>
Output:
Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them.
<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script>
JavaScript - Underscore.js
javascript-functions
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": "\n24 Nov, 2021"
},
{
"code": null,
"e": 434,
"s": 28,
"text": "The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc even without using any built-in objects.The _.uniq() function returns the array which does not contain duplicate elements. The first occurrence of element is included in the resultant array. The operation of checking whether the array is duplicate or not. It is done by the ‘===’ operation."
},
{
"code": null,
"e": 442,
"s": 434,
"text": "Syntax:"
},
{
"code": null,
"e": 482,
"s": 442,
"text": "_.uniq( array, [isSorted], [iteratee] )"
},
{
"code": null,
"e": 557,
"s": 482,
"text": "Parameters: This function accepts three parameters which are listed below:"
},
{
"code": null,
"e": 618,
"s": 557,
"text": "array: This parameter is used to hold the array of elements."
},
{
"code": null,
"e": 708,
"s": 618,
"text": "isSorted: It is optional parameter. This parameter is used to hold true for sorted array."
},
{
"code": null,
"e": 784,
"s": 708,
"text": "iteratee: It is optional parameter which is used ho hold iteratee function."
},
{
"code": null,
"e": 838,
"s": 784,
"text": "Return value: It returns an array of unique elements."
},
{
"code": null,
"e": 1214,
"s": 838,
"text": "Passing a list of numbers to _.uniq() function: The ._uniq() function takes the element from the list one by one and checks whether it is in the resultant array (which is initially empty) by the ‘===’ operator. If it is present then it ignores it and checks the next element. Otherwise since it is the first occurrence of the element so it is included in the resultant array."
},
{
"code": null,
"e": 1223,
"s": 1214,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.uniq([1, 2, 3, 4, 5, 4, 3, 2, 1])); </script> </body></html> ",
"e": 1550,
"s": 1223,
"text": null
},
{
"code": null,
"e": 1558,
"s": 1550,
"text": "Output:"
},
{
"code": null,
"e": 1829,
"s": 1558,
"text": "Passing the second parameter as false to the _.uniq() function: If pass the second parameter as false along with the array then the _.uniq() function will work in the similar manner as in the first example. All the unique elements will be present in the resultant array."
},
{
"code": null,
"e": 1838,
"s": 1829,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.uniq([10, 0, 5, 1, 6, 10, 2, 1, 2], false)); </script> </body></html> ",
"e": 2174,
"s": 1838,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2174,
"text": "Output:"
},
{
"code": null,
"e": 2554,
"s": 2182,
"text": "Passing the second parameter as true to the _.uniq() function: If pass the second parameter as true along with the array then the _.uniq() function will not work in the similar manner rather it will perform any operation on the array. Hence, the resultant array will contain all the elements of the array passed in the same order in which it appeared in the passed array."
},
{
"code": null,
"e": 2563,
"s": 2554,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.uniq([10, 0, 5, 1, 6, 10, 2, 1, 2], true)); </script> </body></html> ",
"e": 2898,
"s": 2563,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 3195,
"s": 2906,
"text": "Passing words to the _.uniq() function: If pass the set of strings to the _.uniq() function then it will work in the similar manner as it will work with numbers etc. Therefore, the resultant array will contain only the first occurrence of all the repeated elements in the resultant array."
},
{
"code": null,
"e": 3204,
"s": 3195,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> console.log(_.uniq([\"HTML\", \"CSS\", \"JS\", \"AJAX\", \"CSS\", \"JS\", \"CSS\"])); </script> </body></html> ",
"e": 3576,
"s": 3204,
"text": null
},
{
"code": null,
"e": 3584,
"s": 3576,
"text": "Output:"
},
{
"code": null,
"e": 3789,
"s": 3584,
"text": "Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them."
},
{
"code": "<script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script> ",
"e": 3917,
"s": 3789,
"text": null
},
{
"code": null,
"e": 3944,
"s": 3917,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 3965,
"s": 3944,
"text": "javascript-functions"
},
{
"code": null,
"e": 3976,
"s": 3965,
"text": "JavaScript"
},
{
"code": null,
"e": 3993,
"s": 3976,
"text": "Web Technologies"
},
{
"code": null,
"e": 4091,
"s": 3993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4152,
"s": 4091,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4224,
"s": 4152,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4264,
"s": 4224,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4317,
"s": 4264,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4369,
"s": 4317,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4431,
"s": 4369,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4464,
"s": 4431,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4525,
"s": 4464,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4575,
"s": 4525,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
LightGBM (Light Gradient Boosting Machine) | 22 Dec, 2021
LightGBM is a gradient boosting framework based on decision trees to increases the efficiency of the model and reduces memory usage. It uses two novel techniques: Gradient-based One Side Sampling and Exclusive Feature Bundling (EFB) which fulfills the limitations of histogram-based algorithm that is primarily used in all GBDT (Gradient Boosting Decision Tree) frameworks. The two techniques of GOSS and EFB described below form the characteristics of LightGBM Algorithm. They comprise together to make the model work efficiently and provide it a cutting edge over other GBDT frameworks Gradient-based One Side Sampling Technique for LightGBM: Different data instances have varied roles in the computation of information gain. The instances with larger gradients(i.e., under-trained instances) will contribute more to the information gain. GOSS keeps those instances with large gradients (e.g., larger than a predefined threshold, or among the top percentiles), and only randomly drop those instances with small gradients to retain the accuracy of information gain estimation. This treatment can lead to a more accurate gain estimation than uniformly random sampling, with the same target sampling rate, especially when the value of information gain has a large range. Algorithm for GOSS:
Input: I: training data, d: iterations
Input: a: sampling ratio of large gradient data
Input: b: sampling ratio of small gradient data
Input: loss: loss function, L: weak learner
models ? {}, fact ? (1-a)/b
topN ? a × len(I), randN ? b × len(I)
for i = 1 to d do
preds ? models.predict(I) g ? loss(I, preds), w ? {1, 1, ...}
sorted ? GetSortedIndices(abs(g))
topSet ? sorted[1:topN]
randSet ? RandomPick(sorted[topN:len(I)],
randN)
usedSet ? topSet + randSet
w[randSet] × = fact . Assign weight f act to the
small gradient data.
newModel ? L(I[usedSet], g[usedSet],
w[usedSet])
models.append(newModel)
Mathematical Analysis for GOSS Technique (Calculation of Variance Gain at splitting feature j) For a training set with n instances {x1, · · ·, xn}, where each xi is a vector with dimension s in space Xs. In each iteration of gradient boosting, the negative gradients of the loss function with respect to the output of the model are denoted as {g1, · · ·, gn}. In this GOSS method, the training instances are ranked according to their absolute values of their gradients in the descending order. Then, the top-a × 100% instances with the larger gradients are kept and we get an instance subset A. Then, for the remaining set Ac consisting (1- a) × 100% instances with smaller gradients., we further randomly sample a subset B with size b × |Ac|. Finally, we split the instances according to the estimated variance gain at vector Vj (d) over the subset A ? B.
(1)
where Al = {xi ? A : xij ? d}, Ar = {xi ? A : xij > d}, Bl = {xi ? B : xij ? d}, Br = {xi ? B : xij > d}, and the coefficient (1-a)/b is used to normalize the sum of the gradients over B back to the size of Ac. Exclusive Feature Bundling Technique for LightGBM: High-dimensional data are usually very sparse which provides us a possibility of designing a nearly lossless approach to reduce the number of features. Specifically, in a sparse feature space, many features are mutually exclusive, i.e., they never take nonzero values simultaneously. The exclusive features can be safely bundled into a single feature (called an Exclusive Feature Bundle). Hence, the complexity of histogram building changes from O(#data × #feature) to O(#data × #bundle), while #bundle<<#feature . Hence, the speed for training framework is improved without hurting accuracy. Algorithm for Exclusive Feature Bundling Technique:
Input: numData: number of data
Input: F: One bundle of exclusive features
binRanges ? {0}, totalBin ? 0
for f in F do
totalBin += f.numBin
binRanges.append(totalBin)
newBin ? new Bin(numData)
for i = 1 to numData do
newBin[i] ? 0
for j = 1 to len(F) do
if F[j].bin[i] != 0 then
newBin[i] ? F[j].bin[i] + binRanges[j]
Output: newBin, binRanges
Architecture : LightGBM splits the tree leaf-wise as opposed to other boosting algorithms that grow tree level-wise. It chooses the leaf with maximum delta loss to grow. Since the leaf is fixed, the leaf-wise algorithm has lower loss compared to the level-wise algorithm. Leaf-wise tree growth might increase the complexity of the model and may lead to overfitting in small datasets.Below is a diagrammatic representation of Leaf-Wise Tree Growth:
Code: Python Implementation of LightGBM Model: The data set used for this example is Breast Cancer Prediction. Click on this to get data set : Link to Data set.
python
# installing LightGBM (Required in Jupyter Notebook and# few other compilers once)pip install lightgbm # Importing Required Libraryimport pandas as pdimport lightgbm as lgb # Similarly LGBMRegressor can also be imported for a regression model.from lightgbm import LGBMClassifier # Reading the train and test datasetdata = pd.read_csv("cancer_prediction.csv) # Removing Columns not Requireddata = data.drop(columns = ['Unnamed: 32'], axis = 1)data = data.drop(columns = ['id'], axis = 1) # Skipping Data Exploration# Dummification of Diagnosis Column (1-Benign, 0-Malignant Cancer)data['diagnosis']= pd.get_dummies(data['diagnosis']) # Splitting Dataset in two partstrain = data[0:400]test = data[400:568] # Separating the independent and target variable on both data setx_train = train.drop(columns =['diagnosis'], axis = 1)y_train = train_data['diagnosis']x_test = test_data.drop(columns =['diagnosis'], axis = 1)y_test = test_data['diagnosis'] # Creating an object for model and fitting it on training data setmodel = LGBMClassifier()model.fit(x_train, y_train) # Predicting the Target variablepred = model.predict(x_test)print(pred)accuracy = model.score(x_test, y_test)print(accuracy)
Output
Prediction array :
[0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1
1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1
1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 0 1 0 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1
1 0 1 0 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0]
Accuracy Score :
0.9702380952380952
Parameter Tuning Few important parameters and their usage is listed below :
max_depth : It sets a limit on the depth of tree. The default value is 20. It is effective in controlling over fitting.categorical_feature : It specifies the categorical feature used for training model.bagging_fraction : It specifies the fraction of data to be considered for each iteration.num_iterations : It specifies the number of iterations to be performed. The default value is 100.num_leaves : It specifies the number of leaves in a tree. It should be smaller than the square of max_depth.max_bin : It specifies the maximum number of bins to bucket the feature values.min_data_in_bin : It specifies minimum amount of data in one bin.task : It specifies the task we wish to perform which is either train or prediction. The default entry is train. Another possible value for this parameter is prediction.feature_fraction : It specifies the fraction of features to be considered in each iteration. The default value is one.
max_depth : It sets a limit on the depth of tree. The default value is 20. It is effective in controlling over fitting.
categorical_feature : It specifies the categorical feature used for training model.
bagging_fraction : It specifies the fraction of data to be considered for each iteration.
num_iterations : It specifies the number of iterations to be performed. The default value is 100.
num_leaves : It specifies the number of leaves in a tree. It should be smaller than the square of max_depth.
max_bin : It specifies the maximum number of bins to bucket the feature values.
min_data_in_bin : It specifies minimum amount of data in one bin.
task : It specifies the task we wish to perform which is either train or prediction. The default entry is train. Another possible value for this parameter is prediction.
feature_fraction : It specifies the fraction of features to be considered in each iteration. The default value is one.
ved78142
surinderdawra388
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Agents in Artificial Intelligence
Search Algorithms in AI
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 1345,
"s": 52,
"text": "LightGBM is a gradient boosting framework based on decision trees to increases the efficiency of the model and reduces memory usage. It uses two novel techniques: Gradient-based One Side Sampling and Exclusive Feature Bundling (EFB) which fulfills the limitations of histogram-based algorithm that is primarily used in all GBDT (Gradient Boosting Decision Tree) frameworks. The two techniques of GOSS and EFB described below form the characteristics of LightGBM Algorithm. They comprise together to make the model work efficiently and provide it a cutting edge over other GBDT frameworks Gradient-based One Side Sampling Technique for LightGBM: Different data instances have varied roles in the computation of information gain. The instances with larger gradients(i.e., under-trained instances) will contribute more to the information gain. GOSS keeps those instances with large gradients (e.g., larger than a predefined threshold, or among the top percentiles), and only randomly drop those instances with small gradients to retain the accuracy of information gain estimation. This treatment can lead to a more accurate gain estimation than uniformly random sampling, with the same target sampling rate, especially when the value of information gain has a large range. Algorithm for GOSS: "
},
{
"code": null,
"e": 1991,
"s": 1345,
"text": "Input: I: training data, d: iterations\nInput: a: sampling ratio of large gradient data\nInput: b: sampling ratio of small gradient data\nInput: loss: loss function, L: weak learner\nmodels ? {}, fact ? (1-a)/b\ntopN ? a × len(I), randN ? b × len(I)\nfor i = 1 to d do\n preds ? models.predict(I) g ? loss(I, preds), w ? {1, 1, ...}\n sorted ? GetSortedIndices(abs(g))\n topSet ? sorted[1:topN]\n randSet ? RandomPick(sorted[topN:len(I)],\n randN)\n usedSet ? topSet + randSet\n w[randSet] × = fact . Assign weight f act to the\n small gradient data.\n newModel ? L(I[usedSet], g[usedSet],\n w[usedSet])\n models.append(newModel)"
},
{
"code": null,
"e": 2850,
"s": 1991,
"text": "Mathematical Analysis for GOSS Technique (Calculation of Variance Gain at splitting feature j) For a training set with n instances {x1, · · ·, xn}, where each xi is a vector with dimension s in space Xs. In each iteration of gradient boosting, the negative gradients of the loss function with respect to the output of the model are denoted as {g1, · · ·, gn}. In this GOSS method, the training instances are ranked according to their absolute values of their gradients in the descending order. Then, the top-a × 100% instances with the larger gradients are kept and we get an instance subset A. Then, for the remaining set Ac consisting (1- a) × 100% instances with smaller gradients., we further randomly sample a subset B with size b × |Ac|. Finally, we split the instances according to the estimated variance gain at vector Vj (d) over the subset A ? B. "
},
{
"code": null,
"e": 2857,
"s": 2850,
"text": "(1) "
},
{
"code": null,
"e": 3766,
"s": 2857,
"text": "where Al = {xi ? A : xij ? d}, Ar = {xi ? A : xij > d}, Bl = {xi ? B : xij ? d}, Br = {xi ? B : xij > d}, and the coefficient (1-a)/b is used to normalize the sum of the gradients over B back to the size of Ac. Exclusive Feature Bundling Technique for LightGBM: High-dimensional data are usually very sparse which provides us a possibility of designing a nearly lossless approach to reduce the number of features. Specifically, in a sparse feature space, many features are mutually exclusive, i.e., they never take nonzero values simultaneously. The exclusive features can be safely bundled into a single feature (called an Exclusive Feature Bundle). Hence, the complexity of histogram building changes from O(#data × #feature) to O(#data × #bundle), while #bundle<<#feature . Hence, the speed for training framework is improved without hurting accuracy. Algorithm for Exclusive Feature Bundling Technique: "
},
{
"code": null,
"e": 4146,
"s": 3766,
"text": "Input: numData: number of data\nInput: F: One bundle of exclusive features\nbinRanges ? {0}, totalBin ? 0\nfor f in F do\n totalBin += f.numBin\n binRanges.append(totalBin)\nnewBin ? new Bin(numData)\nfor i = 1 to numData do\n newBin[i] ? 0\n for j = 1 to len(F) do\n\n if F[j].bin[i] != 0 then\n newBin[i] ? F[j].bin[i] + binRanges[j]\nOutput: newBin, binRanges"
},
{
"code": null,
"e": 4595,
"s": 4146,
"text": "Architecture : LightGBM splits the tree leaf-wise as opposed to other boosting algorithms that grow tree level-wise. It chooses the leaf with maximum delta loss to grow. Since the leaf is fixed, the leaf-wise algorithm has lower loss compared to the level-wise algorithm. Leaf-wise tree growth might increase the complexity of the model and may lead to overfitting in small datasets.Below is a diagrammatic representation of Leaf-Wise Tree Growth: "
},
{
"code": null,
"e": 4757,
"s": 4595,
"text": "Code: Python Implementation of LightGBM Model: The data set used for this example is Breast Cancer Prediction. Click on this to get data set : Link to Data set. "
},
{
"code": null,
"e": 4764,
"s": 4757,
"text": "python"
},
{
"code": "# installing LightGBM (Required in Jupyter Notebook and# few other compilers once)pip install lightgbm # Importing Required Libraryimport pandas as pdimport lightgbm as lgb # Similarly LGBMRegressor can also be imported for a regression model.from lightgbm import LGBMClassifier # Reading the train and test datasetdata = pd.read_csv(\"cancer_prediction.csv) # Removing Columns not Requireddata = data.drop(columns = ['Unnamed: 32'], axis = 1)data = data.drop(columns = ['id'], axis = 1) # Skipping Data Exploration# Dummification of Diagnosis Column (1-Benign, 0-Malignant Cancer)data['diagnosis']= pd.get_dummies(data['diagnosis']) # Splitting Dataset in two partstrain = data[0:400]test = data[400:568] # Separating the independent and target variable on both data setx_train = train.drop(columns =['diagnosis'], axis = 1)y_train = train_data['diagnosis']x_test = test_data.drop(columns =['diagnosis'], axis = 1)y_test = test_data['diagnosis'] # Creating an object for model and fitting it on training data setmodel = LGBMClassifier()model.fit(x_train, y_train) # Predicting the Target variablepred = model.predict(x_test)print(pred)accuracy = model.score(x_test, y_test)print(accuracy)",
"e": 5953,
"s": 4764,
"text": null
},
{
"code": null,
"e": 6359,
"s": 5953,
"text": "Output\nPrediction array : \n[0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1\n 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 1 1\n 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 0 1 0 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1\n 1 0 1 0 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0]\nAccuracy Score : \n0.9702380952380952"
},
{
"code": null,
"e": 6436,
"s": 6359,
"text": "Parameter Tuning Few important parameters and their usage is listed below : "
},
{
"code": null,
"e": 7364,
"s": 6436,
"text": "max_depth : It sets a limit on the depth of tree. The default value is 20. It is effective in controlling over fitting.categorical_feature : It specifies the categorical feature used for training model.bagging_fraction : It specifies the fraction of data to be considered for each iteration.num_iterations : It specifies the number of iterations to be performed. The default value is 100.num_leaves : It specifies the number of leaves in a tree. It should be smaller than the square of max_depth.max_bin : It specifies the maximum number of bins to bucket the feature values.min_data_in_bin : It specifies minimum amount of data in one bin.task : It specifies the task we wish to perform which is either train or prediction. The default entry is train. Another possible value for this parameter is prediction.feature_fraction : It specifies the fraction of features to be considered in each iteration. The default value is one."
},
{
"code": null,
"e": 7484,
"s": 7364,
"text": "max_depth : It sets a limit on the depth of tree. The default value is 20. It is effective in controlling over fitting."
},
{
"code": null,
"e": 7568,
"s": 7484,
"text": "categorical_feature : It specifies the categorical feature used for training model."
},
{
"code": null,
"e": 7658,
"s": 7568,
"text": "bagging_fraction : It specifies the fraction of data to be considered for each iteration."
},
{
"code": null,
"e": 7756,
"s": 7658,
"text": "num_iterations : It specifies the number of iterations to be performed. The default value is 100."
},
{
"code": null,
"e": 7865,
"s": 7756,
"text": "num_leaves : It specifies the number of leaves in a tree. It should be smaller than the square of max_depth."
},
{
"code": null,
"e": 7945,
"s": 7865,
"text": "max_bin : It specifies the maximum number of bins to bucket the feature values."
},
{
"code": null,
"e": 8011,
"s": 7945,
"text": "min_data_in_bin : It specifies minimum amount of data in one bin."
},
{
"code": null,
"e": 8181,
"s": 8011,
"text": "task : It specifies the task we wish to perform which is either train or prediction. The default entry is train. Another possible value for this parameter is prediction."
},
{
"code": null,
"e": 8300,
"s": 8181,
"text": "feature_fraction : It specifies the fraction of features to be considered in each iteration. The default value is one."
},
{
"code": null,
"e": 8309,
"s": 8300,
"text": "ved78142"
},
{
"code": null,
"e": 8326,
"s": 8309,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8352,
"s": 8326,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 8369,
"s": 8352,
"text": "Machine Learning"
},
{
"code": null,
"e": 8386,
"s": 8369,
"text": "Machine Learning"
},
{
"code": null,
"e": 8484,
"s": 8386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8520,
"s": 8484,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 8564,
"s": 8520,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 8600,
"s": 8564,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 8624,
"s": 8600,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 8659,
"s": 8624,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 8693,
"s": 8659,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 8717,
"s": 8693,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 8758,
"s": 8717,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 8791,
"s": 8758,
"text": "Support Vector Machine Algorithm"
}
] |
How to create multi step progress bar using Bootstrap ? - GeeksforGeeks | 03 Aug, 2021
In this article, we will create a multi-step progress bar using Bootstrap. In addition to Bootstrap, we will use jQuery for DOM manipulation.
Progress bars are used to visualize the quantity of work that’s been completed. The strength of the progress bar indicates the progress of the work. It is generally used in online web apps like YouTube, GitHub, etc, to show how the page is loaded so far. You can also find a progress bar while downloading or uploading the content to a web app.
The multi-step progress bar is used to display the progress of work in a step format.
For Example:
Step1 -> Step2 -> Step3 -> Final
Each step has a progress bar that shows its progress to reach the next step.
Example: To create the multi-step progress bar, let’s create 3 files index.html, styles.css, script.js.
index.html:
HTML
<!DOCTYPE html><html> <head> <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'> <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js'> </script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script> <link rel="stylesheet" href="styles.css"></head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-11 col-sm-9 col-md-7 col-lg-6 col-xl-5 text-center p-0 mt-3 mb-2"> <div class="px-0 pt-4 pb-0 mt-3 mb-3"> <form id="form"> <ul id="progressbar"> <li class="active" id="step1"> <strong>Step 1</strong> </li> <li id="step2"><strong>Step 2</strong></li> <li id="step3"><strong>Step 3</strong></li> <li id="step4"><strong>Step 4</strong></li> </ul> <div class="progress"> <div class="progress-bar"></div> </div> <br> <fieldset> <h2>Welcome To GFG Step 1</h2> <input type="button" name="next-step" class="next-step" value="Next Step" /> </fieldset> <fieldset> <h2>Welcome To GFG Step 2</h2> <input type="button" name="next-step" class="next-step" value="Next Step" /> <input type="button" name="previous-step" class="previous-step" value="Previous Step" /> </fieldset> <fieldset> <h2>Welcome To GFG Step 3</h2> <input type="button" name="next-step" class="next-step" value="Final Step" /> <input type="button" name="previous-step" class="previous-step" value="Previous Step" /> </fieldset> <fieldset> <div class="finish"> <h2 class="text text-center"> <strong>FINISHED</strong> </h2> </div> <input type="button" name="previous-step" class="previous-step" value="Previous Step" /> </fieldset> </form> </div> </div> </div> </div></body><script src="script.js"></script> </html>
styles.css:
CSS
* { margin: 0; padding: 0} html { height: 100%} h2{ color: #2F8D46;}#form { text-align: center; position: relative; margin-top: 20px} #form fieldset { background: white; border: 0 none; border-radius: 0.5rem; box-sizing: border-box; width: 100%; margin: 0; padding-bottom: 20px; position: relative} .finish { text-align: center} #form fieldset:not(:first-of-type) { display: none} #form .previous-step, .next-step { width: 100px; font-weight: bold; color: white; border: 0 none; border-radius: 0px; cursor: pointer; padding: 10px 5px; margin: 10px 5px 10px 0px; float: right} .form, .previous-step { background: #616161;} .form, .next-step { background: #2F8D46;} #form .previous-step:hover,#form .previous-step:focus { background-color: #000000} #form .next-step:hover,#form .next-step:focus { background-color: #2F8D46} .text { color: #2F8D46; font-weight: normal} #progressbar { margin-bottom: 30px; overflow: hidden; color: lightgrey} #progressbar .active { color: #2F8D46} #progressbar li { list-style-type: none; font-size: 15px; width: 25%; float: left; position: relative; font-weight: 400} #progressbar #step1:before { content: "1"} #progressbar #step2:before { content: "2"} #progressbar #step3:before { content: "3"} #progressbar #step4:before { content: "4"} #progressbar li:before { width: 50px; height: 50px; line-height: 45px; display: block; font-size: 20px; color: #ffffff; background: lightgray; border-radius: 50%; margin: 0 auto 10px auto; padding: 2px} #progressbar li:after { content: ''; width: 100%; height: 2px; background: lightgray; position: absolute; left: 0; top: 25px; z-index: -1} #progressbar li.active:before,#progressbar li.active:after { background: #2F8D46} .progress { height: 20px} .progress-bar { background-color: #2F8D46}
script.js
Javascript
$(document).ready(function () { var currentGfgStep, nextGfgStep, previousGfgStep; var opacity; var current = 1; var steps = $("fieldset").length; setProgressBar(current); $(".next-step").click(function () { currentGfgStep = $(this).parent(); nextGfgStep = $(this).parent().next(); $("#progressbar li").eq($("fieldset") .index(nextGfgStep)).addClass("active"); nextGfgStep.show(); currentGfgStep.animate({ opacity: 0 }, { step: function (now) { opacity = 1 - now; currentGfgStep.css({ 'display': 'none', 'position': 'relative' }); nextGfgStep.css({ 'opacity': opacity }); }, duration: 500 }); setProgressBar(++current); }); $(".previous-step").click(function () { currentGfgStep = $(this).parent(); previousGfgStep = $(this).parent().prev(); $("#progressbar li").eq($("fieldset") .index(currentGfgStep)).removeClass("active"); previousGfgStep.show(); currentGfgStep.animate({ opacity: 0 }, { step: function (now) { opacity = 1 - now; currentGfgStep.css({ 'display': 'none', 'position': 'relative' }); previousGfgStep.css({ 'opacity': opacity }); }, duration: 500 }); setProgressBar(--current); }); function setProgressBar(currentStep) { var percent = parseFloat(100 / steps) * current; percent = percent.toFixed(); $(".progress-bar") .css("width", percent + "%") } $(".submit").click(function () { return false; })});
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Misc
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
Bootstrap
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to change the background color of the active nav-item?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form | [
{
"code": null,
"e": 25291,
"s": 25263,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25433,
"s": 25291,
"text": "In this article, we will create a multi-step progress bar using Bootstrap. In addition to Bootstrap, we will use jQuery for DOM manipulation."
},
{
"code": null,
"e": 25778,
"s": 25433,
"text": "Progress bars are used to visualize the quantity of work that’s been completed. The strength of the progress bar indicates the progress of the work. It is generally used in online web apps like YouTube, GitHub, etc, to show how the page is loaded so far. You can also find a progress bar while downloading or uploading the content to a web app."
},
{
"code": null,
"e": 25864,
"s": 25778,
"text": "The multi-step progress bar is used to display the progress of work in a step format."
},
{
"code": null,
"e": 25877,
"s": 25864,
"text": "For Example:"
},
{
"code": null,
"e": 25911,
"s": 25877,
"text": " Step1 -> Step2 -> Step3 -> Final"
},
{
"code": null,
"e": 25988,
"s": 25911,
"text": "Each step has a progress bar that shows its progress to reach the next step."
},
{
"code": null,
"e": 26092,
"s": 25988,
"text": "Example: To create the multi-step progress bar, let’s create 3 files index.html, styles.css, script.js."
},
{
"code": null,
"e": 26104,
"s": 26092,
"text": "index.html:"
},
{
"code": null,
"e": 26109,
"s": 26104,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'> <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js'> </script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'> </script> <link rel=\"stylesheet\" href=\"styles.css\"></head> <body> <div class=\"container\"> <div class=\"row justify-content-center\"> <div class=\"col-11 col-sm-9 col-md-7 col-lg-6 col-xl-5 text-center p-0 mt-3 mb-2\"> <div class=\"px-0 pt-4 pb-0 mt-3 mb-3\"> <form id=\"form\"> <ul id=\"progressbar\"> <li class=\"active\" id=\"step1\"> <strong>Step 1</strong> </li> <li id=\"step2\"><strong>Step 2</strong></li> <li id=\"step3\"><strong>Step 3</strong></li> <li id=\"step4\"><strong>Step 4</strong></li> </ul> <div class=\"progress\"> <div class=\"progress-bar\"></div> </div> <br> <fieldset> <h2>Welcome To GFG Step 1</h2> <input type=\"button\" name=\"next-step\" class=\"next-step\" value=\"Next Step\" /> </fieldset> <fieldset> <h2>Welcome To GFG Step 2</h2> <input type=\"button\" name=\"next-step\" class=\"next-step\" value=\"Next Step\" /> <input type=\"button\" name=\"previous-step\" class=\"previous-step\" value=\"Previous Step\" /> </fieldset> <fieldset> <h2>Welcome To GFG Step 3</h2> <input type=\"button\" name=\"next-step\" class=\"next-step\" value=\"Final Step\" /> <input type=\"button\" name=\"previous-step\" class=\"previous-step\" value=\"Previous Step\" /> </fieldset> <fieldset> <div class=\"finish\"> <h2 class=\"text text-center\"> <strong>FINISHED</strong> </h2> </div> <input type=\"button\" name=\"previous-step\" class=\"previous-step\" value=\"Previous Step\" /> </fieldset> </form> </div> </div> </div> </div></body><script src=\"script.js\"></script> </html>",
"e": 29130,
"s": 26109,
"text": null
},
{
"code": null,
"e": 29143,
"s": 29130,
"text": "styles.css: "
},
{
"code": null,
"e": 29147,
"s": 29143,
"text": "CSS"
},
{
"code": "* { margin: 0; padding: 0} html { height: 100%} h2{ color: #2F8D46;}#form { text-align: center; position: relative; margin-top: 20px} #form fieldset { background: white; border: 0 none; border-radius: 0.5rem; box-sizing: border-box; width: 100%; margin: 0; padding-bottom: 20px; position: relative} .finish { text-align: center} #form fieldset:not(:first-of-type) { display: none} #form .previous-step, .next-step { width: 100px; font-weight: bold; color: white; border: 0 none; border-radius: 0px; cursor: pointer; padding: 10px 5px; margin: 10px 5px 10px 0px; float: right} .form, .previous-step { background: #616161;} .form, .next-step { background: #2F8D46;} #form .previous-step:hover,#form .previous-step:focus { background-color: #000000} #form .next-step:hover,#form .next-step:focus { background-color: #2F8D46} .text { color: #2F8D46; font-weight: normal} #progressbar { margin-bottom: 30px; overflow: hidden; color: lightgrey} #progressbar .active { color: #2F8D46} #progressbar li { list-style-type: none; font-size: 15px; width: 25%; float: left; position: relative; font-weight: 400} #progressbar #step1:before { content: \"1\"} #progressbar #step2:before { content: \"2\"} #progressbar #step3:before { content: \"3\"} #progressbar #step4:before { content: \"4\"} #progressbar li:before { width: 50px; height: 50px; line-height: 45px; display: block; font-size: 20px; color: #ffffff; background: lightgray; border-radius: 50%; margin: 0 auto 10px auto; padding: 2px} #progressbar li:after { content: ''; width: 100%; height: 2px; background: lightgray; position: absolute; left: 0; top: 25px; z-index: -1} #progressbar li.active:before,#progressbar li.active:after { background: #2F8D46} .progress { height: 20px} .progress-bar { background-color: #2F8D46}",
"e": 31135,
"s": 29147,
"text": null
},
{
"code": null,
"e": 31145,
"s": 31135,
"text": "script.js"
},
{
"code": null,
"e": 31156,
"s": 31145,
"text": "Javascript"
},
{
"code": "$(document).ready(function () { var currentGfgStep, nextGfgStep, previousGfgStep; var opacity; var current = 1; var steps = $(\"fieldset\").length; setProgressBar(current); $(\".next-step\").click(function () { currentGfgStep = $(this).parent(); nextGfgStep = $(this).parent().next(); $(\"#progressbar li\").eq($(\"fieldset\") .index(nextGfgStep)).addClass(\"active\"); nextGfgStep.show(); currentGfgStep.animate({ opacity: 0 }, { step: function (now) { opacity = 1 - now; currentGfgStep.css({ 'display': 'none', 'position': 'relative' }); nextGfgStep.css({ 'opacity': opacity }); }, duration: 500 }); setProgressBar(++current); }); $(\".previous-step\").click(function () { currentGfgStep = $(this).parent(); previousGfgStep = $(this).parent().prev(); $(\"#progressbar li\").eq($(\"fieldset\") .index(currentGfgStep)).removeClass(\"active\"); previousGfgStep.show(); currentGfgStep.animate({ opacity: 0 }, { step: function (now) { opacity = 1 - now; currentGfgStep.css({ 'display': 'none', 'position': 'relative' }); previousGfgStep.css({ 'opacity': opacity }); }, duration: 500 }); setProgressBar(--current); }); function setProgressBar(currentStep) { var percent = parseFloat(100 / steps) * current; percent = percent.toFixed(); $(\".progress-bar\") .css(\"width\", percent + \"%\") } $(\".submit\").click(function () { return false; })});",
"e": 32961,
"s": 31156,
"text": null
},
{
"code": null,
"e": 32969,
"s": 32961,
"text": "Output:"
},
{
"code": null,
"e": 33237,
"s": 32969,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 33374,
"s": 33237,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 33389,
"s": 33374,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 33398,
"s": 33389,
"text": "CSS-Misc"
},
{
"code": null,
"e": 33408,
"s": 33398,
"text": "HTML-Misc"
},
{
"code": null,
"e": 33420,
"s": 33408,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 33427,
"s": 33420,
"text": "Picked"
},
{
"code": null,
"e": 33437,
"s": 33427,
"text": "Bootstrap"
},
{
"code": null,
"e": 33441,
"s": 33437,
"text": "CSS"
},
{
"code": null,
"e": 33446,
"s": 33441,
"text": "HTML"
},
{
"code": null,
"e": 33453,
"s": 33446,
"text": "JQuery"
},
{
"code": null,
"e": 33470,
"s": 33453,
"text": "Web Technologies"
},
{
"code": null,
"e": 33475,
"s": 33470,
"text": "HTML"
},
{
"code": null,
"e": 33573,
"s": 33475,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33582,
"s": 33573,
"text": "Comments"
},
{
"code": null,
"e": 33595,
"s": 33582,
"text": "Old Comments"
},
{
"code": null,
"e": 33636,
"s": 33595,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 33677,
"s": 33636,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 33740,
"s": 33677,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 33773,
"s": 33740,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 33832,
"s": 33773,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 33894,
"s": 33832,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33944,
"s": 33894,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33992,
"s": 33944,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34050,
"s": 33992,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Java - String subSequence() Method | This method returns a new character sequence that is a subsequence of this sequence.
Here is the syntax of this method −
public CharSequence subSequence(int beginIndex, int endIndex)
Here is the detail of parameters −
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
endIndex − the end index, exclusive.
endIndex − the end index, exclusive.
This method returns the specified subsequence.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.subSequence(0, 10) );
System.out.print("Return Value :" );
System.out.println(Str.subSequence(10, 15) );
}
}
This will produce the following result −
Return Value :Welcome to
Return Value : Tuto
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2462,
"s": 2377,
"text": "This method returns a new character sequence that is a subsequence of this sequence."
},
{
"code": null,
"e": 2498,
"s": 2462,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2561,
"s": 2498,
"text": "public CharSequence subSequence(int beginIndex, int endIndex)\n"
},
{
"code": null,
"e": 2596,
"s": 2561,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2637,
"s": 2596,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 2678,
"s": 2637,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 2715,
"s": 2678,
"text": "endIndex − the end index, exclusive."
},
{
"code": null,
"e": 2752,
"s": 2715,
"text": "endIndex − the end index, exclusive."
},
{
"code": null,
"e": 2799,
"s": 2752,
"text": "This method returns the specified subsequence."
},
{
"code": null,
"e": 3144,
"s": 2799,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.subSequence(0, 10) );\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.subSequence(10, 15) );\n }\n}"
},
{
"code": null,
"e": 3185,
"s": 3144,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3231,
"s": 3185,
"text": "Return Value :Welcome to\nReturn Value : Tuto\n"
},
{
"code": null,
"e": 3264,
"s": 3231,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3280,
"s": 3264,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3313,
"s": 3280,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3329,
"s": 3313,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3364,
"s": 3329,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3378,
"s": 3364,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3412,
"s": 3378,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3426,
"s": 3412,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3463,
"s": 3426,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3478,
"s": 3463,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3511,
"s": 3478,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3530,
"s": 3511,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3537,
"s": 3530,
"text": " Print"
},
{
"code": null,
"e": 3548,
"s": 3537,
"text": " Add Notes"
}
] |
What is the difference between Write() and WriteLine() methods in C#? | The difference between Write() and WriteLine() method is based on new line character.
Write() method displays the output but do not provide a new line character.
WriteLine() method displays the output and also provides a new line character it the end of the string, This would set a new line for the next output.
Let us see an example to learn about the difference between Write() and WriteLine() method −
Live Demo
using System;
class Program {
static void Main() {
Console.Write("One");
Console.Write("Two");
// this will set a new line for the next output
Console.WriteLine("Three");
Console.WriteLine("Four");
}
}
OneTwoThree
Four | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "The difference between Write() and WriteLine() method is based on new line character."
},
{
"code": null,
"e": 1224,
"s": 1148,
"text": "Write() method displays the output but do not provide a new line character."
},
{
"code": null,
"e": 1375,
"s": 1224,
"text": "WriteLine() method displays the output and also provides a new line character it the end of the string, This would set a new line for the next output."
},
{
"code": null,
"e": 1468,
"s": 1375,
"text": "Let us see an example to learn about the difference between Write() and WriteLine() method −"
},
{
"code": null,
"e": 1479,
"s": 1468,
"text": " Live Demo"
},
{
"code": null,
"e": 1718,
"s": 1479,
"text": "using System;\nclass Program {\n static void Main() {\n Console.Write(\"One\");\n Console.Write(\"Two\");\n\n // this will set a new line for the next output\n Console.WriteLine(\"Three\");\n Console.WriteLine(\"Four\");\n }\n}"
},
{
"code": null,
"e": 1735,
"s": 1718,
"text": "OneTwoThree\nFour"
}
] |
Java Tutorial | Java is a popular programming language.
Java is used to develop mobile apps, web apps, desktop apps, games and much
more.
Our "Try it Yourself" editor makes it easy to learn Java. You can edit Java code and view the result
in your browser.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Try it Yourself »
Click on the "Run example" button to see how it works.
We recommend reading this tutorial, in the sequence listed in the left menu.
Java is an object oriented language and some concepts may be new. Take breaks when needed, and go
over the examples as many times as needed.
Insert the missing part of the code below to output "Hello World".
public class MyClass {
public static void main(String[] args) {
..("Hello World");
}
}
Start the Exercise
Test your Java skills with a quiz.
Start Java Quiz
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All Java Examples
Java Keywords
Java String Methods
Java Math Methods
Download Java from the official Java web site:
https://www.oracle.com
Get certified by completing the JAVA course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 40,
"s": 0,
"text": "Java is a popular programming language."
},
{
"code": null,
"e": 123,
"s": 40,
"text": "Java is used to develop mobile apps, web apps, desktop apps, games and much \nmore."
},
{
"code": null,
"e": 242,
"s": 123,
"text": "Our \"Try it Yourself\" editor makes it easy to learn Java. You can edit Java code and view the result \nin your browser."
},
{
"code": null,
"e": 351,
"s": 242,
"text": "public class Main {\n public static void main(String[] args) {\n System.out.println(\"Hello World\");\n }\n}\n"
},
{
"code": null,
"e": 371,
"s": 351,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 426,
"s": 371,
"text": "Click on the \"Run example\" button to see how it works."
},
{
"code": null,
"e": 503,
"s": 426,
"text": "We recommend reading this tutorial, in the sequence listed in the left menu."
},
{
"code": null,
"e": 644,
"s": 503,
"text": "Java is an object oriented language and some concepts may be new. Take breaks when needed, and go\nover the examples as many times as needed."
},
{
"code": null,
"e": 711,
"s": 644,
"text": "Insert the missing part of the code below to output \"Hello World\"."
},
{
"code": null,
"e": 807,
"s": 711,
"text": "public class MyClass {\n public static void main(String[] args) {\n ..(\"Hello World\");\n }\n}\n"
},
{
"code": null,
"e": 826,
"s": 807,
"text": "Start the Exercise"
},
{
"code": null,
"e": 861,
"s": 826,
"text": "Test your Java skills with a quiz."
},
{
"code": null,
"e": 877,
"s": 861,
"text": "Start Java Quiz"
},
{
"code": null,
"e": 965,
"s": 877,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 987,
"s": 965,
"text": "See All Java Examples"
},
{
"code": null,
"e": 1001,
"s": 987,
"text": "Java Keywords"
},
{
"code": null,
"e": 1021,
"s": 1001,
"text": "Java String Methods"
},
{
"code": null,
"e": 1039,
"s": 1021,
"text": "Java Math Methods"
},
{
"code": null,
"e": 1109,
"s": 1039,
"text": "Download Java from the official Java web site:\nhttps://www.oracle.com"
},
{
"code": null,
"e": 1153,
"s": 1109,
"text": "Get certified by completing the JAVA course"
},
{
"code": null,
"e": 1186,
"s": 1153,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1228,
"s": 1186,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1335,
"s": 1228,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1354,
"s": 1335,
"text": "[email protected]"
}
] |
How does Floyd’s slow and fast pointers approach work? | 03 Jul, 2022
We have discussed Floyd’s fast and slow pointer algorithms in Detect loop in a linked list. The algorithm is to start two pointers, slow and fast from head of linked list. We move slow one node at a time and fast two nodes at a time. If there is a loop, then they will definitely meet. This approach works because of the following facts. 1) When slow pointer enters the loop, the fast pointer must be inside the loop. Let fast pointer be distance k from slow. 2) Now if consider movements of slow and fast pointers, we can notice that distance between them (from slow to fast) increase by one after every iteration. After one iteration (of slow = next of slow and fast = next of next of fast), distance between slow and fast becomes k+1, after two iterations, k+2, and so on. When distance becomes n, they meet because they are moving in a cycle of length n. For example, we can see in below diagram, initial distance is 2. After one iteration, distance becomes 3, after 2 iterations, it becomes 4. After 3 iterations, it becomes 5 which is distance 0. And they meet. How does cycle removal algorithm work? Please see method 3 of Detect and Remove Loop in a Linked List
Java
C++
Javascript
Python
C#
// Java program to detect loop in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void detectLoop() { Node slow_p = head, fast_p = head; int flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) System.out.println("Loop found"); else System.out.println("Loop not found"); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; llist.detectLoop(); }}
// C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(Node* list){ Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << "Loop found"; else cout << "No Loop"; return 0;}
<script> // Javascript program to detect loop in a linked listlet head; // head of list /* Linked list Node*/class Node{ constructor(d) { this.data = d; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} function detectLoop(){ let slow_p = head, fast_p = head; let flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) document.write("Loop found<br>"); else document.write("Loop not found<br>");} // Driver codepush(20);push(4);push(15);push(10); // Create loop for testinghead.next.next.next.next = head; detectLoop(); </script>
# Python program to detect loop in the linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next def detectLoop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.headif(llist.detectLoop()): print "Found Loop"else: print "No Loop"
// C# program to detect loop in a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } Boolean detectLoop() { Node slow_p = head, fast_p = head; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { return true; } } return false; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; Boolean found = llist.detectLoop(); if (found) { Console.WriteLine("Loop Found"); } else { Console.WriteLine("No Loop"); } }}
Loop found
nikitamehrotra99
graph-cycle
Linked List
Mathematical
Linked List
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 1224,
"s": 52,
"text": "We have discussed Floyd’s fast and slow pointer algorithms in Detect loop in a linked list. The algorithm is to start two pointers, slow and fast from head of linked list. We move slow one node at a time and fast two nodes at a time. If there is a loop, then they will definitely meet. This approach works because of the following facts. 1) When slow pointer enters the loop, the fast pointer must be inside the loop. Let fast pointer be distance k from slow. 2) Now if consider movements of slow and fast pointers, we can notice that distance between them (from slow to fast) increase by one after every iteration. After one iteration (of slow = next of slow and fast = next of next of fast), distance between slow and fast becomes k+1, after two iterations, k+2, and so on. When distance becomes n, they meet because they are moving in a cycle of length n. For example, we can see in below diagram, initial distance is 2. After one iteration, distance becomes 3, after 2 iterations, it becomes 4. After 3 iterations, it becomes 5 which is distance 0. And they meet. How does cycle removal algorithm work? Please see method 3 of Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 1229,
"s": 1224,
"text": "Java"
},
{
"code": null,
"e": 1233,
"s": 1229,
"text": "C++"
},
{
"code": null,
"e": 1244,
"s": 1233,
"text": "Javascript"
},
{
"code": null,
"e": 1251,
"s": 1244,
"text": "Python"
},
{
"code": null,
"e": 1254,
"s": 1251,
"text": "C#"
},
{
"code": "// Java program to detect loop in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void detectLoop() { Node slow_p = head, fast_p = head; int flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) System.out.println(\"Loop found\"); else System.out.println(\"Loop not found\"); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; llist.detectLoop(); }}",
"e": 2720,
"s": 1254,
"text": null
},
{
"code": "// C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(Node* list){ Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << \"Loop found\"; else cout << \"No Loop\"; return 0;}",
"e": 3803,
"s": 2720,
"text": null
},
{
"code": "<script> // Javascript program to detect loop in a linked listlet head; // head of list /* Linked list Node*/class Node{ constructor(d) { this.data = d; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} function detectLoop(){ let slow_p = head, fast_p = head; let flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) document.write(\"Loop found<br>\"); else document.write(\"Loop not found<br>\");} // Driver codepush(20);push(4);push(15);push(10); // Create loop for testinghead.next.next.next.next = head; detectLoop(); </script>",
"e": 4888,
"s": 3803,
"text": null
},
{
"code": "# Python program to detect loop in the linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next def detectLoop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.headif(llist.detectLoop()): print \"Found Loop\"else: print \"No Loop\"",
"e": 6055,
"s": 4888,
"text": null
},
{
"code": "// C# program to detect loop in a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } Boolean detectLoop() { Node slow_p = head, fast_p = head; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { return true; } } return false; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; Boolean found = llist.detectLoop(); if (found) { Console.WriteLine(\"Loop Found\"); } else { Console.WriteLine(\"No Loop\"); } }}",
"e": 7549,
"s": 6055,
"text": null
},
{
"code": null,
"e": 7560,
"s": 7549,
"text": "Loop found"
},
{
"code": null,
"e": 7577,
"s": 7560,
"text": "nikitamehrotra99"
},
{
"code": null,
"e": 7589,
"s": 7577,
"text": "graph-cycle"
},
{
"code": null,
"e": 7601,
"s": 7589,
"text": "Linked List"
},
{
"code": null,
"e": 7614,
"s": 7601,
"text": "Mathematical"
},
{
"code": null,
"e": 7626,
"s": 7614,
"text": "Linked List"
},
{
"code": null,
"e": 7639,
"s": 7626,
"text": "Mathematical"
}
] |
Python | Delete rows/columns from DataFrame using Pandas.drop() | 17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas provide data analysts a way to delete and filter data frame using .drop() method. Rows or columns can be removed using index label or column name using this method.
Syntax:DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)
Parameters:
labels: String or list of strings referring row or column name.axis: int or string value, 0 ‘index’ for Rows and 1 ‘columns’ for Columns.index or columns: Single label or list. index or columns are an alternative to axis and cannot be used together.level: Used to specify level in case data frame is having multiple level index.inplace: Makes changes in original Data Frame if True.errors: Ignores error if any value from the list doesn’t exists and drops rest of the values when errors = ‘ignore’
Return type: Dataframe with dropped values
To download the CSV used in code, click here.
Example #1: Dropping Rows by index labelIn his code, A list of index labels is passed and the rows corresponding to those labels are dropped using .drop() method.
# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name" ) # dropping passed valuesdata.drop(["Avery Bradley", "John Holland", "R.J. Hunter", "R.J. Hunter"], inplace = True) # displaydata
Output:As shown in the output images, the new output doesn’t have the passed values. Those values were dropped and the changes were made in the original data frame since inplace was True.Data Frame before Dropping values-Data Frame after Dropping values-
Example #2 : Dropping columns with column name
In his code, Passed columns are dropped using column names. axis parameter is kept 1 since 1 refers to columns.
# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name" ) # dropping passed columnsdata.drop(["Team", "Weight"], axis = 1, inplace = True) # displaydata
Output:As shown in the output images, the new output doesn’t have the passed columns. Those values were dropped since axis was set equal to 1 and the changes were made in the original data frame since inplace was True.Data Frame before Dropping Columns-Data Frame after Dropping Columns-
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 268,
"s": 54,
"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": 440,
"s": 268,
"text": "Pandas provide data analysts a way to delete and filter data frame using .drop() method. Rows or columns can be removed using index label or column name using this method."
},
{
"code": null,
"e": 552,
"s": 440,
"text": "Syntax:DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)"
},
{
"code": null,
"e": 564,
"s": 552,
"text": "Parameters:"
},
{
"code": null,
"e": 1062,
"s": 564,
"text": "labels: String or list of strings referring row or column name.axis: int or string value, 0 ‘index’ for Rows and 1 ‘columns’ for Columns.index or columns: Single label or list. index or columns are an alternative to axis and cannot be used together.level: Used to specify level in case data frame is having multiple level index.inplace: Makes changes in original Data Frame if True.errors: Ignores error if any value from the list doesn’t exists and drops rest of the values when errors = ‘ignore’"
},
{
"code": null,
"e": 1105,
"s": 1062,
"text": "Return type: Dataframe with dropped values"
},
{
"code": null,
"e": 1151,
"s": 1105,
"text": "To download the CSV used in code, click here."
},
{
"code": null,
"e": 1314,
"s": 1151,
"text": "Example #1: Dropping Rows by index labelIn his code, A list of index labels is passed and the rows corresponding to those labels are dropped using .drop() method."
},
{
"code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\" ) # dropping passed valuesdata.drop([\"Avery Bradley\", \"John Holland\", \"R.J. Hunter\", \"R.J. Hunter\"], inplace = True) # displaydata",
"e": 1601,
"s": 1314,
"text": null
},
{
"code": null,
"e": 1857,
"s": 1601,
"text": "Output:As shown in the output images, the new output doesn’t have the passed values. Those values were dropped and the changes were made in the original data frame since inplace was True.Data Frame before Dropping values-Data Frame after Dropping values- "
},
{
"code": null,
"e": 1904,
"s": 1857,
"text": "Example #2 : Dropping columns with column name"
},
{
"code": null,
"e": 2016,
"s": 1904,
"text": "In his code, Passed columns are dropped using column names. axis parameter is kept 1 since 1 refers to columns."
},
{
"code": "# importing pandas moduleimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\" ) # dropping passed columnsdata.drop([\"Team\", \"Weight\"], axis = 1, inplace = True) # displaydata",
"e": 2242,
"s": 2016,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2242,
"text": "Output:As shown in the output images, the new output doesn’t have the passed columns. Those values were dropped since axis was set equal to 1 and the changes were made in the original data frame since inplace was True.Data Frame before Dropping Columns-Data Frame after Dropping Columns-"
},
{
"code": null,
"e": 2554,
"s": 2530,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2586,
"s": 2554,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2600,
"s": 2586,
"text": "Python-pandas"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "Python"
}
] |
Python – MenuBars in wxPython | 10 May, 2020
One of the most important part in a GUI is a menubar, which are used to perform various operations on a Window. In this article we will learn how to create a menubar and add menu item to it. This can be achieved using MenuBar() constructor and Append() function in wx.MenuBar class.
Syntax for MenuBar() constructor:
wx.MenuBar(style=0)
Syntax for Append() function:
wx.MenuBar.Append(self, menu, title)
Parameters:
Code Example:
# import wxPython import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # create MenuBar using MenuBar() function menubar = wx.MenuBar() fileMenu = wx.Menu() # add menu to MenuBar menubar.Append(fileMenu, '&Menu# 1') self.SetMenuBar(menubar) self.SetSize((300, 200)) self.SetTitle('Menu Bar')def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()
Output :
Python-gui
Python-wxPython
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "One of the most important part in a GUI is a menubar, which are used to perform various operations on a Window. In this article we will learn how to create a menubar and add menu item to it. This can be achieved using MenuBar() constructor and Append() function in wx.MenuBar class."
},
{
"code": null,
"e": 345,
"s": 311,
"text": "Syntax for MenuBar() constructor:"
},
{
"code": null,
"e": 366,
"s": 345,
"text": "wx.MenuBar(style=0)\n"
},
{
"code": null,
"e": 396,
"s": 366,
"text": "Syntax for Append() function:"
},
{
"code": null,
"e": 434,
"s": 396,
"text": "wx.MenuBar.Append(self, menu, title)\n"
},
{
"code": null,
"e": 446,
"s": 434,
"text": "Parameters:"
},
{
"code": null,
"e": 460,
"s": 446,
"text": "Code Example:"
},
{
"code": "# import wxPython import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): # create MenuBar using MenuBar() function menubar = wx.MenuBar() fileMenu = wx.Menu() # add menu to MenuBar menubar.Append(fileMenu, '&Menu# 1') self.SetMenuBar(menubar) self.SetSize((300, 200)) self.SetTitle('Menu Bar')def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()",
"e": 1061,
"s": 460,
"text": null
},
{
"code": null,
"e": 1070,
"s": 1061,
"text": "Output :"
},
{
"code": null,
"e": 1081,
"s": 1070,
"text": "Python-gui"
},
{
"code": null,
"e": 1097,
"s": 1081,
"text": "Python-wxPython"
},
{
"code": null,
"e": 1104,
"s": 1097,
"text": "Python"
},
{
"code": null,
"e": 1202,
"s": 1104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1220,
"s": 1202,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1262,
"s": 1220,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1284,
"s": 1262,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1316,
"s": 1284,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1342,
"s": 1316,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1371,
"s": 1342,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1398,
"s": 1371,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1419,
"s": 1398,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1442,
"s": 1419,
"text": "Introduction To PYTHON"
}
] |
How to pass query parameters with a routerLink ? | 22 Jul, 2020
The task is to pass query parameters with a routerLink, for that we can use the property binding concept to reach the goal. Using property binding, we can bind queryParams property and can provide the required details in the object.
What is Property Binding?
It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) elements.
Syntax:
<a [routerLink]="[/path]" [queryParams]="{property:value}">
State Details
</a>
An Example of property binding:
Javascript
import { Component, OnInit } from '@angular/core' @Component({ selector: 'app-property', template: // Property Binding `<p [textContent]="title"></p>`}) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } title = 'Property Binding example in GeeksforGeeks'; }
Output:
Illustration of above code
Approach:
First, configure the routes in app.module.ts
Implement query params with required values in the HTML file.
Then in .ts file, in ngOnit try to access the query params using the activated Route by importing it from ‘angular@router’
Once you are able to access them try to render them by using either string interpolation syntax or property binding syntax in HTML file.
Below is the implementation of the above steps:
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; // Importing Routesimport { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { StateComponent } from './state/state.component'; // Configuring Routesconst routes: Routes = [{ path: 'punjab', component: StateComponent },]; @NgModule({ imports: [BrowserModule, R outerModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent]})export class AppModule { }
app.component.html:
HTML
<a [routerLink]="['/punjab']" [queryParams]= "{capital:'mohali',language:'punjabi'}"> State Details</a><router-outlet></router-outlet>
After clicking on the anchor tag the URL will be displayed in the following way:
We can also access the query parameters using the activated route.
In this way, we can pass query parameters via routerLink.
Fetching of query parameters:
state.component.ts :
Javascript
import { Component, OnInit } from '@angular/core';import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-state', templateUrl: './state.component.html', styleUrls: ['./state.component.css']})export class StateComponent implements OnInit { capital: string; language:string; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.queryParams.subscribe( params => { this.capital = params['capital']; this.language=params['language']; } ) } }
state.component.html:
HTML
State Details are : <p>Capital : {{capital}} </p> <p>Language : {{language}} </p>
Output:
Before Click the Button:
Before Click the Button:
After Click the Button: Hence query parameters passed can be seen
After Click the Button: Hence query parameters passed can be seen
AngularJS-Misc
JavaScript-Misc
Picked
AngularJS
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": "\n22 Jul, 2020"
},
{
"code": null,
"e": 261,
"s": 28,
"text": "The task is to pass query parameters with a routerLink, for that we can use the property binding concept to reach the goal. Using property binding, we can bind queryParams property and can provide the required details in the object."
},
{
"code": null,
"e": 287,
"s": 261,
"text": "What is Property Binding?"
},
{
"code": null,
"e": 439,
"s": 287,
"text": "It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) elements."
},
{
"code": null,
"e": 447,
"s": 439,
"text": "Syntax:"
},
{
"code": null,
"e": 532,
"s": 447,
"text": "<a [routerLink]=\"[/path]\" [queryParams]=\"{property:value}\">\n State Details \n</a>\n "
},
{
"code": null,
"e": 564,
"s": 532,
"text": "An Example of property binding:"
},
{
"code": null,
"e": 575,
"s": 564,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core' @Component({ selector: 'app-property', template: // Property Binding `<p [textContent]=\"title\"></p>`}) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } title = 'Property Binding example in GeeksforGeeks'; }",
"e": 901,
"s": 575,
"text": null
},
{
"code": null,
"e": 909,
"s": 901,
"text": "Output:"
},
{
"code": null,
"e": 936,
"s": 909,
"text": "Illustration of above code"
},
{
"code": null,
"e": 946,
"s": 936,
"text": "Approach:"
},
{
"code": null,
"e": 991,
"s": 946,
"text": "First, configure the routes in app.module.ts"
},
{
"code": null,
"e": 1053,
"s": 991,
"text": "Implement query params with required values in the HTML file."
},
{
"code": null,
"e": 1177,
"s": 1053,
"text": "Then in .ts file, in ngOnit try to access the query params using the activated Route by importing it from ‘angular@router’"
},
{
"code": null,
"e": 1314,
"s": 1177,
"text": "Once you are able to access them try to render them by using either string interpolation syntax or property binding syntax in HTML file."
},
{
"code": null,
"e": 1362,
"s": 1314,
"text": "Below is the implementation of the above steps:"
},
{
"code": null,
"e": 1377,
"s": 1362,
"text": "app.module.ts:"
},
{
"code": null,
"e": 1388,
"s": 1377,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; // Importing Routesimport { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { StateComponent } from './state/state.component'; // Configuring Routesconst routes: Routes = [{ path: 'punjab', component: StateComponent },]; @NgModule({ imports: [BrowserModule, R outerModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent]})export class AppModule { }",
"e": 2019,
"s": 1388,
"text": null
},
{
"code": null,
"e": 2039,
"s": 2019,
"text": "app.component.html:"
},
{
"code": null,
"e": 2044,
"s": 2039,
"text": "HTML"
},
{
"code": "<a [routerLink]=\"['/punjab']\" [queryParams]= \"{capital:'mohali',language:'punjabi'}\"> State Details</a><router-outlet></router-outlet>",
"e": 2185,
"s": 2044,
"text": null
},
{
"code": null,
"e": 2266,
"s": 2185,
"text": "After clicking on the anchor tag the URL will be displayed in the following way:"
},
{
"code": null,
"e": 2333,
"s": 2266,
"text": "We can also access the query parameters using the activated route."
},
{
"code": null,
"e": 2391,
"s": 2333,
"text": "In this way, we can pass query parameters via routerLink."
},
{
"code": null,
"e": 2421,
"s": 2391,
"text": "Fetching of query parameters:"
},
{
"code": null,
"e": 2442,
"s": 2421,
"text": "state.component.ts :"
},
{
"code": null,
"e": 2453,
"s": 2442,
"text": "Javascript"
},
{
"code": "import { Component, OnInit } from '@angular/core';import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-state', templateUrl: './state.component.html', styleUrls: ['./state.component.css']})export class StateComponent implements OnInit { capital: string; language:string; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.queryParams.subscribe( params => { this.capital = params['capital']; this.language=params['language']; } ) } }",
"e": 2977,
"s": 2453,
"text": null
},
{
"code": null,
"e": 2999,
"s": 2977,
"text": "state.component.html:"
},
{
"code": null,
"e": 3004,
"s": 2999,
"text": "HTML"
},
{
"code": "State Details are : <p>Capital : {{capital}} </p> <p>Language : {{language}} </p>",
"e": 3090,
"s": 3004,
"text": null
},
{
"code": null,
"e": 3098,
"s": 3090,
"text": "Output:"
},
{
"code": null,
"e": 3123,
"s": 3098,
"text": "Before Click the Button:"
},
{
"code": null,
"e": 3148,
"s": 3123,
"text": "Before Click the Button:"
},
{
"code": null,
"e": 3214,
"s": 3148,
"text": "After Click the Button: Hence query parameters passed can be seen"
},
{
"code": null,
"e": 3280,
"s": 3214,
"text": "After Click the Button: Hence query parameters passed can be seen"
},
{
"code": null,
"e": 3295,
"s": 3280,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3311,
"s": 3295,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3318,
"s": 3311,
"text": "Picked"
},
{
"code": null,
"e": 3328,
"s": 3318,
"text": "AngularJS"
},
{
"code": null,
"e": 3339,
"s": 3328,
"text": "JavaScript"
},
{
"code": null,
"e": 3356,
"s": 3339,
"text": "Web Technologies"
}
] |
ValueTuple in C# | 23 Jul, 2019
ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in .NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other. It can store elements starting from 0 to 8 and can store elements of different types. You can also store duplicate elements in value tuple.
We already have Tuples in C# which is used to store multiple values, but Tuples have some limitation, these limitations are fixed in ValueTuple. Or we can say that ValueTuple is an improved version of Tuples in C#. It overcomes the following limitations of Tuples:
Tuple is of reference type, but ValueTuple is of value type.
Tuple does not provide naming conventions, but ValueTuple provide strong naming conventions.
In Tuples you are not allowed to create a tuple with zero component, but in ValueTuple you are allowed to create a tuple with zero elements.
The performance of ValueTuple is better than Tuple. Because ValueTuple provides a lightweight mechanism for returning multiple values from the existing methods. And the syntax of ValueTuple is more optimized than Tuples.
ValueTuple provides more flexibility for accessing the elements of the value tuples by using deconstruction and the _ keyword. But Tuple cannot provide the concept of deconstruction and the _ keyword.
In ValueTuple the members such as item1 and item2 are fields. But in Tuple, they are properties.
In ValueTuple fields are mutable. But in Tuple, fields are read-only.
Unlike Tuple, ValueTuples provides an easy mechanism to create and initialize the ValueTuples. You can create ValueTuples by using the following 3 ways:
Using Constructor: You can create ValueTuple by using the constructor provided by the ValueTuple<T> Struct. Where you can store elements starting from one to eight with their type.Syntax:// Constructor for creating one element
ValueTuple<T1>(T1)
// Constructor for creating two elements
ValueTuple<T1, T2>(T1, T2)
.
.
.
// Constructor for creating eight elements
ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)
Example:// C# program to illustrate how to// create value tuple using the // ValueTuple constructor.using System; class GFG { // Main method static public void Main() { // ValueTuple with one element ValueTuple<int> ValTpl1 = new ValueTuple<int>(345678); // ValueTuple with three elements ValueTuple<string, string, int> ValTpl2 = new ValueTuple<string, string, int>("C#", "Java", 586); // ValueTuple with eight elements ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> > ValTpl3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> >(45, 67, 65, 34, 34, 34, 23, new ValueTuple<int>(90)); }}
Syntax:
// Constructor for creating one element
ValueTuple<T1>(T1)
// Constructor for creating two elements
ValueTuple<T1, T2>(T1, T2)
.
.
.
// Constructor for creating eight elements
ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)
Example:
// C# program to illustrate how to// create value tuple using the // ValueTuple constructor.using System; class GFG { // Main method static public void Main() { // ValueTuple with one element ValueTuple<int> ValTpl1 = new ValueTuple<int>(345678); // ValueTuple with three elements ValueTuple<string, string, int> ValTpl2 = new ValueTuple<string, string, int>("C#", "Java", 586); // ValueTuple with eight elements ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> > ValTpl3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> >(45, 67, 65, 34, 34, 34, 23, new ValueTuple<int>(90)); }}
Using Create Method: When we use the constructor of ValueTuple<T> struct to create a value tuple we need to provide the type of each element stored in the value tuple which makes your code cumbersome. So, C# provides another ValueTuple struct which contains the static methods for creating value tuple object without providing the type of each element.Syntax:// Method for creating an empty value tuple
Create();
// Method for creating 1-ValueTuple
Create<T1>(T1)
.
.
.
// Method for creating 8-ValueTuple
Create<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, T8)
Example:// C# program to create value tuple// using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 0-ValueTuple // Using Create() Method var Valtpl1 = ValueTuple.Create(); // Creating 3-ValueTuple // Using Create(T1, T2, T3) Method var Valtpl2 = ValueTuple.Create(12, 30, 40, 50); // Creating 8-ValueTuple // Using Create(T1, T2, T3, T4, T5, T6, T7, T8) Method var Valtpl3 = ValueTuple.Create(34, "GeeksforGeks", 'g', 'f', 'g', 56.78, 4323, "geeks"); }}
Syntax:
// Method for creating an empty value tuple
Create();
// Method for creating 1-ValueTuple
Create<T1>(T1)
.
.
.
// Method for creating 8-ValueTuple
Create<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, T8)
Example:
// C# program to create value tuple// using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 0-ValueTuple // Using Create() Method var Valtpl1 = ValueTuple.Create(); // Creating 3-ValueTuple // Using Create(T1, T2, T3) Method var Valtpl2 = ValueTuple.Create(12, 30, 40, 50); // Creating 8-ValueTuple // Using Create(T1, T2, T3, T4, T5, T6, T7, T8) Method var Valtpl3 = ValueTuple.Create(34, "GeeksforGeks", 'g', 'f', 'g', 56.78, 4323, "geeks"); }}
Using parenthesis(): It is the simplest form for creating ValueTuples using parenthesis() and the elements are placed in between them. And the elements are stored in 2 different ways:Named Member: ValueTuple allows you to create a tuple in which each component is allowed to have their own name. So that you can access that component with the help of their name. It makes your program more readable and easy to remember. You can assign the names to the members either left-hand side or right-hand, but not both sides. If you assigned names to both sides, then the left-hand side has precedence over the right-hand side As shown below:Example 1:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, "Sonia", "C#"); }}Example 2:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : "Sonia", Lang : "C#"); }}UnNamed Member: In ValueTuples, the unnamed members are those members which does not have names. They are simply created without any name. As shown below:Example 1:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, "Siya", "Ruby"); }}Example 2:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, "Siya", "Ruby"); }}
Named Member: ValueTuple allows you to create a tuple in which each component is allowed to have their own name. So that you can access that component with the help of their name. It makes your program more readable and easy to remember. You can assign the names to the members either left-hand side or right-hand, but not both sides. If you assigned names to both sides, then the left-hand side has precedence over the right-hand side As shown below:Example 1:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, "Sonia", "C#"); }}Example 2:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : "Sonia", Lang : "C#"); }}
Example 1:
// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, "Sonia", "C#"); }}
Example 2:
// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : "Sonia", Lang : "C#"); }}
UnNamed Member: In ValueTuples, the unnamed members are those members which does not have names. They are simply created without any name. As shown below:Example 1:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, "Siya", "Ruby"); }}Example 2:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, "Siya", "Ruby"); }}
Example 1:
// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, "Siya", "Ruby"); }}
Example 2:
// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, "Siya", "Ruby"); }}
Here we learn how to access named and unnamed members of the ValueTuples.
Accessing unnamed members: In ValueTuple, unnamed members are accessible by using the default item property names like Item1, Item2, Item3, etc. As shown in the below example:Example:// C# program to illustrate how to // access unnamed members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var author = (20, "Siya", "Ruby"); // Accessing the ValueTuple // Using default Item property Console.WriteLine("Age:" + author.Item1); Console.WriteLine("Name:" + author.Item2); Console.WriteLine("Language:" + author.Item3); }}
Example:
// C# program to illustrate how to // access unnamed members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var author = (20, "Siya", "Ruby"); // Accessing the ValueTuple // Using default Item property Console.WriteLine("Age:" + author.Item1); Console.WriteLine("Name:" + author.Item2); Console.WriteLine("Language:" + author.Item3); }}
Accessing Named members: In ValueTuples, the named members are used according to their name. There is no need to access these named members with default item property. As shown in the below example, the ValueTuple contains three elements, i.e, Book_id, Author_name, and Book_name. And we directly access these elements according to their names.Example:// C# program to illustrate how to access// named members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var library = (Book_id : 2340, Author_name : "Arundhati Roy", Book_name : "The God of Small Things"); // Accessing the ValueTuple // according to their names Console.WriteLine("Book Id: {0}", library.Book_id); Console.WriteLine("Author Name: {0}", library.Author_name); Console.WriteLine("Book Name: {0}", library.Book_name); }}Output:Book Id: 2340
Author Name: Arundhati Roy
Book Name: The God of Small Things
Example:
// C# program to illustrate how to access// named members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var library = (Book_id : 2340, Author_name : "Arundhati Roy", Book_name : "The God of Small Things"); // Accessing the ValueTuple // according to their names Console.WriteLine("Book Id: {0}", library.Book_id); Console.WriteLine("Author Name: {0}", library.Author_name); Console.WriteLine("Book Name: {0}", library.Book_name); }}
Output:
Book Id: 2340
Author Name: Arundhati Roy
Book Name: The God of Small Things
In C#, you are allowed to return a ValueTuple from a method. As shown in the below example, the TouristDetails method returns a ValueTuple with 3 elements:
Example:
// C# program to illustrate how a// method return ValueTupleusing System; public class GFG { // This method returns the tourist details static(int, string, string) TouristDetails() { return (384645, "Sophite", "USA"); } // Main method static public void Main() { // Store the data provided by the TouristDetails method var(Tourist_Id, Tourist_Name, Country) = TouristDetails(); // Display data Console.WriteLine("Tourist Details: "); Console.WriteLine($ "Tourist Id: {Tourist_Id}"); Console.WriteLine($ "Tourist Name: {Tourist_Name}"); Console.WriteLine($ "Country: {Country}"); }}
Output:
Tourist Details:
Tourist Id: 384645
Tourist Name: Sophite
Country: USA
CSharp-ValueTuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 454,
"s": 53,
"text": "ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in .NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other. It can store elements starting from 0 to 8 and can store elements of different types. You can also store duplicate elements in value tuple."
},
{
"code": null,
"e": 719,
"s": 454,
"text": "We already have Tuples in C# which is used to store multiple values, but Tuples have some limitation, these limitations are fixed in ValueTuple. Or we can say that ValueTuple is an improved version of Tuples in C#. It overcomes the following limitations of Tuples:"
},
{
"code": null,
"e": 780,
"s": 719,
"text": "Tuple is of reference type, but ValueTuple is of value type."
},
{
"code": null,
"e": 873,
"s": 780,
"text": "Tuple does not provide naming conventions, but ValueTuple provide strong naming conventions."
},
{
"code": null,
"e": 1014,
"s": 873,
"text": "In Tuples you are not allowed to create a tuple with zero component, but in ValueTuple you are allowed to create a tuple with zero elements."
},
{
"code": null,
"e": 1235,
"s": 1014,
"text": "The performance of ValueTuple is better than Tuple. Because ValueTuple provides a lightweight mechanism for returning multiple values from the existing methods. And the syntax of ValueTuple is more optimized than Tuples."
},
{
"code": null,
"e": 1436,
"s": 1235,
"text": "ValueTuple provides more flexibility for accessing the elements of the value tuples by using deconstruction and the _ keyword. But Tuple cannot provide the concept of deconstruction and the _ keyword."
},
{
"code": null,
"e": 1533,
"s": 1436,
"text": "In ValueTuple the members such as item1 and item2 are fields. But in Tuple, they are properties."
},
{
"code": null,
"e": 1603,
"s": 1533,
"text": "In ValueTuple fields are mutable. But in Tuple, fields are read-only."
},
{
"code": null,
"e": 1756,
"s": 1603,
"text": "Unlike Tuple, ValueTuples provides an easy mechanism to create and initialize the ValueTuples. You can create ValueTuples by using the following 3 ways:"
},
{
"code": null,
"e": 3028,
"s": 1756,
"text": "Using Constructor: You can create ValueTuple by using the constructor provided by the ValueTuple<T> Struct. Where you can store elements starting from one to eight with their type.Syntax:// Constructor for creating one element\nValueTuple<T1>(T1)\n\n// Constructor for creating two elements\nValueTuple<T1, T2>(T1, T2)\n.\n.\n.\n\n// Constructor for creating eight elements\nValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest) \nExample:// C# program to illustrate how to// create value tuple using the // ValueTuple constructor.using System; class GFG { // Main method static public void Main() { // ValueTuple with one element ValueTuple<int> ValTpl1 = new ValueTuple<int>(345678); // ValueTuple with three elements ValueTuple<string, string, int> ValTpl2 = new ValueTuple<string, string, int>(\"C#\", \"Java\", 586); // ValueTuple with eight elements ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> > ValTpl3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> >(45, 67, 65, 34, 34, 34, 23, new ValueTuple<int>(90)); }}"
},
{
"code": null,
"e": 3036,
"s": 3028,
"text": "Syntax:"
},
{
"code": null,
"e": 3300,
"s": 3036,
"text": "// Constructor for creating one element\nValueTuple<T1>(T1)\n\n// Constructor for creating two elements\nValueTuple<T1, T2>(T1, T2)\n.\n.\n.\n\n// Constructor for creating eight elements\nValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest) \n"
},
{
"code": null,
"e": 3309,
"s": 3300,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to// create value tuple using the // ValueTuple constructor.using System; class GFG { // Main method static public void Main() { // ValueTuple with one element ValueTuple<int> ValTpl1 = new ValueTuple<int>(345678); // ValueTuple with three elements ValueTuple<string, string, int> ValTpl2 = new ValueTuple<string, string, int>(\"C#\", \"Java\", 586); // ValueTuple with eight elements ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> > ValTpl3 = new ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> >(45, 67, 65, 34, 34, 34, 23, new ValueTuple<int>(90)); }}",
"e": 4123,
"s": 3309,
"text": null
},
{
"code": null,
"e": 5320,
"s": 4123,
"text": "Using Create Method: When we use the constructor of ValueTuple<T> struct to create a value tuple we need to provide the type of each element stored in the value tuple which makes your code cumbersome. So, C# provides another ValueTuple struct which contains the static methods for creating value tuple object without providing the type of each element.Syntax:// Method for creating an empty value tuple\nCreate();\n\n// Method for creating 1-ValueTuple\nCreate<T1>(T1)\n.\n.\n.\n\n// Method for creating 8-ValueTuple\nCreate<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, T8)\n\nExample:// C# program to create value tuple// using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 0-ValueTuple // Using Create() Method var Valtpl1 = ValueTuple.Create(); // Creating 3-ValueTuple // Using Create(T1, T2, T3) Method var Valtpl2 = ValueTuple.Create(12, 30, 40, 50); // Creating 8-ValueTuple // Using Create(T1, T2, T3, T4, T5, T6, T7, T8) Method var Valtpl3 = ValueTuple.Create(34, \"GeeksforGeks\", 'g', 'f', 'g', 56.78, 4323, \"geeks\"); }}"
},
{
"code": null,
"e": 5328,
"s": 5320,
"text": "Syntax:"
},
{
"code": null,
"e": 5553,
"s": 5328,
"text": "// Method for creating an empty value tuple\nCreate();\n\n// Method for creating 1-ValueTuple\nCreate<T1>(T1)\n.\n.\n.\n\n// Method for creating 8-ValueTuple\nCreate<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, T8)\n\n"
},
{
"code": null,
"e": 5562,
"s": 5553,
"text": "Example:"
},
{
"code": "// C# program to create value tuple// using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 0-ValueTuple // Using Create() Method var Valtpl1 = ValueTuple.Create(); // Creating 3-ValueTuple // Using Create(T1, T2, T3) Method var Valtpl2 = ValueTuple.Create(12, 30, 40, 50); // Creating 8-ValueTuple // Using Create(T1, T2, T3, T4, T5, T6, T7, T8) Method var Valtpl3 = ValueTuple.Create(34, \"GeeksforGeks\", 'g', 'f', 'g', 56.78, 4323, \"geeks\"); }}",
"e": 6168,
"s": 5562,
"text": null
},
{
"code": null,
"e": 7749,
"s": 6168,
"text": "Using parenthesis(): It is the simplest form for creating ValueTuples using parenthesis() and the elements are placed in between them. And the elements are stored in 2 different ways:Named Member: ValueTuple allows you to create a tuple in which each component is allowed to have their own name. So that you can access that component with the help of their name. It makes your program more readable and easy to remember. You can assign the names to the members either left-hand side or right-hand, but not both sides. If you assigned names to both sides, then the left-hand side has precedence over the right-hand side As shown below:Example 1:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, \"Sonia\", \"C#\"); }}Example 2:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : \"Sonia\", Lang : \"C#\"); }}UnNamed Member: In ValueTuples, the unnamed members are those members which does not have names. They are simply created without any name. As shown below:Example 1:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, \"Siya\", \"Ruby\"); }}Example 2:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, \"Siya\", \"Ruby\"); }}"
},
{
"code": null,
"e": 8629,
"s": 7749,
"text": "Named Member: ValueTuple allows you to create a tuple in which each component is allowed to have their own name. So that you can access that component with the help of their name. It makes your program more readable and easy to remember. You can assign the names to the members either left-hand side or right-hand, but not both sides. If you assigned names to both sides, then the left-hand side has precedence over the right-hand side As shown below:Example 1:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, \"Sonia\", \"C#\"); }}Example 2:// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : \"Sonia\", Lang : \"C#\"); }}"
},
{
"code": null,
"e": 8640,
"s": 8629,
"text": "Example 1:"
},
{
"code": "// C# program to illustrated named memberusing System; public class GFG { static public void Main() { (int age, string Aname, string Lang) author = (23, \"Sonia\", \"C#\"); }}",
"e": 8829,
"s": 8640,
"text": null
},
{
"code": null,
"e": 8840,
"s": 8829,
"text": "Example 2:"
},
{
"code": "// C# program to illustrated named memberusing System; public class GFG { static public void Main() { var author = (age : 23, Aname : \"Sonia\", Lang : \"C#\"); }}",
"e": 9061,
"s": 8840,
"text": null
},
{
"code": null,
"e": 9580,
"s": 9061,
"text": "UnNamed Member: In ValueTuples, the unnamed members are those members which does not have names. They are simply created without any name. As shown below:Example 1:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, \"Siya\", \"Ruby\"); }}Example 2:// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, \"Siya\", \"Ruby\"); }}"
},
{
"code": null,
"e": 9591,
"s": 9580,
"text": "Example 1:"
},
{
"code": "// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { var author = (20, \"Siya\", \"Ruby\"); }}",
"e": 9750,
"s": 9591,
"text": null
},
{
"code": null,
"e": 9761,
"s": 9750,
"text": "Example 2:"
},
{
"code": "// C# program to illustrated UnNamed memberusing System; public class GFG { static public void Main() { ValueTuple<int, string, string> author = (20, \"Siya\", \"Ruby\"); }}",
"e": 9948,
"s": 9761,
"text": null
},
{
"code": null,
"e": 10022,
"s": 9948,
"text": "Here we learn how to access named and unnamed members of the ValueTuples."
},
{
"code": null,
"e": 10686,
"s": 10022,
"text": "Accessing unnamed members: In ValueTuple, unnamed members are accessible by using the default item property names like Item1, Item2, Item3, etc. As shown in the below example:Example:// C# program to illustrate how to // access unnamed members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var author = (20, \"Siya\", \"Ruby\"); // Accessing the ValueTuple // Using default Item property Console.WriteLine(\"Age:\" + author.Item1); Console.WriteLine(\"Name:\" + author.Item2); Console.WriteLine(\"Language:\" + author.Item3); }}"
},
{
"code": null,
"e": 10695,
"s": 10686,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to // access unnamed members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var author = (20, \"Siya\", \"Ruby\"); // Accessing the ValueTuple // Using default Item property Console.WriteLine(\"Age:\" + author.Item1); Console.WriteLine(\"Name:\" + author.Item2); Console.WriteLine(\"Language:\" + author.Item3); }}",
"e": 11176,
"s": 10695,
"text": null
},
{
"code": null,
"e": 12233,
"s": 11176,
"text": "Accessing Named members: In ValueTuples, the named members are used according to their name. There is no need to access these named members with default item property. As shown in the below example, the ValueTuple contains three elements, i.e, Book_id, Author_name, and Book_name. And we directly access these elements according to their names.Example:// C# program to illustrate how to access// named members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var library = (Book_id : 2340, Author_name : \"Arundhati Roy\", Book_name : \"The God of Small Things\"); // Accessing the ValueTuple // according to their names Console.WriteLine(\"Book Id: {0}\", library.Book_id); Console.WriteLine(\"Author Name: {0}\", library.Author_name); Console.WriteLine(\"Book Name: {0}\", library.Book_name); }}Output:Book Id: 2340\nAuthor Name: Arundhati Roy\nBook Name: The God of Small Things\n"
},
{
"code": null,
"e": 12242,
"s": 12233,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to access// named members of ValueTupleusing System; public class GFG { // Main Method static public void Main() { // ValueTuple with three elements var library = (Book_id : 2340, Author_name : \"Arundhati Roy\", Book_name : \"The God of Small Things\"); // Accessing the ValueTuple // according to their names Console.WriteLine(\"Book Id: {0}\", library.Book_id); Console.WriteLine(\"Author Name: {0}\", library.Author_name); Console.WriteLine(\"Book Name: {0}\", library.Book_name); }}",
"e": 12864,
"s": 12242,
"text": null
},
{
"code": null,
"e": 12872,
"s": 12864,
"text": "Output:"
},
{
"code": null,
"e": 12949,
"s": 12872,
"text": "Book Id: 2340\nAuthor Name: Arundhati Roy\nBook Name: The God of Small Things\n"
},
{
"code": null,
"e": 13105,
"s": 12949,
"text": "In C#, you are allowed to return a ValueTuple from a method. As shown in the below example, the TouristDetails method returns a ValueTuple with 3 elements:"
},
{
"code": null,
"e": 13114,
"s": 13105,
"text": "Example:"
},
{
"code": "// C# program to illustrate how a// method return ValueTupleusing System; public class GFG { // This method returns the tourist details static(int, string, string) TouristDetails() { return (384645, \"Sophite\", \"USA\"); } // Main method static public void Main() { // Store the data provided by the TouristDetails method var(Tourist_Id, Tourist_Name, Country) = TouristDetails(); // Display data Console.WriteLine(\"Tourist Details: \"); Console.WriteLine($ \"Tourist Id: {Tourist_Id}\"); Console.WriteLine($ \"Tourist Name: {Tourist_Name}\"); Console.WriteLine($ \"Country: {Country}\"); }}",
"e": 13785,
"s": 13114,
"text": null
},
{
"code": null,
"e": 13793,
"s": 13785,
"text": "Output:"
},
{
"code": null,
"e": 13866,
"s": 13793,
"text": "Tourist Details: \nTourist Id: 384645\nTourist Name: Sophite\nCountry: USA\n"
},
{
"code": null,
"e": 13884,
"s": 13866,
"text": "CSharp-ValueTuple"
},
{
"code": null,
"e": 13887,
"s": 13884,
"text": "C#"
}
] |
How to Create Full Screen Window in Tkinter? | 13 Apr, 2022
Prerequisite: Tkinter
There are two ways to create a full screen window in tkinter using standard python library for creating GUI applications.
Syntax:
window_name.attributes('-fullscreen',True)
We will set the parameter ‘-fullscreen’ of attributes() to True for setting size of our window to fullscreen and to False otherwise.
Approach:
Importing tkinter package
Creating a tkinter window with name window
Setting the window attribute fullscreen as True
Giving title to the window, here ‘Geeks For Geeks’
Creating a label with text ‘Hello Tkinter’ (just for display to the user here)
Placing the label widget using pack()
Closing the endless loop of windows by calling mainloop()
Disadvantage:
We get an output tkinter WINDOW with no toolbar. This disadvantage is covered by the next method.
Program
Python3
# importing tkinter for guiimport tkinter as tk # creating windowwindow = tk.Tk() # setting attributewindow.attributes('-fullscreen', True)window.title("Geeks For Geeks") # creating text label to display on window screenlabel = tk.Label(window, text="Hello Tkinter!")label.pack() window.mainloop()
Output:
We get an output tkinter window with the toolbar above along with the title of window.
Syntax:
width= window_name.winfo_screenwidth()
height= window_name.winfo_screenheight()
window_name.geometry("%dx%d" % (width, height))
We can set the parameter of geometry() same as the width*height of the screen of our original window to get our full screen tkinter window without making the toolbar invisible. We can get the width and height of our desktop screen by using winfo_screenwidth() and winfo_screenheight() functions respectively.
Approach:
Importing tkinter package
Creating a tkinter window with name window
Getting width and height of the desktop screen using winfo_screenwidth() in variable width and winfo_screenheight() in variable height respectively.
Setting size of tkinter window using geometry () by setting dimensions equivalent to widthxheight.
Giving title to the window, here ‘Geeks For Geeks’
Creating a label with text ‘Hello Tkinter’ (just for display to the user here)
Placing the label widget using pack()
Closing the endless loop of windows by calling mainloop()
Program:
Python3
# importing tkinter guiimport tkinter as tk #creating windowwindow=tk.Tk() #getting screen width and height of displaywidth= window.winfo_screenwidth()height= window.winfo_screenheight()#setting tkinter window sizewindow.geometry("%dx%d" % (width, height))window.title("Geeeks For Geeks")label = tk.Label(window, text="Hello Tkinter!")label.pack() window.mainloop()
Output:
Syntax:
window_name.state('zoomed')
We will set the parameter of state() to ‘zoomed’ for setting the size of our window to fullscreen by maximizing the window.
Approach:
Importing tkinter package
Creating a tkinter window with name window
Setting the window attribute state as ‘zoomed’
Giving a title to the window, here ‘Geeks For Geeks’
Creating a label with text ‘Hello Tkinter’ (just for display to the user here)
Placing the label widget using pack()
Closing the endless loop of windows by calling mainloop()
Result:
We get an output tkinter WINDOW which is already maximized.
Program
Python3
# importing tkinter for guiimport tkinter as tk # creating windowwindow = tk.Tk() # setting attributewindow.state('zoomed')window.title("Geeks For Geeks") # creating text label to display on window screenlabel = tk.Label(window, text="Hello Tkinter!")label.pack() window.mainloop()
Output:
Output using window_name.state(‘zoomed’)
menonkartikeya
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 75,
"s": 53,
"text": "Prerequisite: Tkinter"
},
{
"code": null,
"e": 197,
"s": 75,
"text": "There are two ways to create a full screen window in tkinter using standard python library for creating GUI applications."
},
{
"code": null,
"e": 205,
"s": 197,
"text": "Syntax:"
},
{
"code": null,
"e": 248,
"s": 205,
"text": "window_name.attributes('-fullscreen',True)"
},
{
"code": null,
"e": 382,
"s": 248,
"text": "We will set the parameter ‘-fullscreen’ of attributes() to True for setting size of our window to fullscreen and to False otherwise. "
},
{
"code": null,
"e": 392,
"s": 382,
"text": "Approach:"
},
{
"code": null,
"e": 418,
"s": 392,
"text": "Importing tkinter package"
},
{
"code": null,
"e": 461,
"s": 418,
"text": "Creating a tkinter window with name window"
},
{
"code": null,
"e": 509,
"s": 461,
"text": "Setting the window attribute fullscreen as True"
},
{
"code": null,
"e": 560,
"s": 509,
"text": "Giving title to the window, here ‘Geeks For Geeks’"
},
{
"code": null,
"e": 639,
"s": 560,
"text": "Creating a label with text ‘Hello Tkinter’ (just for display to the user here)"
},
{
"code": null,
"e": 677,
"s": 639,
"text": "Placing the label widget using pack()"
},
{
"code": null,
"e": 735,
"s": 677,
"text": "Closing the endless loop of windows by calling mainloop()"
},
{
"code": null,
"e": 749,
"s": 735,
"text": "Disadvantage:"
},
{
"code": null,
"e": 847,
"s": 749,
"text": "We get an output tkinter WINDOW with no toolbar. This disadvantage is covered by the next method."
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Program"
},
{
"code": null,
"e": 863,
"s": 855,
"text": "Python3"
},
{
"code": "# importing tkinter for guiimport tkinter as tk # creating windowwindow = tk.Tk() # setting attributewindow.attributes('-fullscreen', True)window.title(\"Geeks For Geeks\") # creating text label to display on window screenlabel = tk.Label(window, text=\"Hello Tkinter!\")label.pack() window.mainloop()",
"e": 1161,
"s": 863,
"text": null
},
{
"code": null,
"e": 1169,
"s": 1161,
"text": "Output:"
},
{
"code": null,
"e": 1257,
"s": 1169,
"text": "We get an output tkinter window with the toolbar above along with the title of window. "
},
{
"code": null,
"e": 1267,
"s": 1257,
"text": "Syntax: "
},
{
"code": null,
"e": 1440,
"s": 1267,
"text": " width= window_name.winfo_screenwidth() \n height= window_name.winfo_screenheight() \n window_name.geometry(\"%dx%d\" % (width, height))"
},
{
"code": null,
"e": 1750,
"s": 1440,
"text": "We can set the parameter of geometry() same as the width*height of the screen of our original window to get our full screen tkinter window without making the toolbar invisible. We can get the width and height of our desktop screen by using winfo_screenwidth() and winfo_screenheight() functions respectively. "
},
{
"code": null,
"e": 1760,
"s": 1750,
"text": "Approach:"
},
{
"code": null,
"e": 1786,
"s": 1760,
"text": "Importing tkinter package"
},
{
"code": null,
"e": 1829,
"s": 1786,
"text": "Creating a tkinter window with name window"
},
{
"code": null,
"e": 1978,
"s": 1829,
"text": "Getting width and height of the desktop screen using winfo_screenwidth() in variable width and winfo_screenheight() in variable height respectively."
},
{
"code": null,
"e": 2077,
"s": 1978,
"text": "Setting size of tkinter window using geometry () by setting dimensions equivalent to widthxheight."
},
{
"code": null,
"e": 2128,
"s": 2077,
"text": "Giving title to the window, here ‘Geeks For Geeks’"
},
{
"code": null,
"e": 2207,
"s": 2128,
"text": "Creating a label with text ‘Hello Tkinter’ (just for display to the user here)"
},
{
"code": null,
"e": 2245,
"s": 2207,
"text": "Placing the label widget using pack()"
},
{
"code": null,
"e": 2303,
"s": 2245,
"text": "Closing the endless loop of windows by calling mainloop()"
},
{
"code": null,
"e": 2312,
"s": 2303,
"text": "Program:"
},
{
"code": null,
"e": 2320,
"s": 2312,
"text": "Python3"
},
{
"code": "# importing tkinter guiimport tkinter as tk #creating windowwindow=tk.Tk() #getting screen width and height of displaywidth= window.winfo_screenwidth()height= window.winfo_screenheight()#setting tkinter window sizewindow.geometry(\"%dx%d\" % (width, height))window.title(\"Geeeks For Geeks\")label = tk.Label(window, text=\"Hello Tkinter!\")label.pack() window.mainloop()",
"e": 2686,
"s": 2320,
"text": null
},
{
"code": null,
"e": 2694,
"s": 2686,
"text": "Output:"
},
{
"code": null,
"e": 2702,
"s": 2694,
"text": "Syntax:"
},
{
"code": null,
"e": 2731,
"s": 2702,
"text": "window_name.state('zoomed') "
},
{
"code": null,
"e": 2855,
"s": 2731,
"text": "We will set the parameter of state() to ‘zoomed’ for setting the size of our window to fullscreen by maximizing the window."
},
{
"code": null,
"e": 2865,
"s": 2855,
"text": "Approach:"
},
{
"code": null,
"e": 2891,
"s": 2865,
"text": "Importing tkinter package"
},
{
"code": null,
"e": 2934,
"s": 2891,
"text": "Creating a tkinter window with name window"
},
{
"code": null,
"e": 2981,
"s": 2934,
"text": "Setting the window attribute state as ‘zoomed’"
},
{
"code": null,
"e": 3034,
"s": 2981,
"text": "Giving a title to the window, here ‘Geeks For Geeks’"
},
{
"code": null,
"e": 3113,
"s": 3034,
"text": "Creating a label with text ‘Hello Tkinter’ (just for display to the user here)"
},
{
"code": null,
"e": 3151,
"s": 3113,
"text": "Placing the label widget using pack()"
},
{
"code": null,
"e": 3209,
"s": 3151,
"text": "Closing the endless loop of windows by calling mainloop()"
},
{
"code": null,
"e": 3217,
"s": 3209,
"text": "Result:"
},
{
"code": null,
"e": 3278,
"s": 3217,
"text": "We get an output tkinter WINDOW which is already maximized. "
},
{
"code": null,
"e": 3286,
"s": 3278,
"text": "Program"
},
{
"code": null,
"e": 3294,
"s": 3286,
"text": "Python3"
},
{
"code": "# importing tkinter for guiimport tkinter as tk # creating windowwindow = tk.Tk() # setting attributewindow.state('zoomed')window.title(\"Geeks For Geeks\") # creating text label to display on window screenlabel = tk.Label(window, text=\"Hello Tkinter!\")label.pack() window.mainloop()",
"e": 3576,
"s": 3294,
"text": null
},
{
"code": null,
"e": 3584,
"s": 3576,
"text": "Output:"
},
{
"code": null,
"e": 3626,
"s": 3584,
"text": "Output using window_name.state(‘zoomed’) "
},
{
"code": null,
"e": 3641,
"s": 3626,
"text": "menonkartikeya"
},
{
"code": null,
"e": 3656,
"s": 3641,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3663,
"s": 3656,
"text": "Python"
}
] |
Find all the prime numbers of given number of digits | 07 Mar, 2022
Given an integer D, the task is to find all the prime numbers having D digits.
Examples: Input: D = 1 Output: 2 3 5 7 Input: D = 2 Output: 11 13 17 19 23 29 31 37 41 43 47 53 61 67 71 73 79 83 89 97
Approach: Numbers with D digits lie in the range [10(D – 1), 10D – 1]. So, check all the numbers in this interval and to check the number is prime or not, use Sieve of Eratosthenes to generate all the primes.Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int sz = 1e5;bool isPrime[sz + 1]; // Function for Sieve of Eratosthenesvoid sieve(){ memset(isPrime, true, sizeof(isPrime)); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsvoid findPrimesD(int d){ // Range to check integers int left = pow(10, d - 1); int right = pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { cout << i << " "; } }} // Driver codeint main(){ // Generate primes sieve(); int d = 1; findPrimesD(d); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{static int sz = 100000;static boolean isPrime[] = new boolean[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsstatic void findPrimesD(int d){ // Range to check integers int left = (int)Math.pow(10, d - 1); int right = (int)Math.pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { System.out.print(i + " "); } }} // Driver codepublic static void main(String args[]){ // Generate primes sieve(); int d = 1; findPrimesD(d);}} // This code is contributed by Arnab Kundu
# Python 3 implementation of the approachfrom math import sqrt, powsz = 100005isPrime = [True for i in range(sz + 1)] # Function for Sieve of Eratosthenesdef sieve(): isPrime[0] = isPrime[1] = False for i in range(2, int(sqrt(sz)) + 1, 1): if (isPrime[i]): for j in range(i * i, sz, i): isPrime[j] = False # Function to print all the prime# numbers with d digitsdef findPrimesD(d): # Range to check integers left = int(pow(10, d - 1)) right = int(pow(10, d) - 1) # For every integer in the range for i in range(left, right + 1, 1): # If the current integer is prime if (isPrime[i]): print(i, end = " ") # Driver codeif __name__ == '__main__': # Generate primes sieve() d = 1 findPrimesD(d) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ static int sz = 100000;static bool []isPrime = new bool[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsstatic void findPrimesD(int d){ // Range to check integers int left = (int)Math.Pow(10, d - 1); int right = (int)Math.Pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { Console.Write(i + " "); } }} // Driver codestatic public void Main (){ // Generate primes sieve(); int d = 1; findPrimesD(d); }} // This code is contributed by ajit.
<script> // Javascript implementation of the approach let sz = 100000; let isPrime = new Array(sz + 1); isPrime.fill(false); // Function for Sieve of Eratosthenes function sieve() { for(let i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (let i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (let j = i * i; j < sz; j += i) { isPrime[j] = false; } } } } // Function to print all the prime // numbers with d digits function findPrimesD(d) { // Range to check integers let left = Math.pow(10, d - 1); let right = Math.pow(10, d) - 1; // For every integer in the range for (let i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { document.write(i + " "); } } } // Generate primes sieve(); let d = 1; findPrimesD(d); // This code is contributed by suresh07.</script>
2 3 5 7
Time Complexity: O(sqrt(105) + d)
Auxiliary Space: O(105)
andrew1234
SURENDRA_GANGWAR
jit_t
suresh07
subham348
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Find minimum number of coins that make a given value
Modulo 10^9+7 (1000000007)
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "Given an integer D, the task is to find all the prime numbers having D digits. "
},
{
"code": null,
"e": 230,
"s": 108,
"text": "Examples: Input: D = 1 Output: 2 3 5 7 Input: D = 2 Output: 11 13 17 19 23 29 31 37 41 43 47 53 61 67 71 73 79 83 89 97 "
},
{
"code": null,
"e": 493,
"s": 232,
"text": "Approach: Numbers with D digits lie in the range [10(D – 1), 10D – 1]. So, check all the numbers in this interval and to check the number is prime or not, use Sieve of Eratosthenes to generate all the primes.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 497,
"s": 493,
"text": "C++"
},
{
"code": null,
"e": 502,
"s": 497,
"text": "Java"
},
{
"code": null,
"e": 511,
"s": 502,
"text": "Python 3"
},
{
"code": null,
"e": 514,
"s": 511,
"text": "C#"
},
{
"code": null,
"e": 525,
"s": 514,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int sz = 1e5;bool isPrime[sz + 1]; // Function for Sieve of Eratosthenesvoid sieve(){ memset(isPrime, true, sizeof(isPrime)); isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsvoid findPrimesD(int d){ // Range to check integers int left = pow(10, d - 1); int right = pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { cout << i << \" \"; } }} // Driver codeint main(){ // Generate primes sieve(); int d = 1; findPrimesD(d); return 0;}",
"e": 1431,
"s": 525,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{static int sz = 100000;static boolean isPrime[] = new boolean[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsstatic void findPrimesD(int d){ // Range to check integers int left = (int)Math.pow(10, d - 1); int right = (int)Math.pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { System.out.print(i + \" \"); } }} // Driver codepublic static void main(String args[]){ // Generate primes sieve(); int d = 1; findPrimesD(d);}} // This code is contributed by Arnab Kundu",
"e": 2500,
"s": 1431,
"text": null
},
{
"code": "# Python 3 implementation of the approachfrom math import sqrt, powsz = 100005isPrime = [True for i in range(sz + 1)] # Function for Sieve of Eratosthenesdef sieve(): isPrime[0] = isPrime[1] = False for i in range(2, int(sqrt(sz)) + 1, 1): if (isPrime[i]): for j in range(i * i, sz, i): isPrime[j] = False # Function to print all the prime# numbers with d digitsdef findPrimesD(d): # Range to check integers left = int(pow(10, d - 1)) right = int(pow(10, d) - 1) # For every integer in the range for i in range(left, right + 1, 1): # If the current integer is prime if (isPrime[i]): print(i, end = \" \") # Driver codeif __name__ == '__main__': # Generate primes sieve() d = 1 findPrimesD(d) # This code is contributed by Surendra_Gangwar",
"e": 3361,
"s": 2500,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int sz = 100000;static bool []isPrime = new bool[sz + 1]; // Function for Sieve of Eratosthenesstatic void sieve(){ for(int i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (int i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (int j = i * i; j < sz; j += i) { isPrime[j] = false; } } }} // Function to print all the prime// numbers with d digitsstatic void findPrimesD(int d){ // Range to check integers int left = (int)Math.Pow(10, d - 1); int right = (int)Math.Pow(10, d) - 1; // For every integer in the range for (int i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { Console.Write(i + \" \"); } }} // Driver codestatic public void Main (){ // Generate primes sieve(); int d = 1; findPrimesD(d); }} // This code is contributed by ajit.",
"e": 4405,
"s": 3361,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let sz = 100000; let isPrime = new Array(sz + 1); isPrime.fill(false); // Function for Sieve of Eratosthenes function sieve() { for(let i = 0; i <= sz; i++) isPrime[i] = true; isPrime[0] = isPrime[1] = false; for (let i = 2; i * i <= sz; i++) { if (isPrime[i]) { for (let j = i * i; j < sz; j += i) { isPrime[j] = false; } } } } // Function to print all the prime // numbers with d digits function findPrimesD(d) { // Range to check integers let left = Math.pow(10, d - 1); let right = Math.pow(10, d) - 1; // For every integer in the range for (let i = left; i <= right; i++) { // If the current integer is prime if (isPrime[i]) { document.write(i + \" \"); } } } // Generate primes sieve(); let d = 1; findPrimesD(d); // This code is contributed by suresh07.</script>",
"e": 5546,
"s": 4405,
"text": null
},
{
"code": null,
"e": 5554,
"s": 5546,
"text": "2 3 5 7"
},
{
"code": null,
"e": 5590,
"s": 5556,
"text": "Time Complexity: O(sqrt(105) + d)"
},
{
"code": null,
"e": 5614,
"s": 5590,
"text": "Auxiliary Space: O(105)"
},
{
"code": null,
"e": 5625,
"s": 5614,
"text": "andrew1234"
},
{
"code": null,
"e": 5642,
"s": 5625,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5648,
"s": 5642,
"text": "jit_t"
},
{
"code": null,
"e": 5657,
"s": 5648,
"text": "suresh07"
},
{
"code": null,
"e": 5667,
"s": 5657,
"text": "subham348"
},
{
"code": null,
"e": 5680,
"s": 5667,
"text": "Prime Number"
},
{
"code": null,
"e": 5693,
"s": 5680,
"text": "Mathematical"
},
{
"code": null,
"e": 5706,
"s": 5693,
"text": "Mathematical"
},
{
"code": null,
"e": 5719,
"s": 5706,
"text": "Prime Number"
},
{
"code": null,
"e": 5817,
"s": 5719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5841,
"s": 5817,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5862,
"s": 5841,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5915,
"s": 5862,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 5942,
"s": 5915,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 5979,
"s": 5942,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 6011,
"s": 5979,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 6054,
"s": 6011,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 6095,
"s": 6054,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 6138,
"s": 6095,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
Splay Tree | Set 1 (Search) | 15 May, 2022
The worst case time complexity of Binary Search Tree (BST) operations like search, delete, insert is O(n). The worst case occurs when the tree is skewed. We can get the worst case time complexity as O(Logn) with AVL and Red-Black Trees. Can we do better than AVL or Red-Black trees in practical situations? Like AVL and Red-Black Trees, Splay tree is also self-balancing BST. The main idea of splay tree is to bring the recently accessed item to root of the tree, this makes the recently searched item to be accessible in O(1) time if accessed again. The idea is to use locality of reference (In a typical application, 80% of the access are to 20% of the items). Imagine a situation where we have millions or billions of keys and only few of them are accessed frequently, which is very likely in many practical applications.All splay tree operations run in O(log n) time on average, where n is the number of entries in the tree. Any single operation can take Theta(n) time in the worst case.Search Operation The search operation in Splay tree does the standard BST search, in addition to search, it also splays (move a node to the root). If the search is successful, then the node that is found is splayed and becomes the new root. Else the last node accessed prior to reaching the NULL is splayed and becomes the new root.There are following cases for the node being accessed.1) Node is root We simply return the root, don’t do anything else as the accessed node is already root.2) Zig: Node is child of root (the node has no grandparent). Node is either a left child of root (we do a right rotation) or node is a right child of its parent (we do a left rotation). T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side)
y x
/ \ Zig (Right Rotation) / \
x T3 – - – - – - – - - -> T1 y
/ \ < - - - - - - - - - / \
T1 T2 Zag (Left Rotation) T2 T3
3) Node has both parent and grandparent. There can be following subcases. ........3.a) Zig-Zig and Zag-Zag Node is left child of parent and parent is also left child of grand parent (Two right rotations) OR node is right child of its parent and parent is also right child of grand parent (Two Left Rotations).
Zig-Zig (Left Left Case):
G P X
/ \ / \ / \
P T4 rightRotate(G) X G rightRotate(P) T1 P
/ \ ============> / \ / \ ============> / \
X T3 T1 T2 T3 T4 T2 G
/ \ / \
T1 T2 T3 T4
Zag-Zag (Right Right Case):
G P X
/ \ / \ / \
T1 P leftRotate(G) G X leftRotate(P) P T4
/ \ ============> / \ / \ ============> / \
T2 X T1 T2 T3 T4 G T3
/ \ / \
T3 T4 T1 T2
........3.b) Zig-Zag and Zag-Zig Node is right child of parent and parent is left child of grand parent (Left Rotation followed by right rotation) OR node is left child of its parent and parent is right child of grand parent (Right Rotation followed by left rotation).
Zag-Zig (Left Right Case):
G G X
/ \ / \ / \
P T4 leftRotate(P) X T4 rightRotate(G) P G
/ \ ============> / \ ============> / \ / \
T1 X P T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
Zig-Zag (Right Left Case):
G G X
/ \ / \ / \
T1 P rightRotate(P) T1 X leftRotate(G) G P
/ \ =============> / \ ============> / \ / \
X T4 T2 P T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
Example:
100 100 [20]
/ \ / \ \
50 200 50 200 50
/ search(20) / search(20) / \
40 ======> [20] ========> 30 100
/ 1. Zig-Zig \ 2. Zig-Zig \ \
30 at 40 30 at 100 40 200
/ \
[20] 40
The important thing to note is, the search or splay operation not only brings the searched key to root, but also balances the BST. For example in above case, height of BST is reduced by 1.Implementation:
C++
C
Java
C#
Javascript
#include <bits/stdc++.h>using namespace std; // An AVL tree nodeclass node{ public: int key; node *left, *right;}; /* Helper function that allocatesa new node with the given key and NULL left and right pointers. */node* newNode(int key){ node* Node = new node(); Node->key = key; Node->left = Node->right = NULL; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.node *rightRotate(node *x){ node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.node *leftRotate(node *x){ node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootnode *splay(node *root, int key){ // Base cases: root is NULL or // key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the // key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zag-Zig (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.node *search(node *root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(node *root){ if (root != NULL) { cout<<root->key<<" "; preOrder(root->left); preOrder(root->right); }} /* Driver code*/int main(){ node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = search(root, 20); cout << "Preorder traversal of the modified Splay tree is \n"; preOrder(root); return 0;} // This code is contributed by rathbhupendra
// The code is adopted from http://goo.gl/SDH9hH#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct node{ int key; struct node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = node->right = NULL; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node *rightRotate(struct node *x){ struct node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node *leftRotate(struct node *x){ struct node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at root if key is present in tree.// If key is not present, then it brings the last accessed item at// root. This function modifies the tree and returns the new rootstruct node *splay(struct node *root, int key){ // Base cases: root is NULL or key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zag-Zig (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // The search function for Splay tree. Note that this function// returns the new root of Splay Tree. If key is present in tree// then, it is moved to root.struct node *search(struct node *root, int key){ return splay(root, key);} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node *root){ if (root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = search(root, 20); printf("Preorder traversal of the modified Splay tree is \n"); preOrder(root); return 0;}
// Java implementation for above approachclass GFG{ // An AVL tree nodestatic class node{ int key; node left, right;}; /* Helper function that allocatesa new node with the given key and null left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.static node search(node root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { System.out.print(root.key + " "); preOrder(root.left); preOrder(root.right); }} // Driver codepublic static void main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = search(root, 20); System.out.print("Preorder traversal of the" + " modified Splay tree is \n"); preOrder(root);}} // This code is contributed by 29AjayKumar
// C# implementation for above approachusing System; class GFG{ // An AVL tree nodepublic class node{ public int key; public node left, right;}; /* Helper function that allocatesa new node with the given key andnull left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.static node search(node root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { Console.Write(root.key + " "); preOrder(root.left); preOrder(root.right); }} // Driver codepublic static void Main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = search(root, 20); Console.Write("Preorder traversal of the" + " modified Splay tree is \n"); preOrder(root);}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation for above approach // An AVL tree nodeclass Node{ /* Helper function that allocatesa new node with the given key and null left and right pointers. */ constructor(key) { this.key = key; this.left = this.right = null; }} // A utility function to right// rotate subtree rooted with y// See the diagram given above.function rightRotate(x){ let y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.function leftRotate(x){ let y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootfunction splay(root,key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.function search(root,key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodefunction preOrder(root){ if (root != null) { document.write(root.key + " "); preOrder(root.left); preOrder(root.right); }} // Driver codelet root = new Node(100); root.left = new Node(50); root.right = new Node(200); root.left.left = new Node(40); root.left.left.left = new Node(30); root.left.left.left.left = new Node(20); root = search(root, 20); document.write("Preorder traversal of the" + " modified Splay tree is <br>"); preOrder(root); // This code is contributed by rag2127</script>
Output:
Preorder traversal of the modified Splay tree is
20 50 30 40 100 200
Summary 1) Splay trees have excellent locality properties. Frequently accessed items are easy to find. Infrequent items are out of way.2) All splay tree operations take O(Logn) time on average. Splay trees can be rigorously shown to run in O(log n) average time per operation, over any sequence of operations (assuming we start from an empty tree)3) Splay trees are simpler compared to AVL and Red-Black Trees as no extra field is required in every tree node.4) Unlike AVL tree, a splay tree can change even with read-only operations like search.Applications of Splay Trees Splay trees have become the most widely used basic data structure invented in the last 30 years, because they’re the fastest type of balanced search tree for many applications. Splay trees are used in Windows NT (in the virtual memory, networking, and file system code), the gcc compiler and GNU C++ library, the sed string editor, For Systems network routers, the most popular implementation of Unix malloc, Linux loadable kernel modules, and in much other software (Source: http://www.cs.berkeley.edu/~jrs/61b/lec/36)See Splay Tree | Set 2 (Insert) for splay tree insertion.
Advantages of Splay Trees:
Useful for implementing caches and garbage collection algorithms.
Require less space as there is no balance information is required.
Splay trees provide good performance with nodes containing identical keys.
Disadvantages of Splay Trees:
The height of a splay tree can be linear when accessing elements in non decreasing order.
The performance of a splay tree will be worse than a balanced simple binary search tree in case of uniform access.
References: http://www.cs.berkeley.edu/~jrs/61b/lec/36 http://www.cs.cornell.edu/courses/cs3110/2009fa/recitations/rec-splay.html http://courses.cs.washington.edu/courses/cse326/01au/lectures/SplayTrees.pptPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Ujjwal Mishra
rathbhupendra
nidhi_biet
29AjayKumar
rag2127
tcostell
sagar0719kumar
guptavivek0503
adhamasharkawy
Self-Balancing-BST
splay-tree
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Introduction of B-Tree
Agents in Artificial Intelligence
Red-Black Tree | Set 1 (Introduction)
Decision Tree Introduction with example
Binary Indexed Tree or Fenwick Tree
AVL Tree | Set 2 (Deletion)
Disjoint Set Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 May, 2022"
},
{
"code": null,
"e": 1811,
"s": 54,
"text": "The worst case time complexity of Binary Search Tree (BST) operations like search, delete, insert is O(n). The worst case occurs when the tree is skewed. We can get the worst case time complexity as O(Logn) with AVL and Red-Black Trees. Can we do better than AVL or Red-Black trees in practical situations? Like AVL and Red-Black Trees, Splay tree is also self-balancing BST. The main idea of splay tree is to bring the recently accessed item to root of the tree, this makes the recently searched item to be accessible in O(1) time if accessed again. The idea is to use locality of reference (In a typical application, 80% of the access are to 20% of the items). Imagine a situation where we have millions or billions of keys and only few of them are accessed frequently, which is very likely in many practical applications.All splay tree operations run in O(log n) time on average, where n is the number of entries in the tree. Any single operation can take Theta(n) time in the worst case.Search Operation The search operation in Splay tree does the standard BST search, in addition to search, it also splays (move a node to the root). If the search is successful, then the node that is found is splayed and becomes the new root. Else the last node accessed prior to reaching the NULL is splayed and becomes the new root.There are following cases for the node being accessed.1) Node is root We simply return the root, don’t do anything else as the accessed node is already root.2) Zig: Node is child of root (the node has no grandparent). Node is either a left child of root (we do a right rotation) or node is a right child of its parent (we do a left rotation). T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side) "
},
{
"code": null,
"e": 2107,
"s": 1811,
"text": " y x\n / \\ Zig (Right Rotation) / \\\n x T3 – - – - – - – - - -> T1 y \n / \\ < - - - - - - - - - / \\\n T1 T2 Zag (Left Rotation) T2 T3"
},
{
"code": null,
"e": 2419,
"s": 2107,
"text": "3) Node has both parent and grandparent. There can be following subcases. ........3.a) Zig-Zig and Zag-Zag Node is left child of parent and parent is also left child of grand parent (Two right rotations) OR node is right child of its parent and parent is also right child of grand parent (Two Left Rotations). "
},
{
"code": null,
"e": 3384,
"s": 2419,
"text": "Zig-Zig (Left Left Case):\n G P X \n / \\ / \\ / \\ \n P T4 rightRotate(G) X G rightRotate(P) T1 P \n / \\ ============> / \\ / \\ ============> / \\ \n X T3 T1 T2 T3 T4 T2 G\n / \\ / \\ \n T1 T2 T3 T4 \n\nZag-Zag (Right Right Case):\n G P X \n / \\ / \\ / \\ \nT1 P leftRotate(G) G X leftRotate(P) P T4\n / \\ ============> / \\ / \\ ============> / \\ \n T2 X T1 T2 T3 T4 G T3\n / \\ / \\ \n T3 T4 T1 T2"
},
{
"code": null,
"e": 3655,
"s": 3384,
"text": "........3.b) Zig-Zag and Zag-Zig Node is right child of parent and parent is left child of grand parent (Left Rotation followed by right rotation) OR node is left child of its parent and parent is right child of grand parent (Right Rotation followed by left rotation). "
},
{
"code": null,
"e": 4620,
"s": 3655,
"text": "Zag-Zig (Left Right Case):\n G G X \n / \\ / \\ / \\ \n P T4 leftRotate(P) X T4 rightRotate(G) P G \n / \\ ============> / \\ ============> / \\ / \\ \n T1 X P T3 T1 T2 T3 T4 \n / \\ / \\ \n T2 T3 T1 T2 \n\nZig-Zag (Right Left Case):\n G G X \n / \\ / \\ / \\ \nT1 P rightRotate(P) T1 X leftRotate(G) G P\n / \\ =============> / \\ ============> / \\ / \\ \n X T4 T2 P T1 T2 T3 T4\n / \\ / \\ \n T2 T3 T3 T4 "
},
{
"code": null,
"e": 4631,
"s": 4620,
"text": "Example: "
},
{
"code": null,
"e": 5185,
"s": 4631,
"text": " \n 100 100 [20]\n / \\ / \\ \\ \n 50 200 50 200 50\n / search(20) / search(20) / \\ \n 40 ======> [20] ========> 30 100\n / 1. Zig-Zig \\ 2. Zig-Zig \\ \\\n 30 at 40 30 at 100 40 200 \n / \\ \n[20] 40"
},
{
"code": null,
"e": 5391,
"s": 5185,
"text": "The important thing to note is, the search or splay operation not only brings the searched key to root, but also balances the BST. For example in above case, height of BST is reduced by 1.Implementation: "
},
{
"code": null,
"e": 5395,
"s": 5391,
"text": "C++"
},
{
"code": null,
"e": 5397,
"s": 5395,
"text": "C"
},
{
"code": null,
"e": 5402,
"s": 5397,
"text": "Java"
},
{
"code": null,
"e": 5405,
"s": 5402,
"text": "C#"
},
{
"code": null,
"e": 5416,
"s": 5405,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // An AVL tree nodeclass node{ public: int key; node *left, *right;}; /* Helper function that allocatesa new node with the given key and NULL left and right pointers. */node* newNode(int key){ node* Node = new node(); Node->key = key; Node->left = Node->right = NULL; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.node *rightRotate(node *x){ node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.node *leftRotate(node *x){ node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootnode *splay(node *root, int key){ // Base cases: root is NULL or // key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the // key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zag-Zig (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.node *search(node *root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(node *root){ if (root != NULL) { cout<<root->key<<\" \"; preOrder(root->left); preOrder(root->right); }} /* Driver code*/int main(){ node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = search(root, 20); cout << \"Preorder traversal of the modified Splay tree is \\n\"; preOrder(root); return 0;} // This code is contributed by rathbhupendra",
"e": 9233,
"s": 5416,
"text": null
},
{
"code": "// The code is adopted from http://goo.gl/SDH9hH#include<stdio.h>#include<stdlib.h> // An AVL tree nodestruct node{ int key; struct node *left, *right;}; /* Helper function that allocates a new node with the given key and NULL left and right pointers. */struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = node->right = NULL; return (node);} // A utility function to right rotate subtree rooted with y// See the diagram given above.struct node *rightRotate(struct node *x){ struct node *y = x->left; x->left = y->right; y->right = x; return y;} // A utility function to left rotate subtree rooted with x// See the diagram given above.struct node *leftRotate(struct node *x){ struct node *y = x->right; x->right = y->left; y->left = x; return y;} // This function brings the key at root if key is present in tree.// If key is not present, then it brings the last accessed item at// root. This function modifies the tree and returns the new rootstruct node *splay(struct node *root, int key){ // Base cases: root is NULL or key is present at root if (root == NULL || root->key == key) return root; // Key lies in left subtree if (root->key > key) { // Key is not in tree, we are done if (root->left == NULL) return root; // Zig-Zig (Left Left) if (root->left->key > key) { // First recursively bring the key as root of left-left root->left->left = splay(root->left->left, key); // Do first rotation for root, second rotation is done after else root = rightRotate(root); } else if (root->left->key < key) // Zig-Zag (Left Right) { // First recursively bring the key as root of left-right root->left->right = splay(root->left->right, key); // Do first rotation for root->left if (root->left->right != NULL) root->left = leftRotate(root->left); } // Do second rotation for root return (root->left == NULL)? root: rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root->right == NULL) return root; // Zag-Zig (Right Left) if (root->right->key > key) { // Bring the key as root of right-left root->right->left = splay(root->right->left, key); // Do first rotation for root->right if (root->right->left != NULL) root->right = rightRotate(root->right); } else if (root->right->key < key)// Zag-Zag (Right Right) { // Bring the key as root of right-right and do first rotation root->right->right = splay(root->right->right, key); root = leftRotate(root); } // Do second rotation for root return (root->right == NULL)? root: leftRotate(root); }} // The search function for Splay tree. Note that this function// returns the new root of Splay Tree. If key is present in tree// then, it is moved to root.struct node *search(struct node *root, int key){ return splay(root, key);} // A utility function to print preorder traversal of the tree.// The function also prints height of every nodevoid preOrder(struct node *root){ if (root != NULL) { printf(\"%d \", root->key); preOrder(root->left); preOrder(root->right); }} /* Driver program to test above function*/int main(){ struct node *root = newNode(100); root->left = newNode(50); root->right = newNode(200); root->left->left = newNode(40); root->left->left->left = newNode(30); root->left->left->left->left = newNode(20); root = search(root, 20); printf(\"Preorder traversal of the modified Splay tree is \\n\"); preOrder(root); return 0;}",
"e": 13132,
"s": 9233,
"text": null
},
{
"code": "// Java implementation for above approachclass GFG{ // An AVL tree nodestatic class node{ int key; node left, right;}; /* Helper function that allocatesa new node with the given key and null left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.static node search(node root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { System.out.print(root.key + \" \"); preOrder(root.left); preOrder(root.right); }} // Driver codepublic static void main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = search(root, 20); System.out.print(\"Preorder traversal of the\" + \" modified Splay tree is \\n\"); preOrder(root);}} // This code is contributed by 29AjayKumar",
"e": 17038,
"s": 13132,
"text": null
},
{
"code": "// C# implementation for above approachusing System; class GFG{ // An AVL tree nodepublic class node{ public int key; public node left, right;}; /* Helper function that allocatesa new node with the given key andnull left and right pointers. */static node newNode(int key){ node Node = new node(); Node.key = key; Node.left = Node.right = null; return (Node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.static node rightRotate(node x){ node y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.static node leftRotate(node x){ node y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootstatic node splay(node root, int key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.static node search(node root, int key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodestatic void preOrder(node root){ if (root != null) { Console.Write(root.key + \" \"); preOrder(root.left); preOrder(root.right); }} // Driver codepublic static void Main(String[] args){ node root = newNode(100); root.left = newNode(50); root.right = newNode(200); root.left.left = newNode(40); root.left.left.left = newNode(30); root.left.left.left.left = newNode(20); root = search(root, 20); Console.Write(\"Preorder traversal of the\" + \" modified Splay tree is \\n\"); preOrder(root);}} // This code is contributed by 29AjayKumar",
"e": 20957,
"s": 17038,
"text": null
},
{
"code": "<script>// Javascript implementation for above approach // An AVL tree nodeclass Node{ /* Helper function that allocatesa new node with the given key and null left and right pointers. */ constructor(key) { this.key = key; this.left = this.right = null; }} // A utility function to right// rotate subtree rooted with y// See the diagram given above.function rightRotate(x){ let y = x.left; x.left = y.right; y.right = x; return y;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.function leftRotate(x){ let y = x.right; x.right = y.left; y.left = x; return y;} // This function brings the key at// root if key is present in tree.// If key is not present, then it// brings the last accessed item at// root. This function modifies the// tree and returns the new rootfunction splay(root,key){ // Base cases: root is null or // key is present at root if (root == null || root.key == key) return root; // Key lies in left subtree if (root.key > key) { // Key is not in tree, we are done if (root.left == null) return root; // Zig-Zig (Left Left) if (root.left.key > key) { // First recursively bring the // key as root of left-left root.left.left = splay(root.left.left, key); // Do first rotation for root, // second rotation is done after else root = rightRotate(root); } else if (root.left.key < key) // Zig-Zag (Left Right) { // First recursively bring // the key as root of left-right root.left.right = splay(root.left.right, key); // Do first rotation for root.left if (root.left.right != null) root.left = leftRotate(root.left); } // Do second rotation for root return (root.left == null) ? root : rightRotate(root); } else // Key lies in right subtree { // Key is not in tree, we are done if (root.right == null) return root; // Zag-Zig (Right Left) if (root.right.key > key) { // Bring the key as root of right-left root.right.left = splay(root.right.left, key); // Do first rotation for root.right if (root.right.left != null) root.right = rightRotate(root.right); } else if (root.right.key < key)// Zag-Zag (Right Right) { // Bring the key as root of // right-right and do first rotation root.right.right = splay(root.right.right, key); root = leftRotate(root); } // Do second rotation for root return (root.right == null) ? root : leftRotate(root); }} // The search function for Splay tree.// Note that this function returns the// new root of Splay Tree. If key is// present in tree then, it is moved to root.function search(root,key){ return splay(root, key);} // A utility function to print// preorder traversal of the tree.// The function also prints height of every nodefunction preOrder(root){ if (root != null) { document.write(root.key + \" \"); preOrder(root.left); preOrder(root.right); }} // Driver codelet root = new Node(100); root.left = new Node(50); root.right = new Node(200); root.left.left = new Node(40); root.left.left.left = new Node(30); root.left.left.left.left = new Node(20); root = search(root, 20); document.write(\"Preorder traversal of the\" + \" modified Splay tree is <br>\"); preOrder(root); // This code is contributed by rag2127</script>",
"e": 24722,
"s": 20957,
"text": null
},
{
"code": null,
"e": 24731,
"s": 24722,
"text": "Output: "
},
{
"code": null,
"e": 24800,
"s": 24731,
"text": "Preorder traversal of the modified Splay tree is\n20 50 30 40 100 200"
},
{
"code": null,
"e": 25951,
"s": 24800,
"text": "Summary 1) Splay trees have excellent locality properties. Frequently accessed items are easy to find. Infrequent items are out of way.2) All splay tree operations take O(Logn) time on average. Splay trees can be rigorously shown to run in O(log n) average time per operation, over any sequence of operations (assuming we start from an empty tree)3) Splay trees are simpler compared to AVL and Red-Black Trees as no extra field is required in every tree node.4) Unlike AVL tree, a splay tree can change even with read-only operations like search.Applications of Splay Trees Splay trees have become the most widely used basic data structure invented in the last 30 years, because they’re the fastest type of balanced search tree for many applications. Splay trees are used in Windows NT (in the virtual memory, networking, and file system code), the gcc compiler and GNU C++ library, the sed string editor, For Systems network routers, the most popular implementation of Unix malloc, Linux loadable kernel modules, and in much other software (Source: http://www.cs.berkeley.edu/~jrs/61b/lec/36)See Splay Tree | Set 2 (Insert) for splay tree insertion."
},
{
"code": null,
"e": 25978,
"s": 25951,
"text": "Advantages of Splay Trees:"
},
{
"code": null,
"e": 26044,
"s": 25978,
"text": "Useful for implementing caches and garbage collection algorithms."
},
{
"code": null,
"e": 26111,
"s": 26044,
"text": "Require less space as there is no balance information is required."
},
{
"code": null,
"e": 26186,
"s": 26111,
"text": "Splay trees provide good performance with nodes containing identical keys."
},
{
"code": null,
"e": 26216,
"s": 26186,
"text": "Disadvantages of Splay Trees:"
},
{
"code": null,
"e": 26306,
"s": 26216,
"text": "The height of a splay tree can be linear when accessing elements in non decreasing order."
},
{
"code": null,
"e": 26421,
"s": 26306,
"text": "The performance of a splay tree will be worse than a balanced simple binary search tree in case of uniform access."
},
{
"code": null,
"e": 26752,
"s": 26421,
"text": "References: http://www.cs.berkeley.edu/~jrs/61b/lec/36 http://www.cs.cornell.edu/courses/cs3110/2009fa/recitations/rec-splay.html http://courses.cs.washington.edu/courses/cse326/01au/lectures/SplayTrees.pptPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 26766,
"s": 26752,
"text": "Ujjwal Mishra"
},
{
"code": null,
"e": 26780,
"s": 26766,
"text": "rathbhupendra"
},
{
"code": null,
"e": 26791,
"s": 26780,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26803,
"s": 26791,
"text": "29AjayKumar"
},
{
"code": null,
"e": 26811,
"s": 26803,
"text": "rag2127"
},
{
"code": null,
"e": 26820,
"s": 26811,
"text": "tcostell"
},
{
"code": null,
"e": 26835,
"s": 26820,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 26850,
"s": 26835,
"text": "guptavivek0503"
},
{
"code": null,
"e": 26865,
"s": 26850,
"text": "adhamasharkawy"
},
{
"code": null,
"e": 26884,
"s": 26865,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 26895,
"s": 26884,
"text": "splay-tree"
},
{
"code": null,
"e": 26919,
"s": 26895,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 27017,
"s": 26919,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27046,
"s": 27017,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 27073,
"s": 27046,
"text": "Trie | (Insert and Search)"
},
{
"code": null,
"e": 27098,
"s": 27073,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 27121,
"s": 27098,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 27155,
"s": 27121,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 27193,
"s": 27155,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 27233,
"s": 27193,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 27269,
"s": 27233,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 27297,
"s": 27269,
"text": "AVL Tree | Set 2 (Deletion)"
}
] |
Length of longest non-decreasing subsequence such that difference between adjacent elements is at most one | 01 Jun, 2021
Given an array arr[] consisting of N integers, the task is to find the length of the longest non-decreasing subsequence such that the difference between adjacent elements is at most 1.
Examples:
Input: arr[] = {8, 5, 4, 8, 4}Output: 3Explanation: {4, 4, 5}, {8, 8} are the two such non-decreasing subsequences of length 2 and 3 respectively. Therefore, the length of the longest of the two subsequences is 3.
Input: arr[] = {4, 13, 2, 3}Output: 3Explanation: {2, 3, 4}, {13} are the two such non-decreasing subsequences of length 3 and 1 respectively. Therefore, the length of the longest of the two subsequences is 3.
Approach: Follow the steps below to solve the problem:
Sort the array arr[] in increasing order.
Initialize a variable, say maxLen = 1, to store the maximum possible length of a subsequence. Initialize another variable, say len = 1 to store the current length for each subsequence.
Traverse the array arr[] with a pointer i and for each element:Check if abs(arr[i] – arr[i – 1]) ≤ 1. If found to be true, then increment len by 1. Update maxLen = max(maxLen, len).Otherwise, set len = 1 i.e. start a new subsequence.
Check if abs(arr[i] – arr[i – 1]) ≤ 1. If found to be true, then increment len by 1. Update maxLen = max(maxLen, len).
Otherwise, set len = 1 i.e. start a new subsequence.
Print the value of maxLen as the final answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest non-decreasing// subsequence with difference between// adjacent elements exactly equal to 1void longestSequence(int arr[], int N){ // Base case if (N == 0) { cout << 0; return; } // Sort the array in ascending order sort(arr, arr+N); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length cout << maxLen;} // Driver Codeint main(){ // Given array int arr[] = { 8, 5, 4, 8, 4 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function call to find the longest // subsequence longestSequence(arr, N); return 0;} // This code is contributed by code_hunt.
// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find the longest non-decreasing // subsequence with difference between // adjacent elements exactly equal to 1 static void longestSequence(int arr[], int N) { // Base case if (N == 0) { System.out.println(0); return; } // Sort the array in ascending order Arrays.sort(arr); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length System.out.println(maxLen); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 8, 5, 4, 8, 4 }; // Size of the array int N = arr.length; // Function call to find the longest // subsequence longestSequence(arr, N); }}
# Python program for the above approach # Function to find the longest non-decreasing# subsequence with difference between# adjacent elements exactly equal to 1def longestSequence(arr, N): # Base case if (N == 0): print(0); return; # Sort the array in ascending order arr.sort(); # Stores the maximum length maxLen = 1; len = 1; # Traverse the array for i in range(1,N): # If difference between current # pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] or arr[i] == arr[i - 1] + 1): len += 1; # Extend the current sequence # Update len and max_len maxLen = max(maxLen, len); else: # Otherwise, start a new subsequence len = 1; # Print the maximum length print(maxLen); # Driver Codeif __name__ == '__main__': # Given array arr = [8, 5, 4, 8, 4]; # Size of the array N = len(arr); # Function call to find the longest # subsequence longestSequence(arr, N); # This code is contributed by 29AjayKumar
// C# program for the above approachusing System;public class GFG{ // Function to find the longest non-decreasing // subsequence with difference between // adjacent elements exactly equal to 1 static void longestSequence(int []arr, int N) { // Base case if (N == 0) { Console.WriteLine(0); return; } // Sort the array in ascending order Array.Sort(arr); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.Max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length Console.WriteLine(maxLen); } // Driver Code public static void Main(string[] args) { // Given array int []arr = { 8, 5, 4, 8, 4 }; // Size of the array int N = arr.Length; // Function call to find the longest // subsequence longestSequence(arr, N); }} // This code is contributed by AnkThon
<script> // Javascript program to implement// the above approach // Function to find the longest non-decreasing// subsequence with difference between// adjacent elements exactly equal to 1function longestSequence(arr, N){ // Base case if (N == 0) { document.write(0); return; } // Sort the array in ascending order arr.sort(); // Stores the maximum length var maxLen = 1; var len = 1; var i; // Traverse the array for (i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length document.write(maxLen);} // Driver Code // Given array var arr = [8, 5, 4, 8, 4]; // Size of the array var N = arr.length; // Function call to find the longest // subsequence longestSequence(arr, N); </script>
3
Time Complexity: O(N * logN)Auxiliary Space: O(1)
ankthon
code_hunt
29AjayKumar
bgangwar59
Kirti_Mangal
subsequence
Arrays
Mathematical
Searching
Sorting
Arrays
Searching
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "Given an array arr[] consisting of N integers, the task is to find the length of the longest non-decreasing subsequence such that the difference between adjacent elements is at most 1."
},
{
"code": null,
"e": 223,
"s": 213,
"text": "Examples:"
},
{
"code": null,
"e": 438,
"s": 223,
"text": "Input: arr[] = {8, 5, 4, 8, 4}Output: 3Explanation: {4, 4, 5}, {8, 8} are the two such non-decreasing subsequences of length 2 and 3 respectively. Therefore, the length of the longest of the two subsequences is 3. "
},
{
"code": null,
"e": 649,
"s": 438,
"text": "Input: arr[] = {4, 13, 2, 3}Output: 3Explanation: {2, 3, 4}, {13} are the two such non-decreasing subsequences of length 3 and 1 respectively. Therefore, the length of the longest of the two subsequences is 3. "
},
{
"code": null,
"e": 704,
"s": 649,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 746,
"s": 704,
"text": "Sort the array arr[] in increasing order."
},
{
"code": null,
"e": 931,
"s": 746,
"text": "Initialize a variable, say maxLen = 1, to store the maximum possible length of a subsequence. Initialize another variable, say len = 1 to store the current length for each subsequence."
},
{
"code": null,
"e": 1165,
"s": 931,
"text": "Traverse the array arr[] with a pointer i and for each element:Check if abs(arr[i] – arr[i – 1]) ≤ 1. If found to be true, then increment len by 1. Update maxLen = max(maxLen, len).Otherwise, set len = 1 i.e. start a new subsequence."
},
{
"code": null,
"e": 1284,
"s": 1165,
"text": "Check if abs(arr[i] – arr[i – 1]) ≤ 1. If found to be true, then increment len by 1. Update maxLen = max(maxLen, len)."
},
{
"code": null,
"e": 1337,
"s": 1284,
"text": "Otherwise, set len = 1 i.e. start a new subsequence."
},
{
"code": null,
"e": 1384,
"s": 1337,
"text": "Print the value of maxLen as the final answer."
},
{
"code": null,
"e": 1435,
"s": 1384,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1439,
"s": 1435,
"text": "C++"
},
{
"code": null,
"e": 1444,
"s": 1439,
"text": "Java"
},
{
"code": null,
"e": 1452,
"s": 1444,
"text": "Python3"
},
{
"code": null,
"e": 1455,
"s": 1452,
"text": "C#"
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest non-decreasing// subsequence with difference between// adjacent elements exactly equal to 1void longestSequence(int arr[], int N){ // Base case if (N == 0) { cout << 0; return; } // Sort the array in ascending order sort(arr, arr+N); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length cout << maxLen;} // Driver Codeint main(){ // Given array int arr[] = { 8, 5, 4, 8, 4 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Function call to find the longest // subsequence longestSequence(arr, N); return 0;} // This code is contributed by code_hunt.",
"e": 2616,
"s": 1466,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find the longest non-decreasing // subsequence with difference between // adjacent elements exactly equal to 1 static void longestSequence(int arr[], int N) { // Base case if (N == 0) { System.out.println(0); return; } // Sort the array in ascending order Arrays.sort(arr); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length System.out.println(maxLen); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 8, 5, 4, 8, 4 }; // Size of the array int N = arr.length; // Function call to find the longest // subsequence longestSequence(arr, N); }}",
"e": 4042,
"s": 2616,
"text": null
},
{
"code": "# Python program for the above approach # Function to find the longest non-decreasing# subsequence with difference between# adjacent elements exactly equal to 1def longestSequence(arr, N): # Base case if (N == 0): print(0); return; # Sort the array in ascending order arr.sort(); # Stores the maximum length maxLen = 1; len = 1; # Traverse the array for i in range(1,N): # If difference between current # pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] or arr[i] == arr[i - 1] + 1): len += 1; # Extend the current sequence # Update len and max_len maxLen = max(maxLen, len); else: # Otherwise, start a new subsequence len = 1; # Print the maximum length print(maxLen); # Driver Codeif __name__ == '__main__': # Given array arr = [8, 5, 4, 8, 4]; # Size of the array N = len(arr); # Function call to find the longest # subsequence longestSequence(arr, N); # This code is contributed by 29AjayKumar",
"e": 5133,
"s": 4042,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG{ // Function to find the longest non-decreasing // subsequence with difference between // adjacent elements exactly equal to 1 static void longestSequence(int []arr, int N) { // Base case if (N == 0) { Console.WriteLine(0); return; } // Sort the array in ascending order Array.Sort(arr); // Stores the maximum length int maxLen = 1; int len = 1; // Traverse the array for (int i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.Max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length Console.WriteLine(maxLen); } // Driver Code public static void Main(string[] args) { // Given array int []arr = { 8, 5, 4, 8, 4 }; // Size of the array int N = arr.Length; // Function call to find the longest // subsequence longestSequence(arr, N); }} // This code is contributed by AnkThon",
"e": 6377,
"s": 5133,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to find the longest non-decreasing// subsequence with difference between// adjacent elements exactly equal to 1function longestSequence(arr, N){ // Base case if (N == 0) { document.write(0); return; } // Sort the array in ascending order arr.sort(); // Stores the maximum length var maxLen = 1; var len = 1; var i; // Traverse the array for (i = 1; i < N; i++) { // If difference between current // pair of adjacent elements is 1 or 0 if (arr[i] == arr[i - 1] || arr[i] == arr[i - 1] + 1) { len++; // Extend the current sequence // Update len and max_len maxLen = Math.max(maxLen, len); } else { // Otherwise, start a new subsequence len = 1; } } // Print the maximum length document.write(maxLen);} // Driver Code // Given array var arr = [8, 5, 4, 8, 4]; // Size of the array var N = arr.length; // Function call to find the longest // subsequence longestSequence(arr, N); </script>",
"e": 7432,
"s": 6377,
"text": null
},
{
"code": null,
"e": 7437,
"s": 7435,
"text": "3"
},
{
"code": null,
"e": 7491,
"s": 7441,
"text": "Time Complexity: O(N * logN)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7501,
"s": 7493,
"text": "ankthon"
},
{
"code": null,
"e": 7511,
"s": 7501,
"text": "code_hunt"
},
{
"code": null,
"e": 7523,
"s": 7511,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7534,
"s": 7523,
"text": "bgangwar59"
},
{
"code": null,
"e": 7547,
"s": 7534,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 7559,
"s": 7547,
"text": "subsequence"
},
{
"code": null,
"e": 7566,
"s": 7559,
"text": "Arrays"
},
{
"code": null,
"e": 7579,
"s": 7566,
"text": "Mathematical"
},
{
"code": null,
"e": 7589,
"s": 7579,
"text": "Searching"
},
{
"code": null,
"e": 7597,
"s": 7589,
"text": "Sorting"
},
{
"code": null,
"e": 7604,
"s": 7597,
"text": "Arrays"
},
{
"code": null,
"e": 7614,
"s": 7604,
"text": "Searching"
},
{
"code": null,
"e": 7627,
"s": 7614,
"text": "Mathematical"
},
{
"code": null,
"e": 7635,
"s": 7627,
"text": "Sorting"
}
] |
Read latest news using newsapi | Python | 17 Sep, 2019
In this article, we will learn how to create a Python script to read the latest news. We will fetch news from news API and after that, we will read news using pyttsx3.
Modules required :
pyttsx3 - pip install pyttsx3
requests - pip install requests
Step #1: Import modules needed
import pyttsx3import requestsimport jsonimport time
Step #2: Setting up URL with API key, place your API key here.
url = ('https://newsapi.org/v2/top-headlines?' 'country = in&' 'apiKey =') url += 'your_api_key_here'
Step #3: Setting an engine for pyttsx3 for reading news.
engine = pyttsx3.init()
Step #4: Setting up properties of our engine, means reading rate, volume, and sound of a voice.
rate = engine.getProperty('rate')engine.setProperty('rate', rate + 10) volume = engine.getProperty('volume')engine.setProperty('volume', volume-0.60) sound = engine.getProperty ('voices');engine.setProperty('voice', 'sound[1].id')
Step #5: Trying to send request to get news. Here, engine.say() function is used to read news.
try: response = requests.get(url)except: engine.say("can, t access link, plz check you internet ") news = json.loads(response.text)
for new in news['articles']: print("##############################################################\n") print(str(new['title']), "\n\n") engine.say(str(new['title'])) print('______________________________________________________\n') engine.runAndWait() print(str(new['description']), "\n\n") engine.say(str(new['description'])) engine.runAndWait() print("..............................................................") time.sleep(2)
Now, everything is ready build a loop to read new articles.
Below is the complete Python implementation :
import pyttsx3import requestsimport jsonimport time url = ('https://newsapi.org/v2/top-headlines?' 'country = in&' 'apiKey =') url +='your_api_key_here' engine = pyttsx3.init()rate = engine.getProperty('rate')engine.setProperty('rate', rate + 10) volume = engine.getProperty('volume')engine.setProperty('volume', volume-0.60) sound = engine.getProperty ('voices');engine.setProperty('voice', 'sound[1].id') try: response = requests.get(url)except: engine.say("can, t access link, plz check you internet ") news = json.loads(response.text) for new in news['articles']: print("##############################################################\n") print(str(new['title']), "\n\n") engine.say(str(new['title'])) print('______________________________________________________\n') engine.runAndWait() print(str(new['description']), "\n\n") engine.say(str(new['description'])) engine.runAndWait() print("..............................................................") time.sleep(2)
Output:
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "In this article, we will learn how to create a Python script to read the latest news. We will fetch news from news API and after that, we will read news using pyttsx3."
},
{
"code": null,
"e": 215,
"s": 196,
"text": "Modules required :"
},
{
"code": null,
"e": 277,
"s": 215,
"text": "pyttsx3 - pip install pyttsx3\nrequests - pip install requests"
},
{
"code": null,
"e": 308,
"s": 277,
"text": "Step #1: Import modules needed"
},
{
"code": "import pyttsx3import requestsimport jsonimport time",
"e": 360,
"s": 308,
"text": null
},
{
"code": null,
"e": 423,
"s": 360,
"text": "Step #2: Setting up URL with API key, place your API key here."
},
{
"code": "url = ('https://newsapi.org/v2/top-headlines?' 'country = in&' 'apiKey =') url += 'your_api_key_here'",
"e": 538,
"s": 423,
"text": null
},
{
"code": null,
"e": 595,
"s": 538,
"text": "Step #3: Setting an engine for pyttsx3 for reading news."
},
{
"code": "engine = pyttsx3.init()",
"e": 619,
"s": 595,
"text": null
},
{
"code": null,
"e": 715,
"s": 619,
"text": "Step #4: Setting up properties of our engine, means reading rate, volume, and sound of a voice."
},
{
"code": "rate = engine.getProperty('rate')engine.setProperty('rate', rate + 10) volume = engine.getProperty('volume')engine.setProperty('volume', volume-0.60) sound = engine.getProperty ('voices');engine.setProperty('voice', 'sound[1].id')",
"e": 950,
"s": 715,
"text": null
},
{
"code": null,
"e": 1045,
"s": 950,
"text": "Step #5: Trying to send request to get news. Here, engine.say() function is used to read news."
},
{
"code": "try: response = requests.get(url)except: engine.say(\"can, t access link, plz check you internet \") news = json.loads(response.text)",
"e": 1185,
"s": 1045,
"text": null
},
{
"code": "for new in news['articles']: print(\"##############################################################\\n\") print(str(new['title']), \"\\n\\n\") engine.say(str(new['title'])) print('______________________________________________________\\n') engine.runAndWait() print(str(new['description']), \"\\n\\n\") engine.say(str(new['description'])) engine.runAndWait() print(\"..............................................................\") time.sleep(2)",
"e": 1652,
"s": 1185,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1652,
"text": "Now, everything is ready build a loop to read new articles."
},
{
"code": null,
"e": 1759,
"s": 1712,
"text": " Below is the complete Python implementation :"
},
{
"code": "import pyttsx3import requestsimport jsonimport time url = ('https://newsapi.org/v2/top-headlines?' 'country = in&' 'apiKey =') url +='your_api_key_here' engine = pyttsx3.init()rate = engine.getProperty('rate')engine.setProperty('rate', rate + 10) volume = engine.getProperty('volume')engine.setProperty('volume', volume-0.60) sound = engine.getProperty ('voices');engine.setProperty('voice', 'sound[1].id') try: response = requests.get(url)except: engine.say(\"can, t access link, plz check you internet \") news = json.loads(response.text) for new in news['articles']: print(\"##############################################################\\n\") print(str(new['title']), \"\\n\\n\") engine.say(str(new['title'])) print('______________________________________________________\\n') engine.runAndWait() print(str(new['description']), \"\\n\\n\") engine.say(str(new['description'])) engine.runAndWait() print(\"..............................................................\") time.sleep(2)",
"e": 2798,
"s": 1759,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2798,
"text": "Output:"
},
{
"code": null,
"e": 2821,
"s": 2806,
"text": "python-utility"
},
{
"code": null,
"e": 2828,
"s": 2821,
"text": "Python"
},
{
"code": null,
"e": 2844,
"s": 2828,
"text": "Python Programs"
}
] |
turtle.ondrag() function in Python | 17 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to bind fun to mouse-move event on this turtle on canvas.
Syntax : turtle.ondrag(fun, btn, add)Parameters :
fun : a function with two arguments, to which will be assigned the coordinates of the clicked point on the canvas
btn : number of the mouse-button defaults to 1 (left mouse button)
add : True or False. If True, new binding will be added, otherwise it will replace a former binding
Below is the implementation of the above method with an example :
Example :
# importing packageimport turtle # method to call on dragdef fxn(x, y): # stop backtracking turtle.ondrag(None) # move the turtle's angle and direction # towards x and y turtle.setheading(turtle.towards(x, y)) # go to x, y turtle.goto(x, y) # call again turtle.ondrag(fxn) # set turtle speedturtle.speed(10) # make turtle screen objectsc = turtle.Screen() # set screen sizesc.setup(400, 300) # call fxn on dragturtle.ondrag(fxn) # take screen in mainloopsc.mainloop()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 325,
"s": 245,
"text": "This function is used to bind fun to mouse-move event on this turtle on canvas."
},
{
"code": null,
"e": 375,
"s": 325,
"text": "Syntax : turtle.ondrag(fun, btn, add)Parameters :"
},
{
"code": null,
"e": 489,
"s": 375,
"text": "fun : a function with two arguments, to which will be assigned the coordinates of the clicked point on the canvas"
},
{
"code": null,
"e": 556,
"s": 489,
"text": "btn : number of the mouse-button defaults to 1 (left mouse button)"
},
{
"code": null,
"e": 656,
"s": 556,
"text": "add : True or False. If True, new binding will be added, otherwise it will replace a former binding"
},
{
"code": null,
"e": 722,
"s": 656,
"text": "Below is the implementation of the above method with an example :"
},
{
"code": null,
"e": 733,
"s": 722,
"text": "Example :"
},
{
"code": "# importing packageimport turtle # method to call on dragdef fxn(x, y): # stop backtracking turtle.ondrag(None) # move the turtle's angle and direction # towards x and y turtle.setheading(turtle.towards(x, y)) # go to x, y turtle.goto(x, y) # call again turtle.ondrag(fxn) # set turtle speedturtle.speed(10) # make turtle screen objectsc = turtle.Screen() # set screen sizesc.setup(400, 300) # call fxn on dragturtle.ondrag(fxn) # take screen in mainloopsc.mainloop()",
"e": 1244,
"s": 733,
"text": null
},
{
"code": null,
"e": 1253,
"s": 1244,
"text": "Output :"
},
{
"code": null,
"e": 1267,
"s": 1253,
"text": "Python-turtle"
},
{
"code": null,
"e": 1274,
"s": 1267,
"text": "Python"
}
] |
How to Copy NumPy array into another array? | 05 Sep, 2020
Many times there is a need to copy one array to another. Numpy provides the facility to copy array using different methods. There are 3 methods to copy a Numpy array to another array.
Method 1: Using np.empty_like() function
This function returns a new array with the same shape and type as a given array.
Syntax:
numpy.empty_like(a, dtype = None, order = ‘K’, subok = True)
Python3
# importing Numpy packageimport numpy as np # Creating a numpy array using np.array()ary = np.array([13, 99, 100, 34, 65, 11, 66, 81, 632, 44]) print("Original array: ") # printing the Numpy arrayprint(ary) # Creating an empty Numpy array similar# to arycopy = np.empty_like(ary) # Now assign ary to copycopy[:] = ary print("\nCopy of the given array: ") # printing the copied arrayprint(copy)
Output:
In the above example, the given Numpy array ‘ary‘ is copied to another array ‘copy‘ using np.empty_like () function
Method 2: Using np.copy() function
This function returns an array copy of the given object.
Syntax :
numpy.copy(a, order='K', subok=False)
Example 1:
Python3
# importing Numpy packageimport numpy as np # Creating a numpy array using np.array()org_array = np.array([1.54, 2.99, 3.42, 4.87, 6.94, 8.21, 7.65, 10.50, 77.5]) print("Original array: ") # printing the Numpy arrayprint(org_array) # Now copying the org_array to copy_array# using np.copy() functioncopy_array = np.copy(org_array) print("\nCopied array: ") # printing the copied Numpy arrayprint(copy_array)
Output:
In the above example, the given Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using np.copy () function
Example 2: Copy given 3-D array to another array using np.copy() function
Python3
# importing Numpy packageimport numpy as np # Creating a 3-D numpy array using np.array()org_array = np.array([[23, 46, 85], [43, 56, 99], [11, 34, 55]]) print("Original array: ") # printing the Numpy arrayprint(org_array) # Now copying the org_array to copy_array# using np.copy() functioncopy_array = np.copy(org_array) print("\nCopied array: ") # printing the copied Numpy arrayprint(copy_array)
Output:
In the above example, the given 3-D Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using np.copy () function
Method 3: Using Assignment Operator
Python3
# importing Numpy packageimport numpy as np # Create a 2-D Numpy array using np.array()org_array = np.array([[99, 22, 33], [44, 77, 66]]) # Copying org_array to copy_array# using Assignment operatorcopy_array = org_array # modifying org_arrayorg_array[1, 2] = 13 # checking if copy_array has remained the same # printing original arrayprint('Original Array: \n', org_array) # printing copied arrayprint('\nCopied Array: \n', copy_array)
Output:
In the above example, the given Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using Assignment Operator.
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "Many times there is a need to copy one array to another. Numpy provides the facility to copy array using different methods. There are 3 methods to copy a Numpy array to another array."
},
{
"code": null,
"e": 253,
"s": 212,
"text": "Method 1: Using np.empty_like() function"
},
{
"code": null,
"e": 334,
"s": 253,
"text": "This function returns a new array with the same shape and type as a given array."
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Syntax:"
},
{
"code": null,
"e": 404,
"s": 342,
"text": "numpy.empty_like(a, dtype = None, order = ‘K’, subok = True)\n"
},
{
"code": null,
"e": 412,
"s": 404,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a numpy array using np.array()ary = np.array([13, 99, 100, 34, 65, 11, 66, 81, 632, 44]) print(\"Original array: \") # printing the Numpy arrayprint(ary) # Creating an empty Numpy array similar# to arycopy = np.empty_like(ary) # Now assign ary to copycopy[:] = ary print(\"\\nCopy of the given array: \") # printing the copied arrayprint(copy)",
"e": 829,
"s": 412,
"text": null
},
{
"code": null,
"e": 837,
"s": 829,
"text": "Output:"
},
{
"code": null,
"e": 953,
"s": 837,
"text": "In the above example, the given Numpy array ‘ary‘ is copied to another array ‘copy‘ using np.empty_like () function"
},
{
"code": null,
"e": 988,
"s": 953,
"text": "Method 2: Using np.copy() function"
},
{
"code": null,
"e": 1045,
"s": 988,
"text": "This function returns an array copy of the given object."
},
{
"code": null,
"e": 1054,
"s": 1045,
"text": "Syntax :"
},
{
"code": null,
"e": 1092,
"s": 1054,
"text": "numpy.copy(a, order='K', subok=False)"
},
{
"code": null,
"e": 1103,
"s": 1092,
"text": "Example 1:"
},
{
"code": null,
"e": 1111,
"s": 1103,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a numpy array using np.array()org_array = np.array([1.54, 2.99, 3.42, 4.87, 6.94, 8.21, 7.65, 10.50, 77.5]) print(\"Original array: \") # printing the Numpy arrayprint(org_array) # Now copying the org_array to copy_array# using np.copy() functioncopy_array = np.copy(org_array) print(\"\\nCopied array: \") # printing the copied Numpy arrayprint(copy_array)",
"e": 1546,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1546,
"text": "Output:"
},
{
"code": null,
"e": 1676,
"s": 1554,
"text": "In the above example, the given Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using np.copy () function"
},
{
"code": null,
"e": 1750,
"s": 1676,
"text": "Example 2: Copy given 3-D array to another array using np.copy() function"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Creating a 3-D numpy array using np.array()org_array = np.array([[23, 46, 85], [43, 56, 99], [11, 34, 55]]) print(\"Original array: \") # printing the Numpy arrayprint(org_array) # Now copying the org_array to copy_array# using np.copy() functioncopy_array = np.copy(org_array) print(\"\\nCopied array: \") # printing the copied Numpy arrayprint(copy_array)",
"e": 2205,
"s": 1758,
"text": null
},
{
"code": null,
"e": 2213,
"s": 2205,
"text": "Output:"
},
{
"code": null,
"e": 2339,
"s": 2213,
"text": "In the above example, the given 3-D Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using np.copy () function"
},
{
"code": null,
"e": 2375,
"s": 2339,
"text": "Method 3: Using Assignment Operator"
},
{
"code": null,
"e": 2383,
"s": 2375,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # Create a 2-D Numpy array using np.array()org_array = np.array([[99, 22, 33], [44, 77, 66]]) # Copying org_array to copy_array# using Assignment operatorcopy_array = org_array # modifying org_arrayorg_array[1, 2] = 13 # checking if copy_array has remained the same # printing original arrayprint('Original Array: \\n', org_array) # printing copied arrayprint('\\nCopied Array: \\n', copy_array)",
"e": 2847,
"s": 2383,
"text": null
},
{
"code": null,
"e": 2855,
"s": 2847,
"text": "Output:"
},
{
"code": null,
"e": 2978,
"s": 2855,
"text": "In the above example, the given Numpy array ‘org_array‘ is copied to another array ‘copy_array‘ using Assignment Operator."
},
{
"code": null,
"e": 3005,
"s": 2978,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 3018,
"s": 3005,
"text": "Python-numpy"
},
{
"code": null,
"e": 3025,
"s": 3018,
"text": "Python"
}
] |
DATEFROMPARTS() Function in SQL Server | 18 Jan, 2021
DATEFROMPARTS() function :This function in SQL Server is used to return a date from the given values of year, month and day.
Features :
This function is used to find a date from the stated values of year, month and day.
This function comes under Date Functions.
This function accepts three parameters namely year, month and day.
This function cannot include any time with the stated date.
Syntax :
DATEFROMPARTS(year, month, day)
Parameter :This method accepts three parameters as given below :
year : It is the year specified which is of 4 digits.
month : It is the month specified which is from 1 to 12.
day : It is the day specified which is from 1st to 31st.
Returns :It returns a date from the given values of year, month and day.
Example-1 :Using DATEFROMPARTS() function and getting the date specified.
SELECT DATEFROMPARTS(2021, 01, 04);
Output :
2021-01-04
Example-2 :Using DATEFROMPARTS() function with a variable and getting the date specified.
DECLARE @year Int;
SET @year = 2012;
SELECT DATEFROMPARTS(@year, 09, 13);
Output :
2012-09-13
Example-3 :Using DATEFROMPARTS() function with three variables and getting the date specified.
DECLARE @year Int;
DECLARE @month Int;
DECLARE @day Int;
SET @year = 2016;
SET @month = 08;
SET @day = 29;
SELECT DATEFROMPARTS(@year, @month, @day);
Output :
2016-08-29
Example-4 :Using DATEFROMPARTS() as a default value in the below example and getting the output.
CREATE TABLE date_from_parts
(
id_num INT IDENTITY,
message VARCHAR(150) NOT NULL,
generated_at DATETIME NOT NULL
DEFAULT DATEFROMPARTS(2001, 4, 7),
PRIMARY KEY(id_num)
);
INSERT INTO date_from_parts(message)
VALUES('First Message');
INSERT INTO date_from_parts(message)
VALUES('date_from_parts');
SELECT
id_num,
message,
generated_at
FROM
date_from_parts;
Output :
Here, firstly you need to create a table then insert values into it then generate the required output using DATEFROMPARTS() function as a default value.
Note : For running above code use sql server compiler, you can also use a online compiler.
Application :This function is used to find the date from the specified values year, month and day.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "DATEFROMPARTS() function :This function in SQL Server is used to return a date from the given values of year, month and day."
},
{
"code": null,
"e": 164,
"s": 153,
"text": "Features :"
},
{
"code": null,
"e": 248,
"s": 164,
"text": "This function is used to find a date from the stated values of year, month and day."
},
{
"code": null,
"e": 290,
"s": 248,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 357,
"s": 290,
"text": "This function accepts three parameters namely year, month and day."
},
{
"code": null,
"e": 417,
"s": 357,
"text": "This function cannot include any time with the stated date."
},
{
"code": null,
"e": 426,
"s": 417,
"text": "Syntax :"
},
{
"code": null,
"e": 459,
"s": 426,
"text": "DATEFROMPARTS(year, month, day)\n"
},
{
"code": null,
"e": 524,
"s": 459,
"text": "Parameter :This method accepts three parameters as given below :"
},
{
"code": null,
"e": 578,
"s": 524,
"text": "year : It is the year specified which is of 4 digits."
},
{
"code": null,
"e": 635,
"s": 578,
"text": "month : It is the month specified which is from 1 to 12."
},
{
"code": null,
"e": 692,
"s": 635,
"text": "day : It is the day specified which is from 1st to 31st."
},
{
"code": null,
"e": 765,
"s": 692,
"text": "Returns :It returns a date from the given values of year, month and day."
},
{
"code": null,
"e": 839,
"s": 765,
"text": "Example-1 :Using DATEFROMPARTS() function and getting the date specified."
},
{
"code": null,
"e": 876,
"s": 839,
"text": "SELECT DATEFROMPARTS(2021, 01, 04);\n"
},
{
"code": null,
"e": 885,
"s": 876,
"text": "Output :"
},
{
"code": null,
"e": 896,
"s": 885,
"text": "2021-01-04"
},
{
"code": null,
"e": 986,
"s": 896,
"text": "Example-2 :Using DATEFROMPARTS() function with a variable and getting the date specified."
},
{
"code": null,
"e": 1061,
"s": 986,
"text": "DECLARE @year Int;\nSET @year = 2012;\nSELECT DATEFROMPARTS(@year, 09, 13);\n"
},
{
"code": null,
"e": 1070,
"s": 1061,
"text": "Output :"
},
{
"code": null,
"e": 1081,
"s": 1070,
"text": "2012-09-13"
},
{
"code": null,
"e": 1176,
"s": 1081,
"text": "Example-3 :Using DATEFROMPARTS() function with three variables and getting the date specified."
},
{
"code": null,
"e": 1327,
"s": 1176,
"text": "DECLARE @year Int;\nDECLARE @month Int;\nDECLARE @day Int;\nSET @year = 2016;\nSET @month = 08;\nSET @day = 29;\nSELECT DATEFROMPARTS(@year, @month, @day);\n"
},
{
"code": null,
"e": 1336,
"s": 1327,
"text": "Output :"
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": "2016-08-29"
},
{
"code": null,
"e": 1444,
"s": 1347,
"text": "Example-4 :Using DATEFROMPARTS() as a default value in the below example and getting the output."
},
{
"code": null,
"e": 1860,
"s": 1444,
"text": "CREATE TABLE date_from_parts\n(\n id_num INT IDENTITY, \n message VARCHAR(150) NOT NULL, \n generated_at DATETIME NOT NULL\n DEFAULT DATEFROMPARTS(2001, 4, 7), \n PRIMARY KEY(id_num)\n);\nINSERT INTO date_from_parts(message)\nVALUES('First Message');\n\nINSERT INTO date_from_parts(message)\nVALUES('date_from_parts');\nSELECT \n id_num, \n message, \n generated_at\nFROM \n date_from_parts;\n"
},
{
"code": null,
"e": 1869,
"s": 1860,
"text": "Output :"
},
{
"code": null,
"e": 2022,
"s": 1869,
"text": "Here, firstly you need to create a table then insert values into it then generate the required output using DATEFROMPARTS() function as a default value."
},
{
"code": null,
"e": 2113,
"s": 2022,
"text": "Note : For running above code use sql server compiler, you can also use a online compiler."
},
{
"code": null,
"e": 2212,
"s": 2113,
"text": "Application :This function is used to find the date from the specified values year, month and day."
},
{
"code": null,
"e": 2221,
"s": 2212,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2232,
"s": 2221,
"text": "SQL-Server"
},
{
"code": null,
"e": 2236,
"s": 2232,
"text": "SQL"
},
{
"code": null,
"e": 2240,
"s": 2236,
"text": "SQL"
}
] |
MongoDB – Replace Documents Using MongoShell | 27 Feb, 2020
In MongoDB, you are allowed to replace an existing document with a new document in the collection with the help of db.collection.replaceOne() method. This method will replace the existing document with the replacement document.
replaceOne() is a mongo shell method, which only replaces one document at a time. The replacement document may contain different fields as compared to the original document.
As we know that the _id field is immutable, so you can omit _id field in the replacement document. And if you want to add _id field in the replacement document, then the value of _id field is same as the current value and if you use a different value, then you will get an error.
The replacement document can only contain field-value pairs. It does not contain update operator expressions.
This method replaces the first document that satisfies the given condition in the collection with the replacement document. Or in other words, if multiple documents satisfy the given condition, then this method will replace the very first document with the replacement document that matches the given filter or condition.
This method can be used in the multi-document transactions.
Syntax:
db.collection.replaceOne(
<filter>,
<replacementDocument>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)
Parameters:
filter: First parameter of this method. It specifies the selection criteria for the update. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will replace the first document of the collection with the replacement document.
replacementDocument: Second parameter of this method. It is a replacement document that will replace the original document. It does not contain update operations.Optional Parameters:
upsert: The value of this parameter is either true or false. If the value of this parameter is true, then the method will replace the document that matches the given condition with the replacement document or if any of the documents in the collection does not match the given filter, then this method will insert a new document(i.e., replacementDocument) in the collection. The type of this parameter is a Boolean and the default value of this parameter is false.
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document.
hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
Return: This method return a document that contain a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled), matchedCount represents the total number of matched documents, modifiedCount represents the total number of modified documents, and upsertedId represents the _id of the upserted document. The upsertedId only appears in this document when the value of upsert parameter is set to true.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
In this example, we are going to replace the first document of the employee collection, i.e., {name: "Rohit", age: 20, branch: "CSE", department: "HR"} with the replacement document, i.e., {name: "Anu", age: 30, branch: "EEE", department: "HR", joiningYear: 2018} using the replaceOne() method.
db.collection.replaceOne({}, {replacement document})
In this example, we are replacing a document of the employee collection that matches the given condition or filter, i.e, name: "Sonu" with the replacement document, i.e., {name: "Sonu", age: 25, branch: "CSE", department: "Designing"} using the replaceOne() method. Or in other words, in this example we are replacing a document of an employee whose name is Sonu.
In this example, we are replacing a document with a replacement document. Here, multiple documents match the filter, i.e., name: “Sonu”, so the replaceOne() method replaces the first document that matches the given condition among these documents as shown in the below images –Before replacement:After replacement:
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "In MongoDB, you are allowed to replace an existing document with a new document in the collection with the help of db.collection.replaceOne() method. This method will replace the existing document with the replacement document."
},
{
"code": null,
"e": 430,
"s": 256,
"text": "replaceOne() is a mongo shell method, which only replaces one document at a time. The replacement document may contain different fields as compared to the original document."
},
{
"code": null,
"e": 710,
"s": 430,
"text": "As we know that the _id field is immutable, so you can omit _id field in the replacement document. And if you want to add _id field in the replacement document, then the value of _id field is same as the current value and if you use a different value, then you will get an error."
},
{
"code": null,
"e": 820,
"s": 710,
"text": "The replacement document can only contain field-value pairs. It does not contain update operator expressions."
},
{
"code": null,
"e": 1142,
"s": 820,
"text": "This method replaces the first document that satisfies the given condition in the collection with the replacement document. Or in other words, if multiple documents satisfy the given condition, then this method will replace the very first document with the replacement document that matches the given filter or condition."
},
{
"code": null,
"e": 1202,
"s": 1142,
"text": "This method can be used in the multi-document transactions."
},
{
"code": null,
"e": 1210,
"s": 1202,
"text": "Syntax:"
},
{
"code": null,
"e": 1418,
"s": 1210,
"text": "db.collection.replaceOne(\n <filter>,\n <replacementDocument>,\n {\n upsert: <boolean>,\n writeConcern: <document>,\n collation: <document>,\n hint: <document|string> \n }\n)"
},
{
"code": null,
"e": 1430,
"s": 1418,
"text": "Parameters:"
},
{
"code": null,
"e": 1700,
"s": 1430,
"text": "filter: First parameter of this method. It specifies the selection criteria for the update. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will replace the first document of the collection with the replacement document."
},
{
"code": null,
"e": 1883,
"s": 1700,
"text": "replacementDocument: Second parameter of this method. It is a replacement document that will replace the original document. It does not contain update operations.Optional Parameters:"
},
{
"code": null,
"e": 2347,
"s": 1883,
"text": "upsert: The value of this parameter is either true or false. If the value of this parameter is true, then the method will replace the document that matches the given condition with the replacement document or if any of the documents in the collection does not match the given filter, then this method will insert a new document(i.e., replacementDocument) in the collection. The type of this parameter is a Boolean and the default value of this parameter is false."
},
{
"code": null,
"e": 2472,
"s": 2347,
"text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document."
},
{
"code": null,
"e": 2698,
"s": 2472,
"text": "collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document."
},
{
"code": null,
"e": 2931,
"s": 2698,
"text": "hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error."
},
{
"code": null,
"e": 3376,
"s": 2931,
"text": "Return: This method return a document that contain a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled), matchedCount represents the total number of matched documents, modifiedCount represents the total number of modified documents, and upsertedId represents the _id of the upserted document. The upsertedId only appears in this document when the value of upsert parameter is set to true."
},
{
"code": null,
"e": 3386,
"s": 3376,
"text": "Examples:"
},
{
"code": null,
"e": 3434,
"s": 3386,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 3582,
"s": 3434,
"text": "Database: GeeksforGeeks\nCollection: employee\nDocument: three documents that contain the details of the employees in the form of field-value pairs.\n"
},
{
"code": null,
"e": 3877,
"s": 3582,
"text": "In this example, we are going to replace the first document of the employee collection, i.e., {name: \"Rohit\", age: 20, branch: \"CSE\", department: \"HR\"} with the replacement document, i.e., {name: \"Anu\", age: 30, branch: \"EEE\", department: \"HR\", joiningYear: 2018} using the replaceOne() method."
},
{
"code": null,
"e": 3930,
"s": 3877,
"text": "db.collection.replaceOne({}, {replacement document})"
},
{
"code": null,
"e": 4294,
"s": 3930,
"text": "In this example, we are replacing a document of the employee collection that matches the given condition or filter, i.e, name: \"Sonu\" with the replacement document, i.e., {name: \"Sonu\", age: 25, branch: \"CSE\", department: \"Designing\"} using the replaceOne() method. Or in other words, in this example we are replacing a document of an employee whose name is Sonu."
},
{
"code": null,
"e": 4609,
"s": 4294,
"text": "In this example, we are replacing a document with a replacement document. Here, multiple documents match the filter, i.e., name: “Sonu”, so the replaceOne() method replaces the first document that matches the given condition among these documents as shown in the below images –Before replacement:After replacement:"
},
{
"code": null,
"e": 4617,
"s": 4609,
"text": "MongoDB"
},
{
"code": null,
"e": 4643,
"s": 4617,
"text": "Advanced Computer Subject"
}
] |
Hashing | Set 3 (Open Addressing) | 28 Jun, 2022
We strongly recommend referring below post as a prerequisite of this. Hashing | Set 1 (Introduction) Hashing | Set 2 (Separate Chaining)
Open Addressing:Like separate chaining, open addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys (Note that we can increase table size by copying old data if needed). This approach is also known as closed hashing. This entire procedure is based upon probing. We will understand types of probing ahead.
Insert(k): Keep probing until an empty slot is found. Once an empty slot is found, insert k.
Search(k): Keep probing until slot’s key doesn’t become equal to k or an empty slot is reached.
Delete(k): Delete operation is interesting. If we simply delete a key, then the search may fail. So slots of deleted keys are marked specially as “deleted”. The insert can insert an item in a deleted slot, but the search doesn’t stop at a deleted slot.
Open Addressing is done in the following ways:
a) Linear Probing:
In linear probing, the hash table is searched sequentially that starts from the original location of the hash. If in case the location that we get is already occupied, then we check for the next location. he function used for rehashing is as follows: rehash(key) = (n+1)%table-size. For example, the typical gap between two probes is 1 as seen in the example below. Let hash(x) be the slot index computed using a hash function and S be the table size
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
If slot hash(x) % S is full, then we try (hash(x) + 1) % S
If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S
If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S
..................................................
..................................................
Let us consider a simple hash function as “key mod 7” and a sequence of keys as 50, 700, 76, 85, 92, 73, 101.
Challenges in Linear Probing :
Primary Clustering: One of the problems with linear probing is Primary clustering, many consecutive elements form groups and it starts taking time to find a free slot or to search for an element. Secondary Clustering: Secondary clustering is less severe, two records only have the same collision chain (Probe Sequence) if their initial position is the same.
Primary Clustering: One of the problems with linear probing is Primary clustering, many consecutive elements form groups and it starts taking time to find a free slot or to search for an element.
Secondary Clustering: Secondary clustering is less severe, two records only have the same collision chain (Probe Sequence) if their initial position is the same.
b) Quadratic Probing If you observe carefully, then you will understand that the interval between probes will increase proportionally to the hash value. Quadratic probing is a method with the help of which we can solve the problem of clustering that was discussed above. This method is also known as mid-square method. In this method we look for i2‘th slot in i’th iteration. We always start from the original hash location. If only the location is occupied then we check the other slots.
let hash(x) be the slot index computed using hash function.
If slot hash(x) % S is full, then we try (hash(x) + 1*1) % S
If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S
If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S
..................................................
..................................................
c) Double Hashing The intervals that lie between probes is computed by another hash function. Double hashing is a technique that reduces clustering in an optimized way. In this technique, the increments for the probing sequence are computed by using another hash function. We use another hash function hash2(x) and look for i*hash2(x) slot in i’th rotation.
let hash(x) be the slot index computed using hash function.
If slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S
If (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S
If (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S
..................................................
..................................................
See this for step by step diagrams.
Comparison of above three:
Linear probing has the best cache performance but suffers from clustering. One more advantage of Linear probing is easy to compute.
Quadratic probing lies between the two in terms of cache performance and clustering.
Double hashing has poor cache performance but no clustering. Double hashing requires more computation time as two hash functions need to be computed.
Note: Cache performance of chaining is not good because when we traverse a Linked List, we are basically jumping from one node to another, all across the computer’s memory. For this reason, the CPU cannot cache the nodes which aren’t visited yet, this doesn’t help us. But with Open Addressing, data isn’t spread, so if the CPU detects that a segment of memory is constantly being accessed, it gets cached for quick access.
Performance of Open Addressing: Like Chaining, the performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of the table (simple uniform hashing)
m = Number of slots in the hash table
n = Number of keys to be inserted in the hash table
Load factor α = n/m ( < 1 )
Expected time to search/insert/delete < 1/(1 - α)
So Search, Insert and Delete take (1/(1 - α)) time
PulkitGoel2
shubham_singh
himanshu_shekhar
mrunknowncoder
mallikabachan
dfheintz
ohaddiscretix
ishikapaliwal2001
harshmandalgi
shreyasnaphad
hardikkoriintern
Hash
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Longest Consecutive Subsequence
Count pairs with given sum
Counting frequencies of array elements
Sort string of characters
Sorting a Map by value in C++ STL
Find the smallest window in a string containing all characters of another string
Print Nodes in Top View of Binary Tree | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 190,
"s": 52,
"text": "We strongly recommend referring below post as a prerequisite of this. Hashing | Set 1 (Introduction) Hashing | Set 2 (Separate Chaining) "
},
{
"code": null,
"e": 656,
"s": 190,
"text": "Open Addressing:Like separate chaining, open addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys (Note that we can increase table size by copying old data if needed). This approach is also known as closed hashing. This entire procedure is based upon probing. We will understand types of probing ahead. "
},
{
"code": null,
"e": 750,
"s": 656,
"text": "Insert(k): Keep probing until an empty slot is found. Once an empty slot is found, insert k. "
},
{
"code": null,
"e": 847,
"s": 750,
"text": "Search(k): Keep probing until slot’s key doesn’t become equal to k or an empty slot is reached. "
},
{
"code": null,
"e": 1101,
"s": 847,
"text": "Delete(k): Delete operation is interesting. If we simply delete a key, then the search may fail. So slots of deleted keys are marked specially as “deleted”. The insert can insert an item in a deleted slot, but the search doesn’t stop at a deleted slot. "
},
{
"code": null,
"e": 1149,
"s": 1101,
"text": "Open Addressing is done in the following ways: "
},
{
"code": null,
"e": 1169,
"s": 1149,
"text": "a) Linear Probing: "
},
{
"code": null,
"e": 1621,
"s": 1169,
"text": "In linear probing, the hash table is searched sequentially that starts from the original location of the hash. If in case the location that we get is already occupied, then we check for the next location. he function used for rehashing is as follows: rehash(key) = (n+1)%table-size. For example, the typical gap between two probes is 1 as seen in the example below. Let hash(x) be the slot index computed using a hash function and S be the table size "
},
{
"code": null,
"e": 1630,
"s": 1621,
"text": "Chapters"
},
{
"code": null,
"e": 1657,
"s": 1630,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1707,
"s": 1657,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1730,
"s": 1707,
"text": "captions off, selected"
},
{
"code": null,
"e": 1738,
"s": 1730,
"text": "English"
},
{
"code": null,
"e": 1762,
"s": 1738,
"text": "This is a modal window."
},
{
"code": null,
"e": 1831,
"s": 1762,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1853,
"s": 1831,
"text": "End of dialog window."
},
{
"code": null,
"e": 2145,
"s": 1853,
"text": "If slot hash(x) % S is full, then we try (hash(x) + 1) % S\nIf (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S\nIf (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S \n..................................................\n.................................................."
},
{
"code": null,
"e": 2256,
"s": 2145,
"text": "Let us consider a simple hash function as “key mod 7” and a sequence of keys as 50, 700, 76, 85, 92, 73, 101. "
},
{
"code": null,
"e": 2287,
"s": 2256,
"text": "Challenges in Linear Probing :"
},
{
"code": null,
"e": 2646,
"s": 2287,
"text": "Primary Clustering: One of the problems with linear probing is Primary clustering, many consecutive elements form groups and it starts taking time to find a free slot or to search for an element. Secondary Clustering: Secondary clustering is less severe, two records only have the same collision chain (Probe Sequence) if their initial position is the same."
},
{
"code": null,
"e": 2844,
"s": 2646,
"text": "Primary Clustering: One of the problems with linear probing is Primary clustering, many consecutive elements form groups and it starts taking time to find a free slot or to search for an element. "
},
{
"code": null,
"e": 3006,
"s": 2844,
"text": "Secondary Clustering: Secondary clustering is less severe, two records only have the same collision chain (Probe Sequence) if their initial position is the same."
},
{
"code": null,
"e": 3497,
"s": 3006,
"text": "b) Quadratic Probing If you observe carefully, then you will understand that the interval between probes will increase proportionally to the hash value. Quadratic probing is a method with the help of which we can solve the problem of clustering that was discussed above. This method is also known as mid-square method. In this method we look for i2‘th slot in i’th iteration. We always start from the original hash location. If only the location is occupied then we check the other slots."
},
{
"code": null,
"e": 3860,
"s": 3497,
"text": "let hash(x) be the slot index computed using hash function. \nIf slot hash(x) % S is full, then we try (hash(x) + 1*1) % S\nIf (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S\nIf (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S\n..................................................\n.................................................."
},
{
"code": null,
"e": 4219,
"s": 3860,
"text": "c) Double Hashing The intervals that lie between probes is computed by another hash function. Double hashing is a technique that reduces clustering in an optimized way. In this technique, the increments for the probing sequence are computed by using another hash function. We use another hash function hash2(x) and look for i*hash2(x) slot in i’th rotation. "
},
{
"code": null,
"e": 4617,
"s": 4219,
"text": "let hash(x) be the slot index computed using hash function. \nIf slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S\nIf (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S\nIf (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S\n..................................................\n.................................................."
},
{
"code": null,
"e": 4654,
"s": 4617,
"text": "See this for step by step diagrams. "
},
{
"code": null,
"e": 4682,
"s": 4654,
"text": "Comparison of above three: "
},
{
"code": null,
"e": 4815,
"s": 4682,
"text": "Linear probing has the best cache performance but suffers from clustering. One more advantage of Linear probing is easy to compute. "
},
{
"code": null,
"e": 4901,
"s": 4815,
"text": "Quadratic probing lies between the two in terms of cache performance and clustering. "
},
{
"code": null,
"e": 5052,
"s": 4901,
"text": "Double hashing has poor cache performance but no clustering. Double hashing requires more computation time as two hash functions need to be computed. "
},
{
"code": null,
"e": 5476,
"s": 5052,
"text": "Note: Cache performance of chaining is not good because when we traverse a Linked List, we are basically jumping from one node to another, all across the computer’s memory. For this reason, the CPU cannot cache the nodes which aren’t visited yet, this doesn’t help us. But with Open Addressing, data isn’t spread, so if the CPU detects that a segment of memory is constantly being accessed, it gets cached for quick access."
},
{
"code": null,
"e": 5684,
"s": 5476,
"text": "Performance of Open Addressing: Like Chaining, the performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of the table (simple uniform hashing) "
},
{
"code": null,
"e": 5909,
"s": 5684,
"text": "m = Number of slots in the hash table\nn = Number of keys to be inserted in the hash table\n \nLoad factor α = n/m ( < 1 )\n\nExpected time to search/insert/delete < 1/(1 - α) \n\nSo Search, Insert and Delete take (1/(1 - α)) time"
},
{
"code": null,
"e": 5921,
"s": 5909,
"text": "PulkitGoel2"
},
{
"code": null,
"e": 5935,
"s": 5921,
"text": "shubham_singh"
},
{
"code": null,
"e": 5952,
"s": 5935,
"text": "himanshu_shekhar"
},
{
"code": null,
"e": 5967,
"s": 5952,
"text": "mrunknowncoder"
},
{
"code": null,
"e": 5981,
"s": 5967,
"text": "mallikabachan"
},
{
"code": null,
"e": 5990,
"s": 5981,
"text": "dfheintz"
},
{
"code": null,
"e": 6004,
"s": 5990,
"text": "ohaddiscretix"
},
{
"code": null,
"e": 6022,
"s": 6004,
"text": "ishikapaliwal2001"
},
{
"code": null,
"e": 6036,
"s": 6022,
"text": "harshmandalgi"
},
{
"code": null,
"e": 6050,
"s": 6036,
"text": "shreyasnaphad"
},
{
"code": null,
"e": 6067,
"s": 6050,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6072,
"s": 6067,
"text": "Hash"
},
{
"code": null,
"e": 6077,
"s": 6072,
"text": "Hash"
},
{
"code": null,
"e": 6175,
"s": 6077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6213,
"s": 6175,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6298,
"s": 6213,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6334,
"s": 6298,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 6366,
"s": 6334,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 6393,
"s": 6366,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 6432,
"s": 6393,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 6458,
"s": 6432,
"text": "Sort string of characters"
},
{
"code": null,
"e": 6492,
"s": 6458,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 6573,
"s": 6492,
"text": "Find the smallest window in a string containing all characters of another string"
}
] |
Deploy a Python Visualization Panel App to Google Cloud App Engine | by Sophia Yang | Towards Data Science | Related article: Python Visualization Panel App to Google Cloud Run: Google Cloud Run, Google Cloud Build, and Terraform
Is it possible to deploy a Python app or dashboard to the cloud without knowing anything about Docker or Kubernetes and without using a Dockerfile? Yes, it is possible and it is surprisingly simple using the Google Cloud App Engine! This article will walk you through how to deploy a Panel app to Google Cloud with only three short scripts and show how to automate your workflow with Github Actions.
Here is what my very simple example app looks like. It is hosted here (I will keep it live for 3 months). For more examples and inspirations on Panel apps, check out awesome-panel.org, panel.holoviz.org, and my previous blog post on HoloViz tools.
All the code mentioned in this article is available at this repo: https://github.com/sophiamyang/panel_gcp.
The App Engine documentation (https://cloud.google.com/appengine/docs/standard/python3/quickstart) describes the four steps you need to take to enable running a project:
Select or create a Google Cloud Project (which we will assume the project name and ID are both “your-project”)
Enable App Engine API
Enable Cloud Build API
Enable Billing
Install Google Cloud SDK: The instructions differ by operating system, or you can simply do
conda install -c conda-forge google-cloud-sdk
Initialize gcloud: gcloud init
Set project to “your-project” (or whatever name/ID you used for yours):
gcloud config set project your-project
Make a new directory and either create the following three files in this directory or get them from my repo: https://github.com/sophiamyang/panel_gcp
This is the Python file that creates the Panel App. To run this app locally, you can simply do conda install panel hvplot and runpanel serve app.py
This file lists all the package dependencies of our Panel app.
This is the App Engine configuration file. Panel apps are a type of Bokeh app, and Bokeh apps need env:flex and entrypoint: panel serve app.py --adddress 0.0.0.0 --port 8080 --allow-websocket-origin="*" specified because the App Engine Flexible Environment supports WebSockets. Other types of apps may not need the flex environment and entrypoint.
Initialize your App Engine app: gcloud app create
Deploy your app: gcloud app deploy
After gcloud works hard to set up your project for a few minutes, you should be able to see your dashboard live on your-project.ue.r.appspot.com.
That’s it! You can now share that URL with anyone you want to use your app.If there are any issues with your deployment, it might be helpful to check the logs and debug: https://console.cloud.google.com/debug
To check the overall info: https://console.cloud.google.com/appengine
To see the versions: https://console.cloud.google.com/appengine/versions
In practice, as you develop and improve your Panel application, you’ll often want to redeploy different versions of it over time while keeping a record of each version of your files. To streamline this process, you might find Github Actions quite useful. With Github Actions, we can set up a workflow that whenever we push changes, tag releases, or get a PR, some build, test, or deployment processes will run.
First, we need to follow the steps on these docs to create a service account, add a key to your service account, and download the key in a JSON file.
Enable App Engine Admin API
Now if you haven’t done this already, create a new Github repo and add all the three files in section 3 to this repo and push it to Github.
Go to your Github repo — Settings — Secrets and add two secrets
GCP_CREDENTIALS: copy and paste the key from the JSON file you just downloaded
GCP_PROJECT: the name of your project, which would be “your-project” in the example above.
Add a .github/workflows/python-app.yml file in your directory
This is a Github Actions configuration file. In this example, we deploy the app to Google Cloud App Engine whenever there is a push to the main branch.
Now your Github Actions should be ready to go. You can see the info of the runs on the `Actions` tab. Here I tried to add another app and the workflow automatically starts running.
Now you can see we have two apps running
Overall, this article uses three simple scripts to deploy a visualization Panel app to Google Cloud App Engine and uses another config file to set up Github Actions. You may wonder, why am I not using Google Cloud Run or AWS? I wrote another article on Google Cloud Run. Check it out: Python Visualization Panel App to Google Cloud Run: Google Cloud Run, Google Cloud Build, and Terraform. In terms of AWS, my friends at Anaconda are working on something really cool to help simplify the AWS deployment process, which is scheduled to become available sometime in 2022. Stay tuned!
For those who are interested in a video tutorial, here is the video version of this article:
References:
https://cloud.google.com/appengine/docs/standard/python3/runtime#application_startup
https://cloud.google.com/appengine/docs/flexible/python/quickstart
Acknowledgment: Thank you Jim Bednar and Philipp Rudiger for your support and guidance.
By Sophia Yang on December 18, 2021 | [
{
"code": null,
"e": 293,
"s": 172,
"text": "Related article: Python Visualization Panel App to Google Cloud Run: Google Cloud Run, Google Cloud Build, and Terraform"
},
{
"code": null,
"e": 693,
"s": 293,
"text": "Is it possible to deploy a Python app or dashboard to the cloud without knowing anything about Docker or Kubernetes and without using a Dockerfile? Yes, it is possible and it is surprisingly simple using the Google Cloud App Engine! This article will walk you through how to deploy a Panel app to Google Cloud with only three short scripts and show how to automate your workflow with Github Actions."
},
{
"code": null,
"e": 941,
"s": 693,
"text": "Here is what my very simple example app looks like. It is hosted here (I will keep it live for 3 months). For more examples and inspirations on Panel apps, check out awesome-panel.org, panel.holoviz.org, and my previous blog post on HoloViz tools."
},
{
"code": null,
"e": 1049,
"s": 941,
"text": "All the code mentioned in this article is available at this repo: https://github.com/sophiamyang/panel_gcp."
},
{
"code": null,
"e": 1219,
"s": 1049,
"text": "The App Engine documentation (https://cloud.google.com/appengine/docs/standard/python3/quickstart) describes the four steps you need to take to enable running a project:"
},
{
"code": null,
"e": 1330,
"s": 1219,
"text": "Select or create a Google Cloud Project (which we will assume the project name and ID are both “your-project”)"
},
{
"code": null,
"e": 1352,
"s": 1330,
"text": "Enable App Engine API"
},
{
"code": null,
"e": 1375,
"s": 1352,
"text": "Enable Cloud Build API"
},
{
"code": null,
"e": 1390,
"s": 1375,
"text": "Enable Billing"
},
{
"code": null,
"e": 1482,
"s": 1390,
"text": "Install Google Cloud SDK: The instructions differ by operating system, or you can simply do"
},
{
"code": null,
"e": 1528,
"s": 1482,
"text": "conda install -c conda-forge google-cloud-sdk"
},
{
"code": null,
"e": 1559,
"s": 1528,
"text": "Initialize gcloud: gcloud init"
},
{
"code": null,
"e": 1631,
"s": 1559,
"text": "Set project to “your-project” (or whatever name/ID you used for yours):"
},
{
"code": null,
"e": 1670,
"s": 1631,
"text": "gcloud config set project your-project"
},
{
"code": null,
"e": 1820,
"s": 1670,
"text": "Make a new directory and either create the following three files in this directory or get them from my repo: https://github.com/sophiamyang/panel_gcp"
},
{
"code": null,
"e": 1968,
"s": 1820,
"text": "This is the Python file that creates the Panel App. To run this app locally, you can simply do conda install panel hvplot and runpanel serve app.py"
},
{
"code": null,
"e": 2031,
"s": 1968,
"text": "This file lists all the package dependencies of our Panel app."
},
{
"code": null,
"e": 2379,
"s": 2031,
"text": "This is the App Engine configuration file. Panel apps are a type of Bokeh app, and Bokeh apps need env:flex and entrypoint: panel serve app.py --adddress 0.0.0.0 --port 8080 --allow-websocket-origin=\"*\" specified because the App Engine Flexible Environment supports WebSockets. Other types of apps may not need the flex environment and entrypoint."
},
{
"code": null,
"e": 2429,
"s": 2379,
"text": "Initialize your App Engine app: gcloud app create"
},
{
"code": null,
"e": 2464,
"s": 2429,
"text": "Deploy your app: gcloud app deploy"
},
{
"code": null,
"e": 2610,
"s": 2464,
"text": "After gcloud works hard to set up your project for a few minutes, you should be able to see your dashboard live on your-project.ue.r.appspot.com."
},
{
"code": null,
"e": 2819,
"s": 2610,
"text": "That’s it! You can now share that URL with anyone you want to use your app.If there are any issues with your deployment, it might be helpful to check the logs and debug: https://console.cloud.google.com/debug"
},
{
"code": null,
"e": 2889,
"s": 2819,
"text": "To check the overall info: https://console.cloud.google.com/appengine"
},
{
"code": null,
"e": 2962,
"s": 2889,
"text": "To see the versions: https://console.cloud.google.com/appengine/versions"
},
{
"code": null,
"e": 3373,
"s": 2962,
"text": "In practice, as you develop and improve your Panel application, you’ll often want to redeploy different versions of it over time while keeping a record of each version of your files. To streamline this process, you might find Github Actions quite useful. With Github Actions, we can set up a workflow that whenever we push changes, tag releases, or get a PR, some build, test, or deployment processes will run."
},
{
"code": null,
"e": 3523,
"s": 3373,
"text": "First, we need to follow the steps on these docs to create a service account, add a key to your service account, and download the key in a JSON file."
},
{
"code": null,
"e": 3551,
"s": 3523,
"text": "Enable App Engine Admin API"
},
{
"code": null,
"e": 3691,
"s": 3551,
"text": "Now if you haven’t done this already, create a new Github repo and add all the three files in section 3 to this repo and push it to Github."
},
{
"code": null,
"e": 3755,
"s": 3691,
"text": "Go to your Github repo — Settings — Secrets and add two secrets"
},
{
"code": null,
"e": 3834,
"s": 3755,
"text": "GCP_CREDENTIALS: copy and paste the key from the JSON file you just downloaded"
},
{
"code": null,
"e": 3925,
"s": 3834,
"text": "GCP_PROJECT: the name of your project, which would be “your-project” in the example above."
},
{
"code": null,
"e": 3987,
"s": 3925,
"text": "Add a .github/workflows/python-app.yml file in your directory"
},
{
"code": null,
"e": 4139,
"s": 3987,
"text": "This is a Github Actions configuration file. In this example, we deploy the app to Google Cloud App Engine whenever there is a push to the main branch."
},
{
"code": null,
"e": 4320,
"s": 4139,
"text": "Now your Github Actions should be ready to go. You can see the info of the runs on the `Actions` tab. Here I tried to add another app and the workflow automatically starts running."
},
{
"code": null,
"e": 4361,
"s": 4320,
"text": "Now you can see we have two apps running"
},
{
"code": null,
"e": 4942,
"s": 4361,
"text": "Overall, this article uses three simple scripts to deploy a visualization Panel app to Google Cloud App Engine and uses another config file to set up Github Actions. You may wonder, why am I not using Google Cloud Run or AWS? I wrote another article on Google Cloud Run. Check it out: Python Visualization Panel App to Google Cloud Run: Google Cloud Run, Google Cloud Build, and Terraform. In terms of AWS, my friends at Anaconda are working on something really cool to help simplify the AWS deployment process, which is scheduled to become available sometime in 2022. Stay tuned!"
},
{
"code": null,
"e": 5035,
"s": 4942,
"text": "For those who are interested in a video tutorial, here is the video version of this article:"
},
{
"code": null,
"e": 5047,
"s": 5035,
"text": "References:"
},
{
"code": null,
"e": 5132,
"s": 5047,
"text": "https://cloud.google.com/appengine/docs/standard/python3/runtime#application_startup"
},
{
"code": null,
"e": 5199,
"s": 5132,
"text": "https://cloud.google.com/appengine/docs/flexible/python/quickstart"
},
{
"code": null,
"e": 5287,
"s": 5199,
"text": "Acknowledgment: Thank you Jim Bednar and Philipp Rudiger for your support and guidance."
}
] |
Number of perfect cubes between two given numbers - GeeksforGeeks | 26 Nov, 2021
Given two given numbers a and b where 1<=a<=b, find the number of perfect cubes between a and b (a and b inclusive).Examples:
Input : a = 3, b = 16
Output : 1
The only perfect cube in given range is 8.
Input : a = 7, b = 30
Output : 2
The two cubes in given range are 8,
and 27
Method 1 : One naive approach is to check all the numbers between a and b (inclusive a and b) and increase count by one whenever we encounter a perfect cube.
Below is the implementation of above idea:
CPP
Java
Python3
C#
Javascript
// A Simple Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; // Function to count cubes between two numbersint countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codeint main(){ int a = 7, b = 30; cout << "Count of Cubes is " << countCubes(a, b); return 0;}
// A Simple Method to count cubes between a and b class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codepublic static void main(String[] args){ int a = 7, b = 30; System.out.print("Count of Cubes is " + countCubes(a, b));}} // This code is contributed by 29AjayKumar
# A Simple Method to count cubes between a and b # Function to count cubes between two numbersdef countCubes(a, b): cnt = 0 # Initialize result # Traverse through all numbers for i in range(a,b+1): # Check if current number 'i' is perfect # cube for j in range(i+1): if j*j*j>i: break if j * j * j == i: cnt+=1 return cnt # Driver codeif __name__ == '__main__': a = 7 b = 30 print("Count of Cubes is ",countCubes(a, b)) # This code is contributed by mohit kumar 29
// A Simple Method to count cubes between a and busing System; class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codepublic static void Main(){ int a = 7, b = 30; Console.Write("Count of Cubes is " + countCubes(a, b));}} // This code is contributed by chitranayal
<script>// JavaScript program to count cubes between a and b // Function to count cubes between two numbers function countCubes(a, b) { let cnt = 0; // Initialize result // Traverse through all numbers for (let i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (let j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt; } // Driver code let a = 7, b = 30; document.write("Count of Cubes is " + countCubes(a, b)); // This code is contributed by Surbhi Tyagi </script>
Count of Cubes is 2
Time Complexity: O((b – a)4/3)
Auxiliary Space: O(1)
Method 2 (Efficient): We can simply take cube root of ‘a’ and cube root of ‘b’ and Round cube root of ‘a’ up and cube root of ‘b’ down and count the perfect cubes between them using:
(floor(cbrt(b)) - ceil(cbrt(a)) + 1)
We take floor of cbrt(b) because we need to consider
numbers before b.
We take ceil of cbrt(a) because we need to consider
numbers after a.
For example, let b = 28, a = 7. floor(cbrt(b)) = 3,
ceil(cbrt(a)) = 2. And number of cubes is 3 - 2 + 1
= 2. The two numbers are 8 and 27.
Below is the implementation of above idea :
C++
Java
Python3
C#
Javascript
// An Efficient Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; // Function to count cubes between two numbersint countCubes(int a, int b){ return (floor(cbrt(b)) - ceil(cbrt(a)) + 1);} // Driver codeint main(){ int a = 7, b = 28; cout << "Count of cubes is " << countCubes(a, b); return 0;}
// An Efficient Method to count cubes between a and bclass GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ return (int) (Math.floor(Math.cbrt(b)) - Math.ceil(Math.cbrt(a)) + 1);} // Driver codepublic static void main(String[] args){ int a = 7, b = 28; System.out.print("Count of cubes is " + countCubes(a, b));}} // This code is contributed by 29AjayKumar
# An Efficient Method to count cubes between a and bfrom math import * # Function to count cubes between two numbersdef countCubes(a, b): return (floor(b **(1./3.)) - ceil(a **(1./3.)) + 1) # Driver codea = 7b = 28print("Count of cubes is",countCubes(a, b)) # This code is contributed by shubhamsingh10
// An Efficient Method to count cubes between a and b// C# implementation of the above approachusing System; class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ return (int) (Math.Floor(Math.Cbrt(b)) - Math.Ceiling(Math.Cbrt(a)) + 1);} // Driver codepublic static void Main(string[] args){ int a = 7, b = 28; Console.WriteLine("Count of cubes is " + countCubes(a, b));}} // This code is contributed by Yash_R
<script> // An Efficient Method to count cubes between a and b // Function to count cubes between two numbersfunction countCubes(a, b){ return (Math.floor(b **(1./3.)) - Math.ceil(a **(1./3.)) + 1)} // Driver codelet a = 7;let b = 28;document.write("Count of cubes is "+countCubes(a, b)) // This code is contributed// by pulamolu mohan pavan cse</script>
Count of cubes is 2
Time Complexity: O(Log b).
Auxiliary Space: O(1)
mohit kumar 29
29AjayKumar
ukasp
SHUBHAMSINGH10
Yash_R
surbhityagi15
pulamolusaimohan
simmytarika5
souravmahato348
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Program for Decimal to Binary Conversion
Sieve of Eratosthenes
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number | [
{
"code": null,
"e": 24691,
"s": 24663,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 24819,
"s": 24691,
"text": "Given two given numbers a and b where 1<=a<=b, find the number of perfect cubes between a and b (a and b inclusive).Examples: "
},
{
"code": null,
"e": 24974,
"s": 24819,
"text": "Input : a = 3, b = 16\nOutput : 1\nThe only perfect cube in given range is 8.\n\nInput : a = 7, b = 30\nOutput : 2\nThe two cubes in given range are 8, \nand 27"
},
{
"code": null,
"e": 25136,
"s": 24978,
"text": "Method 1 : One naive approach is to check all the numbers between a and b (inclusive a and b) and increase count by one whenever we encounter a perfect cube."
},
{
"code": null,
"e": 25181,
"s": 25136,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 25185,
"s": 25181,
"text": "CPP"
},
{
"code": null,
"e": 25190,
"s": 25185,
"text": "Java"
},
{
"code": null,
"e": 25198,
"s": 25190,
"text": "Python3"
},
{
"code": null,
"e": 25201,
"s": 25198,
"text": "C#"
},
{
"code": null,
"e": 25212,
"s": 25201,
"text": "Javascript"
},
{
"code": "// A Simple Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; // Function to count cubes between two numbersint countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codeint main(){ int a = 7, b = 30; cout << \"Count of Cubes is \" << countCubes(a, b); return 0;}",
"e": 25789,
"s": 25212,
"text": null
},
{
"code": "// A Simple Method to count cubes between a and b class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codepublic static void main(String[] args){ int a = 7, b = 30; System.out.print(\"Count of Cubes is \" + countCubes(a, b));}} // This code is contributed by 29AjayKumar",
"e": 26413,
"s": 25789,
"text": null
},
{
"code": "# A Simple Method to count cubes between a and b # Function to count cubes between two numbersdef countCubes(a, b): cnt = 0 # Initialize result # Traverse through all numbers for i in range(a,b+1): # Check if current number 'i' is perfect # cube for j in range(i+1): if j*j*j>i: break if j * j * j == i: cnt+=1 return cnt # Driver codeif __name__ == '__main__': a = 7 b = 30 print(\"Count of Cubes is \",countCubes(a, b)) # This code is contributed by mohit kumar 29",
"e": 26980,
"s": 26413,
"text": null
},
{
"code": "// A Simple Method to count cubes between a and busing System; class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ int cnt = 0; // Initialize result // Traverse through all numbers for (int i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (int j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt;} // Driver codepublic static void Main(){ int a = 7, b = 30; Console.Write(\"Count of Cubes is \" + countCubes(a, b));}} // This code is contributed by chitranayal",
"e": 27607,
"s": 26980,
"text": null
},
{
"code": "<script>// JavaScript program to count cubes between a and b // Function to count cubes between two numbers function countCubes(a, b) { let cnt = 0; // Initialize result // Traverse through all numbers for (let i = a; i <= b; i++) // Check if current number 'i' is perfect // cube for (let j = 1; j * j * j <= i; j++) if (j * j * j == i) cnt++; return cnt; } // Driver code let a = 7, b = 30; document.write(\"Count of Cubes is \" + countCubes(a, b)); // This code is contributed by Surbhi Tyagi </script>",
"e": 28243,
"s": 27607,
"text": null
},
{
"code": null,
"e": 28263,
"s": 28243,
"text": "Count of Cubes is 2"
},
{
"code": null,
"e": 28296,
"s": 28265,
"text": "Time Complexity: O((b – a)4/3)"
},
{
"code": null,
"e": 28318,
"s": 28296,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28503,
"s": 28318,
"text": "Method 2 (Efficient): We can simply take cube root of ‘a’ and cube root of ‘b’ and Round cube root of ‘a’ up and cube root of ‘b’ down and count the perfect cubes between them using: "
},
{
"code": null,
"e": 28828,
"s": 28503,
"text": "(floor(cbrt(b)) - ceil(cbrt(a)) + 1)\n\nWe take floor of cbrt(b) because we need to consider \nnumbers before b.\n\nWe take ceil of cbrt(a) because we need to consider \nnumbers after a.\n\n\nFor example, let b = 28, a = 7. floor(cbrt(b)) = 3, \nceil(cbrt(a)) = 2. And number of cubes is 3 - 2 + 1\n= 2. The two numbers are 8 and 27."
},
{
"code": null,
"e": 28873,
"s": 28828,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 28877,
"s": 28873,
"text": "C++"
},
{
"code": null,
"e": 28882,
"s": 28877,
"text": "Java"
},
{
"code": null,
"e": 28890,
"s": 28882,
"text": "Python3"
},
{
"code": null,
"e": 28893,
"s": 28890,
"text": "C#"
},
{
"code": null,
"e": 28904,
"s": 28893,
"text": "Javascript"
},
{
"code": "// An Efficient Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; // Function to count cubes between two numbersint countCubes(int a, int b){ return (floor(cbrt(b)) - ceil(cbrt(a)) + 1);} // Driver codeint main(){ int a = 7, b = 28; cout << \"Count of cubes is \" << countCubes(a, b); return 0;}",
"e": 29250,
"s": 28904,
"text": null
},
{
"code": "// An Efficient Method to count cubes between a and bclass GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ return (int) (Math.floor(Math.cbrt(b)) - Math.ceil(Math.cbrt(a)) + 1);} // Driver codepublic static void main(String[] args){ int a = 7, b = 28; System.out.print(\"Count of cubes is \" + countCubes(a, b));}} // This code is contributed by 29AjayKumar",
"e": 29677,
"s": 29250,
"text": null
},
{
"code": "# An Efficient Method to count cubes between a and bfrom math import * # Function to count cubes between two numbersdef countCubes(a, b): return (floor(b **(1./3.)) - ceil(a **(1./3.)) + 1) # Driver codea = 7b = 28print(\"Count of cubes is\",countCubes(a, b)) # This code is contributed by shubhamsingh10",
"e": 29988,
"s": 29677,
"text": null
},
{
"code": "// An Efficient Method to count cubes between a and b// C# implementation of the above approachusing System; class GFG{ // Function to count cubes between two numbersstatic int countCubes(int a, int b){ return (int) (Math.Floor(Math.Cbrt(b)) - Math.Ceiling(Math.Cbrt(a)) + 1);} // Driver codepublic static void Main(string[] args){ int a = 7, b = 28; Console.WriteLine(\"Count of cubes is \" + countCubes(a, b));}} // This code is contributed by Yash_R",
"e": 30463,
"s": 29988,
"text": null
},
{
"code": "<script> // An Efficient Method to count cubes between a and b // Function to count cubes between two numbersfunction countCubes(a, b){ return (Math.floor(b **(1./3.)) - Math.ceil(a **(1./3.)) + 1)} // Driver codelet a = 7;let b = 28;document.write(\"Count of cubes is \"+countCubes(a, b)) // This code is contributed// by pulamolu mohan pavan cse</script>",
"e": 30826,
"s": 30463,
"text": null
},
{
"code": null,
"e": 30846,
"s": 30826,
"text": "Count of cubes is 2"
},
{
"code": null,
"e": 30875,
"s": 30848,
"text": "Time Complexity: O(Log b)."
},
{
"code": null,
"e": 30898,
"s": 30875,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 30913,
"s": 30898,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30925,
"s": 30913,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30931,
"s": 30925,
"text": "ukasp"
},
{
"code": null,
"e": 30946,
"s": 30931,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 30953,
"s": 30946,
"text": "Yash_R"
},
{
"code": null,
"e": 30967,
"s": 30953,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30984,
"s": 30967,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 30997,
"s": 30984,
"text": "simmytarika5"
},
{
"code": null,
"e": 31013,
"s": 30997,
"text": "souravmahato348"
},
{
"code": null,
"e": 31026,
"s": 31013,
"text": "Mathematical"
},
{
"code": null,
"e": 31039,
"s": 31026,
"text": "Mathematical"
},
{
"code": null,
"e": 31137,
"s": 31039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31146,
"s": 31137,
"text": "Comments"
},
{
"code": null,
"e": 31159,
"s": 31146,
"text": "Old Comments"
},
{
"code": null,
"e": 31183,
"s": 31159,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31226,
"s": 31183,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31240,
"s": 31226,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31282,
"s": 31240,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31323,
"s": 31282,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31345,
"s": 31323,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 31390,
"s": 31345,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 31439,
"s": 31390,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31482,
"s": 31439,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Count of substrings having all distinct characters - GeeksforGeeks | 14 Jan, 2022
Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples:
Input: Str = “gffg” Output: 6 Explanation: All possible substrings from the given string are, ( “g“, “gf“, “gff”, “gffg”, “f“, “ff”, “ffg”, “f“, “fg“, “g” ) Among them, the highlighted ones consists of distinct characters only.
Input: str = “gfg” Output: 5 Explanation: All possible substrings from the given string are, ( “g“, “gf“, “gfg”, “f“, “fg“, “g” ) Among them, the highlighted consists of distinct characters only.
Naive Approach: The simplest approach is to generate all possible substrings from the given string and check for each substring whether it contains all distinct characters or not. If the length of string is N, then there will be N*(N+1)/2 possible substrings.
Time complexity: O(N3) Auxiliary Space: O(1)
Efficient Approach: The problem can be solved in linear time using Two Pointer Technique, with the help of counting frequencies of characters of the string.
Detailed steps for this approach are as follows:
Consider two pointers i and j, initially both pointing to the first character of the string i.e. i = j = 0.
Initialize an array Cnt[ ] to store the count of characters in substring from index i to j both inclusive.
Now, keep on incrementing j pointer until some a repeated character is encountered. While incrementing j, add the count of all the substrings ending at jth index and starting at any index between i and j to the answer. All these substrings will contain distinct characters as no character is repeated in them.
If some repeated character is encountered in substring between index i to j, to exclude this repeated character, keep on incrementing the i pointer until repeated character is removed and keep updating Cnt[ ] array accordingly.
Continue this process until j reaches the end of string. Once the string is traversed completely, print the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count total// number of valid substringslong long int countSub(string str){ int n = (int)str.size(); // Stores the count of // substrings long long int ans = 0; // Stores the frequency // of characters int cnt[26]; memset(cnt, 0, sizeof(cnt)); // Initialised both pointers // to beginning of the string int i = 0, j = 0; while (i < n) { // If all characters in // substring from index i // to j are distinct if (j < n && (cnt[str[j] - 'a'] == 0)) { // Increment count of j-th // character cnt[str[j] - 'a']++; // Add all substring ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i] - 'a']--; // Increment first pointer i++; } } // Return the final // count of substrings return ans;} // Driver Codeint main(){ string str = "gffg"; cout << countSub(str); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count total// number of valid subStringsstatic int countSub(String str){ int n = (int)str.length(); // Stores the count of // subStrings int ans = 0; // Stores the frequency // of characters int []cnt = new int[26]; // Initialised both pointers // to beginning of the String int i = 0, j = 0; while (i < n) { // If all characters in // subString from index i // to j are distinct if (j < n && (cnt[str.charAt(j) - 'a'] == 0)) { // Increment count of j-th // character cnt[str.charAt(j) - 'a']++; // Add all subString ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str.charAt(i) - 'a']--; // Increment first pointer i++; } } // Return the final // count of subStrings return ans;} // Driver Codepublic static void main(String[] args){ String str = "gffg"; System.out.print(countSub(str));}} // This code is contributed by amal kumar choubey
# Python3 program to implement# the above approach # Function to count total# number of valid substringsdef countSub(Str): n = len(Str) # Stores the count of # substrings ans = 0 # Stores the frequency # of characters cnt = 26 * [0] # Initialised both pointers # to beginning of the string i, j = 0, 0 while (i < n): # If all characters in # substring from index i # to j are distinct if (j < n and (cnt[ord(Str[j]) - ord('a')] == 0)): # Increment count of j-th # character cnt[ord(Str[j]) - ord('a')] += 1 # Add all substring ending # at j and starting at any # index between i and j # to the answer ans += (j - i + 1) # Increment 2nd pointer j += 1 # If some characters are repeated # or j pointer has reached to end else: # Decrement count of j-th # character cnt[ord(Str[i]) - ord('a')] -= 1 # Increment first pointer i += 1 # Return the final # count of substrings return ans # Driver codeStr = "gffg" print(countSub(Str)) # This code is contributed by divyeshrabadiya07
// C# program to implement// the above approachusing System; class GFG{ // Function to count total// number of valid subStringsstatic int countSub(String str){ int n = (int)str.Length; // Stores the count of // subStrings int ans = 0; // Stores the frequency // of characters int []cnt = new int[26]; // Initialised both pointers // to beginning of the String int i = 0, j = 0; while (i < n) { // If all characters in // subString from index i // to j are distinct if (j < n && (cnt[str[j] - 'a'] == 0)) { // Increment count of j-th // character cnt[str[j] - 'a']++; // Add all subString ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i] - 'a']--; // Increment first pointer i++; } } // Return the final // count of subStrings return ans;} // Driver Codepublic static void Main(String[] args){ String str = "gffg"; Console.Write(countSub(str));}} // This code is contributed by amal kumar choubey
<script> // JavaScript Program to implement// the above approach // Function to count total// number of valid substringsfunction countSub(str){ var n = str.length; // Stores the count of // substrings var ans = 0; // Stores the frequency // of characters var cnt = Array(26).fill(0); // Initialised both pointers // to beginning of the string var i = 0, j = 0; while (i < n) { // If all characters in // substring from index i // to j are distinct if (j < n && (cnt[str[j].charCodeAt(0) - 'a'.charCodeAt(0)] == 0)) { // Increment count of j-th // character cnt[str[j].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Add all substring ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; // Increment first pointer i++; } } // Return the final // count of substrings return ans;} // Driver Codevar str = "gffg";document.write( countSub(str)); </script>
6
Time complexity: O(N) Auxiliary Space: O(1)
Amal Kumar Choubey
divyeshrabadiya07
noob2000
sumitgumber28
frequency-counting
substring
two-pointer-algorithm
Searching
Strings
two-pointer-algorithm
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find largest element in an array
Search an element in a sorted and rotated array
Given an array of size n and a number k, find all elements that appear more than n/k times
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 25508,
"s": 25480,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 25696,
"s": 25508,
"text": "Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: "
},
{
"code": null,
"e": 25924,
"s": 25696,
"text": "Input: Str = “gffg” Output: 6 Explanation: All possible substrings from the given string are, ( “g“, “gf“, “gff”, “gffg”, “f“, “ff”, “ffg”, “f“, “fg“, “g” ) Among them, the highlighted ones consists of distinct characters only."
},
{
"code": null,
"e": 26122,
"s": 25924,
"text": "Input: str = “gfg” Output: 5 Explanation: All possible substrings from the given string are, ( “g“, “gf“, “gfg”, “f“, “fg“, “g” ) Among them, the highlighted consists of distinct characters only. "
},
{
"code": null,
"e": 26383,
"s": 26122,
"text": "Naive Approach: The simplest approach is to generate all possible substrings from the given string and check for each substring whether it contains all distinct characters or not. If the length of string is N, then there will be N*(N+1)/2 possible substrings. "
},
{
"code": null,
"e": 26428,
"s": 26383,
"text": "Time complexity: O(N3) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26585,
"s": 26428,
"text": "Efficient Approach: The problem can be solved in linear time using Two Pointer Technique, with the help of counting frequencies of characters of the string."
},
{
"code": null,
"e": 26635,
"s": 26585,
"text": "Detailed steps for this approach are as follows: "
},
{
"code": null,
"e": 26743,
"s": 26635,
"text": "Consider two pointers i and j, initially both pointing to the first character of the string i.e. i = j = 0."
},
{
"code": null,
"e": 26850,
"s": 26743,
"text": "Initialize an array Cnt[ ] to store the count of characters in substring from index i to j both inclusive."
},
{
"code": null,
"e": 27160,
"s": 26850,
"text": "Now, keep on incrementing j pointer until some a repeated character is encountered. While incrementing j, add the count of all the substrings ending at jth index and starting at any index between i and j to the answer. All these substrings will contain distinct characters as no character is repeated in them."
},
{
"code": null,
"e": 27388,
"s": 27160,
"text": "If some repeated character is encountered in substring between index i to j, to exclude this repeated character, keep on incrementing the i pointer until repeated character is removed and keep updating Cnt[ ] array accordingly."
},
{
"code": null,
"e": 27504,
"s": 27388,
"text": "Continue this process until j reaches the end of string. Once the string is traversed completely, print the answer."
},
{
"code": null,
"e": 27556,
"s": 27504,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27560,
"s": 27556,
"text": "C++"
},
{
"code": null,
"e": 27565,
"s": 27560,
"text": "Java"
},
{
"code": null,
"e": 27573,
"s": 27565,
"text": "Python3"
},
{
"code": null,
"e": 27576,
"s": 27573,
"text": "C#"
},
{
"code": null,
"e": 27587,
"s": 27576,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count total// number of valid substringslong long int countSub(string str){ int n = (int)str.size(); // Stores the count of // substrings long long int ans = 0; // Stores the frequency // of characters int cnt[26]; memset(cnt, 0, sizeof(cnt)); // Initialised both pointers // to beginning of the string int i = 0, j = 0; while (i < n) { // If all characters in // substring from index i // to j are distinct if (j < n && (cnt[str[j] - 'a'] == 0)) { // Increment count of j-th // character cnt[str[j] - 'a']++; // Add all substring ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i] - 'a']--; // Increment first pointer i++; } } // Return the final // count of substrings return ans;} // Driver Codeint main(){ string str = \"gffg\"; cout << countSub(str); return 0;}",
"e": 28987,
"s": 27587,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count total// number of valid subStringsstatic int countSub(String str){ int n = (int)str.length(); // Stores the count of // subStrings int ans = 0; // Stores the frequency // of characters int []cnt = new int[26]; // Initialised both pointers // to beginning of the String int i = 0, j = 0; while (i < n) { // If all characters in // subString from index i // to j are distinct if (j < n && (cnt[str.charAt(j) - 'a'] == 0)) { // Increment count of j-th // character cnt[str.charAt(j) - 'a']++; // Add all subString ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str.charAt(i) - 'a']--; // Increment first pointer i++; } } // Return the final // count of subStrings return ans;} // Driver Codepublic static void main(String[] args){ String str = \"gffg\"; System.out.print(countSub(str));}} // This code is contributed by amal kumar choubey",
"e": 30444,
"s": 28987,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to count total# number of valid substringsdef countSub(Str): n = len(Str) # Stores the count of # substrings ans = 0 # Stores the frequency # of characters cnt = 26 * [0] # Initialised both pointers # to beginning of the string i, j = 0, 0 while (i < n): # If all characters in # substring from index i # to j are distinct if (j < n and (cnt[ord(Str[j]) - ord('a')] == 0)): # Increment count of j-th # character cnt[ord(Str[j]) - ord('a')] += 1 # Add all substring ending # at j and starting at any # index between i and j # to the answer ans += (j - i + 1) # Increment 2nd pointer j += 1 # If some characters are repeated # or j pointer has reached to end else: # Decrement count of j-th # character cnt[ord(Str[i]) - ord('a')] -= 1 # Increment first pointer i += 1 # Return the final # count of substrings return ans # Driver codeStr = \"gffg\" print(countSub(Str)) # This code is contributed by divyeshrabadiya07",
"e": 31699,
"s": 30444,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to count total// number of valid subStringsstatic int countSub(String str){ int n = (int)str.Length; // Stores the count of // subStrings int ans = 0; // Stores the frequency // of characters int []cnt = new int[26]; // Initialised both pointers // to beginning of the String int i = 0, j = 0; while (i < n) { // If all characters in // subString from index i // to j are distinct if (j < n && (cnt[str[j] - 'a'] == 0)) { // Increment count of j-th // character cnt[str[j] - 'a']++; // Add all subString ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i] - 'a']--; // Increment first pointer i++; } } // Return the final // count of subStrings return ans;} // Driver Codepublic static void Main(String[] args){ String str = \"gffg\"; Console.Write(countSub(str));}} // This code is contributed by amal kumar choubey",
"e": 33122,
"s": 31699,
"text": null
},
{
"code": "<script> // JavaScript Program to implement// the above approach // Function to count total// number of valid substringsfunction countSub(str){ var n = str.length; // Stores the count of // substrings var ans = 0; // Stores the frequency // of characters var cnt = Array(26).fill(0); // Initialised both pointers // to beginning of the string var i = 0, j = 0; while (i < n) { // If all characters in // substring from index i // to j are distinct if (j < n && (cnt[str[j].charCodeAt(0) - 'a'.charCodeAt(0)] == 0)) { // Increment count of j-th // character cnt[str[j].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Add all substring ending // at j and starting at any // index between i and j // to the answer ans += (j - i + 1); // Increment 2nd pointer j++; } // If some characters are repeated // or j pointer has reached to end else { // Decrement count of j-th // character cnt[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; // Increment first pointer i++; } } // Return the final // count of substrings return ans;} // Driver Codevar str = \"gffg\";document.write( countSub(str)); </script>",
"e": 34515,
"s": 33122,
"text": null
},
{
"code": null,
"e": 34517,
"s": 34515,
"text": "6"
},
{
"code": null,
"e": 34564,
"s": 34519,
"text": "Time complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 34583,
"s": 34564,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 34601,
"s": 34583,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34610,
"s": 34601,
"text": "noob2000"
},
{
"code": null,
"e": 34624,
"s": 34610,
"text": "sumitgumber28"
},
{
"code": null,
"e": 34643,
"s": 34624,
"text": "frequency-counting"
},
{
"code": null,
"e": 34653,
"s": 34643,
"text": "substring"
},
{
"code": null,
"e": 34675,
"s": 34653,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 34685,
"s": 34675,
"text": "Searching"
},
{
"code": null,
"e": 34693,
"s": 34685,
"text": "Strings"
},
{
"code": null,
"e": 34715,
"s": 34693,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 34725,
"s": 34715,
"text": "Searching"
},
{
"code": null,
"e": 34733,
"s": 34725,
"text": "Strings"
},
{
"code": null,
"e": 34831,
"s": 34733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34875,
"s": 34831,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 34923,
"s": 34875,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 35014,
"s": 34923,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 35058,
"s": 35014,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 35105,
"s": 35058,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 35151,
"s": 35105,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35176,
"s": 35151,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35210,
"s": 35176,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35270,
"s": 35210,
"text": "Write a program to print all permutations of a given string"
}
] |
Modern Web Automation With Python and Selenium | We can have modern web automation with Python and Selenium. To configure with Selenium webdriver in Python the steps described below need to be followed −
Step1 −To install Python in our system, visit the link − https://www.python.org/downloads/
Step 2 − Click on the Download Python <version number> button. Once the download is completed, the Python executable file should be available in our system.
Step 3 − Double-click on this executable file and the Python installation landing page should be opened. Click on Install Now.
Step 4 − Python should be available in the below path −
C:\Users\<User>\AppData\Local\Programs\Python\Python<version>
Step 5 − We shall configure the path of the folders - Python and Scripts (introduced within the Python folder) in the Environment variables for the Windows users.
Step 6 − To verify, Python has been installed, run the command: python --version.
The Python version should get displayed.
Step 7 − Selenium bindings installation can be done by executing the command: pip install selenium.
Step 8 − A folder called Selenium should be found within the Python folder. To update the Selenium existing version, run the command: pip install –U selenium.
Step 9 − Finally, we should also have a Python editor - PyCharm to create the Selenium scripts((https://www.jetbrains.com/pycharm/).
Step 10 − To launch the Selenium script in a browser, we also need to download the browser drivers. For this, visit the below link − https://www.selenium.dev/downloads/
Step 11 − Scroll down to the Browser section and to download the browser drivers for different browsers.
Code Implementation
from selenium import webdriver
#configure chromedriver path
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.tutorialspoint.com/questions/index.php")
print('Page title: ' + driver.title)
#browser close
driver.close() | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "We can have modern web automation with Python and Selenium. To configure with Selenium webdriver in Python the steps described below need to be followed −"
},
{
"code": null,
"e": 1308,
"s": 1217,
"text": "Step1 −To install Python in our system, visit the link − https://www.python.org/downloads/"
},
{
"code": null,
"e": 1465,
"s": 1308,
"text": "Step 2 − Click on the Download Python <version number> button. Once the download is completed, the Python executable file should be available in our system."
},
{
"code": null,
"e": 1592,
"s": 1465,
"text": "Step 3 − Double-click on this executable file and the Python installation landing page should be opened. Click on Install Now."
},
{
"code": null,
"e": 1648,
"s": 1592,
"text": "Step 4 − Python should be available in the below path −"
},
{
"code": null,
"e": 1710,
"s": 1648,
"text": "C:\\Users\\<User>\\AppData\\Local\\Programs\\Python\\Python<version>"
},
{
"code": null,
"e": 1873,
"s": 1710,
"text": "Step 5 − We shall configure the path of the folders - Python and Scripts (introduced within the Python folder) in the Environment variables for the Windows users."
},
{
"code": null,
"e": 1996,
"s": 1873,
"text": "Step 6 − To verify, Python has been installed, run the command: python --version.\nThe Python version should get displayed."
},
{
"code": null,
"e": 2096,
"s": 1996,
"text": "Step 7 − Selenium bindings installation can be done by executing the command: pip install selenium."
},
{
"code": null,
"e": 2255,
"s": 2096,
"text": "Step 8 − A folder called Selenium should be found within the Python folder. To update the Selenium existing version, run the command: pip install –U selenium."
},
{
"code": null,
"e": 2388,
"s": 2255,
"text": "Step 9 − Finally, we should also have a Python editor - PyCharm to create the Selenium scripts((https://www.jetbrains.com/pycharm/)."
},
{
"code": null,
"e": 2557,
"s": 2388,
"text": "Step 10 − To launch the Selenium script in a browser, we also need to download the browser drivers. For this, visit the below link − https://www.selenium.dev/downloads/"
},
{
"code": null,
"e": 2662,
"s": 2557,
"text": "Step 11 − Scroll down to the Browser section and to download the browser drivers for different browsers."
},
{
"code": null,
"e": 2682,
"s": 2662,
"text": "Code Implementation"
},
{
"code": null,
"e": 2998,
"s": 2682,
"text": "from selenium import webdriver\n#configure chromedriver path\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait\ndriver.implicitly_wait(0.5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/questions/index.php\")\nprint('Page title: ' + driver.title)\n#browser close\ndriver.close()"
}
] |
How can I insert a value in a column at the place of NULL using MySQL COALESCE() function? | To understand it, we are using the data from the table ‘Employee’ having Salary=NULL for ID = 5 and 6, as follows −
mysql> Select * from Employee;
+----+--------+--------+
| ID | Name | Salary |
+----+--------+--------+
| 1 | Gaurav | 50000 |
| 2 | Rahul | 20000 |
| 3 | Advik | 25000 |
| 4 | Aarav | 65000 |
| 5 | Ram | NULL |
| 6 | Mohan | NULL |
+----+--------+--------+
6 rows in set (0.00 sec)
Now, the following queries will use COALESCE() function along with UPDATE and WHERE clause to put values at the place of NULL.
mysql> Update Employee set Salary = COALESCE(Salary,20000) where Id = 5;
Query OK, 1 row affected (0.09 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> Update Employee set Salary = COALESCE(Salary,30000) where Id = 6;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> Select * from Employee;
+----+--------+--------+
| ID | Name | Salary |
+----+--------+--------+
| 1 | Gaurav | 50000 |
| 2 | Rahul | 20000 |
| 3 | Advik | 25000 |
| 4 | Aarav | 65000 |
| 5 | Ram | 20000 |
| 6 | Mohan | 30000 |
+----+--------+--------+
6 rows in set (0.00 sec) | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "To understand it, we are using the data from the table ‘Employee’ having Salary=NULL for ID = 5 and 6, as follows −"
},
{
"code": null,
"e": 1484,
"s": 1178,
"text": "mysql> Select * from Employee;\n+----+--------+--------+\n| ID | Name | Salary |\n+----+--------+--------+\n| 1 | Gaurav | 50000 |\n| 2 | Rahul | 20000 |\n| 3 | Advik | 25000 |\n| 4 | Aarav | 65000 |\n| 5 | Ram | NULL |\n| 6 | Mohan | NULL |\n+----+--------+--------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1611,
"s": 1484,
"text": "Now, the following queries will use COALESCE() function along with UPDATE and WHERE clause to put values at the place of NULL."
},
{
"code": null,
"e": 2215,
"s": 1611,
"text": "mysql> Update Employee set Salary = COALESCE(Salary,20000) where Id = 5;\nQuery OK, 1 row affected (0.09 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> Update Employee set Salary = COALESCE(Salary,30000) where Id = 6;\nQuery OK, 1 row affected (0.06 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> Select * from Employee;\n+----+--------+--------+\n| ID | Name | Salary |\n+----+--------+--------+\n| 1 | Gaurav | 50000 |\n| 2 | Rahul | 20000 |\n| 3 | Advik | 25000 |\n| 4 | Aarav | 65000 |\n| 5 | Ram | 20000 |\n| 6 | Mohan | 30000 |\n+----+--------+--------+\n6 rows in set (0.00 sec)"
}
] |
Compressing Time Series with Pandas | by Gautier Dagan | Towards Data Science | So you’ve done it, you’ve got a nice time series with helpful features in a pandasDataFrame. Maybe you’ve used pd.ffill()or pd.bfill() to fill in empty time steps using the previous or next value and perform analysis or feature extraction on your full series.
What do you do?
We faced this problem today at Mansa, where we were saving hundreds (if not thousands) of unnecessary rows after our pre-processing pipeline was completed.
Since we deal with financial data, we want to be able to tell the balance for an account at any point in time and to calculate statistics over number of days and through time. As a result, our pre-processing includes a step to resample our working DataFrame in order to fill all dates with missing information. The issue here was that we were saving this filled-in DataFrame with the resampled dates and filled-in values instead of compressing it back.
TL;DR: Skip to the end gist for the most efficient way!
To proxy our real data, I’ve made this simple example generator that will spit out a filled up time-series. The date column here is the column of daily timestamps that will be generated and filled to be complete (through resampling).
As a simple example, assume we have a user with an account that dates back to early 2018. This user uses it as a secondary account, and so only has a transaction every two days or so. Over three years, they only have 500 days where the balance actually changes.
Say that in order to plot or analyse their balance over time we want to know it at the end of day mark, and so have to expand back the series of 500 observations to the full three years (resampling). Since balance remains in the account until it is observed to change, then we can fill the values of the days after an observation with the balance of that observation, until the next observation(ffill).
So if I had a 5€ balance on Thursday night and 500€ on Sunday night, then I know that I also had 5€ on Friday night and Saturday night, since observations only happen when there is a change in the balance.
With about 500 random observations in three years, if we resample the dates to get the full daily DataFrame, we will get from 500 rows to around ~1k (365*3).
Why not simply remove duplicates?
Because if a day has the same balance as another day occurring much later, a naive drop_duplicates will ignore the temporal dimensionality of your data.
Depending on how small are your time steps and how sparse are your observations, you can have a lot of repeated or empty rows in your DataFrame.
First naive solution:
First naive solution:
My first approach was to simply iterate over the sorted DataFrame to detect whenever a row is different to a previous one (ignoring the time step column).
In this case, I simply iterate over the rows in the DataFrame and find all indexes where a change happens between the time step i and i-1.
This works, but iterrows is not fast.
Timing the block of code with %%timeit and my small generated DataFrame I get:
2.39 s ± 794 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
We can do better!
2. Taking a stab at using reduce :
Ok so iterrows is slow, what can we do to make it faster. My second thought was to work directly with the numpy values array and use reduce from the standard library in order to efficiently go over two rows at a time.
I first find the column indexes to compare (again ignoring the time step column “date”) and then have a reduce function that appends a row if it is different from a previous one.
We can then create a DataFrame back with the new values.
This was already much faster (100x improvement)!
20.4 ms ± 6.26 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
But can we make it better?
3. Back to pandas:
The next big realization I had was that since I only cared about the previous time step, I could simply shift the entire table to compare all values simultaneously!
This simplifies the code greatly. I still only want to compare all columns excluding “date”, so I shift the selection of columns by one and compare to the original. With ~(...).all(axis=1) I can compare the two row wise in order to select the rows in the original df that are not the same as the previous row.
This is even faster (not a surprise since we are not iterating through anymore)! This is 4x faster than using the reduce approach and 400x faster than the naive iterrows !
4.61 ms ± 319 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
It also has the benefit of fitting on 2 lines of code!
4. To go even faster we can implement this in numpy:
This does the same as the pandas shift essentially.
We construct the shift by using the np.roll function and setting the first element as nan. Again, we compare all values against the shifted array row wise.
This is again faster!
973 μs ± 29 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Nearly 5 times faster than the previous approach and 2000x faster than the naive approach!
Note: For all of the solutions the DataFrame was assumed to be sorted by the time step (in this case “date”) column. These solutions would not work otherwise.
Avoid iterrows , use shift .
In the end I’ve opted for solution #3 and not the most performant since it is less lines of code and probably clearer to understand. Sometimes the simplicity of a solution is more important than its performance gains.
I am sure we could push the performance even more and I challenge you, the reader, to try it!
I hope that you learned something or that this has helped you tackle a similar problem. This is my first blog entry so apologies if a bit unstructured, I’d really appreciate any feedback and if you think you have a different way of doing this don’t hesitate let me know! | [
{
"code": null,
"e": 431,
"s": 171,
"text": "So you’ve done it, you’ve got a nice time series with helpful features in a pandasDataFrame. Maybe you’ve used pd.ffill()or pd.bfill() to fill in empty time steps using the previous or next value and perform analysis or feature extraction on your full series."
},
{
"code": null,
"e": 447,
"s": 431,
"text": "What do you do?"
},
{
"code": null,
"e": 603,
"s": 447,
"text": "We faced this problem today at Mansa, where we were saving hundreds (if not thousands) of unnecessary rows after our pre-processing pipeline was completed."
},
{
"code": null,
"e": 1056,
"s": 603,
"text": "Since we deal with financial data, we want to be able to tell the balance for an account at any point in time and to calculate statistics over number of days and through time. As a result, our pre-processing includes a step to resample our working DataFrame in order to fill all dates with missing information. The issue here was that we were saving this filled-in DataFrame with the resampled dates and filled-in values instead of compressing it back."
},
{
"code": null,
"e": 1112,
"s": 1056,
"text": "TL;DR: Skip to the end gist for the most efficient way!"
},
{
"code": null,
"e": 1346,
"s": 1112,
"text": "To proxy our real data, I’ve made this simple example generator that will spit out a filled up time-series. The date column here is the column of daily timestamps that will be generated and filled to be complete (through resampling)."
},
{
"code": null,
"e": 1608,
"s": 1346,
"text": "As a simple example, assume we have a user with an account that dates back to early 2018. This user uses it as a secondary account, and so only has a transaction every two days or so. Over three years, they only have 500 days where the balance actually changes."
},
{
"code": null,
"e": 2011,
"s": 1608,
"text": "Say that in order to plot or analyse their balance over time we want to know it at the end of day mark, and so have to expand back the series of 500 observations to the full three years (resampling). Since balance remains in the account until it is observed to change, then we can fill the values of the days after an observation with the balance of that observation, until the next observation(ffill)."
},
{
"code": null,
"e": 2217,
"s": 2011,
"text": "So if I had a 5€ balance on Thursday night and 500€ on Sunday night, then I know that I also had 5€ on Friday night and Saturday night, since observations only happen when there is a change in the balance."
},
{
"code": null,
"e": 2375,
"s": 2217,
"text": "With about 500 random observations in three years, if we resample the dates to get the full daily DataFrame, we will get from 500 rows to around ~1k (365*3)."
},
{
"code": null,
"e": 2409,
"s": 2375,
"text": "Why not simply remove duplicates?"
},
{
"code": null,
"e": 2562,
"s": 2409,
"text": "Because if a day has the same balance as another day occurring much later, a naive drop_duplicates will ignore the temporal dimensionality of your data."
},
{
"code": null,
"e": 2707,
"s": 2562,
"text": "Depending on how small are your time steps and how sparse are your observations, you can have a lot of repeated or empty rows in your DataFrame."
},
{
"code": null,
"e": 2729,
"s": 2707,
"text": "First naive solution:"
},
{
"code": null,
"e": 2751,
"s": 2729,
"text": "First naive solution:"
},
{
"code": null,
"e": 2906,
"s": 2751,
"text": "My first approach was to simply iterate over the sorted DataFrame to detect whenever a row is different to a previous one (ignoring the time step column)."
},
{
"code": null,
"e": 3045,
"s": 2906,
"text": "In this case, I simply iterate over the rows in the DataFrame and find all indexes where a change happens between the time step i and i-1."
},
{
"code": null,
"e": 3083,
"s": 3045,
"text": "This works, but iterrows is not fast."
},
{
"code": null,
"e": 3162,
"s": 3083,
"text": "Timing the block of code with %%timeit and my small generated DataFrame I get:"
},
{
"code": null,
"e": 3229,
"s": 3162,
"text": "2.39 s ± 794 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"
},
{
"code": null,
"e": 3247,
"s": 3229,
"text": "We can do better!"
},
{
"code": null,
"e": 3282,
"s": 3247,
"text": "2. Taking a stab at using reduce :"
},
{
"code": null,
"e": 3500,
"s": 3282,
"text": "Ok so iterrows is slow, what can we do to make it faster. My second thought was to work directly with the numpy values array and use reduce from the standard library in order to efficiently go over two rows at a time."
},
{
"code": null,
"e": 3679,
"s": 3500,
"text": "I first find the column indexes to compare (again ignoring the time step column “date”) and then have a reduce function that appends a row if it is different from a previous one."
},
{
"code": null,
"e": 3736,
"s": 3679,
"text": "We can then create a DataFrame back with the new values."
},
{
"code": null,
"e": 3785,
"s": 3736,
"text": "This was already much faster (100x improvement)!"
},
{
"code": null,
"e": 3857,
"s": 3785,
"text": "20.4 ms ± 6.26 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)"
},
{
"code": null,
"e": 3884,
"s": 3857,
"text": "But can we make it better?"
},
{
"code": null,
"e": 3903,
"s": 3884,
"text": "3. Back to pandas:"
},
{
"code": null,
"e": 4068,
"s": 3903,
"text": "The next big realization I had was that since I only cared about the previous time step, I could simply shift the entire table to compare all values simultaneously!"
},
{
"code": null,
"e": 4378,
"s": 4068,
"text": "This simplifies the code greatly. I still only want to compare all columns excluding “date”, so I shift the selection of columns by one and compare to the original. With ~(...).all(axis=1) I can compare the two row wise in order to select the rows in the original df that are not the same as the previous row."
},
{
"code": null,
"e": 4550,
"s": 4378,
"text": "This is even faster (not a surprise since we are not iterating through anymore)! This is 4x faster than using the reduce approach and 400x faster than the naive iterrows !"
},
{
"code": null,
"e": 4621,
"s": 4550,
"text": "4.61 ms ± 319 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)"
},
{
"code": null,
"e": 4676,
"s": 4621,
"text": "It also has the benefit of fitting on 2 lines of code!"
},
{
"code": null,
"e": 4729,
"s": 4676,
"text": "4. To go even faster we can implement this in numpy:"
},
{
"code": null,
"e": 4781,
"s": 4729,
"text": "This does the same as the pandas shift essentially."
},
{
"code": null,
"e": 4937,
"s": 4781,
"text": "We construct the shift by using the np.roll function and setting the first element as nan. Again, we compare all values against the shifted array row wise."
},
{
"code": null,
"e": 4959,
"s": 4937,
"text": "This is again faster!"
},
{
"code": null,
"e": 5029,
"s": 4959,
"text": "973 μs ± 29 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)"
},
{
"code": null,
"e": 5120,
"s": 5029,
"text": "Nearly 5 times faster than the previous approach and 2000x faster than the naive approach!"
},
{
"code": null,
"e": 5279,
"s": 5120,
"text": "Note: For all of the solutions the DataFrame was assumed to be sorted by the time step (in this case “date”) column. These solutions would not work otherwise."
},
{
"code": null,
"e": 5308,
"s": 5279,
"text": "Avoid iterrows , use shift ."
},
{
"code": null,
"e": 5526,
"s": 5308,
"text": "In the end I’ve opted for solution #3 and not the most performant since it is less lines of code and probably clearer to understand. Sometimes the simplicity of a solution is more important than its performance gains."
},
{
"code": null,
"e": 5620,
"s": 5526,
"text": "I am sure we could push the performance even more and I challenge you, the reader, to try it!"
}
] |
How to submit a form using ajax in jQuery ? - GeeksforGeeks | 10 Nov, 2021
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.
The $.ajax() function is used for ajax call using jQuery.
Syntax:
$.ajax({name:value, name:value, ... })
We can submit a form by ajax using submit button and by mentioning the values of the following parameters.
type: It is used to specify the type of request.
url: It is used to specify the URL to send the request to.
data: It is used to specify data to be sent to the server.
Example:
HTML
<!Doctype html><html> <head> <title>JQuery AJAX Call</title> <!--Include JQuery Library --> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script> <script> // When DOM is loaded this // function will get executed $(() => { // function will get executed // on click of submit button $("#submitButton").click(function(ev) { var form = $("#formId"); var url = form.attr('action'); $.ajax({ type: "POST", url: url, data: form.serialize(), success: function(data) { // Ajax call completed successfully alert("Form Submited Successfully"); }, error: function(data) { // Some error in ajax call alert("some Error"); } }); }); }); </script></head> <body> <form id='formId' action=''> Name: <input type='text' id='nm' name='nm'> </input> <br> Student ID: <input type='text' id='studentId' name='studentId'> </input> <br> Contact No. : <input type='text' id='contactNumber' name='contactNumber'> </input> <br> <button type='submit' id='submitButton'> Submit </button> </form></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Questions
jQuery-AJAX
jQuery-Methods
jQuery-Questions
Picked
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ? | [
{
"code": null,
"e": 26226,
"s": 26198,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 26585,
"s": 26226,
"text": "jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development."
},
{
"code": null,
"e": 26643,
"s": 26585,
"text": "The $.ajax() function is used for ajax call using jQuery."
},
{
"code": null,
"e": 26651,
"s": 26643,
"text": "Syntax:"
},
{
"code": null,
"e": 26690,
"s": 26651,
"text": "$.ajax({name:value, name:value, ... })"
},
{
"code": null,
"e": 26797,
"s": 26690,
"text": "We can submit a form by ajax using submit button and by mentioning the values of the following parameters."
},
{
"code": null,
"e": 26846,
"s": 26797,
"text": "type: It is used to specify the type of request."
},
{
"code": null,
"e": 26905,
"s": 26846,
"text": "url: It is used to specify the URL to send the request to."
},
{
"code": null,
"e": 26964,
"s": 26905,
"text": "data: It is used to specify data to be sent to the server."
},
{
"code": null,
"e": 26975,
"s": 26966,
"text": "Example:"
},
{
"code": null,
"e": 26980,
"s": 26975,
"text": "HTML"
},
{
"code": "<!Doctype html><html> <head> <title>JQuery AJAX Call</title> <!--Include JQuery Library --> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script> <script> // When DOM is loaded this // function will get executed $(() => { // function will get executed // on click of submit button $(\"#submitButton\").click(function(ev) { var form = $(\"#formId\"); var url = form.attr('action'); $.ajax({ type: \"POST\", url: url, data: form.serialize(), success: function(data) { // Ajax call completed successfully alert(\"Form Submited Successfully\"); }, error: function(data) { // Some error in ajax call alert(\"some Error\"); } }); }); }); </script></head> <body> <form id='formId' action=''> Name: <input type='text' id='nm' name='nm'> </input> <br> Student ID: <input type='text' id='studentId' name='studentId'> </input> <br> Contact No. : <input type='text' id='contactNumber' name='contactNumber'> </input> <br> <button type='submit' id='submitButton'> Submit </button> </form></body> </html>",
"e": 28517,
"s": 26980,
"text": null
},
{
"code": null,
"e": 28525,
"s": 28517,
"text": "Output:"
},
{
"code": null,
"e": 28662,
"s": 28525,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28677,
"s": 28662,
"text": "HTML-Questions"
},
{
"code": null,
"e": 28689,
"s": 28677,
"text": "jQuery-AJAX"
},
{
"code": null,
"e": 28704,
"s": 28689,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 28721,
"s": 28704,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 28728,
"s": 28721,
"text": "Picked"
},
{
"code": null,
"e": 28733,
"s": 28728,
"text": "HTML"
},
{
"code": null,
"e": 28740,
"s": 28733,
"text": "JQuery"
},
{
"code": null,
"e": 28757,
"s": 28740,
"text": "Web Technologies"
},
{
"code": null,
"e": 28762,
"s": 28757,
"text": "HTML"
},
{
"code": null,
"e": 28860,
"s": 28762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28884,
"s": 28860,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28925,
"s": 28884,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28962,
"s": 28925,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28991,
"s": 28962,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29011,
"s": 28991,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29057,
"s": 29011,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 29086,
"s": 29057,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29149,
"s": 29086,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 29226,
"s": 29149,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Node.js MySQL NULL Values - GeeksforGeeks | 07 Oct, 2021
In this article, will learn to handle NULL values and make Query on the basis of NULL values.
Syntax:
IS NULL;
IS NOT NULL;
Return Value:
‘IS NULL’ returns the row in the column which contains one or more NULL values.
‘IS NOT NULL’ returns the row in the column which does not contains any NULL values.
Module Installation: Install the MySQL module using the following command.
npm install mysql
Database: Our SQL publishers table preview with sample data is shown below.
Example 1:
index.js
const mysql = require("mysql"); let db_con = mysql.createConnection({ host: "localhost", user: "root", password: '', database: 'gfg_db'}); db_con.connect((err) => { if (err) { console.log("Database Connection Failed !!!", err); return; } console.log("We are connected to gfg_db database"); // Here is the query let query = "SELECT * FROM users WHERE address IS NULL"; db_con.query(query, (err, rows) => { if(err) throw err; console.log(rows); });});
Output:
Example 2:
index.js
const mysql = require("mysql"); let db_con = mysql.createConnection({ host: "localhost", user: "root", password: '', database: 'gfg_db'}); db_con.connect((err) => { if (err) { console.log("Database Connection Failed !!!", err); return; } console.log("We are connected to gfg_db database"); // Here is the query let query = "SELECT * FROM users WHERE address IS NOT NULL"; db_con.query(query, (err, rows) => { if(err) throw err; console.log(rows); });});
Output:
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Export Module
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26361,
"s": 26267,
"text": "In this article, will learn to handle NULL values and make Query on the basis of NULL values."
},
{
"code": null,
"e": 26369,
"s": 26361,
"text": "Syntax:"
},
{
"code": null,
"e": 26378,
"s": 26369,
"text": "IS NULL;"
},
{
"code": null,
"e": 26391,
"s": 26378,
"text": "IS NOT NULL;"
},
{
"code": null,
"e": 26405,
"s": 26391,
"text": "Return Value:"
},
{
"code": null,
"e": 26485,
"s": 26405,
"text": "‘IS NULL’ returns the row in the column which contains one or more NULL values."
},
{
"code": null,
"e": 26570,
"s": 26485,
"text": "‘IS NOT NULL’ returns the row in the column which does not contains any NULL values."
},
{
"code": null,
"e": 26645,
"s": 26570,
"text": "Module Installation: Install the MySQL module using the following command."
},
{
"code": null,
"e": 26663,
"s": 26645,
"text": "npm install mysql"
},
{
"code": null,
"e": 26739,
"s": 26663,
"text": "Database: Our SQL publishers table preview with sample data is shown below."
},
{
"code": null,
"e": 26750,
"s": 26739,
"text": "Example 1:"
},
{
"code": null,
"e": 26759,
"s": 26750,
"text": "index.js"
},
{
"code": "const mysql = require(\"mysql\"); let db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: '', database: 'gfg_db'}); db_con.connect((err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); return; } console.log(\"We are connected to gfg_db database\"); // Here is the query let query = \"SELECT * FROM users WHERE address IS NULL\"; db_con.query(query, (err, rows) => { if(err) throw err; console.log(rows); });});",
"e": 27277,
"s": 26759,
"text": null
},
{
"code": null,
"e": 27285,
"s": 27277,
"text": "Output:"
},
{
"code": null,
"e": 27296,
"s": 27285,
"text": "Example 2:"
},
{
"code": null,
"e": 27305,
"s": 27296,
"text": "index.js"
},
{
"code": "const mysql = require(\"mysql\"); let db_con = mysql.createConnection({ host: \"localhost\", user: \"root\", password: '', database: 'gfg_db'}); db_con.connect((err) => { if (err) { console.log(\"Database Connection Failed !!!\", err); return; } console.log(\"We are connected to gfg_db database\"); // Here is the query let query = \"SELECT * FROM users WHERE address IS NOT NULL\"; db_con.query(query, (err, rows) => { if(err) throw err; console.log(rows); });});",
"e": 27827,
"s": 27305,
"text": null
},
{
"code": null,
"e": 27835,
"s": 27827,
"text": "Output:"
},
{
"code": null,
"e": 27848,
"s": 27835,
"text": "NodeJS-MySQL"
},
{
"code": null,
"e": 27872,
"s": 27848,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27880,
"s": 27872,
"text": "Node.js"
},
{
"code": null,
"e": 27899,
"s": 27880,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27916,
"s": 27899,
"text": "Web Technologies"
},
{
"code": null,
"e": 28014,
"s": 27916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28036,
"s": 28014,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 28075,
"s": 28036,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 28145,
"s": 28075,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 28170,
"s": 28145,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 28197,
"s": 28170,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28237,
"s": 28197,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28282,
"s": 28237,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28325,
"s": 28282,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28387,
"s": 28325,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Minimum edge reversals to make a root - GeeksforGeeks | 28 Nov, 2021
Given a directed tree with V vertices and V-1 edges, we need to choose such a root (from given nodes from where we can reach to every other node) with a minimum number of edge reversal.
Examples:
In above tree, if we choose node 3 as our
root then we need to reverse minimum number
of 3 edges to reach every other node,
changed tree is shown on the right side.
We can solve this problem using DFS. we start dfs at any random node of given tree and at each node we store its distance from starting node assuming all edges as undirected and we also store number of edges which need to be reversed in the path from starting node to current node, let’s denote such edges as back edges so back edges are those which point towards the node in a path. With this dfs, we also calculate total number of edge reversals in the tree. After this computation, at each node we can calculate ‘number of edge reversal to reach every other node’ as follows, Let total number of reversals in tree when some node is chosen as starting node for dfs is R then if we want to reach every other node from node i we need to reverse all back edges from path node i to starting node and we also need to reverse all other back edges other than node i to starting node path. First part will be (distance of node i from starting node – back edges count at node i) because we want to reverse edges in path from node i to starting node it will be total edges (i.e. distance) minus back edges from starting node to node i (i.e. back edge count at node i). The second part will be (total edge reversal or total back edges of tree R – back edge count of node i). After calculating this value at each node we will choose minimum of them as our result.
In below code, in the given edge direction weight 0 is added and in reverse direction weight 1 is added which is used to count reversal edges in dfs method.
C++
Java
Python3
C#
Javascript
// C++ program to find min edge reversal to// make every node reachable from root#include <bits/stdc++.h>using namespace std; // method to dfs in tree and populates disRev valuesint dfs(vector< pair<int, int> > g[], pair<int, int> disRev[], bool visit[], int u){ // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g[u].size(); i++) { int v = g[u][i].first; if (!visit[v]) { // distance of v will be one more than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g[u][i].second) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev;} // method prints root and minimum number of edge reversalvoid printMinEdgeReverseForRootNode(int edges[][2], int e){ // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree vector< pair<int, int> > g[V]; // disRev stores two values - distance and back // edge count from root node pair<int, int> disRev[V]; bool visit[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // add 0 weight in direction of u to v g[u].push_back(make_pair(v, 0)); // add 1 weight in reverse direction g[v].push_back(make_pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << " : " << disRev[i].first << " " << disRev[i].second << endl; } */ int res = INT_MAX; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made cout << root << " " << res << endl;} // Driver code to test above methodsint main(){ int edges[][2] = { {0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6} }; int e = sizeof(edges) / sizeof(edges[0]); printMinEdgeReverseForRootNode(edges, e); return 0;}
// Java program to find min edge reversal to // make every node reachable from root import java.util.*; class GFG{ // pair class static class pair { int first,second; pair(int a ,int b) { first = a; second = b; } } // method to dfs in tree and populates disRev values static int dfs(Vector<Vector< pair >> g, pair disRev[], boolean visit[], int u) { // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g.get(u).size(); i++) { int v = g.get(u).get(i).first; if (!visit[v]) { // distance of v will be one more than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g.get(u).get(i).second!=0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev; } // method prints root and minimum number of edge reversal static void printMinEdgeReverseForRootNode(int edges[][], int e) { // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree Vector<Vector< pair >> g=new Vector<Vector< pair >>(); for(int i = 0; i < V + 1; i++) g.add(new Vector<pair>()); // disRev stores two values - distance and back // edge count from root node pair disRev[] = new pair[V]; for(int i = 0; i < V; i++) disRev[i] = new pair(0, 0); boolean visit[] = new boolean[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // add 0 weight in direction of u to v g.get(u).add(new pair(v, 0)); // add 1 weight in reverse direction g.get(v).add(new pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << " : " << disRev[i].first << " " << disRev[i].second << endl; } */ int res = Integer.MAX_VALUE; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made System.out.println(root + " " + res ); } // Driver code public static void main(String args[]){ int edges[][] = { {0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6} }; int e = edges.length; printMinEdgeReverseForRootNode(edges, e); }} // This code is contributed by Arnab Kundu
# Python3 program to find min edge reversal# to make every node reachable from rootimport sys # Method to dfs in tree and populates # disRev valuesdef dfs(g, disRev, visit, u): # Visit current node visit[u] = True totalRev = 0 # Looping over all neighbors for i in range(len(g[u])): v = g[u][i][0] if (not visit[v]): # Distance of v will be one more # than distance of u disRev[v][0] = disRev[u][0] + 1 # Initialize back edge count same as # parent node's count disRev[v][1] = disRev[u][1] # If there is a reverse edge from u to i, # then only update if (g[u][i][1]): disRev[v][1] = disRev[u][1] + 1 totalRev += 1 totalRev += dfs(g, disRev, visit, v) # Return total reversal in subtree rooted at u return totalRev # Method prints root and minimum number of# edge reversaldef printMinEdgeReverseForRootNode(edges, e): # Number of nodes are one more than # number of edges V = e + 1 # Data structure to store directed tree g = [[] for i in range(V)] # disRev stores two values - distance # and back edge count from root node disRev = [[0, 0] for i in range(V)] visit = [False for i in range(V)] # u, v for i in range(e): u = edges[i][0] v = edges[i][1] # Add 0 weight in direction of u to v g[u].append([v, 0]) # Add 1 weight in reverse direction g[v].append([u, 1]) # Initialize all variables for i in range(V): visit[i] = False disRev[i][0] = disRev[i][1] = 0 root = 0 # dfs populates disRev data structure and # store total reverse edge counts totalRev = dfs(g, disRev, visit, root) # UnComment below lines to preach node's # distance and edge reversal count from root node # for (i = 0 i < V i++) # { # cout << i << " : " << disRev[i][0] # << " " << disRev[i][1] << endl # } res = sys.maxsize # Loop over all nodes to choose # minimum edge reversal for i in range(V): # (reversal in path to i) + (reversal # in all other tree parts) edgesToRev = ((totalRev - disRev[i][1]) + (disRev[i][0] - disRev[i][1])) # Choose minimum among all values if (edgesToRev < res): res = edgesToRev root = i # Print the designated root and total # edge reversal made print(root, res) # Driver code if __name__ == '__main__': edges = [ [ 0, 1 ], [ 2, 1 ], [ 3, 2 ], [ 3, 4 ], [ 5, 4 ], [ 5, 6 ], [ 7, 6 ] ] e = len(edges) printMinEdgeReverseForRootNode(edges, e) # This code is contributed by mohit kumar 29
// C# program to find min edge reversal to // make every node reachable from rootusing System;using System.Collections.Generic; class GFG{ // pair class public class pair { public int first,second; public pair(int a, int b) { first = a; second = b; } } // method to dfs in tree and populates disRev values static int dfs(List<List< pair >> g, pair []disRev, Boolean []visit, int u) { // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g[u].Count; i++) { int v = g[u][i].first; if (!visit[v]) { // distance of v will be one more // than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g[u][i].second != 0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev; } // method prints root and minimum number of edge reversal static void printMinEdgeReverseForRootNode(int [,]edges, int e) { // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree List<List< pair >> g = new List<List< pair >>(); for(int i = 0; i < V + 1; i++) g.Add(new List<pair>()); // disRev stores two values - distance and back // edge count from root node pair []disRev = new pair[V]; for(int i = 0; i < V; i++) disRev[i] = new pair(0, 0); Boolean []visit = new Boolean[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i, 0]; v = edges[i, 1]; // add 0 weight in direction of u to v g[u].Add(new pair(v, 0)); // add 1 weight in reverse direction g[v].Add(new pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << " : " << disRev[i].first << " " << disRev[i].second << endl; } */ int res = int.MaxValue; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made Console.WriteLine(root + " " + res); } // Driver code public static void Main(String []args){ int [,]edges = {{0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6}}; int e = edges.GetLength(0); printMinEdgeReverseForRootNode(edges, e); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to find min edge // reversal to make every node reachable // from rootclass pair{ constructor(a, b) { this.first = a; this.second = b; }} // Method to dfs in tree and populates// disRev valuesfunction dfs(g, disRev, visit, u){ // Visit current node visit[u] = true; let totalRev = 0; // Looping over all neighbors for(let i = 0; i < g[u].length; i++) { let v = g[u][i].first; if (!visit[v]) { // Distance of v will be one more // than distance of u disRev[v].first = disRev[u].first + 1; // Initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // If there is a reverse edge from u to i, // then only update if (g[u][i].second != 0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // Return total reversal in subtree // rooted at u return totalRev;} // Method prints root and minimum number// of edge reversalfunction printMinEdgeReverseForRootNode(edges, e){ // Number of nodes are one more // than number of edges let V = e + 1; // Data structure to store directed tree let g = []; for(let i = 0; i < V + 1; i++) g.push([]); // disRev stores two values - distance and // back edge count from root node let disRev = new Array(V); for(let i = 0; i < V; i++) disRev[i] = new pair(0, 0); let visit = new Array(V); let u, v; for(let i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // Add 0 weight in direction of u to v g[u].push(new pair(v, 0)); // Add 1 weight in reverse direction g[v].push(new pair(u, 1)); } // Initialize all variables for(let i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } let root = 0; // dfs populates disRev data structure and // store total reverse edge counts let totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << " : " << disRev[i].first << " " << disRev[i].second << endl; } */ let res = Number.MAX_VALUE; // Loop over all nodes to choose // minimum edge reversal for(let i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) let edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // Choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // Print the designated root and total // edge reversal made document.write(root + " " + res );} // Driver codelet edges = [ [ 0, 1 ], [ 2, 1 ], [ 3, 2 ], [ 3, 4 ], [ 5, 4 ], [ 5, 6 ], [ 7, 6 ] ]; let e = edges.length; printMinEdgeReverseForRootNode(edges, e); // This code is contributed by rag2127 </script>
Output:
3 3
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
andrew1234
29AjayKumar
mohit kumar 29
rag2127
DFS
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Floyd Warshall Algorithm | DP-16
Bellman–Ford Algorithm | DP-23
Strongly Connected Components
Iterative Depth First Traversal of Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) | [
{
"code": null,
"e": 26285,
"s": 26257,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 26472,
"s": 26285,
"text": "Given a directed tree with V vertices and V-1 edges, we need to choose such a root (from given nodes from where we can reach to every other node) with a minimum number of edge reversal. "
},
{
"code": null,
"e": 26484,
"s": 26472,
"text": "Examples: "
},
{
"code": null,
"e": 26653,
"s": 26484,
"text": "In above tree, if we choose node 3 as our \nroot then we need to reverse minimum number\nof 3 edges to reach every other node, \nchanged tree is shown on the right side.\n "
},
{
"code": null,
"e": 28008,
"s": 26653,
"text": "We can solve this problem using DFS. we start dfs at any random node of given tree and at each node we store its distance from starting node assuming all edges as undirected and we also store number of edges which need to be reversed in the path from starting node to current node, let’s denote such edges as back edges so back edges are those which point towards the node in a path. With this dfs, we also calculate total number of edge reversals in the tree. After this computation, at each node we can calculate ‘number of edge reversal to reach every other node’ as follows, Let total number of reversals in tree when some node is chosen as starting node for dfs is R then if we want to reach every other node from node i we need to reverse all back edges from path node i to starting node and we also need to reverse all other back edges other than node i to starting node path. First part will be (distance of node i from starting node – back edges count at node i) because we want to reverse edges in path from node i to starting node it will be total edges (i.e. distance) minus back edges from starting node to node i (i.e. back edge count at node i). The second part will be (total edge reversal or total back edges of tree R – back edge count of node i). After calculating this value at each node we will choose minimum of them as our result. "
},
{
"code": null,
"e": 28165,
"s": 28008,
"text": "In below code, in the given edge direction weight 0 is added and in reverse direction weight 1 is added which is used to count reversal edges in dfs method."
},
{
"code": null,
"e": 28169,
"s": 28165,
"text": "C++"
},
{
"code": null,
"e": 28174,
"s": 28169,
"text": "Java"
},
{
"code": null,
"e": 28182,
"s": 28174,
"text": "Python3"
},
{
"code": null,
"e": 28185,
"s": 28182,
"text": "C#"
},
{
"code": null,
"e": 28196,
"s": 28185,
"text": "Javascript"
},
{
"code": "// C++ program to find min edge reversal to// make every node reachable from root#include <bits/stdc++.h>using namespace std; // method to dfs in tree and populates disRev valuesint dfs(vector< pair<int, int> > g[], pair<int, int> disRev[], bool visit[], int u){ // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g[u].size(); i++) { int v = g[u][i].first; if (!visit[v]) { // distance of v will be one more than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g[u][i].second) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev;} // method prints root and minimum number of edge reversalvoid printMinEdgeReverseForRootNode(int edges[][2], int e){ // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree vector< pair<int, int> > g[V]; // disRev stores two values - distance and back // edge count from root node pair<int, int> disRev[V]; bool visit[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // add 0 weight in direction of u to v g[u].push_back(make_pair(v, 0)); // add 1 weight in reverse direction g[v].push_back(make_pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << \" : \" << disRev[i].first << \" \" << disRev[i].second << endl; } */ int res = INT_MAX; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made cout << root << \" \" << res << endl;} // Driver code to test above methodsint main(){ int edges[][2] = { {0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6} }; int e = sizeof(edges) / sizeof(edges[0]); printMinEdgeReverseForRootNode(edges, e); return 0;}",
"e": 31387,
"s": 28196,
"text": null
},
{
"code": "// Java program to find min edge reversal to // make every node reachable from root import java.util.*; class GFG{ // pair class static class pair { int first,second; pair(int a ,int b) { first = a; second = b; } } // method to dfs in tree and populates disRev values static int dfs(Vector<Vector< pair >> g, pair disRev[], boolean visit[], int u) { // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g.get(u).size(); i++) { int v = g.get(u).get(i).first; if (!visit[v]) { // distance of v will be one more than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g.get(u).get(i).second!=0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev; } // method prints root and minimum number of edge reversal static void printMinEdgeReverseForRootNode(int edges[][], int e) { // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree Vector<Vector< pair >> g=new Vector<Vector< pair >>(); for(int i = 0; i < V + 1; i++) g.add(new Vector<pair>()); // disRev stores two values - distance and back // edge count from root node pair disRev[] = new pair[V]; for(int i = 0; i < V; i++) disRev[i] = new pair(0, 0); boolean visit[] = new boolean[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // add 0 weight in direction of u to v g.get(u).add(new pair(v, 0)); // add 1 weight in reverse direction g.get(v).add(new pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << \" : \" << disRev[i].first << \" \" << disRev[i].second << endl; } */ int res = Integer.MAX_VALUE; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made System.out.println(root + \" \" + res ); } // Driver code public static void main(String args[]){ int edges[][] = { {0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6} }; int e = edges.length; printMinEdgeReverseForRootNode(edges, e); }} // This code is contributed by Arnab Kundu",
"e": 35059,
"s": 31387,
"text": null
},
{
"code": "# Python3 program to find min edge reversal# to make every node reachable from rootimport sys # Method to dfs in tree and populates # disRev valuesdef dfs(g, disRev, visit, u): # Visit current node visit[u] = True totalRev = 0 # Looping over all neighbors for i in range(len(g[u])): v = g[u][i][0] if (not visit[v]): # Distance of v will be one more # than distance of u disRev[v][0] = disRev[u][0] + 1 # Initialize back edge count same as # parent node's count disRev[v][1] = disRev[u][1] # If there is a reverse edge from u to i, # then only update if (g[u][i][1]): disRev[v][1] = disRev[u][1] + 1 totalRev += 1 totalRev += dfs(g, disRev, visit, v) # Return total reversal in subtree rooted at u return totalRev # Method prints root and minimum number of# edge reversaldef printMinEdgeReverseForRootNode(edges, e): # Number of nodes are one more than # number of edges V = e + 1 # Data structure to store directed tree g = [[] for i in range(V)] # disRev stores two values - distance # and back edge count from root node disRev = [[0, 0] for i in range(V)] visit = [False for i in range(V)] # u, v for i in range(e): u = edges[i][0] v = edges[i][1] # Add 0 weight in direction of u to v g[u].append([v, 0]) # Add 1 weight in reverse direction g[v].append([u, 1]) # Initialize all variables for i in range(V): visit[i] = False disRev[i][0] = disRev[i][1] = 0 root = 0 # dfs populates disRev data structure and # store total reverse edge counts totalRev = dfs(g, disRev, visit, root) # UnComment below lines to preach node's # distance and edge reversal count from root node # for (i = 0 i < V i++) # { # cout << i << \" : \" << disRev[i][0] # << \" \" << disRev[i][1] << endl # } res = sys.maxsize # Loop over all nodes to choose # minimum edge reversal for i in range(V): # (reversal in path to i) + (reversal # in all other tree parts) edgesToRev = ((totalRev - disRev[i][1]) + (disRev[i][0] - disRev[i][1])) # Choose minimum among all values if (edgesToRev < res): res = edgesToRev root = i # Print the designated root and total # edge reversal made print(root, res) # Driver code if __name__ == '__main__': edges = [ [ 0, 1 ], [ 2, 1 ], [ 3, 2 ], [ 3, 4 ], [ 5, 4 ], [ 5, 6 ], [ 7, 6 ] ] e = len(edges) printMinEdgeReverseForRootNode(edges, e) # This code is contributed by mohit kumar 29",
"e": 37930,
"s": 35059,
"text": null
},
{
"code": "// C# program to find min edge reversal to // make every node reachable from rootusing System;using System.Collections.Generic; class GFG{ // pair class public class pair { public int first,second; public pair(int a, int b) { first = a; second = b; } } // method to dfs in tree and populates disRev values static int dfs(List<List< pair >> g, pair []disRev, Boolean []visit, int u) { // visit current node visit[u] = true; int totalRev = 0; // looping over all neighbors for (int i = 0; i < g[u].Count; i++) { int v = g[u][i].first; if (!visit[v]) { // distance of v will be one more // than distance of u disRev[v].first = disRev[u].first + 1; // initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // if there is a reverse edge from u to i, // then only update if (g[u][i].second != 0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // return total reversal in subtree rooted at u return totalRev; } // method prints root and minimum number of edge reversal static void printMinEdgeReverseForRootNode(int [,]edges, int e) { // number of nodes are one more than number of edges int V = e + 1; // data structure to store directed tree List<List< pair >> g = new List<List< pair >>(); for(int i = 0; i < V + 1; i++) g.Add(new List<pair>()); // disRev stores two values - distance and back // edge count from root node pair []disRev = new pair[V]; for(int i = 0; i < V; i++) disRev[i] = new pair(0, 0); Boolean []visit = new Boolean[V]; int u, v; for (int i = 0; i < e; i++) { u = edges[i, 0]; v = edges[i, 1]; // add 0 weight in direction of u to v g[u].Add(new pair(v, 0)); // add 1 weight in reverse direction g[v].Add(new pair(u, 1)); } // initialize all variables for (int i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } int root = 0; // dfs populates disRev data structure and // store total reverse edge counts int totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << \" : \" << disRev[i].first << \" \" << disRev[i].second << endl; } */ int res = int.MaxValue; // loop over all nodes to choose minimum edge reversal for (int i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) int edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // print the designated root and total // edge reversal made Console.WriteLine(root + \" \" + res); } // Driver code public static void Main(String []args){ int [,]edges = {{0, 1}, {2, 1}, {3, 2}, {3, 4}, {5, 4}, {5, 6}, {7, 6}}; int e = edges.GetLength(0); printMinEdgeReverseForRootNode(edges, e); }} // This code is contributed by 29AjayKumar",
"e": 41619,
"s": 37930,
"text": null
},
{
"code": "<script> // Javascript program to find min edge // reversal to make every node reachable // from rootclass pair{ constructor(a, b) { this.first = a; this.second = b; }} // Method to dfs in tree and populates// disRev valuesfunction dfs(g, disRev, visit, u){ // Visit current node visit[u] = true; let totalRev = 0; // Looping over all neighbors for(let i = 0; i < g[u].length; i++) { let v = g[u][i].first; if (!visit[v]) { // Distance of v will be one more // than distance of u disRev[v].first = disRev[u].first + 1; // Initialize back edge count same as // parent node's count disRev[v].second = disRev[u].second; // If there is a reverse edge from u to i, // then only update if (g[u][i].second != 0) { disRev[v].second = disRev[u].second + 1; totalRev++; } totalRev += dfs(g, disRev, visit, v); } } // Return total reversal in subtree // rooted at u return totalRev;} // Method prints root and minimum number// of edge reversalfunction printMinEdgeReverseForRootNode(edges, e){ // Number of nodes are one more // than number of edges let V = e + 1; // Data structure to store directed tree let g = []; for(let i = 0; i < V + 1; i++) g.push([]); // disRev stores two values - distance and // back edge count from root node let disRev = new Array(V); for(let i = 0; i < V; i++) disRev[i] = new pair(0, 0); let visit = new Array(V); let u, v; for(let i = 0; i < e; i++) { u = edges[i][0]; v = edges[i][1]; // Add 0 weight in direction of u to v g[u].push(new pair(v, 0)); // Add 1 weight in reverse direction g[v].push(new pair(u, 1)); } // Initialize all variables for(let i = 0; i < V; i++) { visit[i] = false; disRev[i].first = disRev[i].second = 0; } let root = 0; // dfs populates disRev data structure and // store total reverse edge counts let totalRev = dfs(g, disRev, visit, root); // UnComment below lines to print each node's // distance and edge reversal count from root node /* for (int i = 0; i < V; i++) { cout << i << \" : \" << disRev[i].first << \" \" << disRev[i].second << endl; } */ let res = Number.MAX_VALUE; // Loop over all nodes to choose // minimum edge reversal for(let i = 0; i < V; i++) { // (reversal in path to i) + (reversal // in all other tree parts) let edgesToRev = (totalRev - disRev[i].second) + (disRev[i].first - disRev[i].second); // Choose minimum among all values if (edgesToRev < res) { res = edgesToRev; root = i; } } // Print the designated root and total // edge reversal made document.write(root + \" \" + res );} // Driver codelet edges = [ [ 0, 1 ], [ 2, 1 ], [ 3, 2 ], [ 3, 4 ], [ 5, 4 ], [ 5, 6 ], [ 7, 6 ] ]; let e = edges.length; printMinEdgeReverseForRootNode(edges, e); // This code is contributed by rag2127 </script>",
"e": 44989,
"s": 41619,
"text": null
},
{
"code": null,
"e": 44998,
"s": 44989,
"text": "Output: "
},
{
"code": null,
"e": 45002,
"s": 44998,
"text": "3 3"
},
{
"code": null,
"e": 45426,
"s": 45002,
"text": "This article is contributed by Utkarsh Trivedi. 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": 45437,
"s": 45426,
"text": "andrew1234"
},
{
"code": null,
"e": 45449,
"s": 45437,
"text": "29AjayKumar"
},
{
"code": null,
"e": 45464,
"s": 45449,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 45472,
"s": 45464,
"text": "rag2127"
},
{
"code": null,
"e": 45476,
"s": 45472,
"text": "DFS"
},
{
"code": null,
"e": 45482,
"s": 45476,
"text": "Graph"
},
{
"code": null,
"e": 45486,
"s": 45482,
"text": "DFS"
},
{
"code": null,
"e": 45492,
"s": 45486,
"text": "Graph"
},
{
"code": null,
"e": 45590,
"s": 45492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45648,
"s": 45590,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 45668,
"s": 45648,
"text": "Topological Sorting"
},
{
"code": null,
"e": 45701,
"s": 45668,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 45776,
"s": 45701,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 45826,
"s": 45776,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 45859,
"s": 45826,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 45890,
"s": 45859,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 45920,
"s": 45890,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 45961,
"s": 45920,
"text": "Iterative Depth First Traversal of Graph"
}
] |
Hello World in Julia - GeeksforGeeks | 28 Jul, 2020
Julia is a high-level open-source programming language, developed by a group of 4 people at MIT. Julia is a dynamic, high-performance programming language that is used to perform operations in scientific computing. Similar to the R Programming Language, Julia is used for statistical computations and data analytics. Julia was built mainly because of its speed in programming, it has much faster execution as compared to Python and R.
Julia provides support for big data analytics by performing complex tasks such as cloud computing and parallelism, which play a fundamental role in analyzing Big Data.
Before we start to learn to code in Julia, let’s see from where we need to download the needed software and programs. Julia can be downloaded from its official website and can be installed with the help of How to install Julia on Windows and Linux?
At last, we need to have a text editor to write our code. Feel free to use any text editor like VS Code, Sublime Text, Notepad++, etc.
Hello World is the most basic program that is used to show the basic syntax of a programming language. Here, in Julia, there are multiple ways to write and execute a code:
With Julia interactive session:
The easiest way to get started with Julia is by starting an interactive session (also known as a read-eval-print loop or “REPL”) by double-clicking the Julia executable or running Julia from the command line:
To print Hello World as the output in Julia interactive session, we can directly write “Hello World” with double quotes (” “), since we want to print a string so we need to insert it inside the double-quotes.
Julia
"Hello World"
Output:
"Hello World"
We can also use print() function, the print function is used to print data on the output screen, we just need to pass “Hello World” string as an argument in the print() function.
Julia
print("Hello World")
The difference between directly writing “Hello World” and writing it with the print function is that when we directly write “Hello World”, it will also print the quotes (” “) with the text but with the print function, it will only print text.
Output:
Hello World
By creating a helloworld.jl file:
To print Hello World as the output in Julia, we need to create a file with name helloworld.jl. Then we can use the print function discussed above to print Hello World as the output, we just need to pass “Hello World” string as an argument in the print function.
Julia
print("Hello World")
Then run the file on command prompt or terminal with the command:
julia helloworld.jl.
Output:
Hello World
We can also use the println() function to print Hello World as the output, the only difference here is that it will end on a new line after printing the output on the screen.
Julia
println("Hello World")
Output:
Hello World
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Join an array of strings into a single string in Julia - join() Method
Working with Excel Files in Julia
File Handling in Julia
Getting last element of an array in Julia - last() Method | [
{
"code": null,
"e": 25772,
"s": 25744,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 26207,
"s": 25772,
"text": "Julia is a high-level open-source programming language, developed by a group of 4 people at MIT. Julia is a dynamic, high-performance programming language that is used to perform operations in scientific computing. Similar to the R Programming Language, Julia is used for statistical computations and data analytics. Julia was built mainly because of its speed in programming, it has much faster execution as compared to Python and R."
},
{
"code": null,
"e": 26375,
"s": 26207,
"text": "Julia provides support for big data analytics by performing complex tasks such as cloud computing and parallelism, which play a fundamental role in analyzing Big Data."
},
{
"code": null,
"e": 26624,
"s": 26375,
"text": "Before we start to learn to code in Julia, let’s see from where we need to download the needed software and programs. Julia can be downloaded from its official website and can be installed with the help of How to install Julia on Windows and Linux?"
},
{
"code": null,
"e": 26759,
"s": 26624,
"text": "At last, we need to have a text editor to write our code. Feel free to use any text editor like VS Code, Sublime Text, Notepad++, etc."
},
{
"code": null,
"e": 26931,
"s": 26759,
"text": "Hello World is the most basic program that is used to show the basic syntax of a programming language. Here, in Julia, there are multiple ways to write and execute a code:"
},
{
"code": null,
"e": 26963,
"s": 26931,
"text": "With Julia interactive session:"
},
{
"code": null,
"e": 27172,
"s": 26963,
"text": "The easiest way to get started with Julia is by starting an interactive session (also known as a read-eval-print loop or “REPL”) by double-clicking the Julia executable or running Julia from the command line:"
},
{
"code": null,
"e": 27382,
"s": 27172,
"text": "To print Hello World as the output in Julia interactive session, we can directly write “Hello World” with double quotes (” “), since we want to print a string so we need to insert it inside the double-quotes. "
},
{
"code": null,
"e": 27388,
"s": 27382,
"text": "Julia"
},
{
"code": "\"Hello World\"",
"e": 27402,
"s": 27388,
"text": null
},
{
"code": null,
"e": 27410,
"s": 27402,
"text": "Output:"
},
{
"code": null,
"e": 27426,
"s": 27410,
"text": "\"Hello World\"\n\n"
},
{
"code": null,
"e": 27605,
"s": 27426,
"text": "We can also use print() function, the print function is used to print data on the output screen, we just need to pass “Hello World” string as an argument in the print() function."
},
{
"code": null,
"e": 27611,
"s": 27605,
"text": "Julia"
},
{
"code": "print(\"Hello World\")",
"e": 27632,
"s": 27611,
"text": null
},
{
"code": null,
"e": 27875,
"s": 27632,
"text": "The difference between directly writing “Hello World” and writing it with the print function is that when we directly write “Hello World”, it will also print the quotes (” “) with the text but with the print function, it will only print text."
},
{
"code": null,
"e": 27883,
"s": 27875,
"text": "Output:"
},
{
"code": null,
"e": 27897,
"s": 27883,
"text": "Hello World\n\n"
},
{
"code": null,
"e": 27931,
"s": 27897,
"text": "By creating a helloworld.jl file:"
},
{
"code": null,
"e": 28193,
"s": 27931,
"text": "To print Hello World as the output in Julia, we need to create a file with name helloworld.jl. Then we can use the print function discussed above to print Hello World as the output, we just need to pass “Hello World” string as an argument in the print function."
},
{
"code": null,
"e": 28199,
"s": 28193,
"text": "Julia"
},
{
"code": "print(\"Hello World\")",
"e": 28220,
"s": 28199,
"text": null
},
{
"code": null,
"e": 28286,
"s": 28220,
"text": "Then run the file on command prompt or terminal with the command:"
},
{
"code": null,
"e": 28309,
"s": 28286,
"text": "julia helloworld.jl. \n"
},
{
"code": null,
"e": 28317,
"s": 28309,
"text": "Output:"
},
{
"code": null,
"e": 28331,
"s": 28317,
"text": "Hello World\n\n"
},
{
"code": null,
"e": 28506,
"s": 28331,
"text": "We can also use the println() function to print Hello World as the output, the only difference here is that it will end on a new line after printing the output on the screen."
},
{
"code": null,
"e": 28512,
"s": 28506,
"text": "Julia"
},
{
"code": "println(\"Hello World\")",
"e": 28535,
"s": 28512,
"text": null
},
{
"code": null,
"e": 28543,
"s": 28535,
"text": "Output:"
},
{
"code": null,
"e": 28557,
"s": 28543,
"text": "Hello World\n\n"
},
{
"code": null,
"e": 28564,
"s": 28557,
"text": "Picked"
},
{
"code": null,
"e": 28570,
"s": 28564,
"text": "Julia"
},
{
"code": null,
"e": 28668,
"s": 28570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28741,
"s": 28668,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 28811,
"s": 28741,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 28839,
"s": 28811,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 28887,
"s": 28839,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 28957,
"s": 28887,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 29016,
"s": 28957,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 29087,
"s": 29016,
"text": "Join an array of strings into a single string in Julia - join() Method"
},
{
"code": null,
"e": 29121,
"s": 29087,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 29144,
"s": 29121,
"text": "File Handling in Julia"
}
] |
Find perimeter of shapes formed with 1s in binary matrix - GeeksforGeeks | 16 Jan, 2022
Given a matrix of N rows and M columns, consist of 0’s and 1’s. The task is to find the perimeter of subfigure consisting only 1’s in the matrix. Perimeter of single 1 is 4 as it can be covered from all 4 side. Perimeter of double 11 is 6.
| 1 | | 1 1 |
Examples:
Input : mat[][] =
{
1, 0,
1, 1,
}
Output : 8
Cell (1,0) and (1,1) making a L shape whose perimeter is 8.
Input : mat[][] =
{
0, 1, 0, 0, 0,
1, 1, 1, 0, 0,
1, 0, 0, 0, 0
}
Output : 12
The idea is to traverse the matrix, find all ones and find their contribution in perimeter. The maximum contribution of a 1 is four if it is surrounded by all 0s. The contribution reduces by one with 1 around it.
Algorithm for solving this problem:
Traverse the whole matrix and find the cell having value equal to 1.Calculate the number of closed side for that cell and add, 4 – number of closed side to the total perimeter.
Traverse the whole matrix and find the cell having value equal to 1.
Calculate the number of closed side for that cell and add, 4 – number of closed side to the total perimeter.
Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find perimeter of area covered by// 1 in 2D matrix consists of 0's and 1's.#include<bits/stdc++.h>using namespace std;#define R 3#define C 5 // Find the number of covered side for mat[i][j].int numofneighbour(int mat[][C], int i, int j){ int count = 0; // UP if (i > 0 && mat[i - 1][j]) count++; // LEFT if (j > 0 && mat[i][j - 1]) count++; // DOWN if (i < R-1 && mat[i + 1][j]) count++; // RIGHT if (j < C-1 && mat[i][j + 1]) count++; return count;} // Returns sum of perimeter of shapes formed with 1sint findperimeter(int mat[R][C]){ int perimeter = 0; // Traversing the matrix and finding ones to // calculate their contribution. for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (mat[i][j]) perimeter += (4 - numofneighbour(mat, i ,j)); return perimeter;} // Driven Programint main(){ int mat[R][C] = { 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, }; cout << findperimeter(mat) << endl; return 0;}
// Java program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1'sclass GFG { static final int R = 3; static final int C = 5; // Find the number of covered side // for mat[i][j]. static int numofneighbour(int mat[][], int i, int j) { int count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) count++; // LEFT if (j > 0 && mat[i][j - 1] == 1) count++; // DOWN if (i < R - 1 && mat[i + 1][j] == 1) count++; // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) count++; return count; } // Returns sum of perimeter of shapes // formed with 1s static int findperimeter(int mat[][]) { int perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (mat[i][j] == 1) perimeter += (4 - numofneighbour(mat, i, j)); return perimeter; } // Driver code public static void main(String[] args) { int mat[][] = {{0, 1, 0, 0, 0}, {1, 1, 1, 0, 0}, {1, 0, 0, 0, 0}}; System.out.println(findperimeter(mat)); }} // This code is contributed by Anant Agarwal.
# Python3 program to find perimeter of area# covered by 1 in 2D matrix consists of 0's and 1's. R = 3C = 5 # Find the number of covered side for mat[i][j].def numofneighbour(mat, i, j): count = 0; # UP if (i > 0 and mat[i - 1][j]): count+= 1; # LEFT if (j > 0 and mat[i][j - 1]): count+= 1; # DOWN if (i < R-1 and mat[i + 1][j]): count+= 1 # RIGHT if (j < C-1 and mat[i][j + 1]): count+= 1; return count; # Returns sum of perimeter of shapes formed with 1sdef findperimeter(mat): perimeter = 0; # Traversing the matrix and finding ones to # calculate their contribution. for i in range(0, R): for j in range(0, C): if (mat[i][j]): perimeter += (4 - numofneighbour(mat, i, j)); return perimeter; # Driver Codemat = [ [0, 1, 0, 0, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0] ] print(findperimeter(mat), end="\n"); # This code is contributed by Akanksha Rai
using System; // C# program to find perimeter of area// covered by 1 in 2D matrix consists // of 0's and 1'spublic class GFG{ public const int R = 3; public const int C = 5; // Find the number of covered side // for mat[i][j]. public static int numofneighbour(int[][] mat, int i, int j) { int count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) { count++; } // LEFT if (j > 0 && mat[i][j - 1] == 1) { count++; } // DOWN if (i < R - 1 && mat[i + 1][j] == 1) { count++; } // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) { count++; } return count; } // Returns sum of perimeter of shapes // formed with 1s public static int findperimeter(int[][] mat) { int perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] == 1) { perimeter += (4 - numofneighbour(mat, i, j)); } } } return perimeter; } // Driver code public static void Main(string[] args) { int[][] mat = new int[][] { new int[] {0, 1, 0, 0, 0}, new int[] {1, 1, 1, 0, 0}, new int[] {1, 0, 0, 0, 0} }; Console.WriteLine(findperimeter(mat)); }} // This code is contributed by Shrikant13
<?php// PHP program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1's.$R = 3;$C = 5; // Find the number of covered side// for mat[i][j].function numofneighbour($mat, $i, $j){ global $R; global $C; $count = 0; // UP if ($i > 0 && ($mat[$i - 1][$j])) $count++; // LEFT if ($j > 0 && ($mat[$i][$j - 1])) $count++; // DOWN if (($i < $R-1 )&& ($mat[$i + 1][$j])) $count++; // RIGHT if (($j < $C-1) && ($mat[$i][$j + 1])) $count++; return $count;} // Returns sum of perimeter of shapes// formed with 1sfunction findperimeter($mat){ global $R; global $C; $perimeter = 0; // Traversing the matrix and finding ones // to calculate their contribution. for ($i = 0; $i < $R; $i++) for ( $j = 0; $j < $C; $j++) if ($mat[$i][$j]) $perimeter += (4 - numofneighbour($mat, $i, $j)); return $perimeter;} // Driver Code$mat = array(array(0, 1, 0, 0, 0), array(1, 1, 1, 0, 0), array(1, 0, 0, 0, 0)); echo findperimeter($mat), "\n"; // This code is contributed by Sach_Code?>
<script> // JavaScript program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1'slet R = 3;let C = 5; // Find the number of covered side// for mat[i][j].function numofneighbour(mat, i, j){ let count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) count++; // LEFT if (j > 0 && mat[i][j - 1] == 1) count++; // DOWN if (i < R - 1 && mat[i + 1][j] == 1) count++; // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) count++; return count;} // Returns sum of perimeter of shapes// formed with 1sfunction findperimeter(mat){ let perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for(let i = 0; i < R; i++) for(let j = 0; j < C; j++) if (mat[i][j] == 1) perimeter += (4 - numofneighbour(mat, i, j)); return perimeter;} // Driver Codelet mat = [ [ 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 0 ], [ 1, 0, 0, 0, 0 ] ]; document.write(findperimeter(mat)); // This code is contributed by souravghosh0416 </script>
Output:
12
Time Complexity : O(RC).
This article is contributed by Anuj Chauhan(anuj0503). 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
Sach_Code
Akanksha_Rai
souravghosh0416
akshaysingh98088
saurabh1990aror
Geometric
Matrix
Matrix
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Haversine formula to find distance between two points on a sphere
Program to find slope of a line
Equation of circle when three points on the circle are given
Program to find line passing through 2 Points
Maximum Manhattan distance between a distinct pair from N coordinates
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Maximum size square sub-matrix with all 1s | [
{
"code": null,
"e": 26585,
"s": 26557,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 26826,
"s": 26585,
"text": "Given a matrix of N rows and M columns, consist of 0’s and 1’s. The task is to find the perimeter of subfigure consisting only 1’s in the matrix. Perimeter of single 1 is 4 as it can be covered from all 4 side. Perimeter of double 11 is 6. "
},
{
"code": null,
"e": 26921,
"s": 26826,
"text": " \n \n| 1 | | 1 1 |\n "
},
{
"code": null,
"e": 26933,
"s": 26921,
"text": "Examples: "
},
{
"code": null,
"e": 27279,
"s": 26933,
"text": "Input : mat[][] = \n {\n 1, 0,\n 1, 1,\n }\nOutput : 8\nCell (1,0) and (1,1) making a L shape whose perimeter is 8.\n\nInput : mat[][] = \n { \n 0, 1, 0, 0, 0,\n 1, 1, 1, 0, 0,\n 1, 0, 0, 0, 0\n }\nOutput : 12"
},
{
"code": null,
"e": 27493,
"s": 27279,
"text": "The idea is to traverse the matrix, find all ones and find their contribution in perimeter. The maximum contribution of a 1 is four if it is surrounded by all 0s. The contribution reduces by one with 1 around it. "
},
{
"code": null,
"e": 27530,
"s": 27493,
"text": "Algorithm for solving this problem: "
},
{
"code": null,
"e": 27707,
"s": 27530,
"text": "Traverse the whole matrix and find the cell having value equal to 1.Calculate the number of closed side for that cell and add, 4 – number of closed side to the total perimeter."
},
{
"code": null,
"e": 27776,
"s": 27707,
"text": "Traverse the whole matrix and find the cell having value equal to 1."
},
{
"code": null,
"e": 27885,
"s": 27776,
"text": "Calculate the number of closed side for that cell and add, 4 – number of closed side to the total perimeter."
},
{
"code": null,
"e": 27932,
"s": 27885,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 27936,
"s": 27932,
"text": "C++"
},
{
"code": null,
"e": 27941,
"s": 27936,
"text": "Java"
},
{
"code": null,
"e": 27949,
"s": 27941,
"text": "Python3"
},
{
"code": null,
"e": 27952,
"s": 27949,
"text": "C#"
},
{
"code": null,
"e": 27956,
"s": 27952,
"text": "PHP"
},
{
"code": null,
"e": 27967,
"s": 27956,
"text": "Javascript"
},
{
"code": "// C++ program to find perimeter of area covered by// 1 in 2D matrix consists of 0's and 1's.#include<bits/stdc++.h>using namespace std;#define R 3#define C 5 // Find the number of covered side for mat[i][j].int numofneighbour(int mat[][C], int i, int j){ int count = 0; // UP if (i > 0 && mat[i - 1][j]) count++; // LEFT if (j > 0 && mat[i][j - 1]) count++; // DOWN if (i < R-1 && mat[i + 1][j]) count++; // RIGHT if (j < C-1 && mat[i][j + 1]) count++; return count;} // Returns sum of perimeter of shapes formed with 1sint findperimeter(int mat[R][C]){ int perimeter = 0; // Traversing the matrix and finding ones to // calculate their contribution. for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (mat[i][j]) perimeter += (4 - numofneighbour(mat, i ,j)); return perimeter;} // Driven Programint main(){ int mat[R][C] = { 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, }; cout << findperimeter(mat) << endl; return 0;}",
"e": 29049,
"s": 27967,
"text": null
},
{
"code": "// Java program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1'sclass GFG { static final int R = 3; static final int C = 5; // Find the number of covered side // for mat[i][j]. static int numofneighbour(int mat[][], int i, int j) { int count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) count++; // LEFT if (j > 0 && mat[i][j - 1] == 1) count++; // DOWN if (i < R - 1 && mat[i + 1][j] == 1) count++; // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) count++; return count; } // Returns sum of perimeter of shapes // formed with 1s static int findperimeter(int mat[][]) { int perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (mat[i][j] == 1) perimeter += (4 - numofneighbour(mat, i, j)); return perimeter; } // Driver code public static void main(String[] args) { int mat[][] = {{0, 1, 0, 0, 0}, {1, 1, 1, 0, 0}, {1, 0, 0, 0, 0}}; System.out.println(findperimeter(mat)); }} // This code is contributed by Anant Agarwal.",
"e": 30550,
"s": 29049,
"text": null
},
{
"code": "# Python3 program to find perimeter of area# covered by 1 in 2D matrix consists of 0's and 1's. R = 3C = 5 # Find the number of covered side for mat[i][j].def numofneighbour(mat, i, j): count = 0; # UP if (i > 0 and mat[i - 1][j]): count+= 1; # LEFT if (j > 0 and mat[i][j - 1]): count+= 1; # DOWN if (i < R-1 and mat[i + 1][j]): count+= 1 # RIGHT if (j < C-1 and mat[i][j + 1]): count+= 1; return count; # Returns sum of perimeter of shapes formed with 1sdef findperimeter(mat): perimeter = 0; # Traversing the matrix and finding ones to # calculate their contribution. for i in range(0, R): for j in range(0, C): if (mat[i][j]): perimeter += (4 - numofneighbour(mat, i, j)); return perimeter; # Driver Codemat = [ [0, 1, 0, 0, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0] ] print(findperimeter(mat), end=\"\\n\"); # This code is contributed by Akanksha Rai",
"e": 31527,
"s": 30550,
"text": null
},
{
"code": "using System; // C# program to find perimeter of area// covered by 1 in 2D matrix consists // of 0's and 1'spublic class GFG{ public const int R = 3; public const int C = 5; // Find the number of covered side // for mat[i][j]. public static int numofneighbour(int[][] mat, int i, int j) { int count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) { count++; } // LEFT if (j > 0 && mat[i][j - 1] == 1) { count++; } // DOWN if (i < R - 1 && mat[i + 1][j] == 1) { count++; } // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) { count++; } return count; } // Returns sum of perimeter of shapes // formed with 1s public static int findperimeter(int[][] mat) { int perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] == 1) { perimeter += (4 - numofneighbour(mat, i, j)); } } } return perimeter; } // Driver code public static void Main(string[] args) { int[][] mat = new int[][] { new int[] {0, 1, 0, 0, 0}, new int[] {1, 1, 1, 0, 0}, new int[] {1, 0, 0, 0, 0} }; Console.WriteLine(findperimeter(mat)); }} // This code is contributed by Shrikant13",
"e": 33128,
"s": 31527,
"text": null
},
{
"code": "<?php// PHP program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1's.$R = 3;$C = 5; // Find the number of covered side// for mat[i][j].function numofneighbour($mat, $i, $j){ global $R; global $C; $count = 0; // UP if ($i > 0 && ($mat[$i - 1][$j])) $count++; // LEFT if ($j > 0 && ($mat[$i][$j - 1])) $count++; // DOWN if (($i < $R-1 )&& ($mat[$i + 1][$j])) $count++; // RIGHT if (($j < $C-1) && ($mat[$i][$j + 1])) $count++; return $count;} // Returns sum of perimeter of shapes// formed with 1sfunction findperimeter($mat){ global $R; global $C; $perimeter = 0; // Traversing the matrix and finding ones // to calculate their contribution. for ($i = 0; $i < $R; $i++) for ( $j = 0; $j < $C; $j++) if ($mat[$i][$j]) $perimeter += (4 - numofneighbour($mat, $i, $j)); return $perimeter;} // Driver Code$mat = array(array(0, 1, 0, 0, 0), array(1, 1, 1, 0, 0), array(1, 0, 0, 0, 0)); echo findperimeter($mat), \"\\n\"; // This code is contributed by Sach_Code?>",
"e": 34278,
"s": 33128,
"text": null
},
{
"code": "<script> // JavaScript program to find perimeter of area// covered by 1 in 2D matrix consists// of 0's and 1'slet R = 3;let C = 5; // Find the number of covered side// for mat[i][j].function numofneighbour(mat, i, j){ let count = 0; // UP if (i > 0 && mat[i - 1][j] == 1) count++; // LEFT if (j > 0 && mat[i][j - 1] == 1) count++; // DOWN if (i < R - 1 && mat[i + 1][j] == 1) count++; // RIGHT if (j < C - 1 && mat[i][j + 1] == 1) count++; return count;} // Returns sum of perimeter of shapes// formed with 1sfunction findperimeter(mat){ let perimeter = 0; // Traversing the matrix and // finding ones to calculate // their contribution. for(let i = 0; i < R; i++) for(let j = 0; j < C; j++) if (mat[i][j] == 1) perimeter += (4 - numofneighbour(mat, i, j)); return perimeter;} // Driver Codelet mat = [ [ 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 0 ], [ 1, 0, 0, 0, 0 ] ]; document.write(findperimeter(mat)); // This code is contributed by souravghosh0416 </script>",
"e": 35417,
"s": 34278,
"text": null
},
{
"code": null,
"e": 35426,
"s": 35417,
"text": "Output: "
},
{
"code": null,
"e": 35429,
"s": 35426,
"text": "12"
},
{
"code": null,
"e": 35454,
"s": 35429,
"text": "Time Complexity : O(RC)."
},
{
"code": null,
"e": 35885,
"s": 35454,
"text": "This article is contributed by Anuj Chauhan(anuj0503). 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": 35897,
"s": 35885,
"text": "shrikanth13"
},
{
"code": null,
"e": 35907,
"s": 35897,
"text": "Sach_Code"
},
{
"code": null,
"e": 35920,
"s": 35907,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35936,
"s": 35920,
"text": "souravghosh0416"
},
{
"code": null,
"e": 35953,
"s": 35936,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 35969,
"s": 35953,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 35979,
"s": 35969,
"text": "Geometric"
},
{
"code": null,
"e": 35986,
"s": 35979,
"text": "Matrix"
},
{
"code": null,
"e": 35993,
"s": 35986,
"text": "Matrix"
},
{
"code": null,
"e": 36003,
"s": 35993,
"text": "Geometric"
},
{
"code": null,
"e": 36101,
"s": 36003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36167,
"s": 36101,
"text": "Haversine formula to find distance between two points on a sphere"
},
{
"code": null,
"e": 36199,
"s": 36167,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 36260,
"s": 36199,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 36306,
"s": 36260,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 36376,
"s": 36306,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 36411,
"s": 36376,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 36455,
"s": 36411,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 36491,
"s": 36455,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 36522,
"s": 36491,
"text": "Rat in a Maze | Backtracking-2"
}
] |
LinkedHashSet size() method in Java - GeeksforGeeks | 30 Sep, 2019
The Java.util.LinkedHashSet.size() method is used to get the size of the LinkedHashSet or the number of elements present in the LinkedHashSet.
Syntax:
Linked_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 LinkedHashSet.
Below program illustrate the Java.util.LinkedHashSet.size() method:
// Java code to illustrate LinkedHashSet.size() methodimport java.util.*;import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String args[]) { // Creating an empty LinkedHashSet LinkedHashSet<String> set = new LinkedHashSet<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 LinkedHashSet System.out.println("LinkedHashSet: " + set); // Displaying the size of the LinkedHashSet System.out.println("The size of the set is: " + set.size()); }}
LinkedHashSet: [Welcome, To, Geeks, 4]
The size of the set is: 4
Java-Functions
java-LinkedHashSet
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
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java | [
{
"code": null,
"e": 25653,
"s": 25625,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 25796,
"s": 25653,
"text": "The Java.util.LinkedHashSet.size() method is used to get the size of the LinkedHashSet or the number of elements present in the LinkedHashSet."
},
{
"code": null,
"e": 25804,
"s": 25796,
"text": "Syntax:"
},
{
"code": null,
"e": 25828,
"s": 25804,
"text": "Linked_Hash_Set.size()\n"
},
{
"code": null,
"e": 25882,
"s": 25828,
"text": "Parameters: This method does not takes any parameter."
},
{
"code": null,
"e": 25980,
"s": 25882,
"text": "Return Value: The method returns the size or the number of elements present in the LinkedHashSet."
},
{
"code": null,
"e": 26048,
"s": 25980,
"text": "Below program illustrate the Java.util.LinkedHashSet.size() method:"
},
{
"code": "// Java code to illustrate LinkedHashSet.size() methodimport java.util.*;import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String args[]) { // Creating an empty LinkedHashSet LinkedHashSet<String> set = new LinkedHashSet<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 LinkedHashSet System.out.println(\"LinkedHashSet: \" + set); // Displaying the size of the LinkedHashSet System.out.println(\"The size of the set is: \" + set.size()); }}",
"e": 26764,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26830,
"s": 26764,
"text": "LinkedHashSet: [Welcome, To, Geeks, 4]\nThe size of the set is: 4\n"
},
{
"code": null,
"e": 26845,
"s": 26830,
"text": "Java-Functions"
},
{
"code": null,
"e": 26864,
"s": 26845,
"text": "java-LinkedHashSet"
},
{
"code": null,
"e": 26869,
"s": 26864,
"text": "Java"
},
{
"code": null,
"e": 26874,
"s": 26869,
"text": "Java"
},
{
"code": null,
"e": 26972,
"s": 26874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27023,
"s": 26972,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27038,
"s": 27023,
"text": "Stream In Java"
},
{
"code": null,
"e": 27057,
"s": 27038,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27088,
"s": 27057,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27106,
"s": 27088,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27138,
"s": 27106,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27158,
"s": 27138,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27182,
"s": 27158,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27214,
"s": 27182,
"text": "Multidimensional Arrays in Java"
}
] |
Create GeeksforGeeks logo using HTML and CSS - GeeksforGeeks | 25 Feb, 2021
In this article, we will see how to create a GeeksforGeeks logo using HTML and CSS only.
Step 1: To create the GFG logo, first we take two divs (which are inline) and make circles with them. But the div elements are block-level that’s why we wrap both the divs with a wrapper div and make that div (wrapper) to display flex. Apply border with 10px solid colored green. You will get something like this.
Step 2: Now create a triangle on both the circles using pseudo-element: “after” and absolute position property. After applying the triangle we will get the shape like this.
Here the triangle’s background-colors are yellow, this is just for explanation. Change the background-color of triangles into white.
After applying the white background color into the triangles the result is :
Step 3: Now using the pseudo-element :before and position absolute property, create a square. You can apply this rule to any of the circles. The resulting logo looks like this:
Implementation with code :
Step 1: Create two divs having classes named circle1 and circle2, and wrap them into a parent div having the class named wrapper.
HTML
<div class="wrapper"> <div class="circle1"></div> <div class="circle2"></div></div>
Now assign the CSS property to the wrapper class.
.wrapper{
display: flex;
}
And style both the circles
CSS
.circle1{ height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative;} .circle2{ height: 100px; width: 100px; border: 20px solid green; border-radius: 200px; position: relative;}
Till now our logo looks like this
Step 2: Add the invisible triangles into both the circles using pseudo-element :after
CSS
.circle1:after{ content: ""; position: absolute; border-top: 100px solid transparent; border-left: 140px solid white; left: -50px; top: -35px;} .circle2:after{ content: ""; position: absolute; border-top: 100px solid transparent; border-right: 140px solid white; right: -50px; top: -35px;}
The resulting logo looks like this –
Step 3: Now add square onto the logo using before pseudo-element (we are not using after (pseudo-element) because we already used it for creating triangle).
CSS
.circle1:before{ content: ""; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1;}
The resulting logo is:
HTML
<!DOCTYPE html><html> <head> <style> .wrapper { display: flex } .circle1 { height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative; } .circle2 { height: 100px; width: 100px; border: 20px solid green; border-radius: 200px; position: relative; } .circle1:after { content: ""; position: absolute; border-top: 100px solid transparent; border-left: 140px solid white; left: -50px; top: -35px; } .circle2:after { content: ""; position: absolute; border-top: 100px solid transparent; border-right: 140px solid white; right: -50px; top: -35px; } .circle1:before { content: ""; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1; } </style></head> <body> <div class="wrapper"> <div class="circle1"></div> <div class="circle2"></div> </div></body> </html>
You can see that you are using many properties which are the same for both circles. If we use the same id for both the circles then we can write the common properties into that id and different properties into the classes.
Here is the optimized code for the above logo:
HTML
<!DOCTYPE html><html> <head> <style> .wrapper { display: flex } #circle { height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative; } #circle:after { content: ""; position: absolute; border-top: 100px solid transparent; top: -35px; } .circle1:after { border-left: 140px solid white; left: -50px; top: -35px; } .circle2:after { border-right: 140px solid white; right: -50px; } .circle1:before { content: ""; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1; } </style></head> <body> <div class="wrapper"> <div id="circle" class="circle1"></div> <div id="circle" class="circle2"></div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Questions
HTML-Questions
Technical Scripter 2020
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Making a div vertically scrollable using CSS
Form validation using jQuery
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26465,
"s": 26437,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 26554,
"s": 26465,
"text": "In this article, we will see how to create a GeeksforGeeks logo using HTML and CSS only."
},
{
"code": null,
"e": 26868,
"s": 26554,
"text": "Step 1: To create the GFG logo, first we take two divs (which are inline) and make circles with them. But the div elements are block-level that’s why we wrap both the divs with a wrapper div and make that div (wrapper) to display flex. Apply border with 10px solid colored green. You will get something like this."
},
{
"code": null,
"e": 27041,
"s": 26868,
"text": "Step 2: Now create a triangle on both the circles using pseudo-element: “after” and absolute position property. After applying the triangle we will get the shape like this."
},
{
"code": null,
"e": 27174,
"s": 27041,
"text": "Here the triangle’s background-colors are yellow, this is just for explanation. Change the background-color of triangles into white."
},
{
"code": null,
"e": 27251,
"s": 27174,
"text": "After applying the white background color into the triangles the result is :"
},
{
"code": null,
"e": 27428,
"s": 27251,
"text": "Step 3: Now using the pseudo-element :before and position absolute property, create a square. You can apply this rule to any of the circles. The resulting logo looks like this:"
},
{
"code": null,
"e": 27455,
"s": 27428,
"text": "Implementation with code :"
},
{
"code": null,
"e": 27585,
"s": 27455,
"text": "Step 1: Create two divs having classes named circle1 and circle2, and wrap them into a parent div having the class named wrapper."
},
{
"code": null,
"e": 27590,
"s": 27585,
"text": "HTML"
},
{
"code": "<div class=\"wrapper\"> <div class=\"circle1\"></div> <div class=\"circle2\"></div></div>",
"e": 27676,
"s": 27590,
"text": null
},
{
"code": null,
"e": 27726,
"s": 27676,
"text": "Now assign the CSS property to the wrapper class."
},
{
"code": null,
"e": 27756,
"s": 27726,
"text": ".wrapper{\n display: flex;\n}"
},
{
"code": null,
"e": 27784,
"s": 27756,
"text": "And style both the circles "
},
{
"code": null,
"e": 27788,
"s": 27784,
"text": "CSS"
},
{
"code": ".circle1{ height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative;} .circle2{ height: 100px; width: 100px; border: 20px solid green; border-radius: 200px; position: relative;}",
"e": 28037,
"s": 27788,
"text": null
},
{
"code": null,
"e": 28071,
"s": 28037,
"text": "Till now our logo looks like this"
},
{
"code": null,
"e": 28157,
"s": 28071,
"text": "Step 2: Add the invisible triangles into both the circles using pseudo-element :after"
},
{
"code": null,
"e": 28161,
"s": 28157,
"text": "CSS"
},
{
"code": ".circle1:after{ content: \"\"; position: absolute; border-top: 100px solid transparent; border-left: 140px solid white; left: -50px; top: -35px;} .circle2:after{ content: \"\"; position: absolute; border-top: 100px solid transparent; border-right: 140px solid white; right: -50px; top: -35px;}",
"e": 28490,
"s": 28161,
"text": null
},
{
"code": null,
"e": 28527,
"s": 28490,
"text": "The resulting logo looks like this –"
},
{
"code": null,
"e": 28684,
"s": 28527,
"text": "Step 3: Now add square onto the logo using before pseudo-element (we are not using after (pseudo-element) because we already used it for creating triangle)."
},
{
"code": null,
"e": 28688,
"s": 28684,
"text": "CSS"
},
{
"code": ".circle1:before{ content: \"\"; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1;}",
"e": 28846,
"s": 28688,
"text": null
},
{
"code": null,
"e": 28869,
"s": 28846,
"text": "The resulting logo is:"
},
{
"code": null,
"e": 28874,
"s": 28869,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .wrapper { display: flex } .circle1 { height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative; } .circle2 { height: 100px; width: 100px; border: 20px solid green; border-radius: 200px; position: relative; } .circle1:after { content: \"\"; position: absolute; border-top: 100px solid transparent; border-left: 140px solid white; left: -50px; top: -35px; } .circle2:after { content: \"\"; position: absolute; border-top: 100px solid transparent; border-right: 140px solid white; right: -50px; top: -35px; } .circle1:before { content: \"\"; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1; } </style></head> <body> <div class=\"wrapper\"> <div class=\"circle1\"></div> <div class=\"circle2\"></div> </div></body> </html>",
"e": 30175,
"s": 28874,
"text": null
},
{
"code": null,
"e": 30398,
"s": 30175,
"text": "You can see that you are using many properties which are the same for both circles. If we use the same id for both the circles then we can write the common properties into that id and different properties into the classes."
},
{
"code": null,
"e": 30445,
"s": 30398,
"text": "Here is the optimized code for the above logo:"
},
{
"code": null,
"e": 30450,
"s": 30445,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .wrapper { display: flex } #circle { height: 100px; width: 100px; border: 20px solid green; border-radius: 100px; position: relative; } #circle:after { content: \"\"; position: absolute; border-top: 100px solid transparent; top: -35px; } .circle1:after { border-left: 140px solid white; left: -50px; top: -35px; } .circle2:after { border-right: 140px solid white; right: -50px; } .circle1:before { content: \"\"; height: 20px; width: 276px; position: absolute; background: green; left: -18px; top: 45px; z-index: 1; } </style></head> <body> <div class=\"wrapper\"> <div id=\"circle\" class=\"circle1\"></div> <div id=\"circle\" class=\"circle2\"></div> </div></body> </html>",
"e": 31524,
"s": 30450,
"text": null
},
{
"code": null,
"e": 31532,
"s": 31524,
"text": "Output:"
},
{
"code": null,
"e": 31669,
"s": 31532,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31683,
"s": 31669,
"text": "CSS-Questions"
},
{
"code": null,
"e": 31698,
"s": 31683,
"text": "HTML-Questions"
},
{
"code": null,
"e": 31722,
"s": 31698,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31726,
"s": 31722,
"text": "CSS"
},
{
"code": null,
"e": 31731,
"s": 31726,
"text": "HTML"
},
{
"code": null,
"e": 31750,
"s": 31731,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31767,
"s": 31750,
"text": "Web Technologies"
},
{
"code": null,
"e": 31794,
"s": 31767,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31799,
"s": 31794,
"text": "HTML"
},
{
"code": null,
"e": 31897,
"s": 31799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31936,
"s": 31897,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31973,
"s": 31936,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32014,
"s": 31973,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 32059,
"s": 32014,
"text": "Making a div vertically scrollable using CSS"
},
{
"code": null,
"e": 32088,
"s": 32059,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32148,
"s": 32088,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32201,
"s": 32148,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32262,
"s": 32201,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32286,
"s": 32262,
"text": "REST API (Introduction)"
}
] |
Java Program to Find sum of Series with n-th term as n^2 - (n-1)^2 - GeeksforGeeks | 05 Dec, 2018
We are given an integer n and n-th term in a series as expressed below:
Tn = n2 - (n-1)2
We need to find Sn mod (109 + 7), where Sn is the sum of all of the terms of the given series and,
Sn = T1 + T2 + T3 + T4 + ...... + Tn
Examples:
Input : 229137999
Output : 218194447
Input : 344936985
Output : 788019571
Let us do some calculations, before writing the program. Tn can be reduced to give 2n-1 . Let’s see how:
Given, Tn = n2 - (n-1)2
Or, Tn = n2 - (1 + n2 - 2n)
Or, Tn = n2 - 1 - n2 + 2n
Or, Tn = 2n - 1.
Now, we need to find ∑Tn.
∑Tn = ∑(2n – 1)
We can simplify the above formula as,∑(2n – 1) = 2*∑n – ∑1Or, ∑(2n – 1) = 2*∑n – n.Where, ∑n is the sum of first n natural numbers.
We know the sum of n natural number = n(n+1)/2.
Therefore, putting this value in the above equation we will get,
∑Tn = (2*(n)*(n+1)/2)-n = n2
Now the value of n2 can be very large. So instead of direct squaring n and taking mod of the result. We will use the property of modular multiplication for calculating squares:
(a*b)%k = ((a%k)*(b%k))%k
// Java program to find sum of given// series. public class FINDSUM { static long mod = 1000000007; public static long findSum(long n) { return ((n % mod) * (n % mod)) % mod; } public static void main(String[] args) { long n = 229137999; System.out.print(findSum(n)); }} // Contributed by _omg
218194447
Please refer complete article on Find sum of Series with n-th term as n^2 – (n-1)^2 for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Remove first and last character of a string in Java
Java Program to Convert Char to Int
Sorting in Java | [
{
"code": null,
"e": 26733,
"s": 26705,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 26805,
"s": 26733,
"text": "We are given an integer n and n-th term in a series as expressed below:"
},
{
"code": null,
"e": 26822,
"s": 26805,
"text": "Tn = n2 - (n-1)2"
},
{
"code": null,
"e": 26921,
"s": 26822,
"text": "We need to find Sn mod (109 + 7), where Sn is the sum of all of the terms of the given series and,"
},
{
"code": null,
"e": 26958,
"s": 26921,
"text": "Sn = T1 + T2 + T3 + T4 + ...... + Tn"
},
{
"code": null,
"e": 26968,
"s": 26958,
"text": "Examples:"
},
{
"code": null,
"e": 27044,
"s": 26968,
"text": "Input : 229137999\nOutput : 218194447\n\nInput : 344936985\nOutput : 788019571\n"
},
{
"code": null,
"e": 27149,
"s": 27044,
"text": "Let us do some calculations, before writing the program. Tn can be reduced to give 2n-1 . Let’s see how:"
},
{
"code": null,
"e": 27249,
"s": 27149,
"text": "Given, Tn = n2 - (n-1)2\nOr, Tn = n2 - (1 + n2 - 2n)\nOr, Tn = n2 - 1 - n2 + 2n\nOr, Tn = 2n - 1. \n"
},
{
"code": null,
"e": 27275,
"s": 27249,
"text": "Now, we need to find ∑Tn."
},
{
"code": null,
"e": 27291,
"s": 27275,
"text": "∑Tn = ∑(2n – 1)"
},
{
"code": null,
"e": 27423,
"s": 27291,
"text": "We can simplify the above formula as,∑(2n – 1) = 2*∑n – ∑1Or, ∑(2n – 1) = 2*∑n – n.Where, ∑n is the sum of first n natural numbers."
},
{
"code": null,
"e": 27471,
"s": 27423,
"text": "We know the sum of n natural number = n(n+1)/2."
},
{
"code": null,
"e": 27536,
"s": 27471,
"text": "Therefore, putting this value in the above equation we will get,"
},
{
"code": null,
"e": 27565,
"s": 27536,
"text": "∑Tn = (2*(n)*(n+1)/2)-n = n2"
},
{
"code": null,
"e": 27742,
"s": 27565,
"text": "Now the value of n2 can be very large. So instead of direct squaring n and taking mod of the result. We will use the property of modular multiplication for calculating squares:"
},
{
"code": null,
"e": 27768,
"s": 27742,
"text": "(a*b)%k = ((a%k)*(b%k))%k"
},
{
"code": "// Java program to find sum of given// series. public class FINDSUM { static long mod = 1000000007; public static long findSum(long n) { return ((n % mod) * (n % mod)) % mod; } public static void main(String[] args) { long n = 229137999; System.out.print(findSum(n)); }} // Contributed by _omg",
"e": 28112,
"s": 27768,
"text": null
},
{
"code": null,
"e": 28123,
"s": 28112,
"text": "218194447\n"
},
{
"code": null,
"e": 28225,
"s": 28123,
"text": "Please refer complete article on Find sum of Series with n-th term as n^2 – (n-1)^2 for more details!"
},
{
"code": null,
"e": 28239,
"s": 28225,
"text": "Java Programs"
},
{
"code": null,
"e": 28337,
"s": 28239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28369,
"s": 28337,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 28398,
"s": 28369,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 28455,
"s": 28398,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 28493,
"s": 28455,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 28574,
"s": 28493,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 28622,
"s": 28574,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28673,
"s": 28622,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 28725,
"s": 28673,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 28761,
"s": 28725,
"text": "Java Program to Convert Char to Int"
}
] |
setcolor function in C - GeeksforGeeks | 23 Jan, 2018
The header file graphics.h contains setcolor() function which is used to set the current drawing color to the new color.Syntax :
void setcolor(int color);
Explanation : In Graphics, each color is assigned a number. Total number of colors available are 16. Number of available colors depends on current graphics mode and driver. For example, setcolor(RED) or setcolor(4) changes the current drawing color to RED. Remember that default drawing color is WHITE. The Colors table is given below.
COLOR INT VALUES
-------------------------------
BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
Below is the implementation of setcolor() function.
// C Implementation for setcolor()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm, color; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // Draws circle in white color // center at (100, 100) and radius // as 50 circle(100, 100, 50); // setcolor function setcolor(GREEN); // Draws circle in green color // center at (200, 200) and radius // as 50 circle(200, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
fork() in C
Converting Strings to Numbers in C/C++
std::string class in C++
Enumeration (or enum) in C | [
{
"code": null,
"e": 26029,
"s": 26001,
"text": "\n23 Jan, 2018"
},
{
"code": null,
"e": 26158,
"s": 26029,
"text": "The header file graphics.h contains setcolor() function which is used to set the current drawing color to the new color.Syntax :"
},
{
"code": null,
"e": 26185,
"s": 26158,
"text": "void setcolor(int color);\n"
},
{
"code": null,
"e": 26521,
"s": 26185,
"text": "Explanation : In Graphics, each color is assigned a number. Total number of colors available are 16. Number of available colors depends on current graphics mode and driver. For example, setcolor(RED) or setcolor(4) changes the current drawing color to RED. Remember that default drawing color is WHITE. The Colors table is given below."
},
{
"code": null,
"e": 27006,
"s": 26521,
"text": "COLOR INT VALUES\n-------------------------------\nBLACK 0\nBLUE 1\nGREEN 2\nCYAN 3 \nRED 4\nMAGENTA 5\nBROWN 6 \nLIGHTGRAY 7 \nDARKGRAY 8\nLIGHTBLUE 9\nLIGHTGREEN 10\nLIGHTCYAN 11\nLIGHTRED 12\nLIGHTMAGENTA 13\nYELLOW 14\nWHITE 15\n"
},
{
"code": null,
"e": 27058,
"s": 27006,
"text": "Below is the implementation of setcolor() function."
},
{
"code": "// C Implementation for setcolor()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm, color; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // Draws circle in white color // center at (100, 100) and radius // as 50 circle(100, 100, 50); // setcolor function setcolor(GREEN); // Draws circle in green color // center at (200, 200) and radius // as 50 circle(200, 200, 50); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 27935,
"s": 27058,
"text": null
},
{
"code": null,
"e": 27944,
"s": 27935,
"text": "Output :"
},
{
"code": null,
"e": 27957,
"s": 27946,
"text": "c-graphics"
},
{
"code": null,
"e": 27975,
"s": 27957,
"text": "computer-graphics"
},
{
"code": null,
"e": 27986,
"s": 27975,
"text": "C Language"
},
{
"code": null,
"e": 28084,
"s": 27986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28119,
"s": 28084,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28165,
"s": 28119,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28187,
"s": 28165,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 28204,
"s": 28187,
"text": "Substring in C++"
},
{
"code": null,
"e": 28244,
"s": 28204,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 28272,
"s": 28244,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28284,
"s": 28272,
"text": "fork() in C"
},
{
"code": null,
"e": 28323,
"s": 28284,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 28348,
"s": 28323,
"text": "std::string class in C++"
}
] |
Normal Distribution Plot using Numpy and Matplotlib - GeeksforGeeks | 05 May, 2021
In this article, we will see how we can create a normal distribution plot in python with numpy and matplotlib module.
Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a die, and many more.
It is generally observed that data distribution is normal when there is a random collection of data from independent sources. The graph produced after plotting the value of the variable on x-axis and count of the value on y-axis is bell-shaped curve graph. The graph signifies that the peak point is the mean of the data set and half of the values of data set lie on the left side of the mean and other half lies on the right part of the mean telling about the distribution of the values. The graph is symmetric distribution.
Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
Below are some program which create a Normal Distribution plot using Numpy and Matplotlib module:
Example 1:
Python3
# importing numpy as npimport numpy as np # importing pyplot as pltimport matplotlib.pyplot as plt # positionpos = 100# scalescale = 5 # sizesize = 100000 # creating a normal distribution datavalues = np.random.normal(pos, scale, size) # plotting histographplt.hist(values, 100) # showing the graphplt.show()
Output :
Example 2:
Python3
# importing numpy as npimport numpy as np # importing pyplot as pltimport matplotlib.pyplot as plt # positionpos = 0 # scalescale = 10 # sizesize = 10000 # random seednp.random.seed(10) # creating a normal distribution datavalues = np.random.normal(pos, scale, size) # plotting histographplt.hist(values, 100) # plotting mean lineplt.axvline(values.mean(), color='k', linestyle='dashed', linewidth=2) # showing the plotplt.show()
Output :
sweetyty
Python-matplotlib
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 25800,
"s": 25681,
"text": "In this article, we will see how we can create a normal distribution plot in python with numpy and matplotlib module. "
},
{
"code": null,
"e": 26141,
"s": 25800,
"text": "Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a die, and many more."
},
{
"code": null,
"e": 26668,
"s": 26141,
"text": "It is generally observed that data distribution is normal when there is a random collection of data from independent sources. The graph produced after plotting the value of the variable on x-axis and count of the value on y-axis is bell-shaped curve graph. The graph signifies that the peak point is the mean of the data set and half of the values of data set lie on the left side of the mean and other half lies on the right part of the mean telling about the distribution of the values. The graph is symmetric distribution. "
},
{
"code": null,
"e": 27012,
"s": 26668,
"text": "Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data."
},
{
"code": null,
"e": 27291,
"s": 27012,
"text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc."
},
{
"code": null,
"e": 27389,
"s": 27291,
"text": "Below are some program which create a Normal Distribution plot using Numpy and Matplotlib module:"
},
{
"code": null,
"e": 27400,
"s": 27389,
"text": "Example 1:"
},
{
"code": null,
"e": 27408,
"s": 27400,
"text": "Python3"
},
{
"code": "# importing numpy as npimport numpy as np # importing pyplot as pltimport matplotlib.pyplot as plt # positionpos = 100# scalescale = 5 # sizesize = 100000 # creating a normal distribution datavalues = np.random.normal(pos, scale, size) # plotting histographplt.hist(values, 100) # showing the graphplt.show()",
"e": 27717,
"s": 27408,
"text": null
},
{
"code": null,
"e": 27728,
"s": 27717,
"text": "Output : "
},
{
"code": null,
"e": 27739,
"s": 27728,
"text": "Example 2:"
},
{
"code": null,
"e": 27747,
"s": 27739,
"text": "Python3"
},
{
"code": "# importing numpy as npimport numpy as np # importing pyplot as pltimport matplotlib.pyplot as plt # positionpos = 0 # scalescale = 10 # sizesize = 10000 # random seednp.random.seed(10) # creating a normal distribution datavalues = np.random.normal(pos, scale, size) # plotting histographplt.hist(values, 100) # plotting mean lineplt.axvline(values.mean(), color='k', linestyle='dashed', linewidth=2) # showing the plotplt.show()",
"e": 28178,
"s": 27747,
"text": null
},
{
"code": null,
"e": 28189,
"s": 28178,
"text": "Output : "
},
{
"code": null,
"e": 28198,
"s": 28189,
"text": "sweetyty"
},
{
"code": null,
"e": 28216,
"s": 28198,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28229,
"s": 28216,
"text": "Python-numpy"
},
{
"code": null,
"e": 28236,
"s": 28229,
"text": "Python"
},
{
"code": null,
"e": 28334,
"s": 28236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28352,
"s": 28334,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28387,
"s": 28352,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28419,
"s": 28387,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28441,
"s": 28419,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28483,
"s": 28441,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28513,
"s": 28483,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28539,
"s": 28513,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28568,
"s": 28539,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28612,
"s": 28568,
"text": "Reading and Writing to text files in Python"
}
] |
Feature Engineering Techniques. An introduction to some of the main... | by Pier Paolo Ippolito | Towards Data Science | 1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Create Audio Narrations with Play.ht
Feature Engineering is one of the most important steps to complete before starting a Machine Learning analysis. Creating the best possible Machine Learning/Deep Learning model can certainly help to achieve good results, but choosing the right features in the right format to feed in a model can by far boost performances leading to the following benefits:
Enable us to achieve good model performances using simpler Machine Learning models.
Using simpler Machine Learning models, increases the transparency of our model, therefore making easier for us to understand how is making its predictions.
Reduced need to use Ensemble Learning techniques.
Reduced need to perform Hyperparameters Optimization.
Other common techniques which can be used in order to make the best use out of the given data are Features Selection and Extraction, of which I talked about in my previous posts.
We will now walk through some of the most common Feature Engineering techniques. Most of the basic Feature Engineering techniques consist of finding inconsistencies in the data and of creating new features by combining/diving existing ones.
All the code used for this article is available on my GitHub account at this link.
For this example, I decided to create a simple dataset which is affected by some of the most common problems which are faced during a Data Analysis (eg. Missing numbers, outlier values, scaling issues, ...).
When using Log Transform, the distributions of the original features get transformed to resemble more closely Gaussians Distributions. This can particularly useful, especially when using Machine Learning models such as Linear Discriminant Analysis (LDA) and Naive Bayes Classifiers which assume their input data follows a Gaussian Distribution.
In this example, I am going to apply Log Transform to all the Numeric Features available in the dataset. I additionally decided to subtract the original features with their respective minimum values and then add them to one, in order to make sure each element in these columns is positive (Logarithms just support positive values).
Imputation is the art of identifying and replacing missing values from a dataset using appropriate values. Presence of missing values in a dataset can be caused by many possible factors such as: privacy concerns, technical faults when recording data using sensors, humans errors, etc...
There are two main types of Imputation:
Numerical Imputation: missing numbers in numerical features can be imputed using many different techniques. Some of the main methods used, are to replace missing values with the overall mean or mode of the affected column. If you are interested in learning more about advanced techniques, you can find more information here.
Categorical Imputation: for categorical features, missing values are commonly replaced using the overall column mode. In some particular case, if the categorical column structure is not well defined, it might be better instead to replace the missing values creating a new category and naming it “Unknown” or “Other”.
We can now, first of all, examine which features are affected by NaNs (Not a Number) by running the following few lines.
One of the easiest methods to deal with Missing Numbers could be to remove all the rows affected by them. Although, it would better to set up a threshold (eg. 20%), and delete just the rows which have more missing numbers than the threshold.
Another possible solution could be to replace all the NaNs with the column mode for both our numerical and categorical data.
Date Objects can be quite difficult to deal with for Machine Learning models because of their format. It can, therefore, be necessary at times to divide a date into multiple columns. This same consideration can be applied to many other common cases in Data Analysis (eg. Natural Language Processing).
In our example, we are now going to divide our Date column into three different columns: Year, Month and Day.
Outliers are a small fraction of data points which are quite distant from the rest of the observations in a feature. Outliers can be introduced in a dataset mainly because of errors when collecting the data or because of special anomalies which are characteristic of our specific feature.
Four main techniques are used in order to identify outliers:
Data Visualization: determining outlier values by visually inspecting the data distribution.
Z-Score: is used if we know that the distribution of our features is Gaussian. In fact, when working with Gaussian distributions, we know that about 2 standard deviations from the distribution mean about 95% of the data will be covered and 3 standard distributions away from the mean will cover instead about 99.7% of the data. Therefore, using a factor value between 2 and 3 we can be able to quite accurately delete all the outlier values. If you are interested in finding out more about Gaussian Distributions, you can find more information here.
Percentiles: is another statistical method for identifying outliers. When using percentiles, we assume that a certain top and bottom percent of our data are outliers. The key point when using this method is to find the best percentage values. One useful approach could be to visualize the data before and after applying the percentile method to examine the overall results.
Capping: instead of deleting the outlier values, we replace them with the highest normal value in our column.
Other more advanced techniques commonly used to detect outliers are DBSCAN and Isolation Forest.
Going on with our example, we can start by looking at our two left numerical features (X2, X3). By creating a simple BoxPlot using Seaborn, we can clearly see that X2 has some outlier values.
Using both the Z-score (with a factor of 2) and the Percentiles methods, we can now test how many outliers will be identified in X2. As shown from the output box below, 234 values were identified using the Z Score, while using the Percentiles method 800 values were deleted.
800077667200
It could have additionally been possible to deal with our Outliers by capping them instead of dropping them.
Binning is a common technique used to smooth noisy data, by diving a numerical or categorical feature in different bins. This can, therefore, help us to decrease the risk of overfitting (although possibly reducing our model accuracy).
Most of Machine Learning models are currently not able to deal with Categorical Data, therefore it is usually necessary to convert all categorical features to numeric before feeding them into Machine Learning models.
Different techniques can be implemented in Python such as: One Hot Encoding (to convert features) and Label Encoder (to convert labels).
One Hot Encoding takes a feature and split it in as many columns as the number of the different categories present in the original column. It then assigns a zero to all the rows which didn’t have that particular category and one for all the ones which instead had it. One Hot Encoding can be implemented in Python using Pandas get_dummies() function.
Label Encoder replaces instead all the categorical cases by assigning them a different number and storing them in a single column.
It is highly preferable not to use Label Encoder with normal features because some Machine Learning models might get confused and think that the encoded cases which have higher values than the other ones might be more important of them (thinking about them as in hierarchical order). This doesn’t instead happen when using One Hot Encoding.
We can now go on dividing our dataset into features (X) and labels (Y) and then applying respectively One Hot Encoding and Label Encoder.
In most of the datasets, numerical features have all different ranges (eg. Height vs Weight). Although, for some for Machine Learning algorithms, it can be important to limit our input features within a defined range. In fact, for some distance-based models such as Naive Bayes, Support Vector Machines and Clustering Algorithms, it would then be almost impossible to compare different features if they all have different ranges.
Two common ways of scaling features are:
Standardization: scales the input features while taking into account their standard deviation (using Standardization our transformed features will look similar to a Normal Distribution). This method can reduce outliers importance but can lead to different ranges between features because of differences in the standard deviation. Standardization can be implemented in scikit-learn by using StandardScaler().
Normalization: scales all the features in a range between 0 and 1 but can increase the effect of outliers because the standard deviation of each of the different features is not taken into account. Normalization can be implemented in scikit-learn by using MinMaxScaler().
In this example, we will be using Standardization and we will then take care of our Outlier Values. If the dataset you are working with does not extensively suffer from Outlier Values, scikit-learn provides also another Standardization function called RobustScaler() which can by default reduce the effect of outliers.
Different techniques and packages have been developed during the last few years in order to automate Feature Engineering processes. These can certainly result useful when performing a first analysis of our dataset but they are still not able to automate in full the whole Feature Engineering process. Domain Knowledge about the data and expertise of the Data Scientist in modelling the raw data to best fit the analysis purpose can’t yet be replaceable. One of the most popular library for Automated Feature Selection in Python is Featuretools.
It’s now time to finally to test our polished dataset prediction accuracy by using a Random Forest Classifier. As shown below, our classifier is now successfully able to achieve a 100% prediction accuracy.
1.40625[[1204 0] [ 0 1196]] precision recall f1-score support 0 1.00 1.00 1.00 1204 1 1.00 1.00 1.00 1196 micro avg 1.00 1.00 1.00 2400 macro avg 1.00 1.00 1.00 2400weighted avg 1.00 1.00 1.00 2400
I hope you enjoyed this article, thank you for reading!
If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:
Linkedin
Personal Blog
Personal Website
Medium Profile
GitHub
Kaggle
[1] What is One Hot Encoding and How to Do It. Michael DelSole, Medium. Accessed at: https://medium.com/@michaeldelsole/what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179 | [
{
"code": null,
"e": 174,
"s": 172,
"text": "1"
},
{
"code": null,
"e": 176,
"s": 174,
"text": "2"
},
{
"code": null,
"e": 178,
"s": 176,
"text": "3"
},
{
"code": null,
"e": 180,
"s": 178,
"text": "4"
},
{
"code": null,
"e": 182,
"s": 180,
"text": "5"
},
{
"code": null,
"e": 184,
"s": 182,
"text": "6"
},
{
"code": null,
"e": 186,
"s": 184,
"text": "7"
},
{
"code": null,
"e": 188,
"s": 186,
"text": "8"
},
{
"code": null,
"e": 190,
"s": 188,
"text": "9"
},
{
"code": null,
"e": 193,
"s": 190,
"text": "10"
},
{
"code": null,
"e": 212,
"s": 193,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 238,
"s": 212,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 275,
"s": 238,
"text": "Create Audio Narrations with Play.ht"
},
{
"code": null,
"e": 631,
"s": 275,
"text": "Feature Engineering is one of the most important steps to complete before starting a Machine Learning analysis. Creating the best possible Machine Learning/Deep Learning model can certainly help to achieve good results, but choosing the right features in the right format to feed in a model can by far boost performances leading to the following benefits:"
},
{
"code": null,
"e": 715,
"s": 631,
"text": "Enable us to achieve good model performances using simpler Machine Learning models."
},
{
"code": null,
"e": 871,
"s": 715,
"text": "Using simpler Machine Learning models, increases the transparency of our model, therefore making easier for us to understand how is making its predictions."
},
{
"code": null,
"e": 921,
"s": 871,
"text": "Reduced need to use Ensemble Learning techniques."
},
{
"code": null,
"e": 975,
"s": 921,
"text": "Reduced need to perform Hyperparameters Optimization."
},
{
"code": null,
"e": 1154,
"s": 975,
"text": "Other common techniques which can be used in order to make the best use out of the given data are Features Selection and Extraction, of which I talked about in my previous posts."
},
{
"code": null,
"e": 1395,
"s": 1154,
"text": "We will now walk through some of the most common Feature Engineering techniques. Most of the basic Feature Engineering techniques consist of finding inconsistencies in the data and of creating new features by combining/diving existing ones."
},
{
"code": null,
"e": 1478,
"s": 1395,
"text": "All the code used for this article is available on my GitHub account at this link."
},
{
"code": null,
"e": 1686,
"s": 1478,
"text": "For this example, I decided to create a simple dataset which is affected by some of the most common problems which are faced during a Data Analysis (eg. Missing numbers, outlier values, scaling issues, ...)."
},
{
"code": null,
"e": 2031,
"s": 1686,
"text": "When using Log Transform, the distributions of the original features get transformed to resemble more closely Gaussians Distributions. This can particularly useful, especially when using Machine Learning models such as Linear Discriminant Analysis (LDA) and Naive Bayes Classifiers which assume their input data follows a Gaussian Distribution."
},
{
"code": null,
"e": 2363,
"s": 2031,
"text": "In this example, I am going to apply Log Transform to all the Numeric Features available in the dataset. I additionally decided to subtract the original features with their respective minimum values and then add them to one, in order to make sure each element in these columns is positive (Logarithms just support positive values)."
},
{
"code": null,
"e": 2650,
"s": 2363,
"text": "Imputation is the art of identifying and replacing missing values from a dataset using appropriate values. Presence of missing values in a dataset can be caused by many possible factors such as: privacy concerns, technical faults when recording data using sensors, humans errors, etc..."
},
{
"code": null,
"e": 2690,
"s": 2650,
"text": "There are two main types of Imputation:"
},
{
"code": null,
"e": 3015,
"s": 2690,
"text": "Numerical Imputation: missing numbers in numerical features can be imputed using many different techniques. Some of the main methods used, are to replace missing values with the overall mean or mode of the affected column. If you are interested in learning more about advanced techniques, you can find more information here."
},
{
"code": null,
"e": 3332,
"s": 3015,
"text": "Categorical Imputation: for categorical features, missing values are commonly replaced using the overall column mode. In some particular case, if the categorical column structure is not well defined, it might be better instead to replace the missing values creating a new category and naming it “Unknown” or “Other”."
},
{
"code": null,
"e": 3453,
"s": 3332,
"text": "We can now, first of all, examine which features are affected by NaNs (Not a Number) by running the following few lines."
},
{
"code": null,
"e": 3695,
"s": 3453,
"text": "One of the easiest methods to deal with Missing Numbers could be to remove all the rows affected by them. Although, it would better to set up a threshold (eg. 20%), and delete just the rows which have more missing numbers than the threshold."
},
{
"code": null,
"e": 3820,
"s": 3695,
"text": "Another possible solution could be to replace all the NaNs with the column mode for both our numerical and categorical data."
},
{
"code": null,
"e": 4121,
"s": 3820,
"text": "Date Objects can be quite difficult to deal with for Machine Learning models because of their format. It can, therefore, be necessary at times to divide a date into multiple columns. This same consideration can be applied to many other common cases in Data Analysis (eg. Natural Language Processing)."
},
{
"code": null,
"e": 4231,
"s": 4121,
"text": "In our example, we are now going to divide our Date column into three different columns: Year, Month and Day."
},
{
"code": null,
"e": 4520,
"s": 4231,
"text": "Outliers are a small fraction of data points which are quite distant from the rest of the observations in a feature. Outliers can be introduced in a dataset mainly because of errors when collecting the data or because of special anomalies which are characteristic of our specific feature."
},
{
"code": null,
"e": 4581,
"s": 4520,
"text": "Four main techniques are used in order to identify outliers:"
},
{
"code": null,
"e": 4674,
"s": 4581,
"text": "Data Visualization: determining outlier values by visually inspecting the data distribution."
},
{
"code": null,
"e": 5224,
"s": 4674,
"text": "Z-Score: is used if we know that the distribution of our features is Gaussian. In fact, when working with Gaussian distributions, we know that about 2 standard deviations from the distribution mean about 95% of the data will be covered and 3 standard distributions away from the mean will cover instead about 99.7% of the data. Therefore, using a factor value between 2 and 3 we can be able to quite accurately delete all the outlier values. If you are interested in finding out more about Gaussian Distributions, you can find more information here."
},
{
"code": null,
"e": 5598,
"s": 5224,
"text": "Percentiles: is another statistical method for identifying outliers. When using percentiles, we assume that a certain top and bottom percent of our data are outliers. The key point when using this method is to find the best percentage values. One useful approach could be to visualize the data before and after applying the percentile method to examine the overall results."
},
{
"code": null,
"e": 5708,
"s": 5598,
"text": "Capping: instead of deleting the outlier values, we replace them with the highest normal value in our column."
},
{
"code": null,
"e": 5805,
"s": 5708,
"text": "Other more advanced techniques commonly used to detect outliers are DBSCAN and Isolation Forest."
},
{
"code": null,
"e": 5997,
"s": 5805,
"text": "Going on with our example, we can start by looking at our two left numerical features (X2, X3). By creating a simple BoxPlot using Seaborn, we can clearly see that X2 has some outlier values."
},
{
"code": null,
"e": 6272,
"s": 5997,
"text": "Using both the Z-score (with a factor of 2) and the Percentiles methods, we can now test how many outliers will be identified in X2. As shown from the output box below, 234 values were identified using the Z Score, while using the Percentiles method 800 values were deleted."
},
{
"code": null,
"e": 6285,
"s": 6272,
"text": "800077667200"
},
{
"code": null,
"e": 6394,
"s": 6285,
"text": "It could have additionally been possible to deal with our Outliers by capping them instead of dropping them."
},
{
"code": null,
"e": 6629,
"s": 6394,
"text": "Binning is a common technique used to smooth noisy data, by diving a numerical or categorical feature in different bins. This can, therefore, help us to decrease the risk of overfitting (although possibly reducing our model accuracy)."
},
{
"code": null,
"e": 6846,
"s": 6629,
"text": "Most of Machine Learning models are currently not able to deal with Categorical Data, therefore it is usually necessary to convert all categorical features to numeric before feeding them into Machine Learning models."
},
{
"code": null,
"e": 6983,
"s": 6846,
"text": "Different techniques can be implemented in Python such as: One Hot Encoding (to convert features) and Label Encoder (to convert labels)."
},
{
"code": null,
"e": 7334,
"s": 6983,
"text": "One Hot Encoding takes a feature and split it in as many columns as the number of the different categories present in the original column. It then assigns a zero to all the rows which didn’t have that particular category and one for all the ones which instead had it. One Hot Encoding can be implemented in Python using Pandas get_dummies() function."
},
{
"code": null,
"e": 7465,
"s": 7334,
"text": "Label Encoder replaces instead all the categorical cases by assigning them a different number and storing them in a single column."
},
{
"code": null,
"e": 7806,
"s": 7465,
"text": "It is highly preferable not to use Label Encoder with normal features because some Machine Learning models might get confused and think that the encoded cases which have higher values than the other ones might be more important of them (thinking about them as in hierarchical order). This doesn’t instead happen when using One Hot Encoding."
},
{
"code": null,
"e": 7944,
"s": 7806,
"text": "We can now go on dividing our dataset into features (X) and labels (Y) and then applying respectively One Hot Encoding and Label Encoder."
},
{
"code": null,
"e": 8374,
"s": 7944,
"text": "In most of the datasets, numerical features have all different ranges (eg. Height vs Weight). Although, for some for Machine Learning algorithms, it can be important to limit our input features within a defined range. In fact, for some distance-based models such as Naive Bayes, Support Vector Machines and Clustering Algorithms, it would then be almost impossible to compare different features if they all have different ranges."
},
{
"code": null,
"e": 8415,
"s": 8374,
"text": "Two common ways of scaling features are:"
},
{
"code": null,
"e": 8823,
"s": 8415,
"text": "Standardization: scales the input features while taking into account their standard deviation (using Standardization our transformed features will look similar to a Normal Distribution). This method can reduce outliers importance but can lead to different ranges between features because of differences in the standard deviation. Standardization can be implemented in scikit-learn by using StandardScaler()."
},
{
"code": null,
"e": 9095,
"s": 8823,
"text": "Normalization: scales all the features in a range between 0 and 1 but can increase the effect of outliers because the standard deviation of each of the different features is not taken into account. Normalization can be implemented in scikit-learn by using MinMaxScaler()."
},
{
"code": null,
"e": 9414,
"s": 9095,
"text": "In this example, we will be using Standardization and we will then take care of our Outlier Values. If the dataset you are working with does not extensively suffer from Outlier Values, scikit-learn provides also another Standardization function called RobustScaler() which can by default reduce the effect of outliers."
},
{
"code": null,
"e": 9959,
"s": 9414,
"text": "Different techniques and packages have been developed during the last few years in order to automate Feature Engineering processes. These can certainly result useful when performing a first analysis of our dataset but they are still not able to automate in full the whole Feature Engineering process. Domain Knowledge about the data and expertise of the Data Scientist in modelling the raw data to best fit the analysis purpose can’t yet be replaceable. One of the most popular library for Automated Feature Selection in Python is Featuretools."
},
{
"code": null,
"e": 10165,
"s": 9959,
"text": "It’s now time to finally to test our polished dataset prediction accuracy by using a Random Forest Classifier. As shown below, our classifier is now successfully able to achieve a 100% prediction accuracy."
},
{
"code": null,
"e": 10516,
"s": 10165,
"text": "1.40625[[1204 0] [ 0 1196]] precision recall f1-score support 0 1.00 1.00 1.00 1204 1 1.00 1.00 1.00 1196 micro avg 1.00 1.00 1.00 2400 macro avg 1.00 1.00 1.00 2400weighted avg 1.00 1.00 1.00 2400"
},
{
"code": null,
"e": 10572,
"s": 10516,
"text": "I hope you enjoyed this article, thank you for reading!"
},
{
"code": null,
"e": 10730,
"s": 10572,
"text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:"
},
{
"code": null,
"e": 10739,
"s": 10730,
"text": "Linkedin"
},
{
"code": null,
"e": 10753,
"s": 10739,
"text": "Personal Blog"
},
{
"code": null,
"e": 10770,
"s": 10753,
"text": "Personal Website"
},
{
"code": null,
"e": 10785,
"s": 10770,
"text": "Medium Profile"
},
{
"code": null,
"e": 10792,
"s": 10785,
"text": "GitHub"
},
{
"code": null,
"e": 10799,
"s": 10792,
"text": "Kaggle"
}
] |
Convert a byte to hexadecimal equivalent in Java | To convert a byte to hexadecimal equivalent, use the toHexString() method in Java.
Firstly, let us take a byte value.
byte val1 = (byte)90;
Before using the method, let us do some more manipulations. Mask the byte value now:
int res = val1 & 0xFF;
Let us now see the complete example and use the toHexString() method to convert a byte to hexadecimal equivalent.
Live Demo
public class Demo {
public static void main(String[] args) {
byte val1 = (byte)90;
System.out.println("Byte = "+val1);
int res = val1 & 0xFF;
System.out.println("Hexadecimal = "+Integer.toHexString(res));
}
}
Byte = 90
Hexadecimal = 5a | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To convert a byte to hexadecimal equivalent, use the toHexString() method in Java."
},
{
"code": null,
"e": 1180,
"s": 1145,
"text": "Firstly, let us take a byte value."
},
{
"code": null,
"e": 1202,
"s": 1180,
"text": "byte val1 = (byte)90;"
},
{
"code": null,
"e": 1287,
"s": 1202,
"text": "Before using the method, let us do some more manipulations. Mask the byte value now:"
},
{
"code": null,
"e": 1310,
"s": 1287,
"text": "int res = val1 & 0xFF;"
},
{
"code": null,
"e": 1424,
"s": 1310,
"text": "Let us now see the complete example and use the toHexString() method to convert a byte to hexadecimal equivalent."
},
{
"code": null,
"e": 1435,
"s": 1424,
"text": " Live Demo"
},
{
"code": null,
"e": 1674,
"s": 1435,
"text": "public class Demo {\n public static void main(String[] args) {\n byte val1 = (byte)90;\n System.out.println(\"Byte = \"+val1);\n int res = val1 & 0xFF;\n System.out.println(\"Hexadecimal = \"+Integer.toHexString(res));\n }\n}"
},
{
"code": null,
"e": 1701,
"s": 1674,
"text": "Byte = 90\nHexadecimal = 5a"
}
] |
Detect cycle in an undirected graph | Practice | GeeksforGeeks | Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not.
Example 1:
Input:
Output: 1
Explanation: 1->2->3->4->1 is a cycle.
Example 2:
Input:
Output: 0
Explanation: No cycle in the graph.
Your Task:
You don't need to read or print anything. Your task is to complete the function isCycle() which takes V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the undirected graph contains any cycle or not, return 1 if a cycle is present else return 0.
NOTE: The adjacency list denotes the edges of the graph where edges[i][0] and edges[i][1] represent an edge.
Expected Time Complexity: O(V + E)
Expected Space Complexity: O(V)
Constraints:
1 ≤ V, E ≤ 105
0
annanyavijay2 days ago
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) { boolean vis[] = new boolean[V]; for(int i = 0; i < V; i++){ if(!vis[i]){ boolean result = dfs(i, adj, vis,-1); if(result) return true; } } return false; } public boolean dfs(int v, ArrayList<ArrayList<Integer>> adj, boolean vis[], int parent){ vis[v] = true; for(Integer next: adj.get(v)){ if(!vis[next]){ if(dfs(next, adj, vis, parent)) return true; } else if(parent != next) return true; } return false; }
0
udayaashu15022 days ago
bool bfs(int node,vector<int>adj[],vector<int>&visited,int p) { queue<int>q; q.push(node); visited[node ]=p; while(!q.empty()) { int temp=q.front(); q.pop(); for(auto it:adj[temp]) { if(visited[it]==-1) { visited[it]=temp; q.push(it); }else{ if(it!=visited[temp]) { return true; } } } } return false; } bool isCycle(int V, vector<int> adj[]) { // Code here vector<int>visited(V,-1); for(int i=0;i<V;i++) { if(visited[i]==-1) { if(bfs(i,adj,visited,-2)) return true; } } return false; }
0
singhalyash814 days ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
// } Driver Code Endsclass Solution { public: // Function to detect cycle in an undirected graph. bool bfs(int node,vector<int>adj[],vector<int>&visited,int &V) { queue<int>q; q.push(node); while(!q.empty()) { int temp=q.front(); q.pop(); if(visited[temp]==true) return true; if(visited[temp]==false) { visited[temp]=true; for(auto it:adj[temp]) { if(visited[it]==false) q.push(it); } } } return false; } bool isCycle(int V, vector<int> adj[]) { // Code here vector<int>visited(V,false); for(int i=0;i<V;i++) { if(visited[i]==false) { if(bfs(i,adj,visited,V)) return true; } } return false; }};
// { Driver Code Starts.int main() { int tc; cin >> tc; while (tc--) { int V, E; cin >> V >> E; vector<int> adj[V]; for (int i = 0; i < E; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } Solution obj; bool ans = obj.isCycle(V, adj); if (ans) cout << "1\n"; else cout << "0\n"; } return 0;} // } Driver Code Ends
0
thakuraditya6215 days ago
Java Solution :)
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
boolean[] visited =new boolean[V];
for(int i =0; i < V ;i++){
if(visited[i] == false){
boolean ans = BFS(adj, visited, i);
if(ans)
return true;
}
}
return false;
}
public boolean BFS(ArrayList<ArrayList<Integer>> adj, boolean[] visited , int src){
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(src);
while(!queue.isEmpty()){
int rem = queue.remove();
if(visited[rem] == true)
return true;
visited[rem] = true;
for(int nbr : adj.get(rem)){
if(visited[nbr] == false){
queue.add(nbr);
}
}
}
return false;
}
0
rimpisaksham
This comment was deleted.
+1
kharsh8225 days ago
Java Easy Solution
// { Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while (T-- > 0) {
String[] s = br.readLine().trim().split(" ");
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());
for (int i = 0; i < E; i++) {
String[] S = br.readLine().trim().split(" ");
int u = Integer.parseInt(S[0]);
int v = Integer.parseInt(S[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
Solution obj = new Solution();
boolean ans = obj.isCycle(V, adj);
if (ans)
System.out.println("1");
else
System.out.println("0");
}
}
}// } Driver Code Ends
class Solution {
// Function to detect cycle in an undirected graph.
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
for(int i =0;i<V;i++){
if(helper(adj,i,V)==true){
return true;
}
}
return false;
}
public boolean helper( ArrayList<ArrayList<Integer>> adj,int src,int V){
boolean [] visited=new boolean[V];
ArrayDeque <Integer> q=new ArrayDeque();
q.add(src);
while(q.size()!=0){
int a =q.remove();
if(visited[a]==true){
return true;
}
visited[a]=true;
for(int b: adj.get(a)){
if(visited[b]==false){
q.add(b);
}
}
}
return false;
}
}
0
pegasis6 days ago
class Solution { public: bool cycle(int node, int parent, vector<int>& vis, vector<int> adj[]){ vis[node]=1; for(auto it: adj[node]){ if(!vis[it]){ cycle(it,node,vis,adj); } else if(it != parent)return 1; } return 0; } // Function to detect cycle in an undirected graph. bool isCycle(int V, vector<int> adj[]) { // Code here vector<int> vis(V+1,0); for(int i=1;i<V;++i){ if(!vis[i]){ if(cycle(i,-1,vis,adj))return true; } } return 0; }};
0
sandeep55211 week ago
C++ Solution using Union find
class dist{
public:
vector<int> p,c;
dist(int n){
p.resize(n,0);
c.resize(n,0);
for(int i=0;i<n;i++) p[i]=i;
}
int find(int i){
int b=p[i];
int t=i;
while(i!=b){
i=b;
b=p[i];
} if(p[t]!=b) p[t]=b;
return b;
}
void Union(int a,int b){
int pa=find(a),pb=find(b);
if(c[pa]>c[pb]){
p[pb]=pa;
c[pa]++;
}
else{
p[pa]=pb;
c[pb]++;
}
}
};
class Solution {
public:
// Function to detect cycle in an undirected graph.
bool isCycle(int V, vector<int> adj[]) {
// Code here
dist d(V);
vector<int> v(V,0);
for(int i=0;i<V;i++){
v[i]++;
for(auto j:adj[i]){
if(v[j]) continue;
int a=d.find(i),b=d.find(j);
if(a==b) return true;
d.Union(i,j);
}
}
return false;
}
};
0
nitish kumar 171 week ago
//why it is giving wrong answer
// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while (T-- > 0) { String[] s = br.readLine().trim().split(" "); int V = Integer.parseInt(s[0]); int E = Integer.parseInt(s[1]); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>()); for (int i = 0; i < E; i++) { String[] S = br.readLine().trim().split(" "); int u = Integer.parseInt(S[0]); int v = Integer.parseInt(S[1]); adj.get(u).add(v); adj.get(v).add(u); } Solution obj = new Solution(); boolean ans = obj.isCycle(V, adj); if (ans) System.out.println("1"); else System.out.println("0"); } }}// } Driver Code Ends
class Solution { class Pair{ int first; int second; public Pair(int first , int second){ this.first = first; this.second = second; }}
public boolean isBFSCycle(int s, ArrayList<ArrayList<Integer>> adj,boolean[]visited){ Queue<Pair> q = new LinkedList<>(); q.add(new Pair(s,-1)); visited[s]=true; while(!q.isEmpty()){ int node = q.peek().first; int par = q.peek().second; q.remove(); for(Integer it : adj.get(node) ) { if(visited[it]==false) { q.add(new Pair(it,node)); visited[it]=true; } else if(it!=par) { return true; } } } return false; } // Function to detect cycle in an undirected graph. public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) { // Code here boolean visited[] = new boolean[V]; Arrays.fill(visited,false); for(int i=0;i<V;i++) { if(visited[i]==false) { if(isBFSCycle(i,adj,visited)==true) { return true; } } } return false; } }
+1
harshscode2 weeks ago
bool dfs(int src,int par,vector<int> adj[],vector<bool> &vis) { vis[src]=true; for(auto x:adj[src]) { if(!vis[x]) { if(dfs(x,src,adj,vis)) return true; } else if(x!=par) return true; } return false; } bool isCycle(int v, vector<int> adj[]) { vector<bool> vis(v,false); for(int i=0;i<v;i++) { if(!vis[i]) { bool f=dfs(i,-1,adj,vis); if(f) return true; } } return false; }
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": 338,
"s": 238,
"text": "Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not. "
},
{
"code": null,
"e": 349,
"s": 338,
"text": "Example 1:"
},
{
"code": null,
"e": 410,
"s": 349,
"text": "Input: \n\nOutput: 1\nExplanation: 1->2->3->4->1 is a cycle.\n"
},
{
"code": null,
"e": 421,
"s": 410,
"text": "Example 2:"
},
{
"code": null,
"e": 477,
"s": 421,
"text": "Input: \n\nOutput: 0\nExplanation: No cycle in the graph.\n"
},
{
"code": null,
"e": 799,
"s": 479,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function isCycle() which takes V denoting the number of vertices and adjacency list as input parameters and returns a boolean value denoting if the undirected graph contains any cycle or not, return 1 if a cycle is present else return 0."
},
{
"code": null,
"e": 908,
"s": 799,
"text": "NOTE: The adjacency list denotes the edges of the graph where edges[i][0] and edges[i][1] represent an edge."
},
{
"code": null,
"e": 977,
"s": 910,
"text": "Expected Time Complexity: O(V + E)\nExpected Space Complexity: O(V)"
},
{
"code": null,
"e": 1008,
"s": 980,
"text": "Constraints:\n1 ≤ V, E ≤ 105"
},
{
"code": null,
"e": 1010,
"s": 1008,
"text": "0"
},
{
"code": null,
"e": 1033,
"s": 1010,
"text": "annanyavijay2 days ago"
},
{
"code": null,
"e": 1768,
"s": 1033,
"text": "public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) { boolean vis[] = new boolean[V]; for(int i = 0; i < V; i++){ if(!vis[i]){ boolean result = dfs(i, adj, vis,-1); if(result) return true; } } return false; } public boolean dfs(int v, ArrayList<ArrayList<Integer>> adj, boolean vis[], int parent){ vis[v] = true; for(Integer next: adj.get(v)){ if(!vis[next]){ if(dfs(next, adj, vis, parent)) return true; } else if(parent != next) return true; } return false; }"
},
{
"code": null,
"e": 1770,
"s": 1768,
"text": "0"
},
{
"code": null,
"e": 1794,
"s": 1770,
"text": "udayaashu15022 days ago"
},
{
"code": null,
"e": 2664,
"s": 1794,
"text": " bool bfs(int node,vector<int>adj[],vector<int>&visited,int p) { queue<int>q; q.push(node); visited[node ]=p; while(!q.empty()) { int temp=q.front(); q.pop(); for(auto it:adj[temp]) { if(visited[it]==-1) { visited[it]=temp; q.push(it); }else{ if(it!=visited[temp]) { return true; } } } } return false; } bool isCycle(int V, vector<int> adj[]) { // Code here vector<int>visited(V,-1); for(int i=0;i<V;i++) { if(visited[i]==-1) { if(bfs(i,adj,visited,-2)) return true; } } return false; }"
},
{
"code": null,
"e": 2666,
"s": 2664,
"text": "0"
},
{
"code": null,
"e": 2690,
"s": 2666,
"text": "singhalyash814 days ago"
},
{
"code": null,
"e": 2758,
"s": 2690,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 3669,
"s": 2758,
"text": "// } Driver Code Endsclass Solution { public: // Function to detect cycle in an undirected graph. bool bfs(int node,vector<int>adj[],vector<int>&visited,int &V) { queue<int>q; q.push(node); while(!q.empty()) { int temp=q.front(); q.pop(); if(visited[temp]==true) return true; if(visited[temp]==false) { visited[temp]=true; for(auto it:adj[temp]) { if(visited[it]==false) q.push(it); } } } return false; } bool isCycle(int V, vector<int> adj[]) { // Code here vector<int>visited(V,false); for(int i=0;i<V;i++) { if(visited[i]==false) { if(bfs(i,adj,visited,V)) return true; } } return false; }};"
},
{
"code": null,
"e": 4134,
"s": 3669,
"text": "// { Driver Code Starts.int main() { int tc; cin >> tc; while (tc--) { int V, E; cin >> V >> E; vector<int> adj[V]; for (int i = 0; i < E; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } Solution obj; bool ans = obj.isCycle(V, adj); if (ans) cout << \"1\\n\"; else cout << \"0\\n\"; } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 4136,
"s": 4134,
"text": "0"
},
{
"code": null,
"e": 4162,
"s": 4136,
"text": "thakuraditya6215 days ago"
},
{
"code": null,
"e": 4179,
"s": 4162,
"text": "Java Solution :)"
},
{
"code": null,
"e": 5130,
"s": 4179,
"text": " public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {\n // Code here\n boolean[] visited =new boolean[V];\n for(int i =0; i < V ;i++){\n if(visited[i] == false){\n boolean ans = BFS(adj, visited, i);\n if(ans)\n return true;\n }\n }\n return false;\n }\n \n public boolean BFS(ArrayList<ArrayList<Integer>> adj, boolean[] visited , int src){\n ArrayDeque<Integer> queue = new ArrayDeque<>();\n queue.add(src);\n \n while(!queue.isEmpty()){\n int rem = queue.remove();\n \n if(visited[rem] == true)\n return true;\n \n visited[rem] = true;\n \n for(int nbr : adj.get(rem)){\n if(visited[nbr] == false){\n queue.add(nbr);\n }\n }\n }\n return false;\n }"
},
{
"code": null,
"e": 5132,
"s": 5130,
"text": "0"
},
{
"code": null,
"e": 5145,
"s": 5132,
"text": "rimpisaksham"
},
{
"code": null,
"e": 5171,
"s": 5145,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5174,
"s": 5171,
"text": "+1"
},
{
"code": null,
"e": 5194,
"s": 5174,
"text": "kharsh8225 days ago"
},
{
"code": null,
"e": 5214,
"s": 5194,
"text": "Java Easy Solution "
},
{
"code": null,
"e": 7355,
"s": 5214,
"text": "// { Driver Code Starts\nimport java.util.*;\nimport java.lang.*;\nimport java.io.*;\nclass GFG {\n public static void main(String[] args) throws IOException {\n BufferedReader br =\n new BufferedReader(new InputStreamReader(System.in));\n int T = Integer.parseInt(br.readLine().trim());\n while (T-- > 0) {\n String[] s = br.readLine().trim().split(\" \");\n int V = Integer.parseInt(s[0]);\n int E = Integer.parseInt(s[1]);\n ArrayList<ArrayList<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>());\n for (int i = 0; i < E; i++) {\n String[] S = br.readLine().trim().split(\" \");\n int u = Integer.parseInt(S[0]);\n int v = Integer.parseInt(S[1]);\n adj.get(u).add(v);\n adj.get(v).add(u);\n }\n Solution obj = new Solution();\n boolean ans = obj.isCycle(V, adj);\n if (ans)\n System.out.println(\"1\");\n else\n System.out.println(\"0\");\n }\n }\n}// } Driver Code Ends\n\n\nclass Solution {\n // Function to detect cycle in an undirected graph.\n public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {\n \n \n for(int i =0;i<V;i++){\n if(helper(adj,i,V)==true){\n return true;\n }\n }\n \n return false;\n \n }\n \n public boolean helper( ArrayList<ArrayList<Integer>> adj,int src,int V){\n boolean [] visited=new boolean[V];\n ArrayDeque <Integer> q=new ArrayDeque();\n q.add(src);\n \n \n while(q.size()!=0){\n int a =q.remove();\n \n if(visited[a]==true){\n return true;\n }\n visited[a]=true;\n \n for(int b: adj.get(a)){\n if(visited[b]==false){\n q.add(b);\n \n }\n \n \n }\n \n \n }\n \n return false;\n }\n}"
},
{
"code": null,
"e": 7357,
"s": 7355,
"text": "0"
},
{
"code": null,
"e": 7375,
"s": 7357,
"text": "pegasis6 days ago"
},
{
"code": null,
"e": 7937,
"s": 7375,
"text": "class Solution { public: bool cycle(int node, int parent, vector<int>& vis, vector<int> adj[]){ vis[node]=1; for(auto it: adj[node]){ if(!vis[it]){ cycle(it,node,vis,adj); } else if(it != parent)return 1; } return 0; } // Function to detect cycle in an undirected graph. bool isCycle(int V, vector<int> adj[]) { // Code here vector<int> vis(V+1,0); for(int i=1;i<V;++i){ if(!vis[i]){ if(cycle(i,-1,vis,adj))return true; } } return 0; }};"
},
{
"code": null,
"e": 7939,
"s": 7937,
"text": "0"
},
{
"code": null,
"e": 7961,
"s": 7939,
"text": "sandeep55211 week ago"
},
{
"code": null,
"e": 7991,
"s": 7961,
"text": "C++ Solution using Union find"
},
{
"code": null,
"e": 8965,
"s": 7991,
"text": "class dist{\n public:\n vector<int> p,c;\n dist(int n){\n p.resize(n,0);\n c.resize(n,0);\n for(int i=0;i<n;i++) p[i]=i;\n }\n int find(int i){\n int b=p[i];\n int t=i;\n while(i!=b){\n i=b;\n b=p[i];\n } if(p[t]!=b) p[t]=b;\n return b;\n }\n void Union(int a,int b){\n int pa=find(a),pb=find(b);\n if(c[pa]>c[pb]){\n p[pb]=pa;\n c[pa]++;\n }\n else{\n p[pa]=pb;\n c[pb]++;\n }\n }\n};\nclass Solution {\n public:\n // Function to detect cycle in an undirected graph.\n bool isCycle(int V, vector<int> adj[]) {\n // Code here\n dist d(V);\n vector<int> v(V,0);\n for(int i=0;i<V;i++){\n v[i]++;\n for(auto j:adj[i]){\n if(v[j]) continue;\n int a=d.find(i),b=d.find(j);\n if(a==b) return true;\n d.Union(i,j);\n }\n }\n return false;\n }\n};"
},
{
"code": null,
"e": 8967,
"s": 8965,
"text": "0"
},
{
"code": null,
"e": 8993,
"s": 8967,
"text": "nitish kumar 171 week ago"
},
{
"code": null,
"e": 9025,
"s": 8993,
"text": "//why it is giving wrong answer"
},
{
"code": null,
"e": 10128,
"s": 9025,
"text": "// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while (T-- > 0) { String[] s = br.readLine().trim().split(\" \"); int V = Integer.parseInt(s[0]); int E = Integer.parseInt(s[1]); ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for (int i = 0; i < V; i++) adj.add(i, new ArrayList<Integer>()); for (int i = 0; i < E; i++) { String[] S = br.readLine().trim().split(\" \"); int u = Integer.parseInt(S[0]); int v = Integer.parseInt(S[1]); adj.get(u).add(v); adj.get(v).add(u); } Solution obj = new Solution(); boolean ans = obj.isCycle(V, adj); if (ans) System.out.println(\"1\"); else System.out.println(\"0\"); } }}// } Driver Code Ends"
},
{
"code": null,
"e": 10285,
"s": 10128,
"text": "class Solution { class Pair{ int first; int second; public Pair(int first , int second){ this.first = first; this.second = second; }}"
},
{
"code": null,
"e": 11386,
"s": 10285,
"text": " public boolean isBFSCycle(int s, ArrayList<ArrayList<Integer>> adj,boolean[]visited){ Queue<Pair> q = new LinkedList<>(); q.add(new Pair(s,-1)); visited[s]=true; while(!q.isEmpty()){ int node = q.peek().first; int par = q.peek().second; q.remove(); for(Integer it : adj.get(node) ) { if(visited[it]==false) { q.add(new Pair(it,node)); visited[it]=true; } else if(it!=par) { return true; } } } return false; } // Function to detect cycle in an undirected graph. public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) { // Code here boolean visited[] = new boolean[V]; Arrays.fill(visited,false); for(int i=0;i<V;i++) { if(visited[i]==false) { if(isBFSCycle(i,adj,visited)==true) { return true; } } } return false; } }"
},
{
"code": null,
"e": 11389,
"s": 11386,
"text": "+1"
},
{
"code": null,
"e": 11411,
"s": 11389,
"text": "harshscode2 weeks ago"
},
{
"code": null,
"e": 11986,
"s": 11411,
"text": "bool dfs(int src,int par,vector<int> adj[],vector<bool> &vis) { vis[src]=true; for(auto x:adj[src]) { if(!vis[x]) { if(dfs(x,src,adj,vis)) return true; } else if(x!=par) return true; } return false; } bool isCycle(int v, vector<int> adj[]) { vector<bool> vis(v,false); for(int i=0;i<v;i++) { if(!vis[i]) { bool f=dfs(i,-1,adj,vis); if(f) return true; } } return false; }"
},
{
"code": null,
"e": 12132,
"s": 11986,
"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": 12168,
"s": 12132,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12178,
"s": 12168,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12188,
"s": 12178,
"text": "\nContest\n"
},
{
"code": null,
"e": 12251,
"s": 12188,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12399,
"s": 12251,
"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": 12607,
"s": 12399,
"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": 12713,
"s": 12607,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
B+ tree Query in Data Structure | Here we will see, how to perform the searching in B+ Tree. The B+ Tree searching is also known as B+ Tree Querying. This algorithm is very much similar to the querying of B-Tree. Moreover, this supports range query. Suppose we have a B+ tree like below −
Example of B+ Tree −
The searching technique is very similar to the binary search tree. Suppose we want to search 63 from the above tree. So we will start from root, now 63 is larger than root element 60 but smaller than 75. So we will move to the right child of the element 60. The right child is 63. But if we use B Tree, then that will be the result. In this case as the current node is internal node, then that is not an actual data. We have to move to the right child first. And at the leaf level, we can find the 63 as record. That will be the actual result.
if we want to search all elements from 63 to 78, then we do not need to backtrack each element, one by one. We find the leaf node of the initial value, then by using the linked leaf nodes, simply find all nodes before 78. So this supports range query.
Let us see the algorithm to search element inside the B-Tree.
BPlusTreeSearch(root, key) −
Input − The root of the tree, and key to find
Output − The value of the node with key, if it is not present, return null
Apply binary search on records
if record with the ‘key’ is found, then
return required record
else if current node is leaf node, and key is not found, then
return null | [
{
"code": null,
"e": 1317,
"s": 1062,
"text": "Here we will see, how to perform the searching in B+ Tree. The B+ Tree searching is also known as B+ Tree Querying. This algorithm is very much similar to the querying of B-Tree. Moreover, this supports range query. Suppose we have a B+ tree like below −"
},
{
"code": null,
"e": 1338,
"s": 1317,
"text": "Example of B+ Tree −"
},
{
"code": null,
"e": 1882,
"s": 1338,
"text": "The searching technique is very similar to the binary search tree. Suppose we want to search 63 from the above tree. So we will start from root, now 63 is larger than root element 60 but smaller than 75. So we will move to the right child of the element 60. The right child is 63. But if we use B Tree, then that will be the result. In this case as the current node is internal node, then that is not an actual data. We have to move to the right child first. And at the leaf level, we can find the 63 as record. That will be the actual result."
},
{
"code": null,
"e": 2134,
"s": 1882,
"text": "if we want to search all elements from 63 to 78, then we do not need to backtrack each element, one by one. We find the leaf node of the initial value, then by using the linked leaf nodes, simply find all nodes before 78. So this supports range query."
},
{
"code": null,
"e": 2196,
"s": 2134,
"text": "Let us see the algorithm to search element inside the B-Tree."
},
{
"code": null,
"e": 2225,
"s": 2196,
"text": "BPlusTreeSearch(root, key) −"
},
{
"code": null,
"e": 2272,
"s": 2225,
"text": "Input − The root of the tree, and key to find "
},
{
"code": null,
"e": 2347,
"s": 2272,
"text": "Output − The value of the node with key, if it is not present, return null"
},
{
"code": null,
"e": 2521,
"s": 2347,
"text": "Apply binary search on records\nif record with the ‘key’ is found, then\n return required record\nelse if current node is leaf node, and key is not found, then\n return null"
}
] |
PyQt5 QSpinBox – Making it enabled - GeeksforGeeks | 17 May, 2020
In this article we will see how we can make spin box enabled according to the user, disabled spin box is basically spin box which can’t be edited i.e which get disabled and enabled spin box is normal spin box, by default spin box is enabled. In order to make spin box disabled we use setDisabled method.
In order to do so we use setEnabled method.
Syntax : spin_box.setEnabled(bool)
Argument : It takes bool as argument
Return : It returns None
Implementation steps :1. Create a spin box2. Create a push button and add action to the push button3. Inside the action make the spin box disabled4. Create another push button and add action to it5. Inside the action make the spin box enabled
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting prefix to spin self.spin.setPrefix("Prefix ") # setting suffix to spin self.spin.setSuffix(" Suffix") # setting range to spin self.spin.setRange(0, 99999) # creating push button button = QPushButton("Disable", self) # setting button geometry button.setGeometry(100, 160, 100, 40) # adding action to the push button button.clicked.connect(self.push_method) # creating push button e_button = QPushButton("Enable", self) # setting button geometry e_button.setGeometry(220, 160, 100, 40) # adding action to the push button e_button.clicked.connect(self.another_method) # method called by push button def push_method(self): # making spin box disabled self.spin.setDisabled(True) # method called by e_button def another_method(self): # making spin box enabled self.spin.setEnabled(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24130,
"s": 24102,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 24434,
"s": 24130,
"text": "In this article we will see how we can make spin box enabled according to the user, disabled spin box is basically spin box which can’t be edited i.e which get disabled and enabled spin box is normal spin box, by default spin box is enabled. In order to make spin box disabled we use setDisabled method."
},
{
"code": null,
"e": 24478,
"s": 24434,
"text": "In order to do so we use setEnabled method."
},
{
"code": null,
"e": 24513,
"s": 24478,
"text": "Syntax : spin_box.setEnabled(bool)"
},
{
"code": null,
"e": 24550,
"s": 24513,
"text": "Argument : It takes bool as argument"
},
{
"code": null,
"e": 24575,
"s": 24550,
"text": "Return : It returns None"
},
{
"code": null,
"e": 24818,
"s": 24575,
"text": "Implementation steps :1. Create a spin box2. Create a push button and add action to the push button3. Inside the action make the spin box disabled4. Create another push button and add action to it5. Inside the action make the spin box enabled"
},
{
"code": null,
"e": 24846,
"s": 24818,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting prefix to spin self.spin.setPrefix(\"Prefix \") # setting suffix to spin self.spin.setSuffix(\" Suffix\") # setting range to spin self.spin.setRange(0, 99999) # creating push button button = QPushButton(\"Disable\", self) # setting button geometry button.setGeometry(100, 160, 100, 40) # adding action to the push button button.clicked.connect(self.push_method) # creating push button e_button = QPushButton(\"Enable\", self) # setting button geometry e_button.setGeometry(220, 160, 100, 40) # adding action to the push button e_button.clicked.connect(self.another_method) # method called by push button def push_method(self): # making spin box disabled self.spin.setDisabled(True) # method called by e_button def another_method(self): # making spin box enabled self.spin.setEnabled(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26639,
"s": 24846,
"text": null
},
{
"code": null,
"e": 26648,
"s": 26639,
"text": "Output :"
},
{
"code": null,
"e": 26668,
"s": 26648,
"text": "Python PyQt-SpinBox"
},
{
"code": null,
"e": 26679,
"s": 26668,
"text": "Python-gui"
},
{
"code": null,
"e": 26691,
"s": 26679,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26698,
"s": 26691,
"text": "Python"
},
{
"code": null,
"e": 26796,
"s": 26698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26814,
"s": 26796,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26849,
"s": 26814,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26871,
"s": 26849,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26903,
"s": 26871,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26933,
"s": 26903,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26975,
"s": 26933,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27001,
"s": 26975,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27044,
"s": 27001,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27081,
"s": 27044,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Distance between a point and a Plane in 3 D - GeeksforGeeks | 22 Oct, 2021
You are given a points (x1, y1, z1) and a plane a * x + b * y + c * z + d = 0. The task is to find the perpendicular(shortest) distance between that point and the given Plane.
Examples :
Input: x1 = 4, y1 = -4, z1 = 3, a = 2, b = -2, c = 5, d = 8 Output: Perpendicular distance is 6.78902858227Input: x1 = 2, y1 = 8, z1 = 5, a = 1, b = -2, c = -2, d = -1 Output: Perpendicular distance is 8.33333333333
Approach: The perpendicular distance (i.e shortest distance) from a given point to a Plane is the perpendicular distance from that point to the given plane. Let the co-ordinate of the given point be (x1, y1, z1) and equation of the plane be given by the equation a * x + b * y + c * z + d = 0, where a, b and c are real constants.The formula for distance between a point and Plane in 3-D is given by:
Distance = (| a*x1 + b*y1 + c*z1 + d |) / (sqrt( a*a + b*b + c*c))
Below is the implementation of the above formulae:
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.#include<bits/stdc++.h>#include<math.h> using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = fabs((a * x1 + b * y1 + c * z1 + d)); float e = sqrt(a * a + b * b + c * c); cout << "Perpendicular distance is " << (d / e); return;} // Driver Codeint main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);} // This code is contributed// by Akanksha Rai(Abby_akku)
// C program to find the Perpendicular(shortest)// distance between a point and a Plane in 3 D. #include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = fabs((a * x1 + b * y1 + c * z1 + d)); float e = sqrt(a * a + b * b + c * c); printf("Perpendicular distance is %f", d/e); return;} // Driver Codeint main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}// This code is contributed// by Amber_Saxena.
// Java program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.import java .io.*; class GFG{ // Function to find distancestatic void shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = Math.abs((a * x1 + b * y1 + c * z1 + d)); float e = (float)Math.sqrt(a * a + b * b + c * c); System.out.println("Perpendicular distance " + "is " + d / e);} // Driver codepublic static void main(String[] args){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}} // This code is contributed// by Amber_Saxena.
# Python program to find the Perpendicular(shortest)# distance between a point and a Plane in 3 D. import math # Function to find distancedef shortest_distance(x1, y1, z1, a, b, c, d): d = abs((a * x1 + b * y1 + c * z1 + d)) e = (math.sqrt(a * a + b * b + c * c)) print("Perpendicular distance is", d/e) # Driver Codex1 = 4y1 = -4z1 = 3a = 2b = -2c = 5d = 8 # Function callshortest_distance(x1, y1, z1, a, b, c, d)
// C# program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.using System; class GFG{ // Function to find distancestatic void shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = Math.Abs((a * x1 + b * y1 + c * z1 + d)); float e = (float)Math.Sqrt(a * a + b * b + c * c); Console.Write("Perpendicular distance " + "is " + d / e);} // Driver codepublic static void Main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}} // This code is contributed// by ChitraNayal
<?php// PHP program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D. // Function to find distancefunction shortest_distance($x1, $y1, $z1, $a, $b, $c, $d){ $d = abs(($a * $x1 + $b * $y1 + $c * $z1 + $d)); $e = sqrt($a * $a + $b * $b + $c * $c); echo "Perpendicular distance is ". $d / $e;} // Driver Code$x1 = 4;$y1 = -4;$z1 = 3;$a = 2;$b = -2;$c = 5;$d = 8; // function callshortest_distance($x1, $y1, $z1, $a, $b, $c, $d); // This code is contributed// by Amber_Saxena.?>
<script> // Javascript program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D. // Function to find distancefunction shortest_distance( x1, y1, z1, a, b, c, d){ d = Math.abs((a * x1 + b * y1 + c * z1 + d)); let e = Math.sqrt(a * a + b * b + c * c); document.write("Perpendicular distance is " + (d / e)); return;} // driver code let x1 = 4; let y1 = -4; let z1 = 3; let a = 2; let b = -2; let c = 5; let d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d); // This code is contributed by jana_sayantan. </script>
Perpendicular distance is 6.78902858227
Amber_Saxena
ukasp
Akanksha_Rai
jana_sayantan
danielstorc
Geometric
Mathematical
School Programming
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Closest Pair of Points | O(nlogn) Implementation
Convex Hull | Set 2 (Graham Scan)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Given n line segments, find if any two segments intersect
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 25401,
"s": 25224,
"text": "You are given a points (x1, y1, z1) and a plane a * x + b * y + c * z + d = 0. The task is to find the perpendicular(shortest) distance between that point and the given Plane. "
},
{
"code": null,
"e": 25414,
"s": 25401,
"text": "Examples : "
},
{
"code": null,
"e": 25631,
"s": 25414,
"text": "Input: x1 = 4, y1 = -4, z1 = 3, a = 2, b = -2, c = 5, d = 8 Output: Perpendicular distance is 6.78902858227Input: x1 = 2, y1 = 8, z1 = 5, a = 1, b = -2, c = -2, d = -1 Output: Perpendicular distance is 8.33333333333 "
},
{
"code": null,
"e": 26035,
"s": 25633,
"text": "Approach: The perpendicular distance (i.e shortest distance) from a given point to a Plane is the perpendicular distance from that point to the given plane. Let the co-ordinate of the given point be (x1, y1, z1) and equation of the plane be given by the equation a * x + b * y + c * z + d = 0, where a, b and c are real constants.The formula for distance between a point and Plane in 3-D is given by: "
},
{
"code": null,
"e": 26102,
"s": 26035,
"text": "Distance = (| a*x1 + b*y1 + c*z1 + d |) / (sqrt( a*a + b*b + c*c))"
},
{
"code": null,
"e": 26155,
"s": 26102,
"text": "Below is the implementation of the above formulae: "
},
{
"code": null,
"e": 26159,
"s": 26155,
"text": "C++"
},
{
"code": null,
"e": 26161,
"s": 26159,
"text": "C"
},
{
"code": null,
"e": 26166,
"s": 26161,
"text": "Java"
},
{
"code": null,
"e": 26173,
"s": 26166,
"text": "Python"
},
{
"code": null,
"e": 26176,
"s": 26173,
"text": "C#"
},
{
"code": null,
"e": 26180,
"s": 26176,
"text": "PHP"
},
{
"code": null,
"e": 26191,
"s": 26180,
"text": "Javascript"
},
{
"code": "// C++ program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.#include<bits/stdc++.h>#include<math.h> using namespace std; // Function to find distancevoid shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = fabs((a * x1 + b * y1 + c * z1 + d)); float e = sqrt(a * a + b * b + c * c); cout << \"Perpendicular distance is \" << (d / e); return;} // Driver Codeint main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 27020,
"s": 26191,
"text": null
},
{
"code": "// C program to find the Perpendicular(shortest)// distance between a point and a Plane in 3 D. #include<stdio.h>#include<math.h> // Function to find distancevoid shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = fabs((a * x1 + b * y1 + c * z1 + d)); float e = sqrt(a * a + b * b + c * c); printf(\"Perpendicular distance is %f\", d/e); return;} // Driver Codeint main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}// This code is contributed// by Amber_Saxena.",
"e": 27695,
"s": 27020,
"text": null
},
{
"code": "// Java program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.import java .io.*; class GFG{ // Function to find distancestatic void shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = Math.abs((a * x1 + b * y1 + c * z1 + d)); float e = (float)Math.sqrt(a * a + b * b + c * c); System.out.println(\"Perpendicular distance \" + \"is \" + d / e);} // Driver codepublic static void main(String[] args){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}} // This code is contributed// by Amber_Saxena.",
"e": 28601,
"s": 27695,
"text": null
},
{
"code": "# Python program to find the Perpendicular(shortest)# distance between a point and a Plane in 3 D. import math # Function to find distancedef shortest_distance(x1, y1, z1, a, b, c, d): d = abs((a * x1 + b * y1 + c * z1 + d)) e = (math.sqrt(a * a + b * b + c * c)) print(\"Perpendicular distance is\", d/e) # Driver Codex1 = 4y1 = -4z1 = 3a = 2b = -2c = 5d = 8 # Function callshortest_distance(x1, y1, z1, a, b, c, d) ",
"e": 29040,
"s": 28601,
"text": null
},
{
"code": "// C# program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D.using System; class GFG{ // Function to find distancestatic void shortest_distance(float x1, float y1, float z1, float a, float b, float c, float d){ d = Math.Abs((a * x1 + b * y1 + c * z1 + d)); float e = (float)Math.Sqrt(a * a + b * b + c * c); Console.Write(\"Perpendicular distance \" + \"is \" + d / e);} // Driver codepublic static void Main(){ float x1 = 4; float y1 = -4; float z1 = 3; float a = 2; float b = -2; float c = 5; float d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d);}} // This code is contributed// by ChitraNayal",
"e": 29916,
"s": 29040,
"text": null
},
{
"code": "<?php// PHP program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D. // Function to find distancefunction shortest_distance($x1, $y1, $z1, $a, $b, $c, $d){ $d = abs(($a * $x1 + $b * $y1 + $c * $z1 + $d)); $e = sqrt($a * $a + $b * $b + $c * $c); echo \"Perpendicular distance is \". $d / $e;} // Driver Code$x1 = 4;$y1 = -4;$z1 = 3;$a = 2;$b = -2;$c = 5;$d = 8; // function callshortest_distance($x1, $y1, $z1, $a, $b, $c, $d); // This code is contributed// by Amber_Saxena.?>",
"e": 30510,
"s": 29916,
"text": null
},
{
"code": "<script> // Javascript program to find the// Perpendicular(shortest)// distance between a point// and a Plane in 3 D. // Function to find distancefunction shortest_distance( x1, y1, z1, a, b, c, d){ d = Math.abs((a * x1 + b * y1 + c * z1 + d)); let e = Math.sqrt(a * a + b * b + c * c); document.write(\"Perpendicular distance is \" + (d / e)); return;} // driver code let x1 = 4; let y1 = -4; let z1 = 3; let a = 2; let b = -2; let c = 5; let d = 8; // Function call shortest_distance(x1, y1, z1, a, b, c, d); // This code is contributed by jana_sayantan. </script>",
"e": 31220,
"s": 30510,
"text": null
},
{
"code": null,
"e": 31260,
"s": 31220,
"text": "Perpendicular distance is 6.78902858227"
},
{
"code": null,
"e": 31275,
"s": 31262,
"text": "Amber_Saxena"
},
{
"code": null,
"e": 31281,
"s": 31275,
"text": "ukasp"
},
{
"code": null,
"e": 31294,
"s": 31281,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31308,
"s": 31294,
"text": "jana_sayantan"
},
{
"code": null,
"e": 31320,
"s": 31308,
"text": "danielstorc"
},
{
"code": null,
"e": 31330,
"s": 31320,
"text": "Geometric"
},
{
"code": null,
"e": 31343,
"s": 31330,
"text": "Mathematical"
},
{
"code": null,
"e": 31362,
"s": 31343,
"text": "School Programming"
},
{
"code": null,
"e": 31375,
"s": 31362,
"text": "Mathematical"
},
{
"code": null,
"e": 31385,
"s": 31375,
"text": "Geometric"
},
{
"code": null,
"e": 31483,
"s": 31385,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31492,
"s": 31483,
"text": "Comments"
},
{
"code": null,
"e": 31505,
"s": 31492,
"text": "Old Comments"
},
{
"code": null,
"e": 31558,
"s": 31505,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 31607,
"s": 31558,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 31641,
"s": 31607,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 31692,
"s": 31641,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 31750,
"s": 31692,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 31780,
"s": 31750,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31840,
"s": 31780,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31855,
"s": 31840,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31898,
"s": 31855,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
CSS | :active Selector - GeeksforGeeks | 07 May, 2021
The :active selector is used in styling an active link of web page. Style display when user clicks on the link. This selector is different from :link, :visited and :hover selectors. The main use of :active selector is on the links but it can be used on all elements.Syntax:
:active{
//CSS property
}
Below HTML/CSS code shows the functionality of :active selector :
HTML
<!DOCTYPE html><html> <head> <title>Active selector</title> <style> a:active { background-color: green; } p:active { background-color: blue; } </style></head> <body> <h3>Active for link.</h3> <a href="https://www.geeksforgeeks.org/">Geeks for Geeks</a> <h3>Active for text.</h3> <p>Click Me!!</p> </body> </html>
Output:
Supported Browsers
Google Chrome 4.0
Edge 7.0
Firefox 2.0
Safari 3.1
Opera 9.6
arorakashish0911
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 23034,
"s": 23006,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 23310,
"s": 23034,
"text": "The :active selector is used in styling an active link of web page. Style display when user clicks on the link. This selector is different from :link, :visited and :hover selectors. The main use of :active selector is on the links but it can be used on all elements.Syntax: "
},
{
"code": null,
"e": 23344,
"s": 23310,
"text": ":active{\n //CSS property\n}"
},
{
"code": null,
"e": 23412,
"s": 23344,
"text": "Below HTML/CSS code shows the functionality of :active selector : "
},
{
"code": null,
"e": 23417,
"s": 23412,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Active selector</title> <style> a:active { background-color: green; } p:active { background-color: blue; } </style></head> <body> <h3>Active for link.</h3> <a href=\"https://www.geeksforgeeks.org/\">Geeks for Geeks</a> <h3>Active for text.</h3> <p>Click Me!!</p> </body> </html>",
"e": 23811,
"s": 23417,
"text": null
},
{
"code": null,
"e": 23821,
"s": 23811,
"text": "Output: "
},
{
"code": null,
"e": 23844,
"s": 23823,
"text": "Supported Browsers "
},
{
"code": null,
"e": 23862,
"s": 23844,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 23873,
"s": 23864,
"text": "Edge 7.0"
},
{
"code": null,
"e": 23887,
"s": 23875,
"text": "Firefox 2.0"
},
{
"code": null,
"e": 23900,
"s": 23889,
"text": "Safari 3.1"
},
{
"code": null,
"e": 23912,
"s": 23902,
"text": "Opera 9.6"
},
{
"code": null,
"e": 23931,
"s": 23914,
"text": "arorakashish0911"
},
{
"code": null,
"e": 23945,
"s": 23931,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 23949,
"s": 23945,
"text": "CSS"
},
{
"code": null,
"e": 23966,
"s": 23949,
"text": "Web Technologies"
},
{
"code": null,
"e": 24064,
"s": 23966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24126,
"s": 24064,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 24176,
"s": 24126,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 24234,
"s": 24176,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 24282,
"s": 24234,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 24332,
"s": 24282,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 24374,
"s": 24332,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 24407,
"s": 24374,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 24450,
"s": 24407,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 24512,
"s": 24450,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
MySQL Tryit Editor v1.0 | SELECT INSERT("W3Schools.com", 1, 9, "Example");
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 49,
"s": 0,
"text": "SELECT INSERT(\"W3Schools.com\", 1, 9, \"Example\");"
},
{
"code": null,
"e": 51,
"s": 49,
"text": ""
},
{
"code": null,
"e": 123,
"s": 60,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 183,
"s": 123,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 251,
"s": 183,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 289,
"s": 251,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 374,
"s": 289,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 548,
"s": 374,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 599,
"s": 548,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 667,
"s": 599,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 838,
"s": 667,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 938,
"s": 838,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 988,
"s": 938,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
MySQL Order by beginning letter? | To order by the first letter, use ORDER BY CASE statement. Let us first create a table −
mysql> create table DemoTable1535
-> (
-> Value varchar(100)
-> );
Query OK, 0 rows affected (2.26 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1535 values('MySQL is good relational database.');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1535 values('is MySQL easy to lean');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1535 values('You need to start basic SQL');
Query OK, 1 row affected (0.35 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1535;
This will produce the following output −
+------------------------------------+
| Value |
+------------------------------------+
| MySQL is good relational database. |
| is MySQL easy to lean |
| You need to start basic SQL |
+------------------------------------+
3 rows in set (0.00 sec)
Following is the query to order by the first letter −
mysql> select * from DemoTable1535
-> order by case when left(Value, 1) = 'i' then 1 else 2 end,Value;
This will produce the following output −
+------------------------------------+
| Value |
+------------------------------------+
| is MySQL easy to lean |
| MySQL is good relational database. |
| You need to start basic SQL |
+------------------------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To order by the first letter, use ORDER BY CASE statement. Let us first create a table −"
},
{
"code": null,
"e": 1264,
"s": 1151,
"text": "mysql> create table DemoTable1535\n -> (\n -> Value varchar(100)\n -> );\nQuery OK, 0 rows affected (2.26 sec)"
},
{
"code": null,
"e": 1320,
"s": 1264,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1645,
"s": 1320,
"text": "mysql> insert into DemoTable1535 values('MySQL is good relational database.');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1535 values('is MySQL easy to lean');\nQuery OK, 1 row affected (0.35 sec)\nmysql> insert into DemoTable1535 values('You need to start basic SQL');\nQuery OK, 1 row affected (0.35 sec)"
},
{
"code": null,
"e": 1705,
"s": 1645,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1741,
"s": 1705,
"text": "mysql> select * from DemoTable1535;"
},
{
"code": null,
"e": 1782,
"s": 1741,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2080,
"s": 1782,
"text": "+------------------------------------+\n| Value |\n+------------------------------------+\n| MySQL is good relational database. |\n| is MySQL easy to lean |\n| You need to start basic SQL |\n+------------------------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2134,
"s": 2080,
"text": "Following is the query to order by the first letter −"
},
{
"code": null,
"e": 2241,
"s": 2134,
"text": "mysql> select * from DemoTable1535\n -> order by case when left(Value, 1) = 'i' then 1 else 2 end,Value;"
},
{
"code": null,
"e": 2282,
"s": 2241,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2580,
"s": 2282,
"text": "+------------------------------------+\n| Value |\n+------------------------------------+\n| is MySQL easy to lean |\n| MySQL is good relational database. |\n| You need to start basic SQL |\n+------------------------------------+\n3 rows in set (0.00 sec)"
}
] |
Matplotlib.pyplot.get_plot_commands() in Python - GeeksforGeeks | 10 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The get_plot_commands() method in pyplot module of matplotlib library is used to get the sorted list of all of the plotting commands.
Syntax: matplotlib.pyplot.get_plot_commands()
Parameters: This method does not accept any parameters.
Returns: This method returns sorted list of all of the plotting commands.
Below examples illustrate the matplotlib.pyplot.get_plot_commands() function in matplotlib.pyplot:
Example:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt w = plt.get_plot_commands() print("List of all of the plotting commands : ")for i in w: print(i)
Output:
List of all of the plotting commands :
acorr
angle_spectrum
annotate
arrow
autoscale
axes
axhline
axhspan
axis
axvline
axvspan
bar
barbs
barh
box
boxplot
broken_barh
cla
clabel
clf
clim
close
cohere
colorbar
contour
contourf
csd
delaxes
draw
errorbar
eventplot
figimage
figlegend
fignum_exists
figtext
figure
fill
fill_between
fill_betweenx
findobj
gca
gcf
gci
get_figlabels
get_fignums
grid
hexbin
hist
hist2d
hlines
imread
imsave
imshow
install_repl_displayhook
ioff
ion
isinteractive
legend
locator_params
loglog
magnitude_spectrum
margins
matshow
minorticks_off
minorticks_on
pause
pcolor
pcolormesh
phase_spectrum
pie
plot
plot_date
plotfile
polar
psd
quiver
quiverkey
rc
rc_context
rcdefaults
rgrids
savefig
sca
scatter
sci
semilogx
semilogy
set_cmap
setp
show
specgram
spy
stackplot
stem
step
streamplot
subplot
subplot2grid
subplot_tool
subplots
subplots_adjust
suptitle
switch_backend
table
text
thetagrids
tick_params
ticklabel_format
tight_layout
title
tricontour
tricontourf
tripcolor
triplot
twinx
twiny
uninstall_repl_displayhook
violinplot
vlines
xcorr
xkcd
xlabel
xlim
xscale
xticks
ylabel
ylim
yscale
yticks
Matplotlib Pyplot-class
Python-matplotlib
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
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24424,
"s": 24396,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24729,
"s": 24424,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 24863,
"s": 24729,
"text": "The get_plot_commands() method in pyplot module of matplotlib library is used to get the sorted list of all of the plotting commands."
},
{
"code": null,
"e": 24909,
"s": 24863,
"text": "Syntax: matplotlib.pyplot.get_plot_commands()"
},
{
"code": null,
"e": 24965,
"s": 24909,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 25039,
"s": 24965,
"text": "Returns: This method returns sorted list of all of the plotting commands."
},
{
"code": null,
"e": 25138,
"s": 25039,
"text": "Below examples illustrate the matplotlib.pyplot.get_plot_commands() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 25147,
"s": 25138,
"text": "Example:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt w = plt.get_plot_commands() print(\"List of all of the plotting commands : \")for i in w: print(i)",
"e": 25343,
"s": 25147,
"text": null
},
{
"code": null,
"e": 25351,
"s": 25343,
"text": "Output:"
},
{
"code": null,
"e": 26477,
"s": 25351,
"text": "List of all of the plotting commands : \nacorr\nangle_spectrum\nannotate\narrow\nautoscale\naxes\naxhline\naxhspan\naxis\naxvline\naxvspan\nbar\nbarbs\nbarh\nbox\nboxplot\nbroken_barh\ncla\nclabel\nclf\nclim\nclose\ncohere\ncolorbar\ncontour\ncontourf\ncsd\ndelaxes\ndraw\nerrorbar\neventplot\nfigimage\nfiglegend\nfignum_exists\nfigtext\nfigure\nfill\nfill_between\nfill_betweenx\nfindobj\ngca\ngcf\ngci\nget_figlabels\nget_fignums\ngrid\nhexbin\nhist\nhist2d\nhlines\nimread\nimsave\nimshow\ninstall_repl_displayhook\nioff\nion\nisinteractive\nlegend\nlocator_params\nloglog\nmagnitude_spectrum\nmargins\nmatshow\nminorticks_off\nminorticks_on\npause\npcolor\npcolormesh\nphase_spectrum\npie\nplot\nplot_date\nplotfile\npolar\npsd\nquiver\nquiverkey\nrc\nrc_context\nrcdefaults\nrgrids\nsavefig\nsca\nscatter\nsci\nsemilogx\nsemilogy\nset_cmap\nsetp\nshow\nspecgram\nspy\nstackplot\nstem\nstep\nstreamplot\nsubplot\nsubplot2grid\nsubplot_tool\nsubplots\nsubplots_adjust\nsuptitle\nswitch_backend\ntable\ntext\nthetagrids\ntick_params\nticklabel_format\ntight_layout\ntitle\ntricontour\ntricontourf\ntripcolor\ntriplot\ntwinx\ntwiny\nuninstall_repl_displayhook\nviolinplot\nvlines\nxcorr\nxkcd\nxlabel\nxlim\nxscale\nxticks\nylabel\nylim\nyscale\nyticks"
},
{
"code": null,
"e": 26501,
"s": 26477,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 26519,
"s": 26501,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26526,
"s": 26519,
"text": "Python"
},
{
"code": null,
"e": 26624,
"s": 26526,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26633,
"s": 26624,
"text": "Comments"
},
{
"code": null,
"e": 26646,
"s": 26633,
"text": "Old Comments"
},
{
"code": null,
"e": 26664,
"s": 26646,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26699,
"s": 26664,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26721,
"s": 26699,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26753,
"s": 26721,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26783,
"s": 26753,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26825,
"s": 26783,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26851,
"s": 26825,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26894,
"s": 26851,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26931,
"s": 26894,
"text": "Create a Pandas DataFrame from Lists"
}
] |
First Hand Review: BYOL(Bootstrap Your Own Latent) | by Nilesh Vijayrania | Towards Data Science | Lately, Self-supervised learning methods have become the cornerstone for unsupervised visual representation learning. One such method Bootstrap Your Own Latent(BYOL) which is introduced recently is reviewed in this post. I have already covered other interesting self-supervised learning methods based on contrastive learning that came before BYOL such as SimCLR, MoCo, etc. in another post thoroughly and should be considered for understanding the fundamentals of this post. Please find them here.
Unlike other contrastive learning methods, BYOL achieves state-of-the-art performance without using any negative samples. Fundamentally, like a siamese network, BYOL uses two same encoder networks referred to as online and target network for obtaining representations and reduces the contrastive loss between the two representations.
Network Architecture
The architecture of the BYOL network is shown below. θ and ε represent online and target network parameters respectively and f_θ and f_ε are online and target encoders respectively. Target network weights are slowly moving average of the online network weights i.e.
Idea is to train the online network f_θ in the first step and use those learned representations for downstream tasks and fine-tune them further using labelled data in the second step. The first step i.e. BYOL could be summarized in the following 5 straightforward steps.
Given an input image x, two views of the same image v and v’ are generated by applying two random augmentations to x.Given v and v’ to online and target encoders in order, vector representations y_θ and y’_ε are obtained.Now, these representations are projected to another subspace z. These projected representations are indicated by z_θ and z’_ε in the image below.Since the target network is the slow moving average of the online network, the online representations should be predictive of the target representations, i.e. z_θ should predict z’_ε and hence another predictor(q_θ) is put on top of z_θ.Contrastive loss is reduced between <q_θ(z_θ), z’_ε>.
Given an input image x, two views of the same image v and v’ are generated by applying two random augmentations to x.
Given v and v’ to online and target encoders in order, vector representations y_θ and y’_ε are obtained.
Now, these representations are projected to another subspace z. These projected representations are indicated by z_θ and z’_ε in the image below.
Since the target network is the slow moving average of the online network, the online representations should be predictive of the target representations, i.e. z_θ should predict z’_ε and hence another predictor(q_θ) is put on top of z_θ.
Contrastive loss is reduced between <q_θ(z_θ), z’_ε>.
Mathematically, Contrastive loss is computed as mean squared error between q_θ(z_θ) and z’_ε. Before computing the mean squared error, the labels z’_ε and targets q_θ(z_θ) are L2-normalized. The equation is,
z`_ε bar , is the L2 normalized z`_ε and q_θ(z_θ) bar is L2 normalized q_θ(z_θ).
Why BYOL?
The First question is, why and where one should use BYOL?
BYOL method helps in learning useful representations for a variety of downstream computer vision tasks such as object recognition, object detection, semantic segmentation, etc. Once these representations are learned in BYOL way, they could be used with any standard object classification model such as Resnet, VGGnet, or any semantic segmentation network such as FCN8s, deeplabv3, etc or any other task-specific network and it gets to a better result than training these networks from scratch. This is the major reason behind the popularity of BYOL. The below graph shows that the BYOL representations learned using Imagenet images beats all previous unsupervised learning methods and achieves classification accuracy of 74.1% with Resnet50 under linear evaluation protocol. In case you are not sure about Linear evaluation protocol, it is described in my last post in detail.
The power of BYOL is leveraged more efficiently in dense prediction tasks where generally only a few labels are available due to the complex and costly task of data labelling. When BYOL is used for one such task namely semantic segmentation using cityscapes dataset with FCN8s network along with Resnet50 backbone, it outperforms the version of the network trained from scratch i.e. with random weights. The below graph compares the performance of 3 main networks on the cityscapes dataset.
Resnet50 trained from Imagenet weights and fine-tuned using 3k cityscapes labelled images(dotted red line).
Resnet50 trained from random weights using 3k cityscapes images only(dotted black line).
Resnet50 pre-trained on BYOL using 20k unlabelled cityscapes images, then fine-tuned using 3k cityscapes image(solid blue line).
The below graph clearly shows that the BYOL significantly helps in learning useful representations for this task and hints that it should be considered as a pre-training step for other computer vision industrial applications where Imagenet weights could not be used due to licensing regulations and lots of unlabelled data is present for unsupervised training.
Implementation Details
For Image augmentations, the following set of augmentations are used. First, a random crop is selected from the image and resized to 224x224. Then random horizontal flip is applied, followed by random color distortion and random grayscale conversion. Random color distortion consists of a random sequence of brightness, contrast, saturation, hue adjustments. The following code snippet implements the BYOL augmentation pipeline in PyTorch..
from torchvision import transforms as tfmsbyol_tfms = tfms.Compose([ tfms.RandomResizedCrop(size=512, scale=(0.3, 1)), tfms.RandomHorizontalFlip(), tfms.ToPILImage(), tfms.RandomApply([ tfms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), tfms.RandomGrayscale(p=0.2), tfms.ToTensor()])
In the actual BYOL implementations, Resnet50 is used as an encoder network. For the projection MLP, the 2048 dimensional feature vector is projected onto 4096-dimensional vector space first with Batch norm followed by ReLU non-linear activation and then it is reduced to the 256-dimensional feature vector. The same architecture is used for the predictor network. Below PyTorch snippet implements the Resnet50 based BYOL network, but it could also be used in conjunction with any arbitrary encoder network such as VGG, InceptionNet, etc. without any significant change.
Why BYOL works the way it works
Another interesting fact is, although a collapsed solution exists for the task curated for BYOL, the model avoids it safely and the actual reason for it is unknown. Collapsed solution means, the model might get away by learning a constant vector for any view of any image and gets to zero loss, but it does not happen.
The authors of the original paper[1], conjecture that it might be due to the complex network(Deep Resnet with skip connections) used in the backbone, the model never gets to the straightforward collapsed solution. But in another recent paper SimSiam[2] Chen, Xineli and He, found out it is not the complex network architecture but the “stop-gradient” operation that makes the model to avoid the collapsed representations. “stop-gradient” means that the network never gets to update the weights of the target network directly through gradients and hence never gets to the collapsed solution. They also show that there isn’t any need for a momentum target network to avoid collapsed representation but it certainly gives better representations for downstream tasks if used.
That was the quick summary of BYOL along with code in PyTorch. For full implementation, this GitHub repo https://github.com/nilesh0109/self-supervised-sem-seg could be referred.
Below is the list of references used in this post.
Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” arXiv preprint arXiv:2006.07733 (2020).Chen, Xinlei, and Kaiming He. “Exploring Simple Siamese Representation Learning.” arXiv preprint arXiv:2011.10566 (2020).
Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” arXiv preprint arXiv:2006.07733 (2020).
Chen, Xinlei, and Kaiming He. “Exploring Simple Siamese Representation Learning.” arXiv preprint arXiv:2011.10566 (2020). | [
{
"code": null,
"e": 669,
"s": 171,
"text": "Lately, Self-supervised learning methods have become the cornerstone for unsupervised visual representation learning. One such method Bootstrap Your Own Latent(BYOL) which is introduced recently is reviewed in this post. I have already covered other interesting self-supervised learning methods based on contrastive learning that came before BYOL such as SimCLR, MoCo, etc. in another post thoroughly and should be considered for understanding the fundamentals of this post. Please find them here."
},
{
"code": null,
"e": 1003,
"s": 669,
"text": "Unlike other contrastive learning methods, BYOL achieves state-of-the-art performance without using any negative samples. Fundamentally, like a siamese network, BYOL uses two same encoder networks referred to as online and target network for obtaining representations and reduces the contrastive loss between the two representations."
},
{
"code": null,
"e": 1024,
"s": 1003,
"text": "Network Architecture"
},
{
"code": null,
"e": 1290,
"s": 1024,
"text": "The architecture of the BYOL network is shown below. θ and ε represent online and target network parameters respectively and f_θ and f_ε are online and target encoders respectively. Target network weights are slowly moving average of the online network weights i.e."
},
{
"code": null,
"e": 1561,
"s": 1290,
"text": "Idea is to train the online network f_θ in the first step and use those learned representations for downstream tasks and fine-tune them further using labelled data in the second step. The first step i.e. BYOL could be summarized in the following 5 straightforward steps."
},
{
"code": null,
"e": 2218,
"s": 1561,
"text": "Given an input image x, two views of the same image v and v’ are generated by applying two random augmentations to x.Given v and v’ to online and target encoders in order, vector representations y_θ and y’_ε are obtained.Now, these representations are projected to another subspace z. These projected representations are indicated by z_θ and z’_ε in the image below.Since the target network is the slow moving average of the online network, the online representations should be predictive of the target representations, i.e. z_θ should predict z’_ε and hence another predictor(q_θ) is put on top of z_θ.Contrastive loss is reduced between <q_θ(z_θ), z’_ε>."
},
{
"code": null,
"e": 2336,
"s": 2218,
"text": "Given an input image x, two views of the same image v and v’ are generated by applying two random augmentations to x."
},
{
"code": null,
"e": 2441,
"s": 2336,
"text": "Given v and v’ to online and target encoders in order, vector representations y_θ and y’_ε are obtained."
},
{
"code": null,
"e": 2587,
"s": 2441,
"text": "Now, these representations are projected to another subspace z. These projected representations are indicated by z_θ and z’_ε in the image below."
},
{
"code": null,
"e": 2825,
"s": 2587,
"text": "Since the target network is the slow moving average of the online network, the online representations should be predictive of the target representations, i.e. z_θ should predict z’_ε and hence another predictor(q_θ) is put on top of z_θ."
},
{
"code": null,
"e": 2879,
"s": 2825,
"text": "Contrastive loss is reduced between <q_θ(z_θ), z’_ε>."
},
{
"code": null,
"e": 3087,
"s": 2879,
"text": "Mathematically, Contrastive loss is computed as mean squared error between q_θ(z_θ) and z’_ε. Before computing the mean squared error, the labels z’_ε and targets q_θ(z_θ) are L2-normalized. The equation is,"
},
{
"code": null,
"e": 3168,
"s": 3087,
"text": "z`_ε bar , is the L2 normalized z`_ε and q_θ(z_θ) bar is L2 normalized q_θ(z_θ)."
},
{
"code": null,
"e": 3178,
"s": 3168,
"text": "Why BYOL?"
},
{
"code": null,
"e": 3236,
"s": 3178,
"text": "The First question is, why and where one should use BYOL?"
},
{
"code": null,
"e": 4113,
"s": 3236,
"text": "BYOL method helps in learning useful representations for a variety of downstream computer vision tasks such as object recognition, object detection, semantic segmentation, etc. Once these representations are learned in BYOL way, they could be used with any standard object classification model such as Resnet, VGGnet, or any semantic segmentation network such as FCN8s, deeplabv3, etc or any other task-specific network and it gets to a better result than training these networks from scratch. This is the major reason behind the popularity of BYOL. The below graph shows that the BYOL representations learned using Imagenet images beats all previous unsupervised learning methods and achieves classification accuracy of 74.1% with Resnet50 under linear evaluation protocol. In case you are not sure about Linear evaluation protocol, it is described in my last post in detail."
},
{
"code": null,
"e": 4604,
"s": 4113,
"text": "The power of BYOL is leveraged more efficiently in dense prediction tasks where generally only a few labels are available due to the complex and costly task of data labelling. When BYOL is used for one such task namely semantic segmentation using cityscapes dataset with FCN8s network along with Resnet50 backbone, it outperforms the version of the network trained from scratch i.e. with random weights. The below graph compares the performance of 3 main networks on the cityscapes dataset."
},
{
"code": null,
"e": 4712,
"s": 4604,
"text": "Resnet50 trained from Imagenet weights and fine-tuned using 3k cityscapes labelled images(dotted red line)."
},
{
"code": null,
"e": 4801,
"s": 4712,
"text": "Resnet50 trained from random weights using 3k cityscapes images only(dotted black line)."
},
{
"code": null,
"e": 4930,
"s": 4801,
"text": "Resnet50 pre-trained on BYOL using 20k unlabelled cityscapes images, then fine-tuned using 3k cityscapes image(solid blue line)."
},
{
"code": null,
"e": 5291,
"s": 4930,
"text": "The below graph clearly shows that the BYOL significantly helps in learning useful representations for this task and hints that it should be considered as a pre-training step for other computer vision industrial applications where Imagenet weights could not be used due to licensing regulations and lots of unlabelled data is present for unsupervised training."
},
{
"code": null,
"e": 5314,
"s": 5291,
"text": "Implementation Details"
},
{
"code": null,
"e": 5755,
"s": 5314,
"text": "For Image augmentations, the following set of augmentations are used. First, a random crop is selected from the image and resized to 224x224. Then random horizontal flip is applied, followed by random color distortion and random grayscale conversion. Random color distortion consists of a random sequence of brightness, contrast, saturation, hue adjustments. The following code snippet implements the BYOL augmentation pipeline in PyTorch.."
},
{
"code": null,
"e": 6066,
"s": 5755,
"text": "from torchvision import transforms as tfmsbyol_tfms = tfms.Compose([ tfms.RandomResizedCrop(size=512, scale=(0.3, 1)), tfms.RandomHorizontalFlip(), tfms.ToPILImage(), tfms.RandomApply([ tfms.ColorJitter(0.4, 0.4, 0.4, 0.1) ], p=0.8), tfms.RandomGrayscale(p=0.2), tfms.ToTensor()])"
},
{
"code": null,
"e": 6636,
"s": 6066,
"text": "In the actual BYOL implementations, Resnet50 is used as an encoder network. For the projection MLP, the 2048 dimensional feature vector is projected onto 4096-dimensional vector space first with Batch norm followed by ReLU non-linear activation and then it is reduced to the 256-dimensional feature vector. The same architecture is used for the predictor network. Below PyTorch snippet implements the Resnet50 based BYOL network, but it could also be used in conjunction with any arbitrary encoder network such as VGG, InceptionNet, etc. without any significant change."
},
{
"code": null,
"e": 6668,
"s": 6636,
"text": "Why BYOL works the way it works"
},
{
"code": null,
"e": 6987,
"s": 6668,
"text": "Another interesting fact is, although a collapsed solution exists for the task curated for BYOL, the model avoids it safely and the actual reason for it is unknown. Collapsed solution means, the model might get away by learning a constant vector for any view of any image and gets to zero loss, but it does not happen."
},
{
"code": null,
"e": 7759,
"s": 6987,
"text": "The authors of the original paper[1], conjecture that it might be due to the complex network(Deep Resnet with skip connections) used in the backbone, the model never gets to the straightforward collapsed solution. But in another recent paper SimSiam[2] Chen, Xineli and He, found out it is not the complex network architecture but the “stop-gradient” operation that makes the model to avoid the collapsed representations. “stop-gradient” means that the network never gets to update the weights of the target network directly through gradients and hence never gets to the collapsed solution. They also show that there isn’t any need for a momentum target network to avoid collapsed representation but it certainly gives better representations for downstream tasks if used."
},
{
"code": null,
"e": 7937,
"s": 7759,
"text": "That was the quick summary of BYOL along with code in PyTorch. For full implementation, this GitHub repo https://github.com/nilesh0109/self-supervised-sem-seg could be referred."
},
{
"code": null,
"e": 7988,
"s": 7937,
"text": "Below is the list of references used in this post."
},
{
"code": null,
"e": 8250,
"s": 7988,
"text": "Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” arXiv preprint arXiv:2006.07733 (2020).Chen, Xinlei, and Kaiming He. “Exploring Simple Siamese Representation Learning.” arXiv preprint arXiv:2011.10566 (2020)."
},
{
"code": null,
"e": 8391,
"s": 8250,
"text": "Grill, Jean-Bastien, et al. “Bootstrap your own latent: A new approach to self-supervised learning.” arXiv preprint arXiv:2006.07733 (2020)."
}
] |
Card Shuffle Problem | TCS Digital Advanced Coding Question - GeeksforGeeks | 18 Oct, 2019
You have 100 cards, numbered 1 to 100. You distribute them into k piles and collect back the piles in order. For example, if you distribute them into 4 piles, then the first pile will contain the cards numbered 1, 5, 9, ... and the 4th pile will contain the cards numbered 4, 8, 12, ... While collecting back the cards you collect first the last pile, flip it bottom to top, then take the third pile, flip it bottom to top and put the cards on top of the 4th pile and so on. Next round, you distribute the cards into another set of piles and collect in the same manner (last pile first and first pile last).
If we have 10 cards and put them into 2 piles, the order of the cards in the piles (top to bottom) would be 9, 7, 5, 3, 1 and 10, 8, 6, 4, 2We flip the piles to get the order 1, 3, 5, 7, 9 and 2, 4, 6, 8, 10We put the second pile at the bottom and first on top of it to get the deck 1, 3, 5, 7, 9, 2, 4, 6, 8, 10Given the number of rounds (m), the number of piles in each round (ki), you need to write a program to find the Nth card from the top at the end of the final round.
Input: An array arr[] representing the number of piles in each of the round.Output: One integer representing the Nth card after all rounds have been played.
Constraints: Number of rounds ≤ 10, number of piles in each round ≤ 13.
Examples:
Input: arr[] = {2, 2}, N = 4Output: 13We have two rounds. The first round has two piles.At the end of the round, the deck is in the following order: 1, 3, 5, ..., 99, 2, 4, 6, ..., 100The next round also has 2 piles and after the second round, the cards are in the order 1, 5, 9, 13, ...The fourth card from the top has number 13.
Input: arr[] = {2, 2, 3, 8}, N = 18Output: 100
Approach: For every round create empty ArrayLists for each pile then insert the numbers (card numbers) in these lists as described in the problem then update the original list of card numbers after each round. At the end of the last round, print the nth integer from the original (updated) list.
Below is the implementation of the above approach:
Java
C#
// Java implementation of the approachimport java.util.*;class GFG { // Total cards static final int CARDS = 100; // Function to perform the current round static void currentRound(List<Integer> list, int totalPiles) { // Create the required empty piles List<List<Integer> > piles = new ArrayList<>(); for (int i = 0; i < totalPiles; i++) piles.add(new ArrayList<Integer>()); // Add cards to the piles one by one int j = 0; for (int i = 0; i < CARDS; i++) { piles.get(j).add(list.get(i)); j = (j + 1) % totalPiles; } // After all the piles have been reversed // the new order will be first card of the // first pile, second card of the first // pile, ..., last pile of the last pile // (from top to bottom) int pileNo = 0, i = 0; j = 0; while (i < CARDS) { list.set(i, piles.get(pileNo).get(j)); j++; if (j >= piles.get(pileNo).size()) { pileNo++; j = 0; } i++; } } // Function to perform all the rounds static int performRounds(int piles[], int rounds, int n) { // Create the initial list with all the cards List<Integer> list = new ArrayList<>(); for (int i = 1; i <= CARDS; i++) list.add(i); // Perform all the rounds for (int i = 0; i < rounds; i++) currentRound(list, piles[i]); // Return the nth card return list.get(n); } // Driver code public static void main(String[] args) { int piles[] = { 2, 2 }; int rounds = piles.length; int n = 4; // nth card will be at (n - 1)th index n--; System.out.print(performRounds(piles, rounds, n)); }}
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Total cards static int CARDS = 100; // Function to perform the current round static void currentRound(List<int> list, int totalPiles) { int i; // Create the required empty piles List<List<int> > piles = new List<List<int>>(); for (i = 0; i < totalPiles; i++) piles.Add(new List<int>()); // Add cards to the piles one by one int j = 0; for (i = 0; i < CARDS; i++) { piles[j].Add(list[i]); j = (j + 1) % totalPiles; } // After all the piles have been reversed // the new order will be first card of the // first pile, second card of the first // pile, ..., last pile of the last pile // (from top to bottom) int pileNo = 0; i = 0; j = 0; while (i < CARDS) { list.Insert(i, piles[pileNo][j]); j++; if (j >= piles[pileNo].Count) { pileNo++; j = 0; } i++; } } // Function to perform all the rounds static int performRounds(int []piles, int rounds, int n) { // Create the initial list with all the cards List<int> list = new List<int>(); for (int i = 1; i <= CARDS; i++) list.Add(i); // Perform all the rounds for (int i = 0; i < rounds; i++) currentRound(list, piles[i]); // Return the nth card return list[n]; } // Driver code public static void Main(String[] args) { int []piles = { 2, 2 }; int rounds = piles.Length; int n = 4; // nth card will be at (n - 1)th index n--; Console.WriteLine(performRounds(piles, rounds, n)); }} // This code is contributed by PrinciRaj1992
13
princiraj1992
TCS
Game Theory
Mathematical
TCS
Mathematical
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Classification of Algorithms with Examples
Moving on grid
A modified game of Nim
The prisoner's dilemma in Game theory
A Binary String Game
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25166,
"s": 25138,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 25774,
"s": 25166,
"text": "You have 100 cards, numbered 1 to 100. You distribute them into k piles and collect back the piles in order. For example, if you distribute them into 4 piles, then the first pile will contain the cards numbered 1, 5, 9, ... and the 4th pile will contain the cards numbered 4, 8, 12, ... While collecting back the cards you collect first the last pile, flip it bottom to top, then take the third pile, flip it bottom to top and put the cards on top of the 4th pile and so on. Next round, you distribute the cards into another set of piles and collect in the same manner (last pile first and first pile last)."
},
{
"code": null,
"e": 26251,
"s": 25774,
"text": "If we have 10 cards and put them into 2 piles, the order of the cards in the piles (top to bottom) would be 9, 7, 5, 3, 1 and 10, 8, 6, 4, 2We flip the piles to get the order 1, 3, 5, 7, 9 and 2, 4, 6, 8, 10We put the second pile at the bottom and first on top of it to get the deck 1, 3, 5, 7, 9, 2, 4, 6, 8, 10Given the number of rounds (m), the number of piles in each round (ki), you need to write a program to find the Nth card from the top at the end of the final round."
},
{
"code": null,
"e": 26408,
"s": 26251,
"text": "Input: An array arr[] representing the number of piles in each of the round.Output: One integer representing the Nth card after all rounds have been played."
},
{
"code": null,
"e": 26480,
"s": 26408,
"text": "Constraints: Number of rounds ≤ 10, number of piles in each round ≤ 13."
},
{
"code": null,
"e": 26490,
"s": 26480,
"text": "Examples:"
},
{
"code": null,
"e": 26821,
"s": 26490,
"text": "Input: arr[] = {2, 2}, N = 4Output: 13We have two rounds. The first round has two piles.At the end of the round, the deck is in the following order: 1, 3, 5, ..., 99, 2, 4, 6, ..., 100The next round also has 2 piles and after the second round, the cards are in the order 1, 5, 9, 13, ...The fourth card from the top has number 13."
},
{
"code": null,
"e": 26868,
"s": 26821,
"text": "Input: arr[] = {2, 2, 3, 8}, N = 18Output: 100"
},
{
"code": null,
"e": 27164,
"s": 26868,
"text": "Approach: For every round create empty ArrayLists for each pile then insert the numbers (card numbers) in these lists as described in the problem then update the original list of card numbers after each round. At the end of the last round, print the nth integer from the original (updated) list."
},
{
"code": null,
"e": 27215,
"s": 27164,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27220,
"s": 27215,
"text": "Java"
},
{
"code": null,
"e": 27223,
"s": 27220,
"text": "C#"
},
{
"code": "// Java implementation of the approachimport java.util.*;class GFG { // Total cards static final int CARDS = 100; // Function to perform the current round static void currentRound(List<Integer> list, int totalPiles) { // Create the required empty piles List<List<Integer> > piles = new ArrayList<>(); for (int i = 0; i < totalPiles; i++) piles.add(new ArrayList<Integer>()); // Add cards to the piles one by one int j = 0; for (int i = 0; i < CARDS; i++) { piles.get(j).add(list.get(i)); j = (j + 1) % totalPiles; } // After all the piles have been reversed // the new order will be first card of the // first pile, second card of the first // pile, ..., last pile of the last pile // (from top to bottom) int pileNo = 0, i = 0; j = 0; while (i < CARDS) { list.set(i, piles.get(pileNo).get(j)); j++; if (j >= piles.get(pileNo).size()) { pileNo++; j = 0; } i++; } } // Function to perform all the rounds static int performRounds(int piles[], int rounds, int n) { // Create the initial list with all the cards List<Integer> list = new ArrayList<>(); for (int i = 1; i <= CARDS; i++) list.add(i); // Perform all the rounds for (int i = 0; i < rounds; i++) currentRound(list, piles[i]); // Return the nth card return list.get(n); } // Driver code public static void main(String[] args) { int piles[] = { 2, 2 }; int rounds = piles.length; int n = 4; // nth card will be at (n - 1)th index n--; System.out.print(performRounds(piles, rounds, n)); }}",
"e": 29074,
"s": 27223,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Total cards static int CARDS = 100; // Function to perform the current round static void currentRound(List<int> list, int totalPiles) { int i; // Create the required empty piles List<List<int> > piles = new List<List<int>>(); for (i = 0; i < totalPiles; i++) piles.Add(new List<int>()); // Add cards to the piles one by one int j = 0; for (i = 0; i < CARDS; i++) { piles[j].Add(list[i]); j = (j + 1) % totalPiles; } // After all the piles have been reversed // the new order will be first card of the // first pile, second card of the first // pile, ..., last pile of the last pile // (from top to bottom) int pileNo = 0; i = 0; j = 0; while (i < CARDS) { list.Insert(i, piles[pileNo][j]); j++; if (j >= piles[pileNo].Count) { pileNo++; j = 0; } i++; } } // Function to perform all the rounds static int performRounds(int []piles, int rounds, int n) { // Create the initial list with all the cards List<int> list = new List<int>(); for (int i = 1; i <= CARDS; i++) list.Add(i); // Perform all the rounds for (int i = 0; i < rounds; i++) currentRound(list, piles[i]); // Return the nth card return list[n]; } // Driver code public static void Main(String[] args) { int []piles = { 2, 2 }; int rounds = piles.Length; int n = 4; // nth card will be at (n - 1)th index n--; Console.WriteLine(performRounds(piles, rounds, n)); }} // This code is contributed by PrinciRaj1992",
"e": 31069,
"s": 29074,
"text": null
},
{
"code": null,
"e": 31073,
"s": 31069,
"text": "13\n"
},
{
"code": null,
"e": 31087,
"s": 31073,
"text": "princiraj1992"
},
{
"code": null,
"e": 31091,
"s": 31087,
"text": "TCS"
},
{
"code": null,
"e": 31103,
"s": 31091,
"text": "Game Theory"
},
{
"code": null,
"e": 31116,
"s": 31103,
"text": "Mathematical"
},
{
"code": null,
"e": 31120,
"s": 31116,
"text": "TCS"
},
{
"code": null,
"e": 31133,
"s": 31120,
"text": "Mathematical"
},
{
"code": null,
"e": 31145,
"s": 31133,
"text": "Game Theory"
},
{
"code": null,
"e": 31243,
"s": 31145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31286,
"s": 31243,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 31301,
"s": 31286,
"text": "Moving on grid"
},
{
"code": null,
"e": 31324,
"s": 31301,
"text": "A modified game of Nim"
},
{
"code": null,
"e": 31362,
"s": 31324,
"text": "The prisoner's dilemma in Game theory"
},
{
"code": null,
"e": 31383,
"s": 31362,
"text": "A Binary String Game"
},
{
"code": null,
"e": 31413,
"s": 31383,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31473,
"s": 31413,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31488,
"s": 31473,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31531,
"s": 31488,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
jQuery - Attributes | Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.
Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are −
className
tagName
id
href
title
rel
src
Consider the following HTML markup for an image element −
<img id = "imageid" src = "image.gif" alt = "Image" class = "myclass"
title = "This is an image"/>
In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.
jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.
The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.
Following is a simple example which fetches title attribute of <em> tag and set <div id = "divid"> value with the same value −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
var title = $("em").attr("title");
$("#divid").text(title);
});
</script>
</head>
<body>
<div>
<em title = "Bold and Brave">This is first paragraph.</em>
<p id = "myid">This is second paragraph.</p>
<div id = "divid"></div>
</div>
</body>
</html>
This will produce following result −
This is second paragraph.
The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.
Following is a simple example which set src attribute of an image tag to a correct location −
<html>
<head>
<title>The jQuery Example</title>
<base href="https://www.tutorialspoint.com" />
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#myimg").attr("src", "/jquery/images/jquery.jpg");
});
</script>
</head>
<body>
<div>
<img id = "myimg" src = "/images/jquery.jpg" alt = "Sample image" />
</div>
</body>
</html>
This will produce following result −
The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.
Following is a simple example which sets class attribute of a para <p> tag −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<em title = "Bold and Brave">This is first paragraph.</em>
<p id = "myid">This is second paragraph.</p>
</body>
</html>
This will produce following result −
This is second paragraph.
Following table lists down few useful methods which you can use to manipulate attributes and properties −
Set a key/value object as properties to all matched elements.
Set a single property to a computed value, on all matched elements.
Remove an attribute from each of the matched elements.
Returns true if the specified class is present on at least one of the set of matched elements.
Removes all or the specified class(es) from the set of matched elements.
Adds the specified class if it is not present, removes the specified class if it is present.
Get the html contents (innerHTML) of the first matched element.
Set the html contents of every matched element.
Get the combined text contents of all matched elements.
Set the text contents of all matched elements.
Get the input value of the first matched element.
Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.
Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation −
$("#myID").attr("custom")
This would return value of attribute custom for the first element matching with ID myID.
$("img").attr("alt", "Sample Image")
This sets the alt attribute of all the images to a new value "Sample Image".
$("input").attr({ value: "", title: "Please enter a value" });
Sets the value of all <input> elements to the empty string, as well as sets The jQuery Example to the string Please enter a value.
$("a[href^=https://]").attr("target","_blank")
Selects all links with an href attribute starting with https:// and set its target attribute to _blank.
$("a").removeAttr("target")
This would remove target attribute of all the links.
$("form").submit(function() {$(":submit",this).attr("disabled", "disabled");});
This would modify the disabled attribute to the value "disabled" while clicking Submit button.
$("p:last").hasClass("selected")
This return true if last <p> tag has associated classselected.
$("p").text()
Returns string that contains the combined text contents of all matched <p> elements.
$("p").text("<i>Hello World</i>")
This would set "<I>Hello World</I>" as text content of the matching <p> elements.
$("p").html()
This returns the HTML content of the all matching paragraphs.
$("div").html("Hello World")
This would set the HTML content of all matching <div> to Hello World.
$("input:checkbox:checked").val()
Get the first value from a checked checkbox.
$("input:radio[name=bar]:checked").val()
Get the first value from a set of radio buttons.
$("button").val("Hello")
Sets the value attribute of every matched element <button>.
$("input").val("on")
This would check all the radio or check box button whose value is "on".
$("select").val("Orange")
This would select Orange option in a dropdown box with options Orange, Mango and Banana.
$("select").val("Orange", "Mango")
This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2466,
"s": 2322,
"text": "Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements."
},
{
"code": null,
"e": 2589,
"s": 2466,
"text": "Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are −"
},
{
"code": null,
"e": 2599,
"s": 2589,
"text": "className"
},
{
"code": null,
"e": 2607,
"s": 2599,
"text": "tagName"
},
{
"code": null,
"e": 2610,
"s": 2607,
"text": "id"
},
{
"code": null,
"e": 2615,
"s": 2610,
"text": "href"
},
{
"code": null,
"e": 2621,
"s": 2615,
"text": "title"
},
{
"code": null,
"e": 2625,
"s": 2621,
"text": "rel"
},
{
"code": null,
"e": 2629,
"s": 2625,
"text": "src"
},
{
"code": null,
"e": 2687,
"s": 2629,
"text": "Consider the following HTML markup for an image element −"
},
{
"code": null,
"e": 2791,
"s": 2687,
"text": "<img id = \"imageid\" src = \"image.gif\" alt = \"Image\" class = \"myclass\" \n title = \"This is an image\"/>\n"
},
{
"code": null,
"e": 2971,
"s": 2791,
"text": "In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value."
},
{
"code": null,
"e": 3120,
"s": 2971,
"text": "jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties."
},
{
"code": null,
"e": 3285,
"s": 3120,
"text": "The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements."
},
{
"code": null,
"e": 3412,
"s": 3285,
"text": "Following is a simple example which fetches title attribute of <em> tag and set <div id = \"divid\"> value with the same value −"
},
{
"code": null,
"e": 4051,
"s": 3412,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n var title = $(\"em\").attr(\"title\");\n $(\"#divid\").text(title);\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <em title = \"Bold and Brave\">This is first paragraph.</em>\n <p id = \"myid\">This is second paragraph.</p>\n <div id = \"divid\"></div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4088,
"s": 4051,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4114,
"s": 4088,
"text": "This is second paragraph."
},
{
"code": null,
"e": 4243,
"s": 4114,
"text": "The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value."
},
{
"code": null,
"e": 4337,
"s": 4243,
"text": "Following is a simple example which set src attribute of an image tag to a correct location −"
},
{
"code": null,
"e": 4933,
"s": 4337,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <base href=\"https://www.tutorialspoint.com\" />\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#myimg\").attr(\"src\", \"/jquery/images/jquery.jpg\");\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <img id = \"myimg\" src = \"/images/jquery.jpg\" alt = \"Sample image\" />\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4970,
"s": 4933,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5127,
"s": 4970,
"text": "The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space."
},
{
"code": null,
"e": 5204,
"s": 5127,
"text": "Following is a simple example which sets class attribute of a para <p> tag −"
},
{
"code": null,
"e": 5892,
"s": 5204,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"em\").addClass(\"selected\");\n $(\"#myid\").addClass(\"highlight\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n .highlight { background:yellow; }\n </style>\t\n </head>\n\t\n <body>\n <em title = \"Bold and Brave\">This is first paragraph.</em>\n <p id = \"myid\">This is second paragraph.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 5929,
"s": 5892,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5955,
"s": 5929,
"text": "This is second paragraph."
},
{
"code": null,
"e": 6061,
"s": 5955,
"text": "Following table lists down few useful methods which you can use to manipulate attributes and properties −"
},
{
"code": null,
"e": 6123,
"s": 6061,
"text": "Set a key/value object as properties to all matched elements."
},
{
"code": null,
"e": 6191,
"s": 6123,
"text": "Set a single property to a computed value, on all matched elements."
},
{
"code": null,
"e": 6246,
"s": 6191,
"text": "Remove an attribute from each of the matched elements."
},
{
"code": null,
"e": 6341,
"s": 6246,
"text": "Returns true if the specified class is present on at least one of the set of matched elements."
},
{
"code": null,
"e": 6414,
"s": 6341,
"text": "Removes all or the specified class(es) from the set of matched elements."
},
{
"code": null,
"e": 6507,
"s": 6414,
"text": "Adds the specified class if it is not present, removes the specified class if it is present."
},
{
"code": null,
"e": 6571,
"s": 6507,
"text": "Get the html contents (innerHTML) of the first matched element."
},
{
"code": null,
"e": 6619,
"s": 6571,
"text": "Set the html contents of every matched element."
},
{
"code": null,
"e": 6675,
"s": 6619,
"text": "Get the combined text contents of all matched elements."
},
{
"code": null,
"e": 6722,
"s": 6675,
"text": "Set the text contents of all matched elements."
},
{
"code": null,
"e": 6772,
"s": 6722,
"text": "Get the input value of the first matched element."
},
{
"code": null,
"e": 7054,
"s": 6772,
"text": "Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked."
},
{
"code": null,
"e": 7200,
"s": 7054,
"text": "Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation −"
},
{
"code": null,
"e": 7226,
"s": 7200,
"text": "$(\"#myID\").attr(\"custom\")"
},
{
"code": null,
"e": 7315,
"s": 7226,
"text": "This would return value of attribute custom for the first element matching with ID myID."
},
{
"code": null,
"e": 7352,
"s": 7315,
"text": "$(\"img\").attr(\"alt\", \"Sample Image\")"
},
{
"code": null,
"e": 7429,
"s": 7352,
"text": "This sets the alt attribute of all the images to a new value \"Sample Image\"."
},
{
"code": null,
"e": 7492,
"s": 7429,
"text": "$(\"input\").attr({ value: \"\", title: \"Please enter a value\" });"
},
{
"code": null,
"e": 7623,
"s": 7492,
"text": "Sets the value of all <input> elements to the empty string, as well as sets The jQuery Example to the string Please enter a value."
},
{
"code": null,
"e": 7670,
"s": 7623,
"text": "$(\"a[href^=https://]\").attr(\"target\",\"_blank\")"
},
{
"code": null,
"e": 7774,
"s": 7670,
"text": "Selects all links with an href attribute starting with https:// and set its target attribute to _blank."
},
{
"code": null,
"e": 7802,
"s": 7774,
"text": "$(\"a\").removeAttr(\"target\")"
},
{
"code": null,
"e": 7855,
"s": 7802,
"text": "This would remove target attribute of all the links."
},
{
"code": null,
"e": 7935,
"s": 7855,
"text": "$(\"form\").submit(function() {$(\":submit\",this).attr(\"disabled\", \"disabled\");});"
},
{
"code": null,
"e": 8030,
"s": 7935,
"text": "This would modify the disabled attribute to the value \"disabled\" while clicking Submit button."
},
{
"code": null,
"e": 8063,
"s": 8030,
"text": "$(\"p:last\").hasClass(\"selected\")"
},
{
"code": null,
"e": 8126,
"s": 8063,
"text": "This return true if last <p> tag has associated classselected."
},
{
"code": null,
"e": 8140,
"s": 8126,
"text": "$(\"p\").text()"
},
{
"code": null,
"e": 8225,
"s": 8140,
"text": "Returns string that contains the combined text contents of all matched <p> elements."
},
{
"code": null,
"e": 8259,
"s": 8225,
"text": "$(\"p\").text(\"<i>Hello World</i>\")"
},
{
"code": null,
"e": 8342,
"s": 8259,
"text": "This would set \"<I>Hello World</I>\" as text content of the matching <p> elements."
},
{
"code": null,
"e": 8356,
"s": 8342,
"text": "$(\"p\").html()"
},
{
"code": null,
"e": 8418,
"s": 8356,
"text": "This returns the HTML content of the all matching paragraphs."
},
{
"code": null,
"e": 8447,
"s": 8418,
"text": "$(\"div\").html(\"Hello World\")"
},
{
"code": null,
"e": 8517,
"s": 8447,
"text": "This would set the HTML content of all matching <div> to Hello World."
},
{
"code": null,
"e": 8551,
"s": 8517,
"text": "$(\"input:checkbox:checked\").val()"
},
{
"code": null,
"e": 8596,
"s": 8551,
"text": "Get the first value from a checked checkbox."
},
{
"code": null,
"e": 8637,
"s": 8596,
"text": "$(\"input:radio[name=bar]:checked\").val()"
},
{
"code": null,
"e": 8686,
"s": 8637,
"text": "Get the first value from a set of radio buttons."
},
{
"code": null,
"e": 8711,
"s": 8686,
"text": "$(\"button\").val(\"Hello\")"
},
{
"code": null,
"e": 8771,
"s": 8711,
"text": "Sets the value attribute of every matched element <button>."
},
{
"code": null,
"e": 8792,
"s": 8771,
"text": "$(\"input\").val(\"on\")"
},
{
"code": null,
"e": 8864,
"s": 8792,
"text": "This would check all the radio or check box button whose value is \"on\"."
},
{
"code": null,
"e": 8890,
"s": 8864,
"text": "$(\"select\").val(\"Orange\")"
},
{
"code": null,
"e": 8979,
"s": 8890,
"text": "This would select Orange option in a dropdown box with options Orange, Mango and Banana."
},
{
"code": null,
"e": 9014,
"s": 8979,
"text": "$(\"select\").val(\"Orange\", \"Mango\")"
},
{
"code": null,
"e": 9114,
"s": 9014,
"text": "This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana."
},
{
"code": null,
"e": 9147,
"s": 9114,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9161,
"s": 9147,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 9196,
"s": 9161,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9210,
"s": 9196,
"text": " Pratik Singh"
},
{
"code": null,
"e": 9245,
"s": 9210,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9262,
"s": 9245,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9295,
"s": 9262,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9323,
"s": 9295,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9356,
"s": 9323,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9377,
"s": 9356,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 9409,
"s": 9377,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 9426,
"s": 9409,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 9433,
"s": 9426,
"text": " Print"
},
{
"code": null,
"e": 9444,
"s": 9433,
"text": " Add Notes"
}
] |
How to Get the minimum value from the Pandas dataframe in Python? - GeeksforGeeks | 14 Jan, 2022
In this article, we will discuss how to get the minimum value from the Pandas dataframe in Python.
We can get the minimum value by using the min() function
Syntax:
dataframe.min(axis)
where,
axis=0 specifies column
axis=1 specifies row
To get the minimum value in a dataframe row simply call the min() function with axis set to 1.
Syntax:
dataframe.min(axis=1)
Example: Get minimum value in a dataframe row
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in rowdata.min(axis=1)
Output:
To get the minimum value in a column simply call the min() function using axis set to 0.
Syntax:
dataframe.min(axis=0)
Example: Get minimum value in a column
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in columndata.min(axis=0)
Output:
To get the minimum value in a particular column call the dataframe with the specific column name and min() function.
Syntax:
dataframe['column_name'].min()
Example: Get the minimum value in a particular column
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in name columnprint(data['name'].min()) # get the minimum in subjects columnprint(data['subjects'].min()) # get the minimum in age columnprint(data['age'].min()) # get the minimum in marks columnprint(data['marks'].min())
Output:
sumitgumber28
pandas-dataframe-program
Picked
Python pandas-dataFrame
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 ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 24391,
"s": 24292,
"text": "In this article, we will discuss how to get the minimum value from the Pandas dataframe in Python."
},
{
"code": null,
"e": 24448,
"s": 24391,
"text": "We can get the minimum value by using the min() function"
},
{
"code": null,
"e": 24456,
"s": 24448,
"text": "Syntax:"
},
{
"code": null,
"e": 24476,
"s": 24456,
"text": "dataframe.min(axis)"
},
{
"code": null,
"e": 24484,
"s": 24476,
"text": "where, "
},
{
"code": null,
"e": 24508,
"s": 24484,
"text": "axis=0 specifies column"
},
{
"code": null,
"e": 24529,
"s": 24508,
"text": "axis=1 specifies row"
},
{
"code": null,
"e": 24624,
"s": 24529,
"text": "To get the minimum value in a dataframe row simply call the min() function with axis set to 1."
},
{
"code": null,
"e": 24632,
"s": 24624,
"text": "Syntax:"
},
{
"code": null,
"e": 24654,
"s": 24632,
"text": "dataframe.min(axis=1)"
},
{
"code": null,
"e": 24700,
"s": 24654,
"text": "Example: Get minimum value in a dataframe row"
},
{
"code": null,
"e": 24708,
"s": 24700,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in rowdata.min(axis=1)",
"e": 25080,
"s": 24708,
"text": null
},
{
"code": null,
"e": 25088,
"s": 25080,
"text": "Output:"
},
{
"code": null,
"e": 25177,
"s": 25088,
"text": "To get the minimum value in a column simply call the min() function using axis set to 0."
},
{
"code": null,
"e": 25185,
"s": 25177,
"text": "Syntax:"
},
{
"code": null,
"e": 25207,
"s": 25185,
"text": "dataframe.min(axis=0)"
},
{
"code": null,
"e": 25246,
"s": 25207,
"text": "Example: Get minimum value in a column"
},
{
"code": null,
"e": 25254,
"s": 25246,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in columndata.min(axis=0)",
"e": 25629,
"s": 25254,
"text": null
},
{
"code": null,
"e": 25637,
"s": 25629,
"text": "Output:"
},
{
"code": null,
"e": 25754,
"s": 25637,
"text": "To get the minimum value in a particular column call the dataframe with the specific column name and min() function."
},
{
"code": null,
"e": 25762,
"s": 25754,
"text": "Syntax:"
},
{
"code": null,
"e": 25793,
"s": 25762,
"text": "dataframe['column_name'].min()"
},
{
"code": null,
"e": 25848,
"s": 25793,
"text": "Example: Get the minimum value in a particular column "
},
{
"code": null,
"e": 25856,
"s": 25848,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87], 'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in name columnprint(data['name'].min()) # get the minimum in subjects columnprint(data['subjects'].min()) # get the minimum in age columnprint(data['age'].min()) # get the minimum in marks columnprint(data['marks'].min())",
"e": 26431,
"s": 25856,
"text": null
},
{
"code": null,
"e": 26439,
"s": 26431,
"text": "Output:"
},
{
"code": null,
"e": 26453,
"s": 26439,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26478,
"s": 26453,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 26485,
"s": 26478,
"text": "Picked"
},
{
"code": null,
"e": 26509,
"s": 26485,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26523,
"s": 26509,
"text": "Python-pandas"
},
{
"code": null,
"e": 26530,
"s": 26523,
"text": "Python"
},
{
"code": null,
"e": 26628,
"s": 26530,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26660,
"s": 26628,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26716,
"s": 26660,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26758,
"s": 26716,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26800,
"s": 26758,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26822,
"s": 26800,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26861,
"s": 26822,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26892,
"s": 26861,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26947,
"s": 26892,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26976,
"s": 26947,
"text": "Create a directory in Python"
}
] |
ReactJS - Component Life Cycle Using React Hooks | React Hooks provides a special Hook, useEffect() to execute certain functionality during the life cycle of the component. useEffect() combines componentDidMount, componentDidUpdate, and componentWillUnmount life cycle into a single api.
The signature of the useEffect() api is as follows −
useEffect(
<executeFn>,
<values>
);
Here,
executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount).
executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount).
values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn.
values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn.
Let us add useEffect() Hooks in our react-clock-hook-app application.
Open react-clock-hook-app in your favorite editor.
Next, open src/components/Clock.js file and start editing.
Next, import useEffect api.
import React, { useState, useEffect } from 'react';
Next, call useEffect with function to set date and time every second using setInterval and return a function to stop updating the date and time using clearInterval.
useEffect(
() => {
let setTime = () => {
console.log("setTime is called");
setCurrentDateTime(new Date());
}
let interval = setInterval(setTime, 1000);
return () => {
clearInterval(interval);
}
},
[]
);
Here,
Created a function, setTime to set the current time into the state of the component.
Created a function, setTime to set the current time into the state of the component.
Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable.
Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable.
Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference.
Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference.
Now, we have updated the Clock component and the complete source code of the component is as follows −
import React, { useState, useEffect } from 'react';
function Clock() {
const [currentDateTime, setCurrentDateTime] = useState(new Date());
useEffect(
() => {
let setTime = () => {
console.log("setTime is called");
setCurrentDateTime(new Date());
}
let interval = setInterval(setTime, 1000);
return () => {
clearInterval(interval);
}
},
[]
);
return (
<div>
<p>The current time is {currentDateTime.toString()}</p>
</div>
);
}
export default Clock;
Next, open index.js and use setTimeout to remove the clock from the DOM after 5 seconds.
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './components/Clock';
ReactDOM.render(
<React.StrictMode>
<Clock />
</React.StrictMode>,
document.getElementById('root')
);
setTimeout(() => {
ReactDOM.render(
<React.StrictMode>
<div><p>Clock is removed from the DOM.</p></div>
</React.StrictMode>,
document.getElementById('root')
);
}, 5000);
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
The clock will be shown for 5 seconds and then, it will be removed from the DOM. By checking the console log, we can found that the cleanup code is properly executed.
React allows arbitrary children user interface content to be included inside the component. The children of a component can be accessed through this.props.children. Adding children inside the component is called containment. Containment is used in situation where certain section of the component is dynamic in nature.
For example, a rich text message box may not know its content until it is called. Let us create RichTextMessage component to showcase the feature of React children property in this chapter.
First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.
Next, open the application in your favorite editor.
Next, create src folder under the root directory of the application.
Next, create components folder under src folder.
Next, create a file, RichTextMessage.js under src/components folder and start editing.
Next, import React library.
import React from 'react';
Next, create a class, RichTextMessage and call constructor with props.
class RichTextMessage extends React.Component {
constructor(props) {
super(props);
}
}
Next, add render() method and show the user interface of the component along with it’s children
render() {
return (
<div>{this.props.children}</div>
)
}
Here,
props.children returns the children of the component.
props.children returns the children of the component.
Wraped the children inside a div tag.
Wraped the children inside a div tag.
Finally, export the component.
export default RichTextMessage;
The complete source code of the RichTextMessagecomponent is given below −
import React from 'react';
class RichTextMessage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>{this.props.children}</div>
)
}
}
export default RichTextMessage;
Next, create a file, index.js under the src folder and use RichTextMessage component.
import React from 'react';
import ReactDOM from 'react-dom';
import RichTextMessage from './components/RichTextMessage';
ReactDOM.render(
<React.StrictMode>
<RichTextMessage>
<h1>Containment is really a cool feature.</h1>
</RichTextMessage>
</React.StrictMode>,
document.getElementById('root')
);
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
Browser emits component’s children wrapped in div tag as shown below −
<div id="root">
<div>
<div>
<h1>Containment is really a cool feature.</h1>
</div>
</div>
</div>
Next, change the child property of RichTextMessage component in index.js.
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './components/Clock';
ReactDOM.render(
<React.StrictMode>
<RichTextMessage>
<h1>Containment is really an excellent feature.</h1>
</RichTextMessage>
</React.StrictMode>,
document.getElementById('root')
);
Now, browser updates the component’s children content and emits as shown below −
<div id="root">
<div>
<div>
<h1>Containment is really an excellent feature.</h1>
</div>
</div>
</div>
In short, containment is an excellent feature to pass arbitrary user interface content to the component.
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2270,
"s": 2033,
"text": "React Hooks provides a special Hook, useEffect() to execute certain functionality during the life cycle of the component. useEffect() combines componentDidMount, componentDidUpdate, and componentWillUnmount life cycle into a single api."
},
{
"code": null,
"e": 2323,
"s": 2270,
"text": "The signature of the useEffect() api is as follows −"
},
{
"code": null,
"e": 2367,
"s": 2323,
"text": "useEffect(\n <executeFn>, \n <values>\n);\n"
},
{
"code": null,
"e": 2373,
"s": 2367,
"text": "Here,"
},
{
"code": null,
"e": 2560,
"s": 2373,
"text": "executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount)."
},
{
"code": null,
"e": 2747,
"s": 2560,
"text": "executeFn − Function to execute when an effect occurs with an optional return function. The return function will be execute when a clean up is required (similar to componentWillUnmount)."
},
{
"code": null,
"e": 2918,
"s": 2747,
"text": "values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn."
},
{
"code": null,
"e": 3089,
"s": 2918,
"text": "values − array of values the effect depends on. React Hooks execute the executeFn only when the values are changed. This will reduce unnecessary calling of the executeFn."
},
{
"code": null,
"e": 3159,
"s": 3089,
"text": "Let us add useEffect() Hooks in our react-clock-hook-app application."
},
{
"code": null,
"e": 3210,
"s": 3159,
"text": "Open react-clock-hook-app in your favorite editor."
},
{
"code": null,
"e": 3269,
"s": 3210,
"text": "Next, open src/components/Clock.js file and start editing."
},
{
"code": null,
"e": 3297,
"s": 3269,
"text": "Next, import useEffect api."
},
{
"code": null,
"e": 3350,
"s": 3297,
"text": "import React, { useState, useEffect } from 'react';\n"
},
{
"code": null,
"e": 3515,
"s": 3350,
"text": "Next, call useEffect with function to set date and time every second using setInterval and return a function to stop updating the date and time using clearInterval."
},
{
"code": null,
"e": 3784,
"s": 3515,
"text": "useEffect(\n () => {\n let setTime = () => {\n console.log(\"setTime is called\");\n setCurrentDateTime(new Date());\n }\n let interval = setInterval(setTime, 1000);\n return () => {\n clearInterval(interval);\n }\n },\n []\n);"
},
{
"code": null,
"e": 3790,
"s": 3784,
"text": "Here,"
},
{
"code": null,
"e": 3875,
"s": 3790,
"text": "Created a function, setTime to set the current time into the state of the component."
},
{
"code": null,
"e": 3960,
"s": 3875,
"text": "Created a function, setTime to set the current time into the state of the component."
},
{
"code": null,
"e": 4100,
"s": 3960,
"text": "Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable."
},
{
"code": null,
"e": 4240,
"s": 4100,
"text": "Called the setInterval JavaScript api to execute setTime every second and stored the reference of the setInterval in the interval variable."
},
{
"code": null,
"e": 4375,
"s": 4240,
"text": "Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference."
},
{
"code": null,
"e": 4510,
"s": 4375,
"text": "Created a return function, which calls the clearInterval api to stop executing setTime every second by passing the interval reference."
},
{
"code": null,
"e": 4613,
"s": 4510,
"text": "Now, we have updated the Clock component and the complete source code of the component is as follows −"
},
{
"code": null,
"e": 5196,
"s": 4613,
"text": "import React, { useState, useEffect } from 'react';\n\nfunction Clock() {\n const [currentDateTime, setCurrentDateTime] = useState(new Date());\n useEffect(\n () => {\n let setTime = () => {\n console.log(\"setTime is called\");\n setCurrentDateTime(new Date());\n }\n let interval = setInterval(setTime, 1000);\n return () => {\n clearInterval(interval);\n }\n },\n []\n );\n return (\n <div>\n <p>The current time is {currentDateTime.toString()}</p>\n </div>\n );\n}\nexport default Clock;"
},
{
"code": null,
"e": 5285,
"s": 5196,
"text": "Next, open index.js and use setTimeout to remove the clock from the DOM after 5 seconds."
},
{
"code": null,
"e": 5707,
"s": 5285,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport Clock from './components/Clock';\n\nReactDOM.render(\n <React.StrictMode>\n <Clock />\n </React.StrictMode>,\n document.getElementById('root')\n);\nsetTimeout(() => {\n ReactDOM.render(\n <React.StrictMode>\n <div><p>Clock is removed from the DOM.</p></div>\n </React.StrictMode>,\n document.getElementById('root')\n );\n}, 5000);"
},
{
"code": null,
"e": 5754,
"s": 5707,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 5765,
"s": 5754,
"text": "npm start\n"
},
{
"code": null,
"e": 5856,
"s": 5765,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 6023,
"s": 5856,
"text": "The clock will be shown for 5 seconds and then, it will be removed from the DOM. By checking the console log, we can found that the cleanup code is properly executed."
},
{
"code": null,
"e": 6342,
"s": 6023,
"text": "React allows arbitrary children user interface content to be included inside the component. The children of a component can be accessed through this.props.children. Adding children inside the component is called containment. Containment is used in situation where certain section of the component is dynamic in nature."
},
{
"code": null,
"e": 6532,
"s": 6342,
"text": "For example, a rich text message box may not know its content until it is called. Let us create RichTextMessage component to showcase the feature of React children property in this chapter."
},
{
"code": null,
"e": 6696,
"s": 6532,
"text": "First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter."
},
{
"code": null,
"e": 6748,
"s": 6696,
"text": "Next, open the application in your favorite editor."
},
{
"code": null,
"e": 6817,
"s": 6748,
"text": "Next, create src folder under the root directory of the application."
},
{
"code": null,
"e": 6866,
"s": 6817,
"text": "Next, create components folder under src folder."
},
{
"code": null,
"e": 6953,
"s": 6866,
"text": "Next, create a file, RichTextMessage.js under src/components folder and start editing."
},
{
"code": null,
"e": 6981,
"s": 6953,
"text": "Next, import React library."
},
{
"code": null,
"e": 7009,
"s": 6981,
"text": "import React from 'react';\n"
},
{
"code": null,
"e": 7080,
"s": 7009,
"text": "Next, create a class, RichTextMessage and call constructor with props."
},
{
"code": null,
"e": 7183,
"s": 7080,
"text": "class RichTextMessage extends React.Component {\n constructor(props) { \n super(props); \n } \n}\n"
},
{
"code": null,
"e": 7279,
"s": 7183,
"text": "Next, add render() method and show the user interface of the component along with it’s children"
},
{
"code": null,
"e": 7353,
"s": 7279,
"text": "render() { \n return ( \n <div>{this.props.children}</div> \n ) \n}\n"
},
{
"code": null,
"e": 7359,
"s": 7353,
"text": "Here,"
},
{
"code": null,
"e": 7413,
"s": 7359,
"text": "props.children returns the children of the component."
},
{
"code": null,
"e": 7467,
"s": 7413,
"text": "props.children returns the children of the component."
},
{
"code": null,
"e": 7505,
"s": 7467,
"text": "Wraped the children inside a div tag."
},
{
"code": null,
"e": 7543,
"s": 7505,
"text": "Wraped the children inside a div tag."
},
{
"code": null,
"e": 7574,
"s": 7543,
"text": "Finally, export the component."
},
{
"code": null,
"e": 7607,
"s": 7574,
"text": "export default RichTextMessage;\n"
},
{
"code": null,
"e": 7681,
"s": 7607,
"text": "The complete source code of the RichTextMessagecomponent is given below −"
},
{
"code": null,
"e": 7924,
"s": 7681,
"text": "import React from 'react';\n\nclass RichTextMessage extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>{this.props.children}</div>\n )\n }\n}\nexport default RichTextMessage;"
},
{
"code": null,
"e": 8010,
"s": 7924,
"text": "Next, create a file, index.js under the src folder and use RichTextMessage component."
},
{
"code": null,
"e": 8338,
"s": 8010,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport RichTextMessage from './components/RichTextMessage';\n\nReactDOM.render(\n <React.StrictMode>\n <RichTextMessage>\n <h1>Containment is really a cool feature.</h1>\n </RichTextMessage>\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 8420,
"s": 8338,
"text": "Finally, create a public folder under the root folder and create index.html file."
},
{
"code": null,
"e": 8655,
"s": 8420,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 8702,
"s": 8655,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 8713,
"s": 8702,
"text": "npm start\n"
},
{
"code": null,
"e": 8804,
"s": 8713,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 8875,
"s": 8804,
"text": "Browser emits component’s children wrapped in div tag as shown below −"
},
{
"code": null,
"e": 8998,
"s": 8875,
"text": "<div id=\"root\">\n <div>\n <div>\n <h1>Containment is really a cool feature.</h1>\n </div>\n </div>\n</div>"
},
{
"code": null,
"e": 9072,
"s": 8998,
"text": "Next, change the child property of RichTextMessage component in index.js."
},
{
"code": null,
"e": 9394,
"s": 9072,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport Clock from './components/Clock';\n\nReactDOM.render(\n <React.StrictMode>\n <RichTextMessage>\n <h1>Containment is really an excellent feature.</h1>\n </RichTextMessage>\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 9475,
"s": 9394,
"text": "Now, browser updates the component’s children content and emits as shown below −"
},
{
"code": null,
"e": 9613,
"s": 9475,
"text": "<div id=\"root\">\n <div>\n <div>\n <h1>Containment is really an excellent feature.</h1>\n </div>\n </div>\n</div>"
},
{
"code": null,
"e": 9718,
"s": 9613,
"text": "In short, containment is an excellent feature to pass arbitrary user interface content to the component."
},
{
"code": null,
"e": 9753,
"s": 9718,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9767,
"s": 9753,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9802,
"s": 9767,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9822,
"s": 9802,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 9857,
"s": 9822,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 9880,
"s": 9857,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 9915,
"s": 9880,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 9931,
"s": 9915,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9964,
"s": 9931,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9982,
"s": 9964,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 9989,
"s": 9982,
"text": " Print"
},
{
"code": null,
"e": 10000,
"s": 9989,
"text": " Add Notes"
}
] |
What is the Halting Problem in TOC? | Usually, programs consist of loops that are limited or unlimited in length.
The total work done by the program completely depends on the input given to the program.
The program may consist of several different numbers of loops that may be in linear or nested manner.
The Halting Problem is the problem of deciding or concluding based on a given arbitrary computer program and its input, whether that program will stop executing or run-in an infinite loop for the given input.
The Halting Problem tells that it is not easy to write a computer program that executes in the limited time that is capable of deciding whether a program halts for an input.
In addition to that the Halting Problem never says that it is not practicable to determine whether a given random program is going to halt (stop).
Generally, it asks the question like “Given a random program and an input, conclude whether the given random program is going to halt when that input is given”.
An example of writing the Halting Problem is as follows −
INPUT − Program P and a string S.
OUTPUT − if P stops on S, it returns 1.
Otherwise, if P enters into an endless loop on S, it returns 0.
Let us consider the Halting Problem called H having the solution.
Now H takes the following two inputs −
Program P
Program P
Input S.
Input S.
If P stops on S, then H results in “halt”, otherwise H gives the result “loop”.
The diagrammatic representation of H is as follows −
ATM = {(M,w) | M is a TM and M halts at input w }.
We can build a universal Turing machine which can simulate any Turing machine on any input.
Let’s consider TM which recognizing the Altering Turing Machine (ATM) −
Recognize-ATM (<M,w>)
Simulate M using UTM till it halts
If M halts and accept then
Accept
Else
Reject
Suppose, if M goes into an infinite loop on input w, then the TM Recognize-ATM is going to run forever which means TM is only a recognizer, not a decider.
A decider for this problem would call a halt to simulations that loop forever.
Now the question is whether an ATM is TM decidable is equivalent to asking the question whether we can tell if a TM M will halt on input w.
Because of this, both versions of this question are generally called the halting problem. | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Usually, programs consist of loops that are limited or unlimited in length."
},
{
"code": null,
"e": 1227,
"s": 1138,
"text": "The total work done by the program completely depends on the input given to the program."
},
{
"code": null,
"e": 1329,
"s": 1227,
"text": "The program may consist of several different numbers of loops that may be in linear or nested manner."
},
{
"code": null,
"e": 1538,
"s": 1329,
"text": "The Halting Problem is the problem of deciding or concluding based on a given arbitrary computer program and its input, whether that program will stop executing or run-in an infinite loop for the given input."
},
{
"code": null,
"e": 1712,
"s": 1538,
"text": "The Halting Problem tells that it is not easy to write a computer program that executes in the limited time that is capable of deciding whether a program halts for an input."
},
{
"code": null,
"e": 1859,
"s": 1712,
"text": "In addition to that the Halting Problem never says that it is not practicable to determine whether a given random program is going to halt (stop)."
},
{
"code": null,
"e": 2020,
"s": 1859,
"text": "Generally, it asks the question like “Given a random program and an input, conclude whether the given random program is going to halt when that input is given”."
},
{
"code": null,
"e": 2078,
"s": 2020,
"text": "An example of writing the Halting Problem is as follows −"
},
{
"code": null,
"e": 2112,
"s": 2078,
"text": "INPUT − Program P and a string S."
},
{
"code": null,
"e": 2152,
"s": 2112,
"text": "OUTPUT − if P stops on S, it returns 1."
},
{
"code": null,
"e": 2216,
"s": 2152,
"text": "Otherwise, if P enters into an endless loop on S, it returns 0."
},
{
"code": null,
"e": 2282,
"s": 2216,
"text": "Let us consider the Halting Problem called H having the solution."
},
{
"code": null,
"e": 2321,
"s": 2282,
"text": "Now H takes the following two inputs −"
},
{
"code": null,
"e": 2331,
"s": 2321,
"text": "Program P"
},
{
"code": null,
"e": 2341,
"s": 2331,
"text": "Program P"
},
{
"code": null,
"e": 2350,
"s": 2341,
"text": "Input S."
},
{
"code": null,
"e": 2359,
"s": 2350,
"text": "Input S."
},
{
"code": null,
"e": 2439,
"s": 2359,
"text": "If P stops on S, then H results in “halt”, otherwise H gives the result “loop”."
},
{
"code": null,
"e": 2492,
"s": 2439,
"text": "The diagrammatic representation of H is as follows −"
},
{
"code": null,
"e": 2543,
"s": 2492,
"text": "ATM = {(M,w) | M is a TM and M halts at input w }."
},
{
"code": null,
"e": 2635,
"s": 2543,
"text": "We can build a universal Turing machine which can simulate any Turing machine on any input."
},
{
"code": null,
"e": 2707,
"s": 2635,
"text": "Let’s consider TM which recognizing the Altering Turing Machine (ATM) −"
},
{
"code": null,
"e": 2831,
"s": 2707,
"text": "Recognize-ATM (<M,w>)\n Simulate M using UTM till it halts\n If M halts and accept then\n Accept\n Else\n Reject"
},
{
"code": null,
"e": 2986,
"s": 2831,
"text": "Suppose, if M goes into an infinite loop on input w, then the TM Recognize-ATM is going to run forever which means TM is only a recognizer, not a decider."
},
{
"code": null,
"e": 3065,
"s": 2986,
"text": "A decider for this problem would call a halt to simulations that loop forever."
},
{
"code": null,
"e": 3205,
"s": 3065,
"text": "Now the question is whether an ATM is TM decidable is equivalent to asking the question whether we can tell if a TM M will halt on input w."
},
{
"code": null,
"e": 3295,
"s": 3205,
"text": "Because of this, both versions of this question are generally called the halting problem."
}
] |
How to set text font family in HTML? | To change the text font family in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family. HTML5 do not support the <font> tag, so the CSS style is used to add font size.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to change the text font family in an HTML page
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Font Family</title>
</head>
<body>
<h1>Our Products</h1>
<p style="font-family:georgia,garamond,serif;">
This is demo text
</p>
</body>
</html> | [
{
"code": null,
"e": 1349,
"s": 1062,
"text": "To change the text font family in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family. HTML5 do not support the <font> tag, so the CSS style is used to add font size."
},
{
"code": null,
"e": 1511,
"s": 1349,
"text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet."
},
{
"code": null,
"e": 1596,
"s": 1511,
"text": "You can try to run the following code to change the text font family in an HTML page"
},
{
"code": null,
"e": 1606,
"s": 1596,
"text": "Live Demo"
},
{
"code": null,
"e": 1838,
"s": 1606,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Font Family</title>\n </head>\n\n <body>\n <h1>Our Products</h1>\n <p style=\"font-family:georgia,garamond,serif;\">\n This is demo text\n </p>\n </body>\n</html>"
}
] |
Java Program to Print Star Pascal’s Triangle - GeeksforGeeks | 18 Apr, 2022
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.In this article, we will look into the process of printing Pascal’s triangle. Pascal’s triangle is a pattern of the triangle which is based on nCr.below is the pictorial representation of Pascal’s triangle.
Illustration:
Input : N = 5
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Methods:
There are two approaches for the same. Let’s check them out.
Using nCr formulaUsing Binomial Coefficient
Using nCr formula
Using Binomial Coefficient
Method 1: Using nCr formula
Implementation: Follow the below algorithm for printing Pascal’s triangle using the nCr formula
Let n be the number of rows to be printed
Use outer iteration a from 0 to k times to print the rows
Make inner iteration for b from 0 to (K – 1).
Then print space as ” “.
Close the inner ‘b’ loop.
Make inner iteration for b from ‘0’ to ‘a’.
Output nCr of ‘a’ and ‘b’.
Close inner loop.
Print newline character (\n) after each inner iteration.
Example
Java
// Java Program to Print Pascal's Triangle // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Method 1 // To find factorial of a number public int factorial(int a) { // Edge case // Factorial of 0 is unity if (a == 0) // Hence return 1 return 1; // else recursively call the function over the // number whose factorial is to be computed return a * factorial(a - 1); } // Method 2 // Main driver method public static void main(String[] args) { // Declare and initialize number whose // factorial is to be computed int k = 4; int a, b; // Creating an object of GFG class // in the main() method GFG g = new GFG(); // iterating using nested for loop to traverse over // matrix // Outer for loop for (a = 0; a <= k; a++) { // Inner loop 1 for (b = 0; b <= k - a; b++) { // Print white space for left spacing System.out.print(" "); } // Inner loop 2 for (b = 0; b <= a; b++) { // nCr formula System.out.print( " " + g.factorial(a) / (g.factorial(a - b) * g.factorial(b))); } // By now, we are done with one row so // a new line System.out.println(); } }}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Method 2: Using Binomial Coefficient
The ‘A’th entry in a line number line is Binomial Coefficient C(line, a) and all lines start with value 1. The idea is to calculate C(line, a) using C(line, a-1).
C(line, i) = C(line, i-1) * (line - i + 1) / i
Implementation:
Example
Java
// Java Program to Print Pascal's Triangle // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Method 1 // Pascal function public static void printPascal(int k) { for (int line = 1; line <= k; line++) { for (int b = 0; b <= k - line; b++) { // Print whitespace for left spacing System.out.print(" "); } // Variable used to represent C(line, i) int C = 1; for (int a = 1; a <= line; a++) { // The first value in a line is always 1 System.out.print(C + " "); C = C * (line - a) / a; } // By now, we are done with one row so // a new line is required System.out.println(); } } // Method 2 // Main driver method public static void main(String[] args) { // Declare and initialize variable number // upto which Pascal's triangle is required on // console int n = 6; // Calling the Pascal function(Method 1) printPascal(n); }}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
saurabh1990aror
prachisoda1234
simranarora5sos
java-basics
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24384,
"s": 23948,
"text": "Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints the first n lines of Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.In this article, we will look into the process of printing Pascal’s triangle. Pascal’s triangle is a pattern of the triangle which is based on nCr.below is the pictorial representation of Pascal’s triangle."
},
{
"code": null,
"e": 24398,
"s": 24384,
"text": "Illustration:"
},
{
"code": null,
"e": 24524,
"s": 24398,
"text": "Input : N = 5\nOutput:\n 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1\n1 5 10 10 5 1"
},
{
"code": null,
"e": 24534,
"s": 24524,
"text": "Methods: "
},
{
"code": null,
"e": 24595,
"s": 24534,
"text": "There are two approaches for the same. Let’s check them out."
},
{
"code": null,
"e": 24639,
"s": 24595,
"text": "Using nCr formulaUsing Binomial Coefficient"
},
{
"code": null,
"e": 24657,
"s": 24639,
"text": "Using nCr formula"
},
{
"code": null,
"e": 24684,
"s": 24657,
"text": "Using Binomial Coefficient"
},
{
"code": null,
"e": 24712,
"s": 24684,
"text": "Method 1: Using nCr formula"
},
{
"code": null,
"e": 24808,
"s": 24712,
"text": "Implementation: Follow the below algorithm for printing Pascal’s triangle using the nCr formula"
},
{
"code": null,
"e": 24850,
"s": 24808,
"text": "Let n be the number of rows to be printed"
},
{
"code": null,
"e": 24908,
"s": 24850,
"text": "Use outer iteration a from 0 to k times to print the rows"
},
{
"code": null,
"e": 24954,
"s": 24908,
"text": "Make inner iteration for b from 0 to (K – 1)."
},
{
"code": null,
"e": 24979,
"s": 24954,
"text": "Then print space as ” “."
},
{
"code": null,
"e": 25005,
"s": 24979,
"text": "Close the inner ‘b’ loop."
},
{
"code": null,
"e": 25049,
"s": 25005,
"text": "Make inner iteration for b from ‘0’ to ‘a’."
},
{
"code": null,
"e": 25076,
"s": 25049,
"text": "Output nCr of ‘a’ and ‘b’."
},
{
"code": null,
"e": 25094,
"s": 25076,
"text": "Close inner loop."
},
{
"code": null,
"e": 25151,
"s": 25094,
"text": "Print newline character (\\n) after each inner iteration."
},
{
"code": null,
"e": 25159,
"s": 25151,
"text": "Example"
},
{
"code": null,
"e": 25164,
"s": 25159,
"text": "Java"
},
{
"code": "// Java Program to Print Pascal's Triangle // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Method 1 // To find factorial of a number public int factorial(int a) { // Edge case // Factorial of 0 is unity if (a == 0) // Hence return 1 return 1; // else recursively call the function over the // number whose factorial is to be computed return a * factorial(a - 1); } // Method 2 // Main driver method public static void main(String[] args) { // Declare and initialize number whose // factorial is to be computed int k = 4; int a, b; // Creating an object of GFG class // in the main() method GFG g = new GFG(); // iterating using nested for loop to traverse over // matrix // Outer for loop for (a = 0; a <= k; a++) { // Inner loop 1 for (b = 0; b <= k - a; b++) { // Print white space for left spacing System.out.print(\" \"); } // Inner loop 2 for (b = 0; b <= a; b++) { // nCr formula System.out.print( \" \" + g.factorial(a) / (g.factorial(a - b) * g.factorial(b))); } // By now, we are done with one row so // a new line System.out.println(); } }}",
"e": 26690,
"s": 25164,
"text": null
},
{
"code": null,
"e": 26740,
"s": 26690,
"text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1"
},
{
"code": null,
"e": 26777,
"s": 26740,
"text": "Method 2: Using Binomial Coefficient"
},
{
"code": null,
"e": 26942,
"s": 26777,
"text": "The ‘A’th entry in a line number line is Binomial Coefficient C(line, a) and all lines start with value 1. The idea is to calculate C(line, a) using C(line, a-1). "
},
{
"code": null,
"e": 26989,
"s": 26942,
"text": "C(line, i) = C(line, i-1) * (line - i + 1) / i"
},
{
"code": null,
"e": 27005,
"s": 26989,
"text": "Implementation:"
},
{
"code": null,
"e": 27014,
"s": 27005,
"text": "Example "
},
{
"code": null,
"e": 27019,
"s": 27014,
"text": "Java"
},
{
"code": "// Java Program to Print Pascal's Triangle // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Method 1 // Pascal function public static void printPascal(int k) { for (int line = 1; line <= k; line++) { for (int b = 0; b <= k - line; b++) { // Print whitespace for left spacing System.out.print(\" \"); } // Variable used to represent C(line, i) int C = 1; for (int a = 1; a <= line; a++) { // The first value in a line is always 1 System.out.print(C + \" \"); C = C * (line - a) / a; } // By now, we are done with one row so // a new line is required System.out.println(); } } // Method 2 // Main driver method public static void main(String[] args) { // Declare and initialize variable number // upto which Pascal's triangle is required on // console int n = 6; // Calling the Pascal function(Method 1) printPascal(n); }}",
"e": 28157,
"s": 27019,
"text": null
},
{
"code": null,
"e": 28228,
"s": 28157,
"text": " 1 \n 1 1 \n 1 2 1 \n 1 3 3 1 \n 1 4 6 4 1 \n 1 5 10 10 5 1 "
},
{
"code": null,
"e": 28246,
"s": 28230,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28261,
"s": 28246,
"text": "prachisoda1234"
},
{
"code": null,
"e": 28277,
"s": 28261,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28289,
"s": 28277,
"text": "java-basics"
},
{
"code": null,
"e": 28296,
"s": 28289,
"text": "Picked"
},
{
"code": null,
"e": 28301,
"s": 28296,
"text": "Java"
},
{
"code": null,
"e": 28315,
"s": 28301,
"text": "Java Programs"
},
{
"code": null,
"e": 28320,
"s": 28315,
"text": "Java"
},
{
"code": null,
"e": 28418,
"s": 28320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28433,
"s": 28418,
"text": "Stream In Java"
},
{
"code": null,
"e": 28454,
"s": 28433,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28500,
"s": 28454,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28519,
"s": 28500,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28549,
"s": 28519,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28593,
"s": 28549,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28619,
"s": 28593,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28653,
"s": 28619,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28700,
"s": 28653,
"text": "Implementing a Linked List in Java using Class"
}
] |
PyQt5 QSpinBox - Getting the sender signal index value - GeeksforGeeks | 28 May, 2020
In this article we will see how we can get the spin box sender signal index value. Sender signal index is the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender. If called outside of a slot activated by a signal, -1 is returned.
In order to do this we use senderSignalIndex method with the spin box object.
Syntax : spin_box.senderSignalIndex()
Argument : It takes no argument
Return : It returns integer value
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(1, 999999) # setting prefix to spin self.spin.setPrefix("PREFIX ") # setting suffix to spin self.spin.setSuffix(" SUFFIX") # creating a label self.label = QLabel(self) # making label multi line self.label.setWordWrap(True) # setting label geometry self.label.setGeometry(100, 200, 250, 60) # getting sender signal index value = self.spin.senderSignalIndex() # setting text to the label self.label.setText("Sender Signal Index : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24594,
"s": 24292,
"text": "In this article we will see how we can get the spin box sender signal index value. Sender signal index is the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender. If called outside of a slot activated by a signal, -1 is returned."
},
{
"code": null,
"e": 24672,
"s": 24594,
"text": "In order to do this we use senderSignalIndex method with the spin box object."
},
{
"code": null,
"e": 24710,
"s": 24672,
"text": "Syntax : spin_box.senderSignalIndex()"
},
{
"code": null,
"e": 24742,
"s": 24710,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 24776,
"s": 24742,
"text": "Return : It returns integer value"
},
{
"code": null,
"e": 24804,
"s": 24776,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(1, 999999) # setting prefix to spin self.spin.setPrefix(\"PREFIX \") # setting suffix to spin self.spin.setSuffix(\" SUFFIX\") # creating a label self.label = QLabel(self) # making label multi line self.label.setWordWrap(True) # setting label geometry self.label.setGeometry(100, 200, 250, 60) # getting sender signal index value = self.spin.senderSignalIndex() # setting text to the label self.label.setText(\"Sender Signal Index : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26243,
"s": 24804,
"text": null
},
{
"code": null,
"e": 26252,
"s": 26243,
"text": "Output :"
},
{
"code": null,
"e": 26272,
"s": 26252,
"text": "Python PyQt-SpinBox"
},
{
"code": null,
"e": 26283,
"s": 26272,
"text": "Python-gui"
},
{
"code": null,
"e": 26295,
"s": 26283,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26302,
"s": 26295,
"text": "Python"
},
{
"code": null,
"e": 26400,
"s": 26302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26432,
"s": 26400,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26488,
"s": 26432,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26530,
"s": 26488,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26572,
"s": 26530,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26594,
"s": 26572,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26633,
"s": 26594,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26664,
"s": 26633,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26719,
"s": 26664,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26748,
"s": 26719,
"text": "Create a directory in Python"
}
] |
java.util.zip.ZipFile.getInputStream() Method Example | The java.util.zip.ZipFile.getInputStream(ZipEntry entry) method returns an input stream for reading the contents of the specified zip file entry.
Following is the declaration for java.util.zip.ZipFile.getInputStream(ZipEntry entry) method.
public InputStream getInputStream(ZipEntry entry)
throws IOException
entry − the zip file entry.
entry − the zip file entry.
the input stream for reading the contents of the specified zip file entry.
ZipException − if a ZIP format error has occurred.
ZipException − if a ZIP format error has occurred.
IOException − if an I/O error has occurred.
IOException − if an I/O error has occurred.
IllegalStateException − if an I/O error has occurred.
IllegalStateException − if an I/O error has occurred.
Create a file Hello.txt in D:> test > directory with the following content.
This is an example.
The following example shows the usage of java.util.zip.ZipFile.getInputStream(ZipEntry entry) method.
package com.tutorialspoint;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class ZipFileDemo {
private static String SOURCE_FILE = "D:\\test\\Hello.txt";
private static String TARGET_FILE = "D:\\test\\Hello.zip";
public static void main(String[] args) {
try {
createZipFile();
readZipFile();
} catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
private static void createZipFile() throws IOException{
FileOutputStream fout = new FileOutputStream(TARGET_FILE);
CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
ZipOutputStream zout = new ZipOutputStream(checksum);
FileInputStream fin = new FileInputStream(SOURCE_FILE);
ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
zipEntry.setComment("This is a sample file.");
zout.putNextEntry(zipEntry);
int length;
byte[] buffer = new byte[1024];
while((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
zout.close();
}
private static void readZipFile() throws IOException{
final ZipFile file = new ZipFile(TARGET_FILE);
try {
ZipEntry entry = file.getEntry(SOURCE_FILE);
if(entry != null){
System.out.printf("File: %s Size %d Modified on %TD %n",
entry.getName(), entry.getSize(),
new Date(entry.getTime()));
extractFile(entry, file.getInputStream(entry));
}
System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
}
finally {
file.close();
}
}
private static void extractFile(final ZipEntry entry, InputStream is)
throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(entry.getName());
final byte[] buf = new byte[1024];
int read = 0;
int length;
while ((length = is.read(buf, 0, buf.length)) >= 0) {
fos.write(buf, 0, length);
}
} catch (IOException ioex) {
fos.close();
}
}
}
Let us compile and run the above program, this will produce the following result −
File: D:\test\Hello.txt Size 1024 Modified on 05/22/17
Zip file D:\test\Hello.txt extracted successfully.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2338,
"s": 2192,
"text": "The java.util.zip.ZipFile.getInputStream(ZipEntry entry) method returns an input stream for reading the contents of the specified zip file entry."
},
{
"code": null,
"e": 2432,
"s": 2338,
"text": "Following is the declaration for java.util.zip.ZipFile.getInputStream(ZipEntry entry) method."
},
{
"code": null,
"e": 2505,
"s": 2432,
"text": "public InputStream getInputStream(ZipEntry entry)\n throws IOException\n"
},
{
"code": null,
"e": 2533,
"s": 2505,
"text": "entry − the zip file entry."
},
{
"code": null,
"e": 2561,
"s": 2533,
"text": "entry − the zip file entry."
},
{
"code": null,
"e": 2636,
"s": 2561,
"text": "the input stream for reading the contents of the specified zip file entry."
},
{
"code": null,
"e": 2688,
"s": 2636,
"text": "ZipException − if a ZIP format error has occurred."
},
{
"code": null,
"e": 2740,
"s": 2688,
"text": "ZipException − if a ZIP format error has occurred."
},
{
"code": null,
"e": 2785,
"s": 2740,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 2830,
"s": 2785,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 2885,
"s": 2830,
"text": "IllegalStateException − if an I/O error has occurred."
},
{
"code": null,
"e": 2940,
"s": 2885,
"text": "IllegalStateException − if an I/O error has occurred."
},
{
"code": null,
"e": 3017,
"s": 2940,
"text": "Create a file Hello.txt in D:> test > directory with the following content."
},
{
"code": null,
"e": 3038,
"s": 3017,
"text": "This is an example.\n"
},
{
"code": null,
"e": 3140,
"s": 3038,
"text": "The following example shows the usage of java.util.zip.ZipFile.getInputStream(ZipEntry entry) method."
},
{
"code": null,
"e": 5644,
"s": 3140,
"text": "package com.tutorialspoint;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Date;\nimport java.util.Enumeration;\nimport java.util.zip.Adler32;\nimport java.util.zip.CheckedOutputStream;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport java.util.zip.ZipOutputStream;\n\npublic class ZipFileDemo {\n private static String SOURCE_FILE = \"D:\\\\test\\\\Hello.txt\";\n private static String TARGET_FILE = \"D:\\\\test\\\\Hello.zip\";\n\n public static void main(String[] args) {\n try {\n createZipFile();\n readZipFile();\n } catch(IOException ioe) {\n System.out.println(\"IOException : \" + ioe);\n }\n }\n\n private static void createZipFile() throws IOException{\n FileOutputStream fout = new FileOutputStream(TARGET_FILE);\n CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());\n ZipOutputStream zout = new ZipOutputStream(checksum);\n\n FileInputStream fin = new FileInputStream(SOURCE_FILE);\n ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);\n zipEntry.setComment(\"This is a sample file.\");\n zout.putNextEntry(zipEntry);\n int length;\n byte[] buffer = new byte[1024];\n while((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n fin.close();\n zout.close();\n }\n\n private static void readZipFile() throws IOException{\n final ZipFile file = new ZipFile(TARGET_FILE); \n \n try { \n ZipEntry entry = file.getEntry(SOURCE_FILE);\n if(entry != null){\n System.out.printf(\"File: %s Size %d Modified on %TD %n\", \n entry.getName(), entry.getSize(), \n new Date(entry.getTime()));\n extractFile(entry, file.getInputStream(entry)); \n }\n System.out.printf(\"Zip file %s extracted successfully.\", SOURCE_FILE); \n } \n finally { \n file.close(); \n }\n }\n\n private static void extractFile(final ZipEntry entry, InputStream is) \n throws IOException {\n FileOutputStream fos = null; \n try { \n fos = new FileOutputStream(entry.getName()); \n final byte[] buf = new byte[1024]; \n int read = 0; \n int length; \n while ((length = is.read(buf, 0, buf.length)) >= 0) { \n fos.write(buf, 0, length); \n } \n } catch (IOException ioex) { \n fos.close(); \n } \n }\n}"
},
{
"code": null,
"e": 5727,
"s": 5644,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 5835,
"s": 5727,
"text": "File: D:\\test\\Hello.txt Size 1024 Modified on 05/22/17 \nZip file D:\\test\\Hello.txt extracted successfully.\n"
},
{
"code": null,
"e": 5842,
"s": 5835,
"text": " Print"
},
{
"code": null,
"e": 5853,
"s": 5842,
"text": " Add Notes"
}
] |
How to use the wildcard character (*) in Get-ChildItem in PowerShell? | You can also search for files with a specific name or using the wildcard (*) character.
Below command will search for the files (including hidden files) starting with “Bac”.
Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 24-11-2018 11:34 6215 Backup.xml
When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”.
Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*
Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\DomainSysvol\GPO\Machine\microsoft\windows
nt\SecEdit
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 24-11-2018 11:34 16028 GptTmpl.inf | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "You can also search for files with a specific name or using the wildcard (*) character."
},
{
"code": null,
"e": 1236,
"s": 1150,
"text": "Below command will search for the files (including hidden files) starting with “Bac”."
},
{
"code": null,
"e": 1288,
"s": 1236,
"text": "Get-ChildItem D:\\Temp -Recurse -Force -Include Bac*"
},
{
"code": null,
"e": 1605,
"s": 1288,
"text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp -Recurse -Force -Include Bac*\n Directory: D:\\Temp\\GPO_backup\\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 24-11-2018 11:34 6215 Backup.xml"
},
{
"code": null,
"e": 1803,
"s": 1605,
"text": "When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”."
},
{
"code": null,
"e": 1858,
"s": 1803,
"text": "Get-ChildItem D:\\Temp\\ -Recurse -Force -Include *tmp*\n"
},
{
"code": null,
"e": 2236,
"s": 1858,
"text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Recurse -Force -Include *tmp*\n Directory: D:\\Temp\\GPO_backup\\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\\DomainSysvol\\GPO\\Machine\\microsoft\\windows\n nt\\SecEdit\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 24-11-2018 11:34 16028 GptTmpl.inf"
}
] |
Xamarin - Android Widgets | This is a widget used to display date. In this example, we are going to create a date picker which displays the set date on a text view.
First of all, create a new project and call it datePickerExample. Open Main.axml and create a datepicker, textview, and a button.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<DatePicker
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/datePicker1" />
<TextView
android:text = "Current Date"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/txtShowDate" />
<Button
android:text = "Select Date"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/btnSetDate" />
</LinearLayout>
Next, go to Mainactivity.cs. We first create a private instance of a textview inside the mainActivity:Activity class.
The instance will be used to store the date selected or the default date.
private TextView showCurrentDate;
Next, add the following code after setContentView() method.
DatePicker pickDate = FindViewById<DatePicker>(Resource.Id.datePicker1);
showCurrentDate = FindViewById<TextView>(Resource.Id.txtShowDate);
setCurrentDate();
Button button = FindViewById<Button>(Resource.Id.btnSetDate);
button.Click += delegate {
showCurrentDate.Text = String.Format("{0}/{1}/{2}",
pickDate.Month, pickDate.DayOfMonth, pickDate.Year);
};
In the above code, we have referenced our datepicker, textview, and button by finding them from our main.axml file using FindViewById class.
After referencing, we set the button click event which is responsible for passing the selected date from the date picker to the textview.
Next, we create the setCurrentDate() method for displaying the default current date to our textview. The following code explains how it is done.
private void setCurrentDate() {
string TodaysDate = string.Format("{0}",
DateTime.Now.ToString("M/d/yyyy").PadLeft(2, '0'));
showCurrentDate.Text = TodaysDate;
}
DateTime.Now.ToString() class binds today’s time to a string object.
Now, build and run the App. It should display the following output −
Time Picker is a widget used to display time as well as allowing a user to pick and set time. We are going to create a basic time picker app that displays the time and also allows a user to change the time.
Go to main.axml and add a new button, textview, and a time picker as shown in the following code.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TimePicker
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/timePicker1" />
<TextView
android:text = "Time"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/txt_showTime"
android:textColor = "@android:color/black" />
<Button
android:text = "Set Time"
android:layout_width = "200dp"
android:layout_height = "wrap_content"
android:id = "@+id/btnSetTime"
android:textColor = "@android:color/black"
android:background = "@android:color/holo_green_dark" />
</LinearLayout>
Go to MainActivity.cs to add the functionality for displaying a set date on the textview we created.
public class MainActivity : Activity {
private TextView showCurrentTime;
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
TimePicker Tpicker = FindViewById<TimePicker>(Resource.Id.timePicker1);
showCurrentTime = FindViewById<TextView>(Resource.Id.txt_showTime);
setCurrentTime();
Button button = FindViewById<Button>(Resource.Id.btnSetTime);
button.Click += delegate {
showCurrentTime.Text = String.Format("{0}:{1}",
Tpicker.CurrentHour, Tpicker.CurrentMinute);
};
}
private void setCurrentTime() {
string time = string.Format("{0}",
DateTime.Now.ToString("HH:mm").PadLeft(2, '0'));
showCurrentTime.Text = time;
}
}
In the above code, we first referenced the timepicker,set time button and the textview for showing time through the FindViewById<> class. We then created a click event for the set time button which on click sets the time to the time selected by a person. By default, it shows the current system time.
The setCurrentTime() method class initializes the txt_showTime textview to display the current time.
Now, build and run your application. It should display the following output −
A spinner is a widget used to select one option from a set. It is an equivalent of a dropdown/Combo box. First of all, create a new project and call it Spinner App Tutorial.
Open Main.axml under the layout folder and create a new spinner.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<Spinner
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/spinner1"
android:prompt = "@string/daysOfWeek" />
</LinearLayout>
Open Strings.xml file located under values folder and add the following code to create the spinner items.
<resources>
<string name = "daysOfWeek">Choose a planet</string>
<string-array name = "days_array">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>
<item>Sunday</item>
</string-array>
</resources>
Next, open MainActivity.cs to add the functionality for displaying the selected day of the week.
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Spinner spinnerDays = FindViewById<Spinner>(Resource.Id.spinner1);
spinnerDays.ItemSelected += new EventHandler
<AdapterView.ItemSelectedEventArgs>(SelectedDay);
var adapter = ArrayAdapter.CreateFromResource(this,
Resource.Array.days_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropD ownItem);
spinnerDays.Adapter = adapter;
}
private void SelectedDay(object sender, AdapterView.ItemSelectedEventArgs e) {
Spinner spinner = (Spinner)sender;
string toast = string.Format("The selected
day is {0}", spinner.GetItemAtPosition(e.Position));
Toast.MakeText(this, toast, ToastLength.Long).Show();
}
Now, build and run the application. It should display the following output −
In the above code, we referenced the spinner we created in our main.axml file through the FindViewById<> class. We then created a new arrayAdapter() which we used to bind our array items from the strings.xml class.
Finally we created the method SelectedDay() which we used to display the selected day of the week.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2101,
"s": 1964,
"text": "This is a widget used to display date. In this example, we are going to create a date picker which displays the set date on a text view."
},
{
"code": null,
"e": 2231,
"s": 2101,
"text": "First of all, create a new project and call it datePickerExample. Open Main.axml and create a datepicker, textview, and a button."
},
{
"code": null,
"e": 3070,
"s": 2231,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <DatePicker \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/datePicker1\" /> \n <TextView \n android:text = \"Current Date\" \n android:textAppearance = \"?android:attr/textAppearanceLarge\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/txtShowDate\" /> \n <Button \n android:text = \"Select Date\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/btnSetDate\" /> \n</LinearLayout> "
},
{
"code": null,
"e": 3188,
"s": 3070,
"text": "Next, go to Mainactivity.cs. We first create a private instance of a textview inside the mainActivity:Activity class."
},
{
"code": null,
"e": 3262,
"s": 3188,
"text": "The instance will be used to store the date selected or the default date."
},
{
"code": null,
"e": 3297,
"s": 3262,
"text": "private TextView showCurrentDate;\n"
},
{
"code": null,
"e": 3357,
"s": 3297,
"text": "Next, add the following code after setContentView() method."
},
{
"code": null,
"e": 3729,
"s": 3357,
"text": "DatePicker pickDate = FindViewById<DatePicker>(Resource.Id.datePicker1); \nshowCurrentDate = FindViewById<TextView>(Resource.Id.txtShowDate); \nsetCurrentDate(); \nButton button = FindViewById<Button>(Resource.Id.btnSetDate); \nbutton.Click += delegate { \n showCurrentDate.Text = String.Format(\"{0}/{1}/{2}\", \n pickDate.Month, pickDate.DayOfMonth, pickDate.Year); \n}; "
},
{
"code": null,
"e": 3870,
"s": 3729,
"text": "In the above code, we have referenced our datepicker, textview, and button by finding them from our main.axml file using FindViewById class."
},
{
"code": null,
"e": 4008,
"s": 3870,
"text": "After referencing, we set the button click event which is responsible for passing the selected date from the date picker to the textview."
},
{
"code": null,
"e": 4153,
"s": 4008,
"text": "Next, we create the setCurrentDate() method for displaying the default current date to our textview. The following code explains how it is done."
},
{
"code": null,
"e": 4332,
"s": 4153,
"text": "private void setCurrentDate() { \n string TodaysDate = string.Format(\"{0}\", \n DateTime.Now.ToString(\"M/d/yyyy\").PadLeft(2, '0')); \n showCurrentDate.Text = TodaysDate; \n} "
},
{
"code": null,
"e": 4401,
"s": 4332,
"text": "DateTime.Now.ToString() class binds today’s time to a string object."
},
{
"code": null,
"e": 4470,
"s": 4401,
"text": "Now, build and run the App. It should display the following output −"
},
{
"code": null,
"e": 4677,
"s": 4470,
"text": "Time Picker is a widget used to display time as well as allowing a user to pick and set time. We are going to create a basic time picker app that displays the time and also allows a user to change the time."
},
{
"code": null,
"e": 4775,
"s": 4677,
"text": "Go to main.axml and add a new button, textview, and a time picker as shown in the following code."
},
{
"code": null,
"e": 5792,
"s": 4775,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:background = \"#d3d3d3\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <TimePicker \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/timePicker1\" /> \n <TextView\n android:text = \"Time\" \n android:textAppearance = \"?android:attr/textAppearanceLarge\" \n android:layout_width = \"match_parent\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/txt_showTime\" \n android:textColor = \"@android:color/black\" /> \n <Button \n android:text = \"Set Time\" \n android:layout_width = \"200dp\" \n android:layout_height = \"wrap_content\" \n android:id = \"@+id/btnSetTime\" \n android:textColor = \"@android:color/black\" \n android:background = \"@android:color/holo_green_dark\" /> \n</LinearLayout> "
},
{
"code": null,
"e": 5893,
"s": 5792,
"text": "Go to MainActivity.cs to add the functionality for displaying a set date on the textview we created."
},
{
"code": null,
"e": 6717,
"s": 5893,
"text": "public class MainActivity : Activity { \n \n private TextView showCurrentTime; \n \n protected override void OnCreate(Bundle bundle) { \n \n base.OnCreate(bundle); \n SetContentView(Resource.Layout.Main); \n TimePicker Tpicker = FindViewById<TimePicker>(Resource.Id.timePicker1); \n showCurrentTime = FindViewById<TextView>(Resource.Id.txt_showTime); \n setCurrentTime(); \n Button button = FindViewById<Button>(Resource.Id.btnSetTime); \n \n button.Click += delegate { \n showCurrentTime.Text = String.Format(\"{0}:{1}\", \n Tpicker.CurrentHour, Tpicker.CurrentMinute); \n }; \n } \n private void setCurrentTime() { \n string time = string.Format(\"{0}\", \n DateTime.Now.ToString(\"HH:mm\").PadLeft(2, '0')); \n showCurrentTime.Text = time;\n } \n} "
},
{
"code": null,
"e": 7018,
"s": 6717,
"text": "In the above code, we first referenced the timepicker,set time button and the textview for showing time through the FindViewById<> class. We then created a click event for the set time button which on click sets the time to the time selected by a person. By default, it shows the current system time."
},
{
"code": null,
"e": 7119,
"s": 7018,
"text": "The setCurrentTime() method class initializes the txt_showTime textview to display the current time."
},
{
"code": null,
"e": 7197,
"s": 7119,
"text": "Now, build and run your application. It should display the following output −"
},
{
"code": null,
"e": 7371,
"s": 7197,
"text": "A spinner is a widget used to select one option from a set. It is an equivalent of a dropdown/Combo box. First of all, create a new project and call it Spinner App Tutorial."
},
{
"code": null,
"e": 7436,
"s": 7371,
"text": "Open Main.axml under the layout folder and create a new spinner."
},
{
"code": null,
"e": 7887,
"s": 7436,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?> \n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\" \n android:orientation = \"vertical\" \n android:layout_width = \"fill_parent\" \n android:layout_height = \"fill_parent\"> \n <Spinner \n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" \n android:id = \"@+id/spinner1\" \n android:prompt = \"@string/daysOfWeek\" /> \n</LinearLayout> "
},
{
"code": null,
"e": 7993,
"s": 7887,
"text": "Open Strings.xml file located under values folder and add the following code to create the spinner items."
},
{
"code": null,
"e": 8357,
"s": 7993,
"text": "<resources> \n <string name = \"daysOfWeek\">Choose a planet</string> \n <string-array name = \"days_array\"> \n <item>Sunday</item> \n <item>Monday</item> \n <item>Tuesday</item> \n <item>Wednesday</item> \n <item>Thursday</item> \n <item>Friday</item> \n <item>Saturday</item> \n <item>Sunday</item> \n </string-array> \n</resources>"
},
{
"code": null,
"e": 8454,
"s": 8357,
"text": "Next, open MainActivity.cs to add the functionality for displaying the selected day of the week."
},
{
"code": null,
"e": 9353,
"s": 8454,
"text": "protected override void OnCreate(Bundle bundle) { \n base.OnCreate(bundle); \n // Set our view from the \"main\" layout resource \n SetContentView(Resource.Layout.Main); \n Spinner spinnerDays = FindViewById<Spinner>(Resource.Id.spinner1); \n spinnerDays.ItemSelected += new EventHandler\n <AdapterView.ItemSelectedEventArgs>(SelectedDay); \n var adapter = ArrayAdapter.CreateFromResource(this, \n Resource.Array.days_array, Android.Resource.Layout.SimpleSpinnerItem); \n adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropD ownItem); \n spinnerDays.Adapter = adapter; \n} \nprivate void SelectedDay(object sender, AdapterView.ItemSelectedEventArgs e) { \n Spinner spinner = (Spinner)sender; \n string toast = string.Format(\"The selected \n day is {0}\", spinner.GetItemAtPosition(e.Position)); \n Toast.MakeText(this, toast, ToastLength.Long).Show(); \n} "
},
{
"code": null,
"e": 9430,
"s": 9353,
"text": "Now, build and run the application. It should display the following output −"
},
{
"code": null,
"e": 9645,
"s": 9430,
"text": "In the above code, we referenced the spinner we created in our main.axml file through the FindViewById<> class. We then created a new arrayAdapter() which we used to bind our array items from the strings.xml class."
},
{
"code": null,
"e": 9744,
"s": 9645,
"text": "Finally we created the method SelectedDay() which we used to display the selected day of the week."
},
{
"code": null,
"e": 9751,
"s": 9744,
"text": " Print"
},
{
"code": null,
"e": 9762,
"s": 9751,
"text": " Add Notes"
}
] |
How to rotate a node in JavaFX? | If you move an object in the XY plane around a fixed point with an angle it is known as rotation.
In JavaFX using the object of the javafx.scene.transform.Rotate class, you can rotate a node. This class internally rotates the coordinate space of the node around a given fixed point, this makes the node to appear rotated.
This class contains five properties −
The angle property (double) specifying the angle of rotation. You can set the value to this property using the setAngle() method.
The angle property (double) specifying the angle of rotation. You can set the value to this property using the setAngle() method.
The axis property (Point3D) specifying the axis of rotation. You can set the value to this property using the setAxis() method.
The axis property (Point3D) specifying the axis of rotation. You can set the value to this property using the setAxis() method.
The pivotX property (double) specifying the x coordinates of the pivot point. You can set the value to this property using the setPivotX() method.
The pivotX property (double) specifying the x coordinates of the pivot point. You can set the value to this property using the setPivotX() method.
The pivotY property (double) specifying the y coordinates of the pivot point. You can set the value to this property using the setPivotY() method.
The pivotY property (double) specifying the y coordinates of the pivot point. You can set the value to this property using the setPivotY() method.
The pivotZ property (double) specifying the z coordinates of the pivot point. You can set the value to this property using the setPivotZ() method.
The pivotZ property (double) specifying the z coordinates of the pivot point. You can set the value to this property using the setPivotZ() method.
Every node in JavaFX contains an observable list to hold all the transforms to be applied on a node. You can get this list using the getTransforms() method.
To rotate a Node in JavaFX −
Instantiate the Rotate class.
Instantiate the Rotate class.
Set the angle and the pivot point using the setter methods.
Set the angle and the pivot point using the setter methods.
Get the list of transforms from the node (which you want to rotate) using the getTransforms() method.
Get the list of transforms from the node (which you want to rotate) using the getTransforms() method.
Add the above created rotate object to it.
Add the above created rotate object to it.
Add the node to the scene.
Add the node to the scene.
Following the JavaFX example demonstrates the rotation transform. It contains a 2D geometric shape and a slider, representing the angle value. If you move the slider the object will be rotated.
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class RotationExample extends Application {
public void start(Stage stage) {
//Creating a rectangle
Rectangle rect = new Rectangle(300, 100, 75, 75);
rect.setFill(Color.BLUEVIOLET);
rect.setStrokeWidth(5.0);
rect.setStroke(Color.BROWN);
//Setting the slider
Slider slider = new Slider(0, 360, 0);
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(90);
slider.setBlockIncrement(10);
slider.setOrientation(Orientation.VERTICAL);
slider.setLayoutX(2);
slider.setLayoutY(195);
//creating the rotation transformation
Rotate rotate = new Rotate();
//Setting pivot points for the rotation
rotate.setPivotX(300);
rotate.setPivotY(100);
//Adding the transformation to rectangle
rect.getTransforms().addAll(rotate);
//Linking the transformation to the slider
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){
//Setting the angle for the rotation
rotate.setAngle((double) newValue);
}
});
//Adding the transformation to the circle
rect.getTransforms().add(rotate);
//Creating the pane
BorderPane pane = new BorderPane();
pane.setRight(new VBox(new Label("Rotate"), slider));
pane.setCenter(rect);
//Preparing the scene
Scene scene = new Scene(pane, 600, 300);
stage.setTitle("Rotation Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "If you move an object in the XY plane around a fixed point with an angle it is known as rotation."
},
{
"code": null,
"e": 1384,
"s": 1160,
"text": "In JavaFX using the object of the javafx.scene.transform.Rotate class, you can rotate a node. This class internally rotates the coordinate space of the node around a given fixed point, this makes the node to appear rotated."
},
{
"code": null,
"e": 1422,
"s": 1384,
"text": "This class contains five properties −"
},
{
"code": null,
"e": 1552,
"s": 1422,
"text": "The angle property (double) specifying the angle of rotation. You can set the value to this property using the setAngle() method."
},
{
"code": null,
"e": 1682,
"s": 1552,
"text": "The angle property (double) specifying the angle of rotation. You can set the value to this property using the setAngle() method."
},
{
"code": null,
"e": 1810,
"s": 1682,
"text": "The axis property (Point3D) specifying the axis of rotation. You can set the value to this property using the setAxis() method."
},
{
"code": null,
"e": 1938,
"s": 1810,
"text": "The axis property (Point3D) specifying the axis of rotation. You can set the value to this property using the setAxis() method."
},
{
"code": null,
"e": 2085,
"s": 1938,
"text": "The pivotX property (double) specifying the x coordinates of the pivot point. You can set the value to this property using the setPivotX() method."
},
{
"code": null,
"e": 2232,
"s": 2085,
"text": "The pivotX property (double) specifying the x coordinates of the pivot point. You can set the value to this property using the setPivotX() method."
},
{
"code": null,
"e": 2379,
"s": 2232,
"text": "The pivotY property (double) specifying the y coordinates of the pivot point. You can set the value to this property using the setPivotY() method."
},
{
"code": null,
"e": 2526,
"s": 2379,
"text": "The pivotY property (double) specifying the y coordinates of the pivot point. You can set the value to this property using the setPivotY() method."
},
{
"code": null,
"e": 2673,
"s": 2526,
"text": "The pivotZ property (double) specifying the z coordinates of the pivot point. You can set the value to this property using the setPivotZ() method."
},
{
"code": null,
"e": 2820,
"s": 2673,
"text": "The pivotZ property (double) specifying the z coordinates of the pivot point. You can set the value to this property using the setPivotZ() method."
},
{
"code": null,
"e": 2977,
"s": 2820,
"text": "Every node in JavaFX contains an observable list to hold all the transforms to be applied on a node. You can get this list using the getTransforms() method."
},
{
"code": null,
"e": 3006,
"s": 2977,
"text": "To rotate a Node in JavaFX −"
},
{
"code": null,
"e": 3036,
"s": 3006,
"text": "Instantiate the Rotate class."
},
{
"code": null,
"e": 3066,
"s": 3036,
"text": "Instantiate the Rotate class."
},
{
"code": null,
"e": 3126,
"s": 3066,
"text": "Set the angle and the pivot point using the setter methods."
},
{
"code": null,
"e": 3186,
"s": 3126,
"text": "Set the angle and the pivot point using the setter methods."
},
{
"code": null,
"e": 3288,
"s": 3186,
"text": "Get the list of transforms from the node (which you want to rotate) using the getTransforms() method."
},
{
"code": null,
"e": 3390,
"s": 3288,
"text": "Get the list of transforms from the node (which you want to rotate) using the getTransforms() method."
},
{
"code": null,
"e": 3433,
"s": 3390,
"text": "Add the above created rotate object to it."
},
{
"code": null,
"e": 3476,
"s": 3433,
"text": "Add the above created rotate object to it."
},
{
"code": null,
"e": 3503,
"s": 3476,
"text": "Add the node to the scene."
},
{
"code": null,
"e": 3530,
"s": 3503,
"text": "Add the node to the scene."
},
{
"code": null,
"e": 3724,
"s": 3530,
"text": "Following the JavaFX example demonstrates the rotation transform. It contains a 2D geometric shape and a slider, representing the angle value. If you move the slider the object will be rotated."
},
{
"code": null,
"e": 5901,
"s": 3724,
"text": "import javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Orientation;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.shape.Rectangle;\nimport javafx.scene.transform.Rotate;\nimport javafx.stage.Stage;\npublic class RotationExample extends Application {\n public void start(Stage stage) {\n //Creating a rectangle\n Rectangle rect = new Rectangle(300, 100, 75, 75);\n rect.setFill(Color.BLUEVIOLET);\n rect.setStrokeWidth(5.0);\n rect.setStroke(Color.BROWN);\n //Setting the slider\n Slider slider = new Slider(0, 360, 0);\n slider.setShowTickLabels(true);\n slider.setShowTickMarks(true);\n slider.setMajorTickUnit(90);\n slider.setBlockIncrement(10);\n slider.setOrientation(Orientation.VERTICAL);\n slider.setLayoutX(2);\n slider.setLayoutY(195);\n //creating the rotation transformation\n Rotate rotate = new Rotate();\n //Setting pivot points for the rotation\n rotate.setPivotX(300);\n rotate.setPivotY(100);\n //Adding the transformation to rectangle\n rect.getTransforms().addAll(rotate);\n //Linking the transformation to the slider\n slider.valueProperty().addListener(new ChangeListener<Number>() {\n public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){\n //Setting the angle for the rotation\n rotate.setAngle((double) newValue);\n }\n });\n //Adding the transformation to the circle\n rect.getTransforms().add(rotate);\n //Creating the pane\n BorderPane pane = new BorderPane();\n pane.setRight(new VBox(new Label(\"Rotate\"), slider));\n pane.setCenter(rect);\n //Preparing the scene\n Scene scene = new Scene(pane, 600, 300);\n stage.setTitle(\"Rotation Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
How to Create a Basic Intro Slider of an Android App? - GeeksforGeeks | 20 Jan, 2021
When we download any app and use that app for the very first time. Then we will get to see the intro slider inside our app. With the help of this slider, we educate our users on how they can use that app and it tells in detail about the app. In this article, we will take a look at the implementation of Intro Slider inside our app. Now, let’s move towards the implementation of this feature in our app.
We will be building a simple application in which we will be adding an intro slider that will tell about the different courses which are available on GeeksforGeeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency of Intro Slider in build.gradle file.
Navigate to the gradle scripts > build.gradle (app) file and add the below dependency to it in the dependencies section.
implementation ‘com.github.AppIntro:AppIntro:6.0.0’
Now navigate to the Gradle Scripts > build.gradle file of (Project) and add below code inside the repositories section.
allprojects {
repositories {
// add below line in repositories section
maven { url ‘https://jitpack.io’ }
google()
jcenter()
}
}
Step 3: Create a new Java class that will display the slides for our slider
For creating a new java class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java class and name it as IntroSlider. After creating this class add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle; import androidx.core.content.ContextCompat; import com.github.appintro.AppIntro;import com.github.appintro.AppIntroFragment; public class IntroSlider extends AppIntro { // we are calling on create method // to generate the view for our java file. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // below line is for adding the new slide to our app. // we are creating a new instance and inside that // we are adding the title, description, image and // background color for our slide. // below line is use for creating first slide addSlide(AppIntroFragment.newInstance("C++", "C++ Self Paced Course", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); // below line is for creating second slide. addSlide(AppIntroFragment.newInstance("DSA", "Data Structures and Algorithms", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); // below line is use to create third slide. addSlide(AppIntroFragment.newInstance("Java", "Java Self Paced Course", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); }}
Step 4: Working with the AndroidManifest.xml file
As we are creating a new activity for displaying our Intro Slider we are adding this activity to your AndroidManifest.xml file. Add the below lines to your AndroidManifest.xml file
<!–adding activity for our intro slider–>
<activity
android:name=”.IntroSlider”
android:theme=”@style/Theme.AppCompat.NoActionBar” />
Below is the complete code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.firebaseapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.FirebaseApp"> <!--adding activity for our intro slider--> <activity android:name=".IntroSlider" android:theme="@style/Theme.AppCompat.NoActionBar" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Java
import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.os.Bundle;import android.widget.GridView;import android.widget.Toast; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent i =new Intent(getApplicationContext(),IntroSlider.class); startActivity(i); }}
After adding this code now run your app and see the output of the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 25141,
"s": 25113,
"text": "\n20 Jan, 2021"
},
{
"code": null,
"e": 25546,
"s": 25141,
"text": "When we download any app and use that app for the very first time. Then we will get to see the intro slider inside our app. With the help of this slider, we educate our users on how they can use that app and it tells in detail about the app. In this article, we will take a look at the implementation of Intro Slider inside our app. Now, let’s move towards the implementation of this feature in our app. "
},
{
"code": null,
"e": 25876,
"s": 25546,
"text": "We will be building a simple application in which we will be adding an intro slider that will tell about the different courses which are available on GeeksforGeeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25905,
"s": 25876,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26067,
"s": 25905,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26128,
"s": 26067,
"text": "Step 2: Add dependency of Intro Slider in build.gradle file."
},
{
"code": null,
"e": 26249,
"s": 26128,
"text": "Navigate to the gradle scripts > build.gradle (app) file and add the below dependency to it in the dependencies section."
},
{
"code": null,
"e": 26301,
"s": 26249,
"text": "implementation ‘com.github.AppIntro:AppIntro:6.0.0’"
},
{
"code": null,
"e": 26422,
"s": 26301,
"text": "Now navigate to the Gradle Scripts > build.gradle file of (Project) and add below code inside the repositories section. "
},
{
"code": null,
"e": 26436,
"s": 26422,
"text": "allprojects {"
},
{
"code": null,
"e": 26454,
"s": 26436,
"text": " repositories {"
},
{
"code": null,
"e": 26503,
"s": 26454,
"text": " // add below line in repositories section"
},
{
"code": null,
"e": 26545,
"s": 26503,
"text": " maven { url ‘https://jitpack.io’ }"
},
{
"code": null,
"e": 26561,
"s": 26545,
"text": " google()"
},
{
"code": null,
"e": 26578,
"s": 26561,
"text": " jcenter()"
},
{
"code": null,
"e": 26588,
"s": 26578,
"text": " }"
},
{
"code": null,
"e": 26590,
"s": 26588,
"text": "}"
},
{
"code": null,
"e": 26666,
"s": 26590,
"text": "Step 3: Create a new Java class that will display the slides for our slider"
},
{
"code": null,
"e": 26953,
"s": 26666,
"text": "For creating a new java class navigate to the app > java > your app’s package name > Right-click on it and click on New > Java class and name it as IntroSlider. After creating this class add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 26958,
"s": 26953,
"text": "Java"
},
{
"code": "import android.os.Bundle; import androidx.core.content.ContextCompat; import com.github.appintro.AppIntro;import com.github.appintro.AppIntroFragment; public class IntroSlider extends AppIntro { // we are calling on create method // to generate the view for our java file. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // below line is for adding the new slide to our app. // we are creating a new instance and inside that // we are adding the title, description, image and // background color for our slide. // below line is use for creating first slide addSlide(AppIntroFragment.newInstance(\"C++\", \"C++ Self Paced Course\", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); // below line is for creating second slide. addSlide(AppIntroFragment.newInstance(\"DSA\", \"Data Structures and Algorithms\", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); // below line is use to create third slide. addSlide(AppIntroFragment.newInstance(\"Java\", \"Java Self Paced Course\", R.drawable.gfgimage, ContextCompat.getColor(getApplicationContext(), R.color.purple_200))); }}",
"e": 28303,
"s": 26958,
"text": null
},
{
"code": null,
"e": 28354,
"s": 28303,
"text": "Step 4: Working with the AndroidManifest.xml file "
},
{
"code": null,
"e": 28535,
"s": 28354,
"text": "As we are creating a new activity for displaying our Intro Slider we are adding this activity to your AndroidManifest.xml file. Add the below lines to your AndroidManifest.xml file"
},
{
"code": null,
"e": 28577,
"s": 28535,
"text": "<!–adding activity for our intro slider–>"
},
{
"code": null,
"e": 28587,
"s": 28577,
"text": "<activity"
},
{
"code": null,
"e": 28626,
"s": 28587,
"text": " android:name=”.IntroSlider”"
},
{
"code": null,
"e": 28691,
"s": 28626,
"text": " android:theme=”@style/Theme.AppCompat.NoActionBar” />"
},
{
"code": null,
"e": 28752,
"s": 28691,
"text": "Below is the complete code for the AndroidManifest.xml file."
},
{
"code": null,
"e": 28756,
"s": 28752,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.gtappdevelopers.firebaseapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.FirebaseApp\"> <!--adding activity for our intro slider--> <activity android:name=\".IntroSlider\" android:theme=\"@style/Theme.AppCompat.NoActionBar\" /> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 29665,
"s": 28756,
"text": null
},
{
"code": null,
"e": 29713,
"s": 29665,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 29830,
"s": 29713,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. "
},
{
"code": null,
"e": 29835,
"s": 29830,
"text": "Java"
},
{
"code": "import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.os.Bundle;import android.widget.GridView;import android.widget.Toast; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent i =new Intent(getApplicationContext(),IntroSlider.class); startActivity(i); }}",
"e": 30409,
"s": 29835,
"text": null
},
{
"code": null,
"e": 30481,
"s": 30409,
"text": "After adding this code now run your app and see the output of the app. "
},
{
"code": null,
"e": 30489,
"s": 30481,
"text": "android"
},
{
"code": null,
"e": 30513,
"s": 30489,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30521,
"s": 30513,
"text": "Android"
},
{
"code": null,
"e": 30526,
"s": 30521,
"text": "Java"
},
{
"code": null,
"e": 30545,
"s": 30526,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30550,
"s": 30545,
"text": "Java"
},
{
"code": null,
"e": 30558,
"s": 30550,
"text": "Android"
},
{
"code": null,
"e": 30656,
"s": 30558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30665,
"s": 30656,
"text": "Comments"
},
{
"code": null,
"e": 30678,
"s": 30665,
"text": "Old Comments"
},
{
"code": null,
"e": 30717,
"s": 30678,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30759,
"s": 30717,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30792,
"s": 30759,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 30830,
"s": 30792,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 30880,
"s": 30830,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 30895,
"s": 30880,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30939,
"s": 30895,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30961,
"s": 30939,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 30997,
"s": 30961,
"text": "Arrays.sort() in Java with examples"
}
] |
Perl - Database Access | This chapter teaches you how to access a database inside your Perl script. Starting from Perl 5 has become very easy to write database applications using DBI module. DBI stands for Database Independent Interface for Perl, which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily.
The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.
DBI is independent of any database available in backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architure diagram.
Here DBI is responsible of taking all SQL commands through the API, (i.e., Application Programming Interface) and to dispatch them to the appropriate driver for actual execution. And finally, DBI is responsible of taking results from the driver and giving back it to the calling scritp.
Throughout this chapter following notations will be used and it is recommended that you should also follow the same convention.
$dsn Database source name
$dbh Database handle object
$sth Statement handle object
$h Any of the handle types above ($dbh, $sth, or $drh)
$rc General Return Code (boolean: true=ok, false=error)
$rv General Return Value (typically an integer)
@ary List of values returned from the database.
$rows Number of rows processed (if available, else -1)
$fh A filehandle
undef NULL values are represented by undefined values in Perl
\%attr Reference to a hash of attribute values passed to methods
Assuming we are going to work with MySQL database. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database.
You have created a database with a name TESTDB.
You have created a database with a name TESTDB.
You have created a table with a name TEST_TABLE in TESTDB.
You have created a table with a name TEST_TABLE in TESTDB.
This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
User ID "testuser" and password "test123" are set to access TESTDB.
Perl Module DBI is installed properly on your machine.
Perl Module DBI is installed properly on your machine.
You have gone through MySQL tutorial to understand MySQL Basics.
You have gone through MySQL tutorial to understand MySQL Basics.
Following is the example of connecting with MySQL database "TESTDB" −
#!/usr/bin/perl
use DBI
use strict;
my $driver = "mysql";
my $database = "TESTDB";
my $dsn = "DBI:$driver:database=$database";
my $userid = "testuser";
my $password = "test123";
my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
If a connection is established with the datasource then a Database Handle is returned and saved into $dbh for further use otherwise $dbh is set to undef value and $DBI::errstr returns an error string.
INSERT operation is required when you want to create some records into a table. Here we are using table TEST_TABLE to create our records. So once our database connection is established, we are ready to create records into TEST_TABLE. Following is the procedure to create single record into TEST_TABLE. You can create as many as records you like using the same concept.
Record creation takes the following steps −
Preparing SQL statement with INSERT statement. This will be done using prepare() API.
Preparing SQL statement with INSERT statement. This will be done using prepare() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Releasing Stattement handle. This will be done using finish() API.
Releasing Stattement handle. This will be done using finish() API.
If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections.
If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections.
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
(FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
values
('john', 'poul', 'M', 30, 13000)");
$sth->execute() or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
There may be a case when values to be entered is not given in advance. So you can use bind variables which will take the required values at run time. Perl DBI modules make use of a question mark in place of actual value and then actual values are passed through execute() API at the run time. Following is the example −
my $first_name = "john";
my $last_name = "poul";
my $sex = "M";
my $income = 13000;
my $age = 30;
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
(FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )
values
(?,?,?,?)");
$sth->execute($first_name,$last_name,$sex, $age, $income)
or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;
READ Operation on any databasse means to fetch some useful information from the database, i.e., one or more records from one or more tables. So once our database connection is established, we are ready to make a query into this database. Following is the procedure to query all the records having AGE greater than 20. This will take four steps −
Preparing SQL SELECT query based on required conditions. This will be done using prepare() API.
Preparing SQL SELECT query based on required conditions. This will be done using prepare() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Fetching all the results one by one and printing those results.This will be done using fetchrow_array() API.
Fetching all the results one by one and printing those results.This will be done using fetchrow_array() API.
Releasing Stattement handle. This will be done using finish() API.
Releasing Stattement handle. This will be done using finish() API.
my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
FROM TEST_TABLE
WHERE AGE > 20");
$sth->execute() or die $DBI::errstr;
print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
my ($first_name, $last_name ) = @row;
print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();
There may be a case when condition is not given in advance. So you can use bind variables, which will take the required values at run time. Perl DBI modules makes use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example −
$age = 20;
my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
FROM TEST_TABLE
WHERE AGE > ?");
$sth->execute( $age ) or die $DBI::errstr;
print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
my ($first_name, $last_name ) = @row;
print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();
UPDATE Operation on any database means to update one or more records already available in the database tables. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year. This will take three steps −
Preparing SQL query based on required conditions. This will be done using prepare() API.
Preparing SQL query based on required conditions. This will be done using prepare() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Executing SQL query to select all the results from the database. This will be done using execute() API.
Releasing Stattement handle. This will be done using finish() API.
Releasing Stattement handle. This will be done using finish() API.
If everything goes fine then commit this operation otherwise you can rollback complete transaction. See next section for commit and rollback APIs.
If everything goes fine then commit this operation otherwise you can rollback complete transaction. See next section for commit and rollback APIs.
my $sth = $dbh->prepare("UPDATE TEST_TABLE
SET AGE = AGE + 1
WHERE SEX = 'M'");
$sth->execute() or die $DBI::errstr;
print "Number of rows updated :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
There may be a case when condition is not given in advance. So you can use bind variables, which will take required values at run time. Perl DBI modules make use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example −
$sex = 'M';
my $sth = $dbh->prepare("UPDATE TEST_TABLE
SET AGE = AGE + 1
WHERE SEX = ?");
$sth->execute('$sex') or die $DBI::errstr;
print "Number of rows updated :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
In some case you would like to set a value, which is not given in advance so you can use binding value as follows. In this example income of all males will be set to 10000.
$sex = 'M';
$income = 10000;
my $sth = $dbh->prepare("UPDATE TEST_TABLE
SET INCOME = ?
WHERE SEX = ?");
$sth->execute( $income, '$sex') or die $DBI::errstr;
print "Number of rows updated :" + $sth->rows;
$sth->finish();
DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from TEST_TABLE where AGE is equal to 30. This operation will take the following steps.
Preparing SQL query based on required conditions. This will be done using prepare() API.
Preparing SQL query based on required conditions. This will be done using prepare() API.
Executing SQL query to delete required records from the database. This will be done using execute() API.
Executing SQL query to delete required records from the database. This will be done using execute() API.
Releasing Stattement handle. This will be done using finish() API.
Releasing Stattement handle. This will be done using finish() API.
If everything goes fine then commit this operation otherwise you can rollback complete transaction.
If everything goes fine then commit this operation otherwise you can rollback complete transaction.
$age = 30;
my $sth = $dbh->prepare("DELETE FROM TEST_TABLE
WHERE AGE = ?");
$sth->execute( $age ) or die $DBI::errstr;
print "Number of rows deleted :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr;
If you're doing an UPDATE, INSERT, or DELETE there is no data that comes back from the database, so there is a short cut to perform this operation. You can use do statement to execute any of the command as follows.
$dbh->do('DELETE FROM TEST_TABLE WHERE age =30');
do returns a true value if it succeeded, and a false value if it failed. Actually, if it succeeds it returns the number of affected rows. In the example it would return the number of rows that were actually deleted.
Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted to its orignal position.
Here is a simple example to call commit API.
$dbh->commit or die $dbh->errstr;
If you are not satisfied with all the changes or you encounter an error in between of any operation , you can revert those changes to use rollback API.
Here is a simple example to call rollback API.
$dbh->rollback or die $dbh->errstr;
Many databases support transactions. This means that you can make a whole bunch of queries which would modify the databases, but none of the changes are actually made. Then at the end, you issue the special SQL query COMMIT, and all the changes are made simultaneously. Alternatively, you can issue the query ROLLBACK, in which case all the changes are thrown away and database remains unchanged.
Perl DBI module provided begin_work API, which enables transactions (by turning AutoCommit off) until the next call to commit or rollback. After the next commit or rollback, AutoCommit will automatically be turned on again.
$rc = $dbh->begin_work or die $dbh->errstr;
If your transactions are simple, you can save yourself the trouble of having to issue a lot of commits. When you make the connect call, you can specify an AutoCommit option which will perform an automatic commit operation after every successful query. Here's what it looks like −
my $dbh = DBI->connect($dsn, $userid, $password,
{AutoCommit => 1})
or die $DBI::errstr;
Here AutoCommit can take value 1 or 0, where 1 means AutoCommit is on and 0 means AutoCommit is off.
When you make the connect call, you can specify a RaiseErrors option that handles errors for you automatically. When an error occurs, DBI will abort your program instead of returning a failure code. If all you want is to abort the program on an error, this can be convenient. Here's what it looks like −
my $dbh = DBI->connect($dsn, $userid, $password,
{RaiseError => 1})
or die $DBI::errstr;
Here RaiseError can take value 1 or 0.
To disconnect Database connection, use disconnect API as follows −
$rc = $dbh->disconnect or warn $dbh->errstr;
The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect.
Undefined values, or undef, are used to indicate NULL values. You can insert and update columns with a NULL value as you would a non-NULL value. These examples insert and update the column age with a NULL value −
$sth = $dbh->prepare(qq {
INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?)
});
$sth->execute("Joe", undef);
Here qq{} is used to return a quoted string to prepare API. However, care must be taken when trying to use NULL values in a WHERE clause. Consider −
SELECT FIRST_NAME FROM TEST_TABLE WHERE age = ?
Binding an undef (NULL) to the placeholder will not select rows, which have a NULL age! At least for database engines that conform to the SQL standard. Refer to the SQL manual for your database engine or any SQL book for the reasons for this. To explicitly select NULLs you have to say "WHERE age IS NULL".
A common issue is to have a code fragment handle a value that could be either defined or undef (non-NULL or NULL) at runtime. A simple technique is to prepare the appropriate statement as needed, and substitute the placeholder for non-NULL cases −
$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq {
SELECT FIRST_NAME FROM TEST_TABLE WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());
@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);
Returns a list of all available drivers by searching for DBD::* modules through the directories in @INC. By default, a warning is given if some drivers are hidden by others of the same name in earlier directories. Passing a true value for $quiet will inhibit the warning.
%drivers = DBI->installed_drivers();
Returns a list of driver name and driver handle pairs for all drivers 'installed' (loaded) into the current process. The driver name does not include the 'DBD::' prefix.
@ary = DBI->data_sources($driver);
Returns a list of data sources (databases) available via the named driver. If $driver is empty or undef, then the value of the DBI_DRIVER environment variable is used.
$sql = $dbh->quote($value);
$sql = $dbh->quote($value, $data_type);
Quote a string literal for use as a literal value in an SQL statement, by escaping any special characters (such as quotation marks) contained within the string and adding the required type of outer quotation marks.
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
$dbh->quote("Don't");
For most database types, quote would return 'Don''t' (including the outer quotation marks). It is valid for the quote() method to return an SQL expression that evaluates to the desired string. For example −
$quoted = $dbh->quote("one\ntwo\0three")
may produce results which will be equivalent to
CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
$rv = $h->err;
or
$rv = $DBI::err
or
$rv = $h->err
Returns the native database engine error code from the last driver method called. The code is typically an integer but you should not assume that. This is equivalent to $DBI::err or $h->err.
$str = $h->errstr;
or
$str = $DBI::errstr
or
$str = $h->errstr
Returns the native database engine error message from the last DBI method called. This has the same lifespan issues as the "err" method described above. This is equivalent to $DBI::errstr or $h->errstr.
$rv = $h->rows;
or
$rv = $DBI::rows
This returns the number of rows effected by previous SQL statement and equivalent to $DBI::rows.
$h->trace($trace_settings);
DBI sports an extremely useful ability to generate runtime tracing information of what it's doing, which can be a huge time-saver when trying to track down strange problems in your DBI programs. You can use different values to set trace level. These values varies from 0 to 4. The value 0 means disable trace and 4 means generate complete trace.
It is highly recommended not to use interpolated statements as follows −
while ($first_name = <>) {
my $sth = $dbh->prepare("SELECT *
FROM TEST_TABLE
WHERE FIRST_NAME = '$first_name'");
$sth->execute();
# and so on ...
}
Thus don't use interpolated statement instead use bind value to prepare dynamic SQL statement.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2602,
"s": 2220,
"text": "This chapter teaches you how to access a database inside your Perl script. Starting from Perl 5 has become very easy to write database applications using DBI module. DBI stands for Database Independent Interface for Perl, which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily."
},
{
"code": null,
"e": 2823,
"s": 2602,
"text": "The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used."
},
{
"code": null,
"e": 3009,
"s": 2823,
"text": "DBI is independent of any database available in backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architure diagram."
},
{
"code": null,
"e": 3296,
"s": 3009,
"text": "Here DBI is responsible of taking all SQL commands through the API, (i.e., Application Programming Interface) and to dispatch them to the appropriate driver for actual execution. And finally, DBI is responsible of taking results from the driver and giving back it to the calling scritp."
},
{
"code": null,
"e": 3424,
"s": 3296,
"text": "Throughout this chapter following notations will be used and it is recommended that you should also follow the same convention."
},
{
"code": null,
"e": 3949,
"s": 3424,
"text": "$dsn Database source name\n$dbh Database handle object\n$sth Statement handle object\n$h Any of the handle types above ($dbh, $sth, or $drh)\n$rc General Return Code (boolean: true=ok, false=error)\n$rv General Return Value (typically an integer)\n@ary List of values returned from the database.\n$rows Number of rows processed (if available, else -1)\n$fh A filehandle\nundef NULL values are represented by undefined values in Perl\n\\%attr Reference to a hash of attribute values passed to methods\n"
},
{
"code": null,
"e": 4186,
"s": 3949,
"text": "Assuming we are going to work with MySQL database. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database."
},
{
"code": null,
"e": 4234,
"s": 4186,
"text": "You have created a database with a name TESTDB."
},
{
"code": null,
"e": 4282,
"s": 4234,
"text": "You have created a database with a name TESTDB."
},
{
"code": null,
"e": 4341,
"s": 4282,
"text": "You have created a table with a name TEST_TABLE in TESTDB."
},
{
"code": null,
"e": 4400,
"s": 4341,
"text": "You have created a table with a name TEST_TABLE in TESTDB."
},
{
"code": null,
"e": 4472,
"s": 4400,
"text": "This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 4544,
"s": 4472,
"text": "This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME."
},
{
"code": null,
"e": 4612,
"s": 4544,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 4680,
"s": 4612,
"text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB."
},
{
"code": null,
"e": 4735,
"s": 4680,
"text": "Perl Module DBI is installed properly on your machine."
},
{
"code": null,
"e": 4790,
"s": 4735,
"text": "Perl Module DBI is installed properly on your machine."
},
{
"code": null,
"e": 4855,
"s": 4790,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 4920,
"s": 4855,
"text": "You have gone through MySQL tutorial to understand MySQL Basics."
},
{
"code": null,
"e": 4990,
"s": 4920,
"text": "Following is the example of connecting with MySQL database \"TESTDB\" −"
},
{
"code": null,
"e": 5243,
"s": 4990,
"text": "#!/usr/bin/perl\n\nuse DBI\nuse strict;\n\nmy $driver = \"mysql\"; \nmy $database = \"TESTDB\";\nmy $dsn = \"DBI:$driver:database=$database\";\nmy $userid = \"testuser\";\nmy $password = \"test123\";\n\nmy $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;"
},
{
"code": null,
"e": 5444,
"s": 5243,
"text": "If a connection is established with the datasource then a Database Handle is returned and saved into $dbh for further use otherwise $dbh is set to undef value and $DBI::errstr returns an error string."
},
{
"code": null,
"e": 5813,
"s": 5444,
"text": "INSERT operation is required when you want to create some records into a table. Here we are using table TEST_TABLE to create our records. So once our database connection is established, we are ready to create records into TEST_TABLE. Following is the procedure to create single record into TEST_TABLE. You can create as many as records you like using the same concept."
},
{
"code": null,
"e": 5857,
"s": 5813,
"text": "Record creation takes the following steps −"
},
{
"code": null,
"e": 5943,
"s": 5857,
"text": "Preparing SQL statement with INSERT statement. This will be done using prepare() API."
},
{
"code": null,
"e": 6029,
"s": 5943,
"text": "Preparing SQL statement with INSERT statement. This will be done using prepare() API."
},
{
"code": null,
"e": 6133,
"s": 6029,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 6237,
"s": 6133,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 6304,
"s": 6237,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 6371,
"s": 6304,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 6523,
"s": 6371,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections."
},
{
"code": null,
"e": 6675,
"s": 6523,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections."
},
{
"code": null,
"e": 6967,
"s": 6675,
"text": "my $sth = $dbh->prepare(\"INSERT INTO TEST_TABLE\n (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )\n values\n ('john', 'poul', 'M', 30, 13000)\");\n$sth->execute() or die $DBI::errstr;\n$sth->finish();\n$dbh->commit or die $DBI::errstr;"
},
{
"code": null,
"e": 7287,
"s": 6967,
"text": "There may be a case when values to be entered is not given in advance. So you can use bind variables which will take the required values at run time. Perl DBI modules make use of a question mark in place of actual value and then actual values are passed through execute() API at the run time. Following is the example −"
},
{
"code": null,
"e": 7710,
"s": 7287,
"text": "my $first_name = \"john\";\nmy $last_name = \"poul\";\nmy $sex = \"M\";\nmy $income = 13000;\nmy $age = 30;\nmy $sth = $dbh->prepare(\"INSERT INTO TEST_TABLE\n (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME )\n values\n (?,?,?,?)\");\n$sth->execute($first_name,$last_name,$sex, $age, $income) \n or die $DBI::errstr;\n$sth->finish();\n$dbh->commit or die $DBI::errstr;"
},
{
"code": null,
"e": 8056,
"s": 7710,
"text": "READ Operation on any databasse means to fetch some useful information from the database, i.e., one or more records from one or more tables. So once our database connection is established, we are ready to make a query into this database. Following is the procedure to query all the records having AGE greater than 20. This will take four steps −"
},
{
"code": null,
"e": 8152,
"s": 8056,
"text": "Preparing SQL SELECT query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 8248,
"s": 8152,
"text": "Preparing SQL SELECT query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 8352,
"s": 8248,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 8456,
"s": 8352,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 8565,
"s": 8456,
"text": "Fetching all the results one by one and printing those results.This will be done using fetchrow_array() API."
},
{
"code": null,
"e": 8674,
"s": 8565,
"text": "Fetching all the results one by one and printing those results.This will be done using fetchrow_array() API."
},
{
"code": null,
"e": 8741,
"s": 8674,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 8808,
"s": 8741,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 9192,
"s": 8808,
"text": "my $sth = $dbh->prepare(\"SELECT FIRST_NAME, LAST_NAME\n FROM TEST_TABLE \n WHERE AGE > 20\");\n$sth->execute() or die $DBI::errstr;\nprint \"Number of rows found :\" + $sth->rows;\nwhile (my @row = $sth->fetchrow_array()) {\n my ($first_name, $last_name ) = @row;\n print \"First Name = $first_name, Last Name = $last_name\\n\";\n}\n$sth->finish();"
},
{
"code": null,
"e": 9507,
"s": 9192,
"text": "There may be a case when condition is not given in advance. So you can use bind variables, which will take the required values at run time. Perl DBI modules makes use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example −"
},
{
"code": null,
"e": 9906,
"s": 9507,
"text": "$age = 20;\nmy $sth = $dbh->prepare(\"SELECT FIRST_NAME, LAST_NAME\n FROM TEST_TABLE\n WHERE AGE > ?\");\n$sth->execute( $age ) or die $DBI::errstr;\nprint \"Number of rows found :\" + $sth->rows;\nwhile (my @row = $sth->fetchrow_array()) {\n my ($first_name, $last_name ) = @row;\n print \"First Name = $first_name, Last Name = $last_name\\n\";\n}\n$sth->finish();"
},
{
"code": null,
"e": 10174,
"s": 9906,
"text": "UPDATE Operation on any database means to update one or more records already available in the database tables. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year. This will take three steps −"
},
{
"code": null,
"e": 10263,
"s": 10174,
"text": "Preparing SQL query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 10352,
"s": 10263,
"text": "Preparing SQL query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 10456,
"s": 10352,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 10560,
"s": 10456,
"text": "Executing SQL query to select all the results from the database. This will be done using execute() API."
},
{
"code": null,
"e": 10627,
"s": 10560,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 10694,
"s": 10627,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 10841,
"s": 10694,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction. See next section for commit and rollback APIs."
},
{
"code": null,
"e": 10988,
"s": 10841,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction. See next section for commit and rollback APIs."
},
{
"code": null,
"e": 11253,
"s": 10988,
"text": "my $sth = $dbh->prepare(\"UPDATE TEST_TABLE\n SET AGE = AGE + 1 \n WHERE SEX = 'M'\");\n$sth->execute() or die $DBI::errstr;\nprint \"Number of rows updated :\" + $sth->rows;\n$sth->finish();\n$dbh->commit or die $DBI::errstr;"
},
{
"code": null,
"e": 11563,
"s": 11253,
"text": "There may be a case when condition is not given in advance. So you can use bind variables, which will take required values at run time. Perl DBI modules make use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example −"
},
{
"code": null,
"e": 11843,
"s": 11563,
"text": "$sex = 'M';\nmy $sth = $dbh->prepare(\"UPDATE TEST_TABLE\n SET AGE = AGE + 1\n WHERE SEX = ?\");\n$sth->execute('$sex') or die $DBI::errstr;\nprint \"Number of rows updated :\" + $sth->rows;\n$sth->finish();\n$dbh->commit or die $DBI::errstr;"
},
{
"code": null,
"e": 12016,
"s": 11843,
"text": "In some case you would like to set a value, which is not given in advance so you can use binding value as follows. In this example income of all males will be set to 10000."
},
{
"code": null,
"e": 12286,
"s": 12016,
"text": "$sex = 'M';\n$income = 10000;\nmy $sth = $dbh->prepare(\"UPDATE TEST_TABLE\n SET INCOME = ?\n WHERE SEX = ?\");\n$sth->execute( $income, '$sex') or die $DBI::errstr;\nprint \"Number of rows updated :\" + $sth->rows;\n$sth->finish();"
},
{
"code": null,
"e": 12513,
"s": 12286,
"text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from TEST_TABLE where AGE is equal to 30. This operation will take the following steps."
},
{
"code": null,
"e": 12602,
"s": 12513,
"text": "Preparing SQL query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 12691,
"s": 12602,
"text": "Preparing SQL query based on required conditions. This will be done using prepare() API."
},
{
"code": null,
"e": 12796,
"s": 12691,
"text": "Executing SQL query to delete required records from the database. This will be done using execute() API."
},
{
"code": null,
"e": 12901,
"s": 12796,
"text": "Executing SQL query to delete required records from the database. This will be done using execute() API."
},
{
"code": null,
"e": 12968,
"s": 12901,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 13035,
"s": 12968,
"text": "Releasing Stattement handle. This will be done using finish() API."
},
{
"code": null,
"e": 13135,
"s": 13035,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction."
},
{
"code": null,
"e": 13235,
"s": 13135,
"text": "If everything goes fine then commit this operation otherwise you can rollback complete transaction."
},
{
"code": null,
"e": 13476,
"s": 13235,
"text": "$age = 30;\nmy $sth = $dbh->prepare(\"DELETE FROM TEST_TABLE\n WHERE AGE = ?\");\n$sth->execute( $age ) or die $DBI::errstr;\nprint \"Number of rows deleted :\" + $sth->rows;\n$sth->finish();\n$dbh->commit or die $DBI::errstr;"
},
{
"code": null,
"e": 13691,
"s": 13476,
"text": "If you're doing an UPDATE, INSERT, or DELETE there is no data that comes back from the database, so there is a short cut to perform this operation. You can use do statement to execute any of the command as follows."
},
{
"code": null,
"e": 13741,
"s": 13691,
"text": "$dbh->do('DELETE FROM TEST_TABLE WHERE age =30');"
},
{
"code": null,
"e": 13957,
"s": 13741,
"text": "do returns a true value if it succeeded, and a false value if it failed. Actually, if it succeeds it returns the number of affected rows. In the example it would return the number of rows that were actually deleted."
},
{
"code": null,
"e": 14120,
"s": 13957,
"text": "Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted to its orignal position."
},
{
"code": null,
"e": 14165,
"s": 14120,
"text": "Here is a simple example to call commit API."
},
{
"code": null,
"e": 14199,
"s": 14165,
"text": "$dbh->commit or die $dbh->errstr;"
},
{
"code": null,
"e": 14351,
"s": 14199,
"text": "If you are not satisfied with all the changes or you encounter an error in between of any operation , you can revert those changes to use rollback API."
},
{
"code": null,
"e": 14398,
"s": 14351,
"text": "Here is a simple example to call rollback API."
},
{
"code": null,
"e": 14434,
"s": 14398,
"text": "$dbh->rollback or die $dbh->errstr;"
},
{
"code": null,
"e": 14831,
"s": 14434,
"text": "Many databases support transactions. This means that you can make a whole bunch of queries which would modify the databases, but none of the changes are actually made. Then at the end, you issue the special SQL query COMMIT, and all the changes are made simultaneously. Alternatively, you can issue the query ROLLBACK, in which case all the changes are thrown away and database remains unchanged."
},
{
"code": null,
"e": 15055,
"s": 14831,
"text": "Perl DBI module provided begin_work API, which enables transactions (by turning AutoCommit off) until the next call to commit or rollback. After the next commit or rollback, AutoCommit will automatically be turned on again."
},
{
"code": null,
"e": 15101,
"s": 15055,
"text": "$rc = $dbh->begin_work or die $dbh->errstr;"
},
{
"code": null,
"e": 15381,
"s": 15101,
"text": "If your transactions are simple, you can save yourself the trouble of having to issue a lot of commits. When you make the connect call, you can specify an AutoCommit option which will perform an automatic commit operation after every successful query. Here's what it looks like −"
},
{
"code": null,
"e": 15499,
"s": 15381,
"text": "my $dbh = DBI->connect($dsn, $userid, $password,\n {AutoCommit => 1}) \n or die $DBI::errstr;"
},
{
"code": null,
"e": 15600,
"s": 15499,
"text": "Here AutoCommit can take value 1 or 0, where 1 means AutoCommit is on and 0 means AutoCommit is off."
},
{
"code": null,
"e": 15904,
"s": 15600,
"text": "When you make the connect call, you can specify a RaiseErrors option that handles errors for you automatically. When an error occurs, DBI will abort your program instead of returning a failure code. If all you want is to abort the program on an error, this can be convenient. Here's what it looks like −"
},
{
"code": null,
"e": 16021,
"s": 15904,
"text": "my $dbh = DBI->connect($dsn, $userid, $password,\n {RaiseError => 1})\n or die $DBI::errstr;"
},
{
"code": null,
"e": 16060,
"s": 16021,
"text": "Here RaiseError can take value 1 or 0."
},
{
"code": null,
"e": 16127,
"s": 16060,
"text": "To disconnect Database connection, use disconnect API as follows −"
},
{
"code": null,
"e": 16173,
"s": 16127,
"text": "$rc = $dbh->disconnect or warn $dbh->errstr;"
},
{
"code": null,
"e": 16519,
"s": 16173,
"text": "The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect."
},
{
"code": null,
"e": 16732,
"s": 16519,
"text": "Undefined values, or undef, are used to indicate NULL values. You can insert and update columns with a NULL value as you would a non-NULL value. These examples insert and update the column age with a NULL value −"
},
{
"code": null,
"e": 16862,
"s": 16732,
"text": "$sth = $dbh->prepare(qq {\n INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?)\n });\n$sth->execute(\"Joe\", undef);"
},
{
"code": null,
"e": 17011,
"s": 16862,
"text": "Here qq{} is used to return a quoted string to prepare API. However, care must be taken when trying to use NULL values in a WHERE clause. Consider −"
},
{
"code": null,
"e": 17059,
"s": 17011,
"text": "SELECT FIRST_NAME FROM TEST_TABLE WHERE age = ?"
},
{
"code": null,
"e": 17366,
"s": 17059,
"text": "Binding an undef (NULL) to the placeholder will not select rows, which have a NULL age! At least for database engines that conform to the SQL standard. Refer to the SQL manual for your database engine or any SQL book for the reasons for this. To explicitly select NULLs you have to say \"WHERE age IS NULL\"."
},
{
"code": null,
"e": 17614,
"s": 17366,
"text": "A common issue is to have a code fragment handle a value that could be either defined or undef (non-NULL or NULL) at runtime. A simple technique is to prepare the appropriate statement as needed, and substitute the placeholder for non-NULL cases −"
},
{
"code": null,
"e": 17808,
"s": 17614,
"text": "$sql_clause = defined $age? \"age = ?\" : \"age IS NULL\";\n$sth = $dbh->prepare(qq {\n SELECT FIRST_NAME FROM TEST_TABLE WHERE $sql_clause\n });\n$sth->execute(defined $age ? $age : ());"
},
{
"code": null,
"e": 17878,
"s": 17808,
"text": "@ary = DBI->available_drivers;\n@ary = DBI->available_drivers($quiet);"
},
{
"code": null,
"e": 18150,
"s": 17878,
"text": "Returns a list of all available drivers by searching for DBD::* modules through the directories in @INC. By default, a warning is given if some drivers are hidden by others of the same name in earlier directories. Passing a true value for $quiet will inhibit the warning."
},
{
"code": null,
"e": 18187,
"s": 18150,
"text": "%drivers = DBI->installed_drivers();"
},
{
"code": null,
"e": 18357,
"s": 18187,
"text": "Returns a list of driver name and driver handle pairs for all drivers 'installed' (loaded) into the current process. The driver name does not include the 'DBD::' prefix."
},
{
"code": null,
"e": 18392,
"s": 18357,
"text": "@ary = DBI->data_sources($driver);"
},
{
"code": null,
"e": 18560,
"s": 18392,
"text": "Returns a list of data sources (databases) available via the named driver. If $driver is empty or undef, then the value of the DBI_DRIVER environment variable is used."
},
{
"code": null,
"e": 18628,
"s": 18560,
"text": "$sql = $dbh->quote($value);\n$sql = $dbh->quote($value, $data_type);"
},
{
"code": null,
"e": 18843,
"s": 18628,
"text": "Quote a string literal for use as a literal value in an SQL statement, by escaping any special characters (such as quotation marks) contained within the string and adding the required type of outer quotation marks."
},
{
"code": null,
"e": 18934,
"s": 18843,
"text": "$sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(\"Don't\");"
},
{
"code": null,
"e": 19141,
"s": 18934,
"text": "For most database types, quote would return 'Don''t' (including the outer quotation marks). It is valid for the quote() method to return an SQL expression that evaluates to the desired string. For example −"
},
{
"code": null,
"e": 19281,
"s": 19141,
"text": "$quoted = $dbh->quote(\"one\\ntwo\\0three\")\n\nmay produce results which will be equivalent to\n\nCONCAT('one', CHAR(12), 'two', CHAR(0), 'three')"
},
{
"code": null,
"e": 19332,
"s": 19281,
"text": "$rv = $h->err;\nor\n$rv = $DBI::err\nor\n$rv = $h->err"
},
{
"code": null,
"e": 19523,
"s": 19332,
"text": "Returns the native database engine error code from the last driver method called. The code is typically an integer but you should not assume that. This is equivalent to $DBI::err or $h->err."
},
{
"code": null,
"e": 19586,
"s": 19523,
"text": "$str = $h->errstr;\nor\n$str = $DBI::errstr\nor\n$str = $h->errstr"
},
{
"code": null,
"e": 19789,
"s": 19586,
"text": "Returns the native database engine error message from the last DBI method called. This has the same lifespan issues as the \"err\" method described above. This is equivalent to $DBI::errstr or $h->errstr."
},
{
"code": null,
"e": 19825,
"s": 19789,
"text": "$rv = $h->rows;\nor\n$rv = $DBI::rows"
},
{
"code": null,
"e": 19922,
"s": 19825,
"text": "This returns the number of rows effected by previous SQL statement and equivalent to $DBI::rows."
},
{
"code": null,
"e": 19950,
"s": 19922,
"text": "$h->trace($trace_settings);"
},
{
"code": null,
"e": 20296,
"s": 19950,
"text": "DBI sports an extremely useful ability to generate runtime tracing information of what it's doing, which can be a huge time-saver when trying to track down strange problems in your DBI programs. You can use different values to set trace level. These values varies from 0 to 4. The value 0 means disable trace and 4 means generate complete trace."
},
{
"code": null,
"e": 20369,
"s": 20296,
"text": "It is highly recommended not to use interpolated statements as follows −"
},
{
"code": null,
"e": 20580,
"s": 20369,
"text": "while ($first_name = <>) {\n my $sth = $dbh->prepare(\"SELECT * \n FROM TEST_TABLE \n WHERE FIRST_NAME = '$first_name'\");\n $sth->execute();\n # and so on ...\n}"
},
{
"code": null,
"e": 20675,
"s": 20580,
"text": "Thus don't use interpolated statement instead use bind value to prepare dynamic SQL statement."
},
{
"code": null,
"e": 20710,
"s": 20675,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 20724,
"s": 20710,
"text": " Devi Killada"
},
{
"code": null,
"e": 20759,
"s": 20724,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 20779,
"s": 20759,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 20812,
"s": 20779,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 20828,
"s": 20812,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 20861,
"s": 20828,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 20878,
"s": 20861,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 20911,
"s": 20878,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 20934,
"s": 20911,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 20969,
"s": 20934,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 20992,
"s": 20969,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 20999,
"s": 20992,
"text": " Print"
},
{
"code": null,
"e": 21010,
"s": 20999,
"text": " Add Notes"
}
] |
E-commerce Website using Django - GeeksforGeeks | 04 Jul, 2021
This project deals with developing a Virtual website ‘E-commerce Website’. It provides the user with a list of the various products available for purchase in the store. For the convenience of online shopping, a shopping cart is provided to the user. After the selection of the goods, it is sent for the order confirmation process. The system is implemented using Python’s web framework Django. To develop an e-commerce website, it is necessary to study and understand many technologies.
Scope: The scope of the project will be limited to some functions of the e-commerce website. It will display products, customers can select catalogs and select products, and can remove products from their cart specifying the quantity of each item. Selected items will be collected in a cart. At checkout, the item on the card will be presented as an order. Customers can pay for the items in the cart to complete an order. This project has great future scope. The project also provides security with the use of login ID and passwords, so that no unauthorized users can access your account. The only authorized person who has the appropriate access authority can access the software.
Django framework and SQLite database which comes by default with Django.
Knowledge of Python and basics of Django Framework.
Customer Interface:
Customer shops for a productCustomer changes quantityThe customer adds an item to the cartCustomer views cartCustomer checks outCustomer sends order
Customer shops for a product
Customer changes quantity
The customer adds an item to the cart
Customer views cart
Customer checks out
Customer sends order
ER-diagram for Customer
Use-Case diagram for Customer
Admin Interface:
Admin logs inAdmin inserts itemAdmin removes itemAdmin modifies item
Admin logs in
Admin inserts item
Admin removes item
Admin modifies item
ER-diagram for Admin
Use-Case diagram for Admin
Create Normal Project: Open the IDE and create a normal project by selecting File -> New Project.
Install Django: Next, we will install the Django module from the terminal. We will use PyCharm integrated terminal to do this task. One can also use cmd on windows to install the module by running python -m pip install django command
Check Installed Django version: To check the installed Django version, you can run the python -m django -version command as shown below.
Create Django Project: When we execute django-admin startproject command, then it will create a Django project inside the normal project which we already have created here. django-admin startproject ProjectName.
Check Python3 version: python3 –version
Run Default Django webserver:- Django internally provides a default webserver where we can launch our applications. python manage.py runserver command in terminal. By default, the server runs on port 8000. Access the webserver at the highlighted URL.
Open the project folder using a text editor. The directory structure should look like this :
Project Structure
Now add store app in E-commerce website in settings.py.
This file contains all the URL patterns used by the website
Python3
from django.contrib import adminfrom django.urls import path, includefrom django.conf.urls.static import staticfrom . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls'))] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The below screenshot shows the required models that we will need to create. These models are tables that will be stored in the SQLite database.
Let’s see each model and the fields required by each model.
Python3
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name
Python3
from django.db import models class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=10) email = models.EmailField() password = models.CharField(max_length=100) # to save the data def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email=self.email): return True return False
Python3
from django.db import modelsfrom .category import Category class Products(models.Model): name = models.CharField(max_length=60) price = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) description = models.CharField( max_length=250, default='', blank=True, null=True) image = models.ImageField(upload_to='uploads/products/') @staticmethod def get_products_by_id(ids): return Products.objects.filter(id__in=ids) @staticmethod def get_all_products(): return Products.objects.all() @staticmethod def get_all_products_by_categoryid(category_id): if category_id: return Products.objects.filter(category=category_id) else: return Products.get_all_products()
Python
from django.db import modelsfrom .product import Productsfrom .customer import Customerimport datetime class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) def placeOrder(self): self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id).order_by('-date')
In views, we create a view named home.py, login.py, signup.py, cart.py, checkout.py, orders.py which takes a request and renders an HTML as a response. Create an home.html, login.html, signup.html, cart.html, checkout.html, orders.html in the templates. And map the views to the store\urls.py folder.
Python3
from django.contrib import adminfrom django.urls import pathfrom .views.home import Index, storefrom .views.signup import Signupfrom .views.login import Login, logoutfrom .views.cart import Cartfrom .views.checkout import CheckOutfrom .views.orders import OrderViewfrom .middlewares.auth import auth_middleware urlpatterns = [ path('', Index.as_view(), name='homepage'), path('store', store, name='store'), path('signup', Signup.as_view(), name='signup'), path('login', Login.as_view(), name='login'), path('logout', logout, name='logout'), path('cart', auth_middleware(Cart.as_view()), name='cart'), path('check-out', CheckOut.as_view(), name='checkout'), path('orders', auth_middleware(OrderView.as_view()), name='orders'), ]
The below files show the views for each functionality of the site.
Python3
from django.shortcuts import render, redirect, HttpResponseRedirectfrom store.models.product import Productsfrom store.models.category import Categoryfrom django.views import View # Create your views here.class Index(View): def post(self, request): product = request.POST.get('product') remove = request.POST.get('remove') cart = request.session.get('cart') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart print('cart', request.session['cart']) return redirect('homepage') def get(self, request): # print() return HttpResponseRedirect(f'/store{request.get_full_path()[1:]}') def store(request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None categories = Category.get_all_categories() categoryID = request.GET.get('category') if categoryID: products = Products.get_all_products_by_categoryid(categoryID) else: products = Products.get_all_products() data = {} data['products'] = products data['categories'] = categories print('you are : ', request.session.get('email')) return render(request, 'index.html', data)
Python3
from django.shortcuts import render, redirect, HttpResponseRedirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import View class Login(View): return_url = None def get(self, request): Login.return_url = request.GET.get('return_url') return render(request, 'login.html') def post(self, request): email = request.POST.get('email') password = request.POST.get('password') customer = Customer.get_customer_by_email(email) error_message = None if customer: flag = check_password(password, customer.password) if flag: request.session['customer'] = customer.id if Login.return_url: return HttpResponseRedirect(Login.return_url) else: Login.return_url = None return redirect('homepage') else: error_message = 'Invalid !!' else: error_message = 'Invalid !!' print(email, password) return render(request, 'login.html', {'error': error_message}) def logout(request): request.session.clear() return redirect('login')
Python3
from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import make_passwordfrom store.models.customer import Customerfrom django.views import View class Signup (View): def get(self, request): return render(request, 'signup.html') def post(self, request): postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') phone = postData.get('phone') email = postData.get('email') password = postData.get('password') # validation value = { 'first_name': first_name, 'last_name': last_name, 'phone': phone, 'email': email } error_message = None customer = Customer(first_name=first_name, last_name=last_name, phone=phone, email=email, password=password) error_message = self.validateCustomer(customer) if not error_message: print(first_name, last_name, phone, email, password) customer.password = make_password(customer.password) customer.register() return redirect('homepage') else: data = { 'error': error_message, 'values': value } return render(request, 'signup.html', data) def validateCustomer(self, customer): error_message = None if (not customer.first_name): error_message = "Please Enter your First Name !!" elif len(customer.first_name) < 3: error_message = 'First Name must be 3 char long or more' elif not customer.last_name: error_message = 'Please Enter your Last Name' elif len(customer.last_name) < 3: error_message = 'Last Name must be 3 char long or more' elif not customer.phone: error_message = 'Enter your Phone Number' elif len(customer.phone) < 10: error_message = 'Phone Number must be 10 char Long' elif len(customer.password) < 5: error_message = 'Password must be 5 char long' elif len(customer.email) < 5: error_message = 'Email must be 5 char long' elif customer.isExists(): error_message = 'Email Address Already Registered..' # saving return error_message
Python3
from django.db import modelsfrom .product import Productsfrom .customer import Customerimport datetime class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) def placeOrder(self): self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id).order_by('-date')
Python3
from django.shortcuts import render, redirect from django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import View from store.models.product import Productsfrom store.models.orders import Order class CheckOut(View): def post(self, request): address = request.POST.get('address') phone = request.POST.get('phone') customer = request.session.get('customer') cart = request.session.get('cart') products = Products.get_products_by_id(list(cart.keys())) print(address, phone, customer, cart, products) for product in products: print(cart.get(str(product.id))) order = Order(customer=Customer(id=customer), product=product, price=product.price, address=address, phone=phone, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart')
Python3
from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import Viewfrom store.models.product import Productsfrom store.models.orders import Orderfrom store.middlewares.auth import auth_middleware class OrderView(View): def get(self, request): customer = request.session.get('customer') orders = Order.get_orders_by_customer(customer) print(orders) return render(request, 'orders.html', {'orders': orders})
The project already includes a lot of features. The main beneficiaries are both customers and administrators who take longer to behave online. In addition, additional features can be identified and incorporated in the future. It will take more time and effort to understand the need and adjust it to a computerized system to accommodate additional features.
GitHub Link to the project
Django-Projects
ProGeek 2021
Python Django
ProGeek
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Build a Simple Note Android App using MVVM and Room Database?
Handwritten Digit Recognition using Neural Network
AI Driven Snake Game using Deep Q Learning
Rock, Paper, Scissor game - Python Project
Twitter Sentiment Analysis WebApp Using Flask
SDE SHEET - A Complete Guide for SDE Preparation
XML parsing in Python
Python | Simple GUI calculator using Tkinter
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python | [
{
"code": null,
"e": 25140,
"s": 25112,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 25627,
"s": 25140,
"text": "This project deals with developing a Virtual website ‘E-commerce Website’. It provides the user with a list of the various products available for purchase in the store. For the convenience of online shopping, a shopping cart is provided to the user. After the selection of the goods, it is sent for the order confirmation process. The system is implemented using Python’s web framework Django. To develop an e-commerce website, it is necessary to study and understand many technologies."
},
{
"code": null,
"e": 26310,
"s": 25627,
"text": "Scope: The scope of the project will be limited to some functions of the e-commerce website. It will display products, customers can select catalogs and select products, and can remove products from their cart specifying the quantity of each item. Selected items will be collected in a cart. At checkout, the item on the card will be presented as an order. Customers can pay for the items in the cart to complete an order. This project has great future scope. The project also provides security with the use of login ID and passwords, so that no unauthorized users can access your account. The only authorized person who has the appropriate access authority can access the software."
},
{
"code": null,
"e": 26383,
"s": 26310,
"text": "Django framework and SQLite database which comes by default with Django."
},
{
"code": null,
"e": 26435,
"s": 26383,
"text": "Knowledge of Python and basics of Django Framework."
},
{
"code": null,
"e": 26455,
"s": 26435,
"text": "Customer Interface:"
},
{
"code": null,
"e": 26604,
"s": 26455,
"text": "Customer shops for a productCustomer changes quantityThe customer adds an item to the cartCustomer views cartCustomer checks outCustomer sends order"
},
{
"code": null,
"e": 26633,
"s": 26604,
"text": "Customer shops for a product"
},
{
"code": null,
"e": 26659,
"s": 26633,
"text": "Customer changes quantity"
},
{
"code": null,
"e": 26697,
"s": 26659,
"text": "The customer adds an item to the cart"
},
{
"code": null,
"e": 26717,
"s": 26697,
"text": "Customer views cart"
},
{
"code": null,
"e": 26737,
"s": 26717,
"text": "Customer checks out"
},
{
"code": null,
"e": 26758,
"s": 26737,
"text": "Customer sends order"
},
{
"code": null,
"e": 26782,
"s": 26758,
"text": "ER-diagram for Customer"
},
{
"code": null,
"e": 26812,
"s": 26782,
"text": "Use-Case diagram for Customer"
},
{
"code": null,
"e": 26829,
"s": 26812,
"text": "Admin Interface:"
},
{
"code": null,
"e": 26898,
"s": 26829,
"text": "Admin logs inAdmin inserts itemAdmin removes itemAdmin modifies item"
},
{
"code": null,
"e": 26912,
"s": 26898,
"text": "Admin logs in"
},
{
"code": null,
"e": 26931,
"s": 26912,
"text": "Admin inserts item"
},
{
"code": null,
"e": 26950,
"s": 26931,
"text": "Admin removes item"
},
{
"code": null,
"e": 26970,
"s": 26950,
"text": "Admin modifies item"
},
{
"code": null,
"e": 26991,
"s": 26970,
"text": "ER-diagram for Admin"
},
{
"code": null,
"e": 27018,
"s": 26991,
"text": "Use-Case diagram for Admin"
},
{
"code": null,
"e": 27116,
"s": 27018,
"text": "Create Normal Project: Open the IDE and create a normal project by selecting File -> New Project."
},
{
"code": null,
"e": 27350,
"s": 27116,
"text": "Install Django: Next, we will install the Django module from the terminal. We will use PyCharm integrated terminal to do this task. One can also use cmd on windows to install the module by running python -m pip install django command"
},
{
"code": null,
"e": 27487,
"s": 27350,
"text": "Check Installed Django version: To check the installed Django version, you can run the python -m django -version command as shown below."
},
{
"code": null,
"e": 27699,
"s": 27487,
"text": "Create Django Project: When we execute django-admin startproject command, then it will create a Django project inside the normal project which we already have created here. django-admin startproject ProjectName."
},
{
"code": null,
"e": 27739,
"s": 27699,
"text": "Check Python3 version: python3 –version"
},
{
"code": null,
"e": 27990,
"s": 27739,
"text": "Run Default Django webserver:- Django internally provides a default webserver where we can launch our applications. python manage.py runserver command in terminal. By default, the server runs on port 8000. Access the webserver at the highlighted URL."
},
{
"code": null,
"e": 28083,
"s": 27990,
"text": "Open the project folder using a text editor. The directory structure should look like this :"
},
{
"code": null,
"e": 28101,
"s": 28083,
"text": "Project Structure"
},
{
"code": null,
"e": 28157,
"s": 28101,
"text": "Now add store app in E-commerce website in settings.py."
},
{
"code": null,
"e": 28217,
"s": 28157,
"text": "This file contains all the URL patterns used by the website"
},
{
"code": null,
"e": 28225,
"s": 28217,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import path, includefrom django.conf.urls.static import staticfrom . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls'))] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)",
"e": 28512,
"s": 28225,
"text": null
},
{
"code": null,
"e": 28656,
"s": 28512,
"text": "The below screenshot shows the required models that we will need to create. These models are tables that will be stored in the SQLite database."
},
{
"code": null,
"e": 28716,
"s": 28656,
"text": "Let’s see each model and the fields required by each model."
},
{
"code": null,
"e": 28724,
"s": 28716,
"text": "Python3"
},
{
"code": "from django.db import models class Category(models.Model): name = models.CharField(max_length=50) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name",
"e": 28961,
"s": 28724,
"text": null
},
{
"code": null,
"e": 28969,
"s": 28961,
"text": "Python3"
},
{
"code": "from django.db import models class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=10) email = models.EmailField() password = models.CharField(max_length=100) # to save the data def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email=self.email): return True return False",
"e": 29595,
"s": 28969,
"text": null
},
{
"code": null,
"e": 29603,
"s": 29595,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom .category import Category class Products(models.Model): name = models.CharField(max_length=60) price = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) description = models.CharField( max_length=250, default='', blank=True, null=True) image = models.ImageField(upload_to='uploads/products/') @staticmethod def get_products_by_id(ids): return Products.objects.filter(id__in=ids) @staticmethod def get_all_products(): return Products.objects.all() @staticmethod def get_all_products_by_categoryid(category_id): if category_id: return Products.objects.filter(category=category_id) else: return Products.get_all_products()",
"e": 30412,
"s": 29603,
"text": null
},
{
"code": null,
"e": 30419,
"s": 30412,
"text": "Python"
},
{
"code": "from django.db import modelsfrom .product import Productsfrom .customer import Customerimport datetime class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) def placeOrder(self): self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id).order_by('-date')",
"e": 31255,
"s": 30419,
"text": null
},
{
"code": null,
"e": 31558,
"s": 31255,
"text": "In views, we create a view named home.py, login.py, signup.py, cart.py, checkout.py, orders.py which takes a request and renders an HTML as a response. Create an home.html, login.html, signup.html, cart.html, checkout.html, orders.html in the templates. And map the views to the store\\urls.py folder. "
},
{
"code": null,
"e": 31566,
"s": 31558,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import pathfrom .views.home import Index, storefrom .views.signup import Signupfrom .views.login import Login, logoutfrom .views.cart import Cartfrom .views.checkout import CheckOutfrom .views.orders import OrderViewfrom .middlewares.auth import auth_middleware urlpatterns = [ path('', Index.as_view(), name='homepage'), path('store', store, name='store'), path('signup', Signup.as_view(), name='signup'), path('login', Login.as_view(), name='login'), path('logout', logout, name='logout'), path('cart', auth_middleware(Cart.as_view()), name='cart'), path('check-out', CheckOut.as_view(), name='checkout'), path('orders', auth_middleware(OrderView.as_view()), name='orders'), ]",
"e": 32324,
"s": 31566,
"text": null
},
{
"code": null,
"e": 32392,
"s": 32324,
"text": "The below files show the views for each functionality of the site. "
},
{
"code": null,
"e": 32400,
"s": 32392,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirect, HttpResponseRedirectfrom store.models.product import Productsfrom store.models.category import Categoryfrom django.views import View # Create your views here.class Index(View): def post(self, request): product = request.POST.get('product') remove = request.POST.get('remove') cart = request.session.get('cart') if cart: quantity = cart.get(product) if quantity: if remove: if quantity <= 1: cart.pop(product) else: cart[product] = quantity-1 else: cart[product] = quantity+1 else: cart[product] = 1 else: cart = {} cart[product] = 1 request.session['cart'] = cart print('cart', request.session['cart']) return redirect('homepage') def get(self, request): # print() return HttpResponseRedirect(f'/store{request.get_full_path()[1:]}') def store(request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} products = None categories = Category.get_all_categories() categoryID = request.GET.get('category') if categoryID: products = Products.get_all_products_by_categoryid(categoryID) else: products = Products.get_all_products() data = {} data['products'] = products data['categories'] = categories print('you are : ', request.session.get('email')) return render(request, 'index.html', data)",
"e": 34017,
"s": 32400,
"text": null
},
{
"code": null,
"e": 34025,
"s": 34017,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirect, HttpResponseRedirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import View class Login(View): return_url = None def get(self, request): Login.return_url = request.GET.get('return_url') return render(request, 'login.html') def post(self, request): email = request.POST.get('email') password = request.POST.get('password') customer = Customer.get_customer_by_email(email) error_message = None if customer: flag = check_password(password, customer.password) if flag: request.session['customer'] = customer.id if Login.return_url: return HttpResponseRedirect(Login.return_url) else: Login.return_url = None return redirect('homepage') else: error_message = 'Invalid !!' else: error_message = 'Invalid !!' print(email, password) return render(request, 'login.html', {'error': error_message}) def logout(request): request.session.clear() return redirect('login')",
"e": 35260,
"s": 34025,
"text": null
},
{
"code": null,
"e": 35268,
"s": 35260,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import make_passwordfrom store.models.customer import Customerfrom django.views import View class Signup (View): def get(self, request): return render(request, 'signup.html') def post(self, request): postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') phone = postData.get('phone') email = postData.get('email') password = postData.get('password') # validation value = { 'first_name': first_name, 'last_name': last_name, 'phone': phone, 'email': email } error_message = None customer = Customer(first_name=first_name, last_name=last_name, phone=phone, email=email, password=password) error_message = self.validateCustomer(customer) if not error_message: print(first_name, last_name, phone, email, password) customer.password = make_password(customer.password) customer.register() return redirect('homepage') else: data = { 'error': error_message, 'values': value } return render(request, 'signup.html', data) def validateCustomer(self, customer): error_message = None if (not customer.first_name): error_message = \"Please Enter your First Name !!\" elif len(customer.first_name) < 3: error_message = 'First Name must be 3 char long or more' elif not customer.last_name: error_message = 'Please Enter your Last Name' elif len(customer.last_name) < 3: error_message = 'Last Name must be 3 char long or more' elif not customer.phone: error_message = 'Enter your Phone Number' elif len(customer.phone) < 10: error_message = 'Phone Number must be 10 char Long' elif len(customer.password) < 5: error_message = 'Password must be 5 char long' elif len(customer.email) < 5: error_message = 'Email must be 5 char long' elif customer.isExists(): error_message = 'Email Address Already Registered..' # saving return error_message",
"e": 37681,
"s": 35268,
"text": null
},
{
"code": null,
"e": 37689,
"s": 37681,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom .product import Productsfrom .customer import Customerimport datetime class Order(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() address = models.CharField(max_length=50, default='', blank=True) phone = models.CharField(max_length=50, default='', blank=True) date = models.DateField(default=datetime.datetime.today) status = models.BooleanField(default=False) def placeOrder(self): self.save() @staticmethod def get_orders_by_customer(customer_id): return Order.objects.filter(customer=customer_id).order_by('-date')",
"e": 38525,
"s": 37689,
"text": null
},
{
"code": null,
"e": 38533,
"s": 38525,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirect from django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import View from store.models.product import Productsfrom store.models.orders import Order class CheckOut(View): def post(self, request): address = request.POST.get('address') phone = request.POST.get('phone') customer = request.session.get('customer') cart = request.session.get('cart') products = Products.get_products_by_id(list(cart.keys())) print(address, phone, customer, cart, products) for product in products: print(cart.get(str(product.id))) order = Order(customer=Customer(id=customer), product=product, price=product.price, address=address, phone=phone, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('cart')",
"e": 39594,
"s": 38533,
"text": null
},
{
"code": null,
"e": 39602,
"s": 39594,
"text": "Python3"
},
{
"code": "from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import Viewfrom store.models.product import Productsfrom store.models.orders import Orderfrom store.middlewares.auth import auth_middleware class OrderView(View): def get(self, request): customer = request.session.get('customer') orders = Order.get_orders_by_customer(customer) print(orders) return render(request, 'orders.html', {'orders': orders})",
"e": 40147,
"s": 39602,
"text": null
},
{
"code": null,
"e": 40505,
"s": 40147,
"text": "The project already includes a lot of features. The main beneficiaries are both customers and administrators who take longer to behave online. In addition, additional features can be identified and incorporated in the future. It will take more time and effort to understand the need and adjust it to a computerized system to accommodate additional features."
},
{
"code": null,
"e": 40533,
"s": 40505,
"text": "GitHub Link to the project "
},
{
"code": null,
"e": 40549,
"s": 40533,
"text": "Django-Projects"
},
{
"code": null,
"e": 40562,
"s": 40549,
"text": "ProGeek 2021"
},
{
"code": null,
"e": 40576,
"s": 40562,
"text": "Python Django"
},
{
"code": null,
"e": 40584,
"s": 40576,
"text": "ProGeek"
},
{
"code": null,
"e": 40592,
"s": 40584,
"text": "Project"
},
{
"code": null,
"e": 40599,
"s": 40592,
"text": "Python"
},
{
"code": null,
"e": 40697,
"s": 40599,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40766,
"s": 40697,
"text": "How to Build a Simple Note Android App using MVVM and Room Database?"
},
{
"code": null,
"e": 40817,
"s": 40766,
"text": "Handwritten Digit Recognition using Neural Network"
},
{
"code": null,
"e": 40860,
"s": 40817,
"text": "AI Driven Snake Game using Deep Q Learning"
},
{
"code": null,
"e": 40903,
"s": 40860,
"text": "Rock, Paper, Scissor game - Python Project"
},
{
"code": null,
"e": 40949,
"s": 40903,
"text": "Twitter Sentiment Analysis WebApp Using Flask"
},
{
"code": null,
"e": 40998,
"s": 40949,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 41020,
"s": 40998,
"text": "XML parsing in Python"
},
{
"code": null,
"e": 41065,
"s": 41020,
"text": "Python | Simple GUI calculator using Tkinter"
},
{
"code": null,
"e": 41120,
"s": 41065,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
}
] |
Java - The BitSet Class | The BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.
BitSet( )
This constructor creates a default object.
BitSet(int size)
This constructor allows you to specify its initial size, i.e., the number of bits that it can hold. All bits are initialized to zero.
BitSet implements the Cloneable interface and defines the methods listed in the following table −
void and(BitSet bitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object.
void andNot(BitSet bitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
int cardinality( )
Returns the number of set bits in the invoking object.
void clear( )
Zeros all bits.
void clear(int index)
Zeros the bit specified by index.
void clear(int startIndex, int endIndex)
Zeros the bits from startIndex to endIndex.
Object clone( )
Duplicates the invoking BitSet object.
boolean equals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the method returns false.
void flip(int index)
Reverses the bit specified by the index.
void flip(int startIndex, int endIndex)
Reverses the bits from startIndex to endIndex.
boolean get(int index)
Returns the current state of the bit at the specified index.
BitSet get(int startIndex, int endIndex)
Returns a BitSet that consists of the bits from startIndex to endIndex. The invoking object is not changed.
int hashCode( )
Returns the hash code for the invoking object.
boolean intersects(BitSet bitSet)
Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1.
boolean isEmpty( )
Returns true if all bits in the invoking object are zero.
int length( )
Returns the number of bits required to hold the contents of the invoking BitSet. This value is determined by the location of the last 1 bit.
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startIndex.
int nextSetBit(int startIndex)
Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no bit is set, -1 is returned.
void or(BitSet bitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.
void set(int index)
Sets the bit specified by index.
void set(int index, boolean v)
Sets the bit specified by index to the value passed in v. True sets the bit, false clears the bit.
void set(int startIndex, int endIndex)
Sets the bits from startIndex to endIndex.
void set(int startIndex, int endIndex, boolean v)
Sets the bits from startIndex to endIndex, to the value passed in v. true sets the bits, false clears the bits.
int size( )
Returns the number of bits in the invoking BitSet object.
String toString( )
Returns the string equivalent of the invoking BitSet object.
void xor(BitSet bitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.
The following program illustrates several of the methods supported by this data structure −
import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i = 0; i < 16; i++) {
if((i % 2) == 0) bits1.set(i);
if((i % 5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
This will produce the following result −
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2629,
"s": 2377,
"text": "The BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4."
},
{
"code": null,
"e": 2680,
"s": 2629,
"text": "The BitSet defines the following two constructors."
},
{
"code": null,
"e": 2690,
"s": 2680,
"text": "BitSet( )"
},
{
"code": null,
"e": 2733,
"s": 2690,
"text": "This constructor creates a default object."
},
{
"code": null,
"e": 2750,
"s": 2733,
"text": "BitSet(int size)"
},
{
"code": null,
"e": 2884,
"s": 2750,
"text": "This constructor allows you to specify its initial size, i.e., the number of bits that it can hold. All bits are initialized to zero."
},
{
"code": null,
"e": 2982,
"s": 2884,
"text": "BitSet implements the Cloneable interface and defines the methods listed in the following table −"
},
{
"code": null,
"e": 3006,
"s": 2982,
"text": "void and(BitSet bitSet)"
},
{
"code": null,
"e": 3133,
"s": 3006,
"text": "ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object."
},
{
"code": null,
"e": 3160,
"s": 3133,
"text": "void andNot(BitSet bitSet)"
},
{
"code": null,
"e": 3243,
"s": 3160,
"text": "For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared."
},
{
"code": null,
"e": 3262,
"s": 3243,
"text": "int cardinality( )"
},
{
"code": null,
"e": 3317,
"s": 3262,
"text": "Returns the number of set bits in the invoking object."
},
{
"code": null,
"e": 3331,
"s": 3317,
"text": "void clear( )"
},
{
"code": null,
"e": 3347,
"s": 3331,
"text": "Zeros all bits."
},
{
"code": null,
"e": 3369,
"s": 3347,
"text": "void clear(int index)"
},
{
"code": null,
"e": 3403,
"s": 3369,
"text": "Zeros the bit specified by index."
},
{
"code": null,
"e": 3444,
"s": 3403,
"text": "void clear(int startIndex, int endIndex)"
},
{
"code": null,
"e": 3488,
"s": 3444,
"text": "Zeros the bits from startIndex to endIndex."
},
{
"code": null,
"e": 3504,
"s": 3488,
"text": "Object clone( )"
},
{
"code": null,
"e": 3543,
"s": 3504,
"text": "Duplicates the invoking BitSet object."
},
{
"code": null,
"e": 3573,
"s": 3543,
"text": "boolean equals(Object bitSet)"
},
{
"code": null,
"e": 3690,
"s": 3573,
"text": "Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the method returns false."
},
{
"code": null,
"e": 3711,
"s": 3690,
"text": "void flip(int index)"
},
{
"code": null,
"e": 3752,
"s": 3711,
"text": "Reverses the bit specified by the index."
},
{
"code": null,
"e": 3792,
"s": 3752,
"text": "void flip(int startIndex, int endIndex)"
},
{
"code": null,
"e": 3839,
"s": 3792,
"text": "Reverses the bits from startIndex to endIndex."
},
{
"code": null,
"e": 3862,
"s": 3839,
"text": "boolean get(int index)"
},
{
"code": null,
"e": 3923,
"s": 3862,
"text": "Returns the current state of the bit at the specified index."
},
{
"code": null,
"e": 3964,
"s": 3923,
"text": "BitSet get(int startIndex, int endIndex)"
},
{
"code": null,
"e": 4072,
"s": 3964,
"text": "Returns a BitSet that consists of the bits from startIndex to endIndex. The invoking object is not changed."
},
{
"code": null,
"e": 4088,
"s": 4072,
"text": "int hashCode( )"
},
{
"code": null,
"e": 4135,
"s": 4088,
"text": "Returns the hash code for the invoking object."
},
{
"code": null,
"e": 4169,
"s": 4135,
"text": "boolean intersects(BitSet bitSet)"
},
{
"code": null,
"e": 4270,
"s": 4169,
"text": "Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1."
},
{
"code": null,
"e": 4289,
"s": 4270,
"text": "boolean isEmpty( )"
},
{
"code": null,
"e": 4347,
"s": 4289,
"text": "Returns true if all bits in the invoking object are zero."
},
{
"code": null,
"e": 4361,
"s": 4347,
"text": "int length( )"
},
{
"code": null,
"e": 4502,
"s": 4361,
"text": "Returns the number of bits required to hold the contents of the invoking BitSet. This value is determined by the location of the last 1 bit."
},
{
"code": null,
"e": 4535,
"s": 4502,
"text": "int nextClearBit(int startIndex)"
},
{
"code": null,
"e": 4657,
"s": 4535,
"text": "Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startIndex."
},
{
"code": null,
"e": 4688,
"s": 4657,
"text": "int nextSetBit(int startIndex)"
},
{
"code": null,
"e": 4836,
"s": 4688,
"text": "Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no bit is set, -1 is returned."
},
{
"code": null,
"e": 4859,
"s": 4836,
"text": "void or(BitSet bitSet)"
},
{
"code": null,
"e": 4984,
"s": 4859,
"text": "ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object."
},
{
"code": null,
"e": 5004,
"s": 4984,
"text": "void set(int index)"
},
{
"code": null,
"e": 5037,
"s": 5004,
"text": "Sets the bit specified by index."
},
{
"code": null,
"e": 5068,
"s": 5037,
"text": "void set(int index, boolean v)"
},
{
"code": null,
"e": 5167,
"s": 5068,
"text": "Sets the bit specified by index to the value passed in v. True sets the bit, false clears the bit."
},
{
"code": null,
"e": 5206,
"s": 5167,
"text": "void set(int startIndex, int endIndex)"
},
{
"code": null,
"e": 5249,
"s": 5206,
"text": "Sets the bits from startIndex to endIndex."
},
{
"code": null,
"e": 5299,
"s": 5249,
"text": "void set(int startIndex, int endIndex, boolean v)"
},
{
"code": null,
"e": 5411,
"s": 5299,
"text": "Sets the bits from startIndex to endIndex, to the value passed in v. true sets the bits, false clears the bits."
},
{
"code": null,
"e": 5423,
"s": 5411,
"text": "int size( )"
},
{
"code": null,
"e": 5481,
"s": 5423,
"text": "Returns the number of bits in the invoking BitSet object."
},
{
"code": null,
"e": 5500,
"s": 5481,
"text": "String toString( )"
},
{
"code": null,
"e": 5561,
"s": 5500,
"text": "Returns the string equivalent of the invoking BitSet object."
},
{
"code": null,
"e": 5585,
"s": 5561,
"text": "void xor(BitSet bitSet)"
},
{
"code": null,
"e": 5711,
"s": 5585,
"text": "XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object."
},
{
"code": null,
"e": 5803,
"s": 5711,
"text": "The following program illustrates several of the methods supported by this data structure −"
},
{
"code": null,
"e": 6691,
"s": 5803,
"text": "import java.util.BitSet;\npublic class BitSetDemo {\n\n public static void main(String args[]) {\n BitSet bits1 = new BitSet(16);\n BitSet bits2 = new BitSet(16);\n \n // set some bits\n for(int i = 0; i < 16; i++) {\n if((i % 2) == 0) bits1.set(i);\n if((i % 5) != 0) bits2.set(i);\n }\n \n System.out.println(\"Initial pattern in bits1: \");\n System.out.println(bits1);\n System.out.println(\"\\nInitial pattern in bits2: \");\n System.out.println(bits2);\n\n // AND bits\n bits2.and(bits1);\n System.out.println(\"\\nbits2 AND bits1: \");\n System.out.println(bits2);\n\n // OR bits\n bits2.or(bits1);\n System.out.println(\"\\nbits2 OR bits1: \");\n System.out.println(bits2);\n\n // XOR bits\n bits2.xor(bits1);\n System.out.println(\"\\nbits2 XOR bits1: \");\n System.out.println(bits2);\n }\n}"
},
{
"code": null,
"e": 6732,
"s": 6691,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6960,
"s": 6732,
"text": "Initial pattern in bits1:\n{0, 2, 4, 6, 8, 10, 12, 14}\n\nInitial pattern in bits2:\n{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}\n\nbits2 AND bits1:\n{2, 4, 6, 8, 12, 14}\n\nbits2 OR bits1:\n{0, 2, 4, 6, 8, 10, 12, 14}\n\nbits2 XOR bits1:\n{}\n"
},
{
"code": null,
"e": 6993,
"s": 6960,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7009,
"s": 6993,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7042,
"s": 7009,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7058,
"s": 7042,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7093,
"s": 7058,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7107,
"s": 7093,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7141,
"s": 7107,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7155,
"s": 7141,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7192,
"s": 7155,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7207,
"s": 7192,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7240,
"s": 7207,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7259,
"s": 7240,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7266,
"s": 7259,
"text": " Print"
},
{
"code": null,
"e": 7277,
"s": 7266,
"text": " Add Notes"
}
] |
Powershell - Read XML File | Get-Content cmdlet is used to read content of a xml file.
In this example, we're reading content of test.xml.
Get-Content D:\temp\test\test.xml
You can see following output in PowerShell console.
<title>Welcome to TutorialsPoint</title>
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2092,
"s": 2034,
"text": "Get-Content cmdlet is used to read content of a xml file."
},
{
"code": null,
"e": 2144,
"s": 2092,
"text": "In this example, we're reading content of test.xml."
},
{
"code": null,
"e": 2180,
"s": 2144,
"text": "Get-Content D:\\temp\\test\\test.xml \n"
},
{
"code": null,
"e": 2232,
"s": 2180,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2274,
"s": 2232,
"text": "<title>Welcome to TutorialsPoint</title>\n"
},
{
"code": null,
"e": 2309,
"s": 2274,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2330,
"s": 2309,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2365,
"s": 2330,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2378,
"s": 2365,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2415,
"s": 2378,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2427,
"s": 2415,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2434,
"s": 2427,
"text": " Print"
},
{
"code": null,
"e": 2445,
"s": 2434,
"text": " Add Notes"
}
] |
C# Program to Check a Specified Type is an Interface or not - GeeksforGeeks | 23 Nov, 2021
The interface is just like a class, it can also have methods, properties, events, etc. as its members, but it only contains the declaration of the members and the implementation of these members will be given by the class that implements the interface implicitly or explicitly. We can check the specified type is an interface or not by using the IsInterface property of the Type class. It will return true if the given type is an interface. Otherwise, it will return false. It is a read-only property.
Syntax:
public bool IsInterface { get; }
Example 1:
C#
// C# program to check whether the // given type is interface or notusing System;using System.Reflection; // Declare an interfaceinterface myinterface{ // Method in interface void gfg();} class GFG{ // Driver codestatic void Main(){ // Check the type is interface or not // Using the IsInterface property if (typeof(myinterface).IsInterface == true) { Console.WriteLine("Yes it is Interface"); } else { Console.WriteLine("No it is not an Interface"); }}}
Output:
Yes it is Interface
Example 2:
C#
// C# program to check whether the // given type is interface or notusing System;using System.Reflection; // Declare an interfaceinterface myinterface{ // Method in interface void gfg();} // Declare a classpublic class myclass{ public void myfunc(){}} // Declare a structpublic struct mystruct{ int a;} class GFG{ // Driver codestatic void Main(){ // Check the type is interface or not // Using the IsInterface property Console.WriteLine(typeof(myinterface).IsInterface); Console.WriteLine(typeof(myclass).IsInterface); Console.WriteLine(typeof(mystruct).IsInterface);}}
Output:
True
False
False
CSharp-Interfaces
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24804,
"s": 24302,
"text": "The interface is just like a class, it can also have methods, properties, events, etc. as its members, but it only contains the declaration of the members and the implementation of these members will be given by the class that implements the interface implicitly or explicitly. We can check the specified type is an interface or not by using the IsInterface property of the Type class. It will return true if the given type is an interface. Otherwise, it will return false. It is a read-only property."
},
{
"code": null,
"e": 24812,
"s": 24804,
"text": "Syntax:"
},
{
"code": null,
"e": 24845,
"s": 24812,
"text": "public bool IsInterface { get; }"
},
{
"code": null,
"e": 24856,
"s": 24845,
"text": "Example 1:"
},
{
"code": null,
"e": 24859,
"s": 24856,
"text": "C#"
},
{
"code": "// C# program to check whether the // given type is interface or notusing System;using System.Reflection; // Declare an interfaceinterface myinterface{ // Method in interface void gfg();} class GFG{ // Driver codestatic void Main(){ // Check the type is interface or not // Using the IsInterface property if (typeof(myinterface).IsInterface == true) { Console.WriteLine(\"Yes it is Interface\"); } else { Console.WriteLine(\"No it is not an Interface\"); }}}",
"e": 25379,
"s": 24859,
"text": null
},
{
"code": null,
"e": 25387,
"s": 25379,
"text": "Output:"
},
{
"code": null,
"e": 25407,
"s": 25387,
"text": "Yes it is Interface"
},
{
"code": null,
"e": 25418,
"s": 25407,
"text": "Example 2:"
},
{
"code": null,
"e": 25421,
"s": 25418,
"text": "C#"
},
{
"code": "// C# program to check whether the // given type is interface or notusing System;using System.Reflection; // Declare an interfaceinterface myinterface{ // Method in interface void gfg();} // Declare a classpublic class myclass{ public void myfunc(){}} // Declare a structpublic struct mystruct{ int a;} class GFG{ // Driver codestatic void Main(){ // Check the type is interface or not // Using the IsInterface property Console.WriteLine(typeof(myinterface).IsInterface); Console.WriteLine(typeof(myclass).IsInterface); Console.WriteLine(typeof(mystruct).IsInterface);}}",
"e": 26040,
"s": 25421,
"text": null
},
{
"code": null,
"e": 26048,
"s": 26040,
"text": "Output:"
},
{
"code": null,
"e": 26065,
"s": 26048,
"text": "True\nFalse\nFalse"
},
{
"code": null,
"e": 26083,
"s": 26065,
"text": "CSharp-Interfaces"
},
{
"code": null,
"e": 26090,
"s": 26083,
"text": "Picked"
},
{
"code": null,
"e": 26093,
"s": 26090,
"text": "C#"
},
{
"code": null,
"e": 26105,
"s": 26093,
"text": "C# Programs"
},
{
"code": null,
"e": 26203,
"s": 26105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26226,
"s": 26203,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26254,
"s": 26226,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26294,
"s": 26254,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26337,
"s": 26294,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26353,
"s": 26337,
"text": "C# | List Class"
},
{
"code": null,
"e": 26393,
"s": 26353,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26418,
"s": 26393,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 26452,
"s": 26418,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 26498,
"s": 26452,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
How to rename the drive letter in Windows using PowerShell? | We can rename a drive letter of a disk using PowerShell with the Set-Partition command. An example is shown below.
In the Windows OS, we have E: and we need to rename its partition to the F: You can run the below command.
Set-Partition -DriveLetter 'E' -NewDriveLetter 'F'
You can also run the Get-Partition command and Pipeline the Set-Partition command. For example,
Get-Partition -DriveLetter 'E' | Set-Partition -NewDriveLetter 'F'
If you want to rename the drive on the remote computer, then you need to take the CIMSession of the system and run the command. For example,
$sess = New-CimSession -ComputerName 'Test1-Win2k12' Set-Partition -CimSession $sess -DriveLetter 'E' -NewDriveLetter 'F' | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "We can rename a drive letter of a disk using PowerShell with the Set-Partition command. An example is shown below."
},
{
"code": null,
"e": 1284,
"s": 1177,
"text": "In the Windows OS, we have E: and we need to rename its partition to the F: You can run the below command."
},
{
"code": null,
"e": 1335,
"s": 1284,
"text": "Set-Partition -DriveLetter 'E' -NewDriveLetter 'F'"
},
{
"code": null,
"e": 1431,
"s": 1335,
"text": "You can also run the Get-Partition command and Pipeline the Set-Partition command. For example,"
},
{
"code": null,
"e": 1498,
"s": 1431,
"text": "Get-Partition -DriveLetter 'E' | Set-Partition -NewDriveLetter 'F'"
},
{
"code": null,
"e": 1639,
"s": 1498,
"text": "If you want to rename the drive on the remote computer, then you need to take the CIMSession of the system and run the command. For example,"
},
{
"code": null,
"e": 1761,
"s": 1639,
"text": "$sess = New-CimSession -ComputerName 'Test1-Win2k12' Set-Partition -CimSession $sess -DriveLetter 'E' -NewDriveLetter 'F'"
}
] |
Bootstrap Badges, Labels, Page Headers - GeeksforGeeks | 19 Jan, 2022
Introduction and InstallationButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron
Introduction and Installation
Buttons, Glyphicons, Tables
Vertical Forms, Horizontal Forms, Inline Forms
DropDowns and Responsive Tabs
Progress Bar and Jumbotron
Badges
We all have seen some numerical indicators beside some links in various websites. These are called badges. These badges tells how many items are available or associated with the link. To add a badges to your webpage, add a class .badge to a span element like this-
HTML
<a href="#">Messages <span class="badge">2</span></a><br><a href="#">Drafts <span class="badge">3</span></a><br><a href="#">Comments <span class="badge">4</span></a>
Output
Badges inside buttons To insert badges inside buttons, add a class .badge to a button element like this-
HTML
<button type="button" class="btn btn-primary">Messages<span class="badge">2</span></button>
Output
Labels
We all have seen some additional information beside some links in various websites. These are called labels. These labels tells additional information about the link or text. To add a labels to your webpage, add a class .label to a span element like this-
Use the following classes to style the colour of the label Grey – label-default Green – label-success Blue – label-info Yellow –label-warning Red – label-danger
Use the following classes to style the colour of the label Grey – label-default Green – label-success Blue – label-info Yellow –label-warning Red – label-danger
HTML
<span class="label label-default">Grey Label</span><span class="label label-success">Green Label</span><span class="label label-info">Blue Label</span><span class="label label-warning">Yellow Label</span><span class="label label-danger">Red Label</span>
Panels
We all have seen a box around some text or any information in various websites. These are called panels. These panels are bordered box with some padding which can be easily added around some text using bootstrap classes. The content we need to write inside the panel is written in a div element with a class.panel-body To add a panels to your webpage, add a class .panel to a div element like this-
Use the following classes to style the colour of the label Grey – panel-default Green – panel-success Blue – panel-info Yellow –panel-warning Red – panel-danger
HTML
<div class="panel panel-default"> <div class="panel-body">Panel</div></div>
Coloured Panels
HTML
<div class="panel panel-default"> <div class="panel-body">Panel</div> </div> <div class="panel panel-primary"> <div class="panel-body">Panel</div> </div> <div class="panel panel-success"> <div class="panel-body">Green Panel</div> </div> <div class="panel panel-info"> <div class="panel-body">Blue Panel</div> </div> <div class="panel panel-warning"> <div class="panel-body">Yellow Panel</div> </div> <div class="panel panel-danger"> <div class="panel-body">Red Panel</div> </div>
Output
Page Header
Page header allows us to write a heading on our webpage with proper spacing around it so that it can be distinguished from other text on the webpage. To add a pageheader to your webpage, add a class .page-header to a div element like this-
HTML
<div class = "page-header"> <h1> Hi ! </h1> </div> <p>My name is Ayush.</p>
Output
Note the difference if we don’t use page-header class
This article is contributed by Ayush Saxena. 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.
sagartomar9927
anikakapoor
Web technologies
Bootstrap
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to align navbar items to the right in Bootstrap 4 ?
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 28456,
"s": 28428,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 28614,
"s": 28456,
"text": "Introduction and InstallationButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron"
},
{
"code": null,
"e": 28644,
"s": 28614,
"text": "Introduction and Installation"
},
{
"code": null,
"e": 28672,
"s": 28644,
"text": "Buttons, Glyphicons, Tables"
},
{
"code": null,
"e": 28719,
"s": 28672,
"text": "Vertical Forms, Horizontal Forms, Inline Forms"
},
{
"code": null,
"e": 28749,
"s": 28719,
"text": "DropDowns and Responsive Tabs"
},
{
"code": null,
"e": 28776,
"s": 28749,
"text": "Progress Bar and Jumbotron"
},
{
"code": null,
"e": 28783,
"s": 28776,
"text": "Badges"
},
{
"code": null,
"e": 29049,
"s": 28783,
"text": "We all have seen some numerical indicators beside some links in various websites. These are called badges. These badges tells how many items are available or associated with the link. To add a badges to your webpage, add a class .badge to a span element like this- "
},
{
"code": null,
"e": 29056,
"s": 29051,
"text": "HTML"
},
{
"code": "<a href=\"#\">Messages <span class=\"badge\">2</span></a><br><a href=\"#\">Drafts <span class=\"badge\">3</span></a><br><a href=\"#\">Comments <span class=\"badge\">4</span></a>",
"e": 29222,
"s": 29056,
"text": null
},
{
"code": null,
"e": 29231,
"s": 29222,
"text": "Output "
},
{
"code": null,
"e": 29337,
"s": 29231,
"text": "Badges inside buttons To insert badges inside buttons, add a class .badge to a button element like this- "
},
{
"code": null,
"e": 29344,
"s": 29339,
"text": "HTML"
},
{
"code": "<button type=\"button\" class=\"btn btn-primary\">Messages<span class=\"badge\">2</span></button>",
"e": 29436,
"s": 29344,
"text": null
},
{
"code": null,
"e": 29445,
"s": 29436,
"text": "Output "
},
{
"code": null,
"e": 29454,
"s": 29447,
"text": "Labels"
},
{
"code": null,
"e": 29712,
"s": 29454,
"text": "We all have seen some additional information beside some links in various websites. These are called labels. These labels tells additional information about the link or text. To add a labels to your webpage, add a class .label to a span element like this- "
},
{
"code": null,
"e": 29873,
"s": 29712,
"text": "Use the following classes to style the colour of the label Grey – label-default Green – label-success Blue – label-info Yellow –label-warning Red – label-danger"
},
{
"code": null,
"e": 30034,
"s": 29873,
"text": "Use the following classes to style the colour of the label Grey – label-default Green – label-success Blue – label-info Yellow –label-warning Red – label-danger"
},
{
"code": null,
"e": 30041,
"s": 30036,
"text": "HTML"
},
{
"code": "<span class=\"label label-default\">Grey Label</span><span class=\"label label-success\">Green Label</span><span class=\"label label-info\">Blue Label</span><span class=\"label label-warning\">Yellow Label</span><span class=\"label label-danger\">Red Label</span>",
"e": 30295,
"s": 30041,
"text": null
},
{
"code": null,
"e": 30302,
"s": 30295,
"text": "Panels"
},
{
"code": null,
"e": 30703,
"s": 30302,
"text": "We all have seen a box around some text or any information in various websites. These are called panels. These panels are bordered box with some padding which can be easily added around some text using bootstrap classes. The content we need to write inside the panel is written in a div element with a class.panel-body To add a panels to your webpage, add a class .panel to a div element like this- "
},
{
"code": null,
"e": 30864,
"s": 30703,
"text": "Use the following classes to style the colour of the label Grey – panel-default Green – panel-success Blue – panel-info Yellow –panel-warning Red – panel-danger"
},
{
"code": null,
"e": 30871,
"s": 30866,
"text": "HTML"
},
{
"code": "<div class=\"panel panel-default\"> <div class=\"panel-body\">Panel</div></div>",
"e": 30948,
"s": 30871,
"text": null
},
{
"code": null,
"e": 30965,
"s": 30948,
"text": "Coloured Panels "
},
{
"code": null,
"e": 30972,
"s": 30967,
"text": "HTML"
},
{
"code": "<div class=\"panel panel-default\"> <div class=\"panel-body\">Panel</div> </div> <div class=\"panel panel-primary\"> <div class=\"panel-body\">Panel</div> </div> <div class=\"panel panel-success\"> <div class=\"panel-body\">Green Panel</div> </div> <div class=\"panel panel-info\"> <div class=\"panel-body\">Blue Panel</div> </div> <div class=\"panel panel-warning\"> <div class=\"panel-body\">Yellow Panel</div> </div> <div class=\"panel panel-danger\"> <div class=\"panel-body\">Red Panel</div> </div>",
"e": 31469,
"s": 30972,
"text": null
},
{
"code": null,
"e": 31478,
"s": 31469,
"text": "Output "
},
{
"code": null,
"e": 31492,
"s": 31480,
"text": "Page Header"
},
{
"code": null,
"e": 31733,
"s": 31492,
"text": "Page header allows us to write a heading on our webpage with proper spacing around it so that it can be distinguished from other text on the webpage. To add a pageheader to your webpage, add a class .page-header to a div element like this- "
},
{
"code": null,
"e": 31740,
"s": 31735,
"text": "HTML"
},
{
"code": "<div class = \"page-header\"> <h1> Hi ! </h1> </div> <p>My name is Ayush.</p>",
"e": 31826,
"s": 31740,
"text": null
},
{
"code": null,
"e": 31835,
"s": 31826,
"text": "Output "
},
{
"code": null,
"e": 31891,
"s": 31835,
"text": "Note the difference if we don’t use page-header class "
},
{
"code": null,
"e": 32312,
"s": 31891,
"text": "This article is contributed by Ayush Saxena. 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": 32327,
"s": 32312,
"text": "sagartomar9927"
},
{
"code": null,
"e": 32339,
"s": 32327,
"text": "anikakapoor"
},
{
"code": null,
"e": 32356,
"s": 32339,
"text": "Web technologies"
},
{
"code": null,
"e": 32366,
"s": 32356,
"text": "Bootstrap"
},
{
"code": null,
"e": 32372,
"s": 32366,
"text": "GBlog"
},
{
"code": null,
"e": 32470,
"s": 32372,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32520,
"s": 32470,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 32549,
"s": 32520,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32605,
"s": 32549,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 32646,
"s": 32605,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32687,
"s": 32646,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 32729,
"s": 32687,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32803,
"s": 32729,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 32828,
"s": 32803,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32856,
"s": 32828,
"text": "Socket Programming in C/C++"
}
] |
How to get the list of shared folders using PowerShell? | Get-SmbShare gives all the shared folders on the local system.
PS C:\Temp> Get-SmbShare
Name ScopeName Path Description
---- --------- ---- -----------
ADMIN$ * C:\Windows Remote Admin
C$ * C:\ Default share
DSC * E:\DSC
E$ * E:\ Default share
IPC$ * Remote IPC
Shared1 * E:\Extract
To get the shared folders on the remote computer we can use the CIM session. For example,
$sess = New-CimSession -ComputerName Labmachine2k16
Get-SmbShare -Session $sess
PS C:\Users\Administrator> Get-SmbShare -Session $sess
Name ScopeName Path Description PSComputerName
---- --------- ---- ----------- --------------
ADMIN$ * C:\Windows Remote Admin Labmachine2k16
C$ * C:\ Default share Labmachine2k16
DSC * E:\DSC Labmachine2k16
E$ * E:\ Default share Labmachine2k16
IPC$ * Remote IPC Labmachine2k16
Shared1 * E:\Extract Labmachine2k16 | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Get-SmbShare gives all the shared folders on the local system."
},
{
"code": null,
"e": 1466,
"s": 1125,
"text": "PS C:\\Temp> Get-SmbShare\nName ScopeName Path Description\n---- --------- ---- -----------\nADMIN$ * C:\\Windows Remote Admin\nC$ * C:\\ Default share\nDSC * E:\\DSC\nE$ * E:\\ Default share\nIPC$ * Remote IPC\nShared1 * E:\\Extract"
},
{
"code": null,
"e": 1556,
"s": 1466,
"text": "To get the shared folders on the remote computer we can use the CIM session. For example,"
},
{
"code": null,
"e": 1636,
"s": 1556,
"text": "$sess = New-CimSession -ComputerName Labmachine2k16\nGet-SmbShare -Session $sess"
},
{
"code": null,
"e": 2217,
"s": 1636,
"text": "PS C:\\Users\\Administrator> Get-SmbShare -Session $sess\nName ScopeName Path Description PSComputerName\n---- --------- ---- ----------- --------------\nADMIN$ * C:\\Windows Remote Admin Labmachine2k16\nC$ * C:\\ Default share Labmachine2k16\nDSC * E:\\DSC Labmachine2k16\nE$ * E:\\ Default share Labmachine2k16\nIPC$ * Remote IPC Labmachine2k16\nShared1 * E:\\Extract Labmachine2k16"
}
] |
What are the different operations on files in C language? | The operations that can be carried out on files in C language are as follows −
Naming the file.
Opening the file.
Reading from the file.
Writing into the file.
Closing the file.
The syntax for opening and naming file is as follows −
FILE *File pointer;
For example, FILE * fptr;
File pointer = fopen ("File name”, "mode”);
For example, fptr = fopen ("sample.txt”, "r”)
FILE *fp;
fp = fopen ("sample.txt”, "w”);
The modes of opening the file in C language are explained below −
Write mode of opening the file
The syntax is as follows −
FILE *fp;
fp =fopen ("sample.txt”, "w”);
If the file is not existing, then a new file is created.
If the file exists then, old content gets erased and current content will be stored.
Read mode of opening the file
The syntax is as follows −
FILE *fp
fp =fopen ("sample.txt”, "r”);
If the file is not existing, then fopen function returns NULL value.
If the file exists, then data is read successfully from file
Append mode of opening a file
The syntax is as follows −
FILE *fp;
fp =fopen ("sample.txt", "a");
If the file doesn’t exist, then a new file will be created.
If the file exists, the current content will be adding to the old content.
Following is the C program for operations on files −
Live Demo
//Program for copying the contents of one file into another file
#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
When the above program is executed, it produces the following result −
Enter the filename to open for reading
file2.txt
Enter the filename to open for writing
file1.txt
Contents copied to file1.txt | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "The operations that can be carried out on files in C language are as follows −"
},
{
"code": null,
"e": 1158,
"s": 1141,
"text": "Naming the file."
},
{
"code": null,
"e": 1176,
"s": 1158,
"text": "Opening the file."
},
{
"code": null,
"e": 1199,
"s": 1176,
"text": "Reading from the file."
},
{
"code": null,
"e": 1222,
"s": 1199,
"text": "Writing into the file."
},
{
"code": null,
"e": 1240,
"s": 1222,
"text": "Closing the file."
},
{
"code": null,
"e": 1295,
"s": 1240,
"text": "The syntax for opening and naming file is as follows −"
},
{
"code": null,
"e": 1315,
"s": 1295,
"text": "FILE *File pointer;"
},
{
"code": null,
"e": 1341,
"s": 1315,
"text": "For example, FILE * fptr;"
},
{
"code": null,
"e": 1385,
"s": 1341,
"text": "File pointer = fopen (\"File name”, \"mode”);"
},
{
"code": null,
"e": 1431,
"s": 1385,
"text": "For example, fptr = fopen (\"sample.txt”, \"r”)"
},
{
"code": null,
"e": 1473,
"s": 1431,
"text": "FILE *fp;\nfp = fopen (\"sample.txt”, \"w”);"
},
{
"code": null,
"e": 1539,
"s": 1473,
"text": "The modes of opening the file in C language are explained below −"
},
{
"code": null,
"e": 1570,
"s": 1539,
"text": "Write mode of opening the file"
},
{
"code": null,
"e": 1597,
"s": 1570,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1638,
"s": 1597,
"text": "FILE *fp;\nfp =fopen (\"sample.txt”, \"w”);"
},
{
"code": null,
"e": 1695,
"s": 1638,
"text": "If the file is not existing, then a new file is created."
},
{
"code": null,
"e": 1780,
"s": 1695,
"text": "If the file exists then, old content gets erased and current content will be stored."
},
{
"code": null,
"e": 1810,
"s": 1780,
"text": "Read mode of opening the file"
},
{
"code": null,
"e": 1837,
"s": 1810,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1877,
"s": 1837,
"text": "FILE *fp\nfp =fopen (\"sample.txt”, \"r”);"
},
{
"code": null,
"e": 1946,
"s": 1877,
"text": "If the file is not existing, then fopen function returns NULL value."
},
{
"code": null,
"e": 2007,
"s": 1946,
"text": "If the file exists, then data is read successfully from file"
},
{
"code": null,
"e": 2037,
"s": 2007,
"text": "Append mode of opening a file"
},
{
"code": null,
"e": 2064,
"s": 2037,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2105,
"s": 2064,
"text": "FILE *fp;\nfp =fopen (\"sample.txt\", \"a\");"
},
{
"code": null,
"e": 2165,
"s": 2105,
"text": "If the file doesn’t exist, then a new file will be created."
},
{
"code": null,
"e": 2240,
"s": 2165,
"text": "If the file exists, the current content will be adding to the old content."
},
{
"code": null,
"e": 2293,
"s": 2240,
"text": "Following is the C program for operations on files −"
},
{
"code": null,
"e": 2304,
"s": 2293,
"text": " Live Demo"
},
{
"code": null,
"e": 3190,
"s": 2304,
"text": "//Program for copying the contents of one file into another file\n#include <stdio.h>\n#include <stdlib.h> // For exit()\nint main(){\n FILE *fptr1, *fptr2;\n char filename[100], c;\n printf(\"Enter the filename to open for reading \\n\");\n scanf(\"%s\",filename);\n // Open one file for reading\n fptr1 = fopen(filename, \"r\");\n if (fptr1 == NULL){\n printf(\"Cannot open file %s \\n\", filename);\n exit(0);\n }\n printf(\"Enter the filename to open for writing \\n\");\n scanf(\"%s\", filename);\n // Open another file for writing\n fptr2 = fopen(filename, \"w\");\n if (fptr2 == NULL){\n printf(\"Cannot open file %s \\n\", filename);\n exit(0);\n }\n // Read contents from file\n c = fgetc(fptr1);\n while (c != EOF){\n fputc(c, fptr2);\n c = fgetc(fptr1);\n }\n printf(\"\\nContents copied to %s\", filename);\n fclose(fptr1);\n fclose(fptr2);\n return 0;\n}"
},
{
"code": null,
"e": 3261,
"s": 3190,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3388,
"s": 3261,
"text": "Enter the filename to open for reading\nfile2.txt\nEnter the filename to open for writing\nfile1.txt\nContents copied to file1.txt"
}
] |
How to set a cookie and get a cookie with JavaScript? | The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
document.cookie = "key1=value1;key2=value2;expires=date";
Here the “expires” attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Try the following. It sets a customer name in an input cookie.
Live Demo
<html>
<head>
<script>
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.
You can try to run the following code to read a cookie −
Live Demo
<html>
<head>
<script>
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html> | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:"
},
{
"code": null,
"e": 1238,
"s": 1180,
"text": "document.cookie = \"key1=value1;key2=value2;expires=date\";"
},
{
"code": null,
"e": 1448,
"s": 1238,
"text": "Here the “expires” attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible."
},
{
"code": null,
"e": 1511,
"s": 1448,
"text": "Try the following. It sets a customer name in an input cookie."
},
{
"code": null,
"e": 1521,
"s": 1511,
"text": "Live Demo"
},
{
"code": null,
"e": 2230,
"s": 1521,
"text": "<html>\n <head>\n <script>\n <!--\n function WriteCookie() {\n if( document.myform.customer.value == \"\" ) {\n alert(\"Enter some value!\");\n return;\n }\n cookievalue= escape(document.myform.customer.value) + \";\";\n document.cookie=\"name=\" + cookievalue;\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script>\n </head>\n <body>\n <form name=\"myform\" action=\"\">\n Enter name: <input type=\"text\" name=\"customer\"/>\n <input type=\"button\" value=\"Set Cookie\" onclick=\"WriteCookie();\"/>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 2573,
"s": 2230,
"text": "Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value."
},
{
"code": null,
"e": 2630,
"s": 2573,
"text": "You can try to run the following code to read a cookie −"
},
{
"code": null,
"e": 2640,
"s": 2630,
"text": "Live Demo"
},
{
"code": null,
"e": 3546,
"s": 2640,
"text": "<html>\n <head>\n <script>\n <!--\n function ReadCookie() {\n var allcookies = document.cookie;\n document.write (\"All Cookies : \" + allcookies );\n // Get all the cookies pairs in an array\n cookiearray = allcookies.split(';');\n // Now take key value pair out of this array\n for(var i=0; i<cookiearray.length; i++) {\n name = cookiearray[i].split('=')[0];\n value = cookiearray[i].split('=')[1];\n document.write (\"Key is : \" + name + \" and Value is : \" + value);\n }\n }\n //-->\n </script>\n </head>\n <body>\n <form name=\"myform\" action=\"\">\n <p> click the following button and see the result:</p>\n <input type=\"button\" value=\"Get Cookie\" onclick=\"ReadCookie()\"/>\n </form>\n </body>\n</html>"
}
] |
How can I tell when a MySQL table was last updated? | We can know that with the help of the column name ‘UPDATED_TIME’ using information_schema.tables with WHERE clause.
Let us first create a table for our example.
mysql> create table MyISAMTableDemo
-> (
-> id int
-> );
Query OK, 0 rows affected (0.56 sec)
Inserting some records into table.
mysql> insert into MyISAMTableDemo values(1);
Query OK, 1 row affected (0.72 sec)
mysql> insert into MyISAMTableDemo values(2);
Query OK, 1 row affected (0.16 sec)
Syntax to know the last updated time.
SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'yourDatabaseName'
AND TABLE_NAME = 'yourTableName';
Let us implement the following query to get the last updated time.
mysql> SELECT UPDATE_TIME
-> FROM information_schema.tables
-> WHERE TABLE_SCHEMA = 'business'
-> AND TABLE_NAME = 'MyISAMTableDemo';
The following is the output.
+---------------------+
| UPDATE_TIME |
+---------------------+
| 2018-11-01 19:00:02 |
+---------------------+
1 row in set (0.08 sec) | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "We can know that with the help of the column name ‘UPDATED_TIME’ using information_schema.tables with WHERE clause."
},
{
"code": null,
"e": 1223,
"s": 1178,
"text": "Let us first create a table for our example."
},
{
"code": null,
"e": 1326,
"s": 1223,
"text": "mysql> create table MyISAMTableDemo\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.56 sec)"
},
{
"code": null,
"e": 1361,
"s": 1326,
"text": "Inserting some records into table."
},
{
"code": null,
"e": 1526,
"s": 1361,
"text": "mysql> insert into MyISAMTableDemo values(1);\nQuery OK, 1 row affected (0.72 sec)\n\nmysql> insert into MyISAMTableDemo values(2);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1564,
"s": 1526,
"text": "Syntax to know the last updated time."
},
{
"code": null,
"e": 1691,
"s": 1564,
"text": "SELECT UPDATE_TIME\nFROM information_schema.tables\nWHERE TABLE_SCHEMA = 'yourDatabaseName'\nAND TABLE_NAME = 'yourTableName';"
},
{
"code": null,
"e": 1758,
"s": 1691,
"text": "Let us implement the following query to get the last updated time."
},
{
"code": null,
"e": 1905,
"s": 1758,
"text": "mysql> SELECT UPDATE_TIME\n -> FROM information_schema.tables\n -> WHERE TABLE_SCHEMA = 'business'\n -> AND TABLE_NAME = 'MyISAMTableDemo';"
},
{
"code": null,
"e": 1934,
"s": 1905,
"text": "The following is the output."
},
{
"code": null,
"e": 2079,
"s": 1934,
"text": "+---------------------+\n| UPDATE_TIME |\n+---------------------+\n| 2018-11-01 19:00:02 |\n+---------------------+\n1 row in set (0.08 sec)\n"
}
] |
Differences between static and non-static variables in Java | A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
A static variable is also called a class variable and is common across the objects of the class and this variable can be accessed using class name as well.
Any variable of a class which is not static is called non-static variable or an instance variable.
Following are the important differences between static and non-static variable.
public class JavaTester {
public int counter = 0;
public static int staticCounter = 0;
public JavaTester(){
counter++;
staticCounter++;
}
public static void main(String args[]) {
JavaTester tester = new JavaTester();
JavaTester tester1 = new JavaTester();
JavaTester tester2 = new JavaTester();
System.out.println("Counter: " + tester2.counter);
System.out.println("Static Counter: " + tester2.staticCounter);
}
}
Counter: 1
Static Counter: 3 | [
{
"code": null,
"e": 1366,
"s": 1062,
"text": "A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 1522,
"s": 1366,
"text": "A static variable is also called a class variable and is common across the objects of the class and this variable can be accessed using class name as well."
},
{
"code": null,
"e": 1621,
"s": 1522,
"text": "Any variable of a class which is not static is called non-static variable or an instance variable."
},
{
"code": null,
"e": 1701,
"s": 1621,
"text": "Following are the important differences between static and non-static variable."
},
{
"code": null,
"e": 2175,
"s": 1701,
"text": "public class JavaTester {\n public int counter = 0;\n public static int staticCounter = 0;\n public JavaTester(){\n counter++;\n staticCounter++;\n }\n public static void main(String args[]) {\n JavaTester tester = new JavaTester();\n JavaTester tester1 = new JavaTester();\n JavaTester tester2 = new JavaTester();\n System.out.println(\"Counter: \" + tester2.counter);\n System.out.println(\"Static Counter: \" + tester2.staticCounter);\n }\n}"
},
{
"code": null,
"e": 2204,
"s": 2175,
"text": "Counter: 1\nStatic Counter: 3"
}
] |
How to alter a MySQL Column from varchar(30) to varchar(100)? | You need to use ALTER TABLE command along with MODIFY
The syntax is as follows
ALTER TABLE yourTableName MODIFY COLUMN yourColumnName varchar(100) NOT NULL;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table syntaxOfAlterCommandDemo
-> (
-> UserId int,
-> UserName varchar(30),
-> UserAge int,
-> UserCityName varchar(50)
-> );
Query OK, 0 rows affected (0.51 sec)
Let us check the description of the table.
The query is as follows
mysql> desc syntaxOfAlterCommandDemo;
The following is the output
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| UserId | int(11) | YES | | NULL | |
| UserName | varchar(30) | YES | | NULL | |
| UserAge | int(11) | YES | | NULL | |
| UserCityName | varchar(50) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)
Now let us change UserName column from varchar(30) to varchar(100). Remember, right now we have set the UserName column to varchar(30). The query is as follows to change the column
mysql> alter table syntaxOfAlterCommandDemo modify column UserName varchar(100) NOT NULL;
Query OK, 0 rows affected (1.36 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the table description once again.
The query is as follows
mysql> desc syntaxOfAlterCommandDemo;
The following is the output
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| UserId | int(11) | YES | | NULL | |
| UserName | varchar(100) | NO | | NULL | |
| UserAge | int(11) | YES | | NULL | |
| UserCityName | varchar(50) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
Look at the sample output above, the column UserName is now varchar(100). | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "You need to use ALTER TABLE command along with MODIFY"
},
{
"code": null,
"e": 1141,
"s": 1116,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 1219,
"s": 1141,
"text": "ALTER TABLE yourTableName MODIFY COLUMN yourColumnName varchar(100) NOT NULL;"
},
{
"code": null,
"e": 1316,
"s": 1219,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1511,
"s": 1316,
"text": "mysql> create table syntaxOfAlterCommandDemo\n -> (\n -> UserId int,\n -> UserName varchar(30),\n -> UserAge int,\n -> UserCityName varchar(50)\n -> );\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 1554,
"s": 1511,
"text": "Let us check the description of the table."
},
{
"code": null,
"e": 1578,
"s": 1554,
"text": "The query is as follows"
},
{
"code": null,
"e": 1616,
"s": 1578,
"text": "mysql> desc syntaxOfAlterCommandDemo;"
},
{
"code": null,
"e": 1644,
"s": 1616,
"text": "The following is the output"
},
{
"code": null,
"e": 2165,
"s": 1644,
"text": "+--------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+-------------+------+-----+---------+-------+\n| UserId | int(11) | YES | | NULL | |\n| UserName | varchar(30) | YES | | NULL | |\n| UserAge | int(11) | YES | | NULL | |\n| UserCityName | varchar(50) | YES | | NULL | |\n+--------------+-------------+------+-----+---------+-------+\n4 rows in set (0.04 sec)"
},
{
"code": null,
"e": 2346,
"s": 2165,
"text": "Now let us change UserName column from varchar(30) to varchar(100). Remember, right now we have set the UserName column to varchar(30). The query is as follows to change the column"
},
{
"code": null,
"e": 2510,
"s": 2346,
"text": "mysql> alter table syntaxOfAlterCommandDemo modify column UserName varchar(100) NOT NULL;\nQuery OK, 0 rows affected (1.36 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2557,
"s": 2510,
"text": "Let us check the table description once again."
},
{
"code": null,
"e": 2581,
"s": 2557,
"text": "The query is as follows"
},
{
"code": null,
"e": 2619,
"s": 2581,
"text": "mysql> desc syntaxOfAlterCommandDemo;"
},
{
"code": null,
"e": 2647,
"s": 2619,
"text": "The following is the output"
},
{
"code": null,
"e": 3176,
"s": 2647,
"text": "+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| UserId | int(11) | YES | | NULL | |\n| UserName | varchar(100) | NO | | NULL | |\n| UserAge | int(11) | YES | | NULL | |\n| UserCityName | varchar(50) | YES | | NULL | |\n+--------------+--------------+------+-----+---------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3250,
"s": 3176,
"text": "Look at the sample output above, the column UserName is now varchar(100)."
}
] |
Tryit Editor v3.7 | HTML Input types
Tryit: input type = range | [
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
How to count the total number of tables in a page in Selenium with python? | We can count the total number of tables in a page in Selenium with the
help of find_elements method. While working on any tables, we will always find
the tagname in the html code and its value should be table (<table>).
This characteristic is only applicable to tables on that particular page and to no
other types of UI elements like edit box, radio buttons and so on.
To retrieve all the elements with the tagname as a table we will use
find_elements_by_tag_name() method. This method returns a list of web elements
with the type of tagname specified in the method argument. In case there are no
matching elements, an empty list will be returned.
After the list of tables is fetched, in order to count its total numbers, we need to
get the size of that list. The size of the list can be obtained from the len() method
of the list data structure.
Finally this length is printed on the console.
driver.find_elements_by_tag_name("table")
Code Implementation for counting the number of tables.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to get the list of tables present on the web page
t = driver.find_elements_by_tag_name('table')
#print the count with the len method on console
print(len(t))
#to close the browser
driver.quit() | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "We can count the total number of tables in a page in Selenium with the\nhelp of find_elements method. While working on any tables, we will always find\nthe tagname in the html code and its value should be table (<table>)."
},
{
"code": null,
"e": 1432,
"s": 1282,
"text": "This characteristic is only applicable to tables on that particular page and to no\nother types of UI elements like edit box, radio buttons and so on."
},
{
"code": null,
"e": 1711,
"s": 1432,
"text": "To retrieve all the elements with the tagname as a table we will use\nfind_elements_by_tag_name() method. This method returns a list of web elements\nwith the type of tagname specified in the method argument. In case there are no\nmatching elements, an empty list will be returned."
},
{
"code": null,
"e": 1910,
"s": 1711,
"text": "After the list of tables is fetched, in order to count its total numbers, we need to\nget the size of that list. The size of the list can be obtained from the len() method\nof the list data structure."
},
{
"code": null,
"e": 1957,
"s": 1910,
"text": "Finally this length is printed on the console."
},
{
"code": null,
"e": 1999,
"s": 1957,
"text": "driver.find_elements_by_tag_name(\"table\")"
},
{
"code": null,
"e": 2054,
"s": 1999,
"text": "Code Implementation for counting the number of tables."
},
{
"code": null,
"e": 2530,
"s": 2054,
"text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to get the list of tables present on the web page\nt = driver.find_elements_by_tag_name('table')\n#print the count with the len method on console\nprint(len(t))\n#to close the browser\ndriver.quit()"
}
] |
Minimum Moves to Equal Array Elements in C++ | Suppose we have an array of size n, we have to find the minimum number of moves required to make all array elements the same, where a move means incrementing n - 1 elements by 1.
So, if the input is like [3,2,3,4], then the output will be 4.
To solve this, we will follow these steps −
n := size of nums
n := size of nums
if n is same as 0, then −return 0
if n is same as 0, then −
return 0
return 0
sort the array nums
sort the array nums
ans := 0
ans := 0
for initialize i := 0, when i < n, update (increase i by 1), do −ans := ans + nums[i] - nums[0]
for initialize i := 0, when i < n, update (increase i by 1), do −
ans := ans + nums[i] - nums[0]
ans := ans + nums[i] - nums[0]
return ans
return ans
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minMoves(vector<int>& nums) {
int n = nums.size();
if (n == 0)
return 0;
sort(nums.begin(), nums.end());
int ans = 0;
for (int i = 0; i < n; i++) {
ans += nums[i] - nums[0];
}
return ans;
}
};
main(){
Solution ob;
vector<int> v = {3,2,3,4};
cout << (ob.minMoves(v));
}
{3,2,3,4}
4 | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "Suppose we have an array of size n, we have to find the minimum number of moves required to make all array elements the same, where a move means incrementing n - 1 elements by 1."
},
{
"code": null,
"e": 1304,
"s": 1241,
"text": "So, if the input is like [3,2,3,4], then the output will be 4."
},
{
"code": null,
"e": 1348,
"s": 1304,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1366,
"s": 1348,
"text": "n := size of nums"
},
{
"code": null,
"e": 1384,
"s": 1366,
"text": "n := size of nums"
},
{
"code": null,
"e": 1418,
"s": 1384,
"text": "if n is same as 0, then −return 0"
},
{
"code": null,
"e": 1444,
"s": 1418,
"text": "if n is same as 0, then −"
},
{
"code": null,
"e": 1453,
"s": 1444,
"text": "return 0"
},
{
"code": null,
"e": 1462,
"s": 1453,
"text": "return 0"
},
{
"code": null,
"e": 1482,
"s": 1462,
"text": "sort the array nums"
},
{
"code": null,
"e": 1502,
"s": 1482,
"text": "sort the array nums"
},
{
"code": null,
"e": 1511,
"s": 1502,
"text": "ans := 0"
},
{
"code": null,
"e": 1520,
"s": 1511,
"text": "ans := 0"
},
{
"code": null,
"e": 1616,
"s": 1520,
"text": "for initialize i := 0, when i < n, update (increase i by 1), do −ans := ans + nums[i] - nums[0]"
},
{
"code": null,
"e": 1682,
"s": 1616,
"text": "for initialize i := 0, when i < n, update (increase i by 1), do −"
},
{
"code": null,
"e": 1713,
"s": 1682,
"text": "ans := ans + nums[i] - nums[0]"
},
{
"code": null,
"e": 1744,
"s": 1713,
"text": "ans := ans + nums[i] - nums[0]"
},
{
"code": null,
"e": 1755,
"s": 1744,
"text": "return ans"
},
{
"code": null,
"e": 1766,
"s": 1755,
"text": "return ans"
},
{
"code": null,
"e": 1838,
"s": 1766,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1849,
"s": 1838,
"text": " Live Demo"
},
{
"code": null,
"e": 2268,
"s": 1849,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int minMoves(vector<int>& nums) {\n int n = nums.size();\n if (n == 0)\n return 0;\n sort(nums.begin(), nums.end());\n int ans = 0;\n for (int i = 0; i < n; i++) {\n ans += nums[i] - nums[0];\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {3,2,3,4};\n cout << (ob.minMoves(v));\n}"
},
{
"code": null,
"e": 2278,
"s": 2268,
"text": "{3,2,3,4}"
},
{
"code": null,
"e": 2280,
"s": 2278,
"text": "4"
}
] |
Enum with Customized Value in Java | An enum in java represents a group of named constants. It can also have custom properties and methods.
Let us look at an example.
import java.lang.*;
// enum showing Mobile prices
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret = Mobile.Motorola;
System.out.println("MobileName = " + ret.name());
}
}
This will produce the following result −
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
MobileName = Motorola
Here we've added a price as field and showPrice() as method to Enum.
Here we've added a price as field and showPrice() as method to Enum.
We've assign custom values to enum using its constructor.
We've assign custom values to enum using its constructor. | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "An enum in java represents a group of named constants. It can also have custom properties and methods."
},
{
"code": null,
"e": 1192,
"s": 1165,
"text": "Let us look at an example."
},
{
"code": null,
"e": 1740,
"s": 1192,
"text": "import java.lang.*;\n\n// enum showing Mobile prices\nenum Mobile {\n Samsung(400), Nokia(250),Motorola(325);\n\n int price;\n Mobile(int p) {\n price = p;\n }\n int showPrice() {\n return price;\n }\n}\n\npublic class EnumDemo {\n public static void main(String args[]) {\n System.out.println(\"CellPhone List:\");\n\n for(Mobile m : Mobile.values()) {\n System.out.println(m + \" costs \" + m.showPrice() + \" dollars\");\n }\n\n Mobile ret = Mobile.Motorola;\n System.out.println(\"MobileName = \" + ret.name());\n }\n}"
},
{
"code": null,
"e": 1781,
"s": 1740,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1896,
"s": 1781,
"text": "CellPhone List:\nSamsung costs 400 dollars\nNokia costs 250 dollars\nMotorola costs 325 dollars\nMobileName = Motorola"
},
{
"code": null,
"e": 1965,
"s": 1896,
"text": "Here we've added a price as field and showPrice() as method to Enum."
},
{
"code": null,
"e": 2034,
"s": 1965,
"text": "Here we've added a price as field and showPrice() as method to Enum."
},
{
"code": null,
"e": 2092,
"s": 2034,
"text": "We've assign custom values to enum using its constructor."
},
{
"code": null,
"e": 2150,
"s": 2092,
"text": "We've assign custom values to enum using its constructor."
}
] |
How to Move an Image in Tkinter canvas with Arrow Keys? | Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can provide a dynamic attribute to the image defined in a Canvas widget by using the move() method.
Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the Image in the Canvas. We declare images globally in order to track the Image location in the Canvas.
We can follow these steps to make our image movable within the canvas,
First, define the Canvas widget and add images to it.
First, define the Canvas widget and add images to it.
Define the move() function to allow the image to be dynamic within the Canvas.
Define the move() function to allow the image to be dynamic within the Canvas.
Bind the Arrow Keys with the function that allows images to be moved within the Canvas.
Bind the Arrow Keys with the function that allows images to be moved within the Canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)
# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('favicon.ico'))
img = canvas.create_image(250, 120, anchor=NW, image=image)
def left(e):
x = -20
y = 0
canvas.move(img, x, y)
def right(e):
x = 20
y = 0
canvas.move(img, x, y)
def up(e):
x = 0
y = -20
canvas.move(img, x, y)
def down(e):
x = 0
y = 20
canvas.move(img, x, y)
# Bind the move function
win.bind("<Left>", left)
win.bind("<Right>", right)
win.bind("<Up>", up)
win.bind("<Down>", down)
win.mainloop()
Running the above code will display a window that contains an image that can be moved across the window using the arrow keys.
You can move the object on the canvas around with the Arrow keys. | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can provide a dynamic attribute to the image defined in a Canvas widget by using the move() method."
},
{
"code": null,
"e": 1508,
"s": 1313,
"text": "Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the Image in the Canvas. We declare images globally in order to track the Image location in the Canvas."
},
{
"code": null,
"e": 1579,
"s": 1508,
"text": "We can follow these steps to make our image movable within the canvas,"
},
{
"code": null,
"e": 1633,
"s": 1579,
"text": "First, define the Canvas widget and add images to it."
},
{
"code": null,
"e": 1687,
"s": 1633,
"text": "First, define the Canvas widget and add images to it."
},
{
"code": null,
"e": 1766,
"s": 1687,
"text": "Define the move() function to allow the image to be dynamic within the Canvas."
},
{
"code": null,
"e": 1845,
"s": 1766,
"text": "Define the move() function to allow the image to be dynamic within the Canvas."
},
{
"code": null,
"e": 1933,
"s": 1845,
"text": "Bind the Arrow Keys with the function that allows images to be moved within the Canvas."
},
{
"code": null,
"e": 2021,
"s": 1933,
"text": "Bind the Arrow Keys with the function that allows images to be moved within the Canvas."
},
{
"code": null,
"e": 2843,
"s": 2021,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a Canvas widget\ncanvas = Canvas(win, width=600, height=400, bg=\"white\")\ncanvas.pack(pady=20)\n\n# Add Images to Canvas widget\nimage = ImageTk.PhotoImage(Image.open('favicon.ico'))\nimg = canvas.create_image(250, 120, anchor=NW, image=image)\n\ndef left(e):\n x = -20\n y = 0\n canvas.move(img, x, y)\n\ndef right(e):\n x = 20\n y = 0\n canvas.move(img, x, y)\n\ndef up(e):\n x = 0\n y = -20\n canvas.move(img, x, y)\n\ndef down(e):\n x = 0\n y = 20\n canvas.move(img, x, y)\n\n# Bind the move function\nwin.bind(\"<Left>\", left)\nwin.bind(\"<Right>\", right)\nwin.bind(\"<Up>\", up)\nwin.bind(\"<Down>\", down)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2969,
"s": 2843,
"text": "Running the above code will display a window that contains an image that can be moved across the window using the arrow keys."
},
{
"code": null,
"e": 3035,
"s": 2969,
"text": "You can move the object on the canvas around with the Arrow keys."
}
] |
Markov Chain for music generation | by Alexander Osipenko | Towards Data Science | From this article, you will learn about the Markov Chain model and how it can be applied for the music generation.
Markov chain is a model that describes a sequence of possible events. This sequence needs to satisfied Markov assumption — the probability of the next state depends on a previous state and not on all previous states in a sequence.
It may sound like a simplification of the real cases. For example to applied Markov chain for the weather prediction, we need to make an assumption that weather tomorrow only depends on current weather and pretend that there are no other factors, like time of the year, e.t.c.
In spite this simplification in many cases, we will be able to generate useful predictions, but at the same time, we will be able to solve our task faster, by making it less computationally expensive.
Markov chain models have many applications in finance, natural language processing and anywhere where you have time series data.
There are plenty of great papers and blog posts explaineing Markov Chain. So without digging into theoretical details, let’s apply this model on practice! The most popular application of the Markov Chain is language and speech, for example, predict next word in a sentence. But what if we try to generate music?
Same as natural languages we may think about music as a sequence of notes. But because I play guitar I’ll be operating with chords. If we take chords sequence and learn its patternt we may find that certain chords may follow particular chords more often, and other chords rarely follow that chords. We will build our model to find and understand this pattern.
Take corpus of chordsCalculate probability distribution for chords to follow a particular chordDefine the first chord or make a random choiceMake a random choice of the next chord taking into an account probability distributionRepeat steps 4 for the generated chord...Stochastic music is awesome!
Take corpus of chords
Calculate probability distribution for chords to follow a particular chord
Define the first chord or make a random choice
Make a random choice of the next chord taking into an account probability distribution
Repeat steps 4 for the generated chord
...
Stochastic music is awesome!
For the data source, I prepared a CSV file with chords sequence that I took from one famous band from Liverpool. You can find this file on the GitHub.
Example of sequence:
['F', 'Em7', 'A7', 'Dm', 'Dm7', 'Bb', 'C7', 'F', 'C', 'Dm7',...]
First, we make bigrams:
['F Em7', 'Em7 A7', 'A7 Dm', 'Dm Dm7', 'Dm7 Bb', 'Bb C7', ...]
Now if I take chord F as initial chord in a sequence, what will be the probability for other chords to follow it?
There are 18 bigrams that start with chord F:
['F Em7', 'F C', 'F F', 'F Em7', 'F C', 'F A7sus4', 'F A7sus4', ...]
Then we’ll calculate the frequency of each unique bigram to appear in the sequence:
{'F Em7': 4, 'F C': 4, 'F F': 3, 'F A7sus4': 4, 'F Fsus4': 2, 'F G7': 1}
If we normalize it, we’ll get probabilities:
{'F Em7': 0.222, 'F C': 0.222, 'F F': 0.167, 'F A7sus4': 0.222, 'F Fsus4': 0.111, 'F G7': 0.056}
This often can be interpreted in the form of a graph:
Each node of this graph, except initial node F in the center, represents possible states that our sequence can achieve, in our case they are chords that may follow F. Some of the chords have higher probabilities than other, some chords can’t follow F chord at all, for example, Am, because there was no bigram than combine this chord with F.
Now, Markov Chain is a stochastic process, or random process is you prefer. In order to move to the next state, we will be choosing chord randomly but according to the probability distribution, in our case, that means that we are more likely to choice chord C than G7.
For a given chord F, we have 6 candidates for the next chord:
options>>> ['Em7', 'C', 'F', 'A7sus4', 'Fsus4', 'G7']
And each chord has its own probabilities accordingly:
probabilities>>> [0.222, 0.222, 0.167, 0.222, 0.111, 0.056]
Numpy since version 1.7.0 can perform random sampling according to probability distribution it was given, let’s use that:
import numpy as npchoise = np.random.choice(options, p=probabilities)
Let’s say our result of this random choice was Em7. Now we have a new state and can repeat the whole process again.
The overall workflow looks like this:
# Our current statechord = 'F'# create list of bigrams which stats with current chordbigrams_with_current_chord = [bigram for bigram in bigrams if bigram.split(' ')[0]==chord]# count appearance of each bigramcount_appearance = dict(Counter(bigrams_with_current_chord))# convert apperance into probabilitiesfor ngram in count_appearance.keys(): count_appearance[ngram] = count_appearance[ngram]/len(bigrams_with_current_chord)# create list of possible options for the next chordoptions = [key.split(' ')[1] for key in count_appearance.keys()]# create list of probability distributionprobabilities = list(count_appearance.values())# Make random predictionnp.random.choice(options, p=probabilities)
Because it’s a stochastic process each time you will run this model it will give you different results. For repeatability you can set seed like that:
np.random.seed(42)
We can summarize the whole process into two functions:
def predict_next_state(chord:str, data:list=bigrams): """Predict next chord based on current state.""" # create list of bigrams which stats with current chord bigrams_with_current_chord = [bigram for bigram in bigrams if bigram.split(' ')[0]==chord] # count appearance of each bigram count_appearance = dict(Counter(bigrams_with_current_chord)) # convert apperance into probabilities for ngram in count_appearance.keys(): count_appearance[ngram] = count_appearance[ngram]/len(bigrams_with_current_chord) # create list of possible options for the next chord options = [key.split(' ')[1] for key in count_appearance.keys()] # create list of probability distribution probabilities = list(count_appearance.values()) # return random prediction return np.random.choice(options, p=probabilities)def generate_sequence(chord:str=None, data:list=bigrams, length:int=30): """Generate sequence of defined length.""" # create list to store future chords chords = [] for n in range(length): # append next chord for the list chords.append(predict_next_state(chord, bigrams)) # use last chord in sequence to predict next chord chord = chords[-1] return chords
Now we can generate a sequence of the length we want:
generate_sequence('C')
Example of the sequence:
['Bb', 'Dm', 'C', 'Bb', 'C7', 'F', 'Em7', 'A7', 'Dm', 'Dm7', 'Bb', 'Dm', 'Gm6' ... ]
I’ve tried to play it on the guitar and it does sound like a song that band from the Liverpool may write. The only thing that missing is text, but we can use the same model trained on text corpus to generate text for a song :).
We only touched the tip of the iceberg with simple Markov Chain, the worlds of the stochastic model are so large, including Hidden Markov Chain, Markov Chain Monte Carlo, Hamiltonian Monte Carlo, and many others. But in the essence of each models same Markov assumption — next state depends upon current state and not on the previous sequence of states.
Because of this simple yet powerful rule, Markov chain models found applications in many areas and can be also successfully applied for the music generation.
One of the coolest things here is we will get different results based on a corpus we train our model. Train on a corpus from the Radiohead and model will generate chord sequences in a Radiohead style.
Eugene Seneta. “Markov and the creation of Markov chains” (2006) Original Paper PDFHayes, Brian. “First links in the Markov chain.” American Scientist 101.2 (2013): 252. Original Paper PDF
Eugene Seneta. “Markov and the creation of Markov chains” (2006) Original Paper PDF
Hayes, Brian. “First links in the Markov chain.” American Scientist 101.2 (2013): 252. Original Paper PDF | [
{
"code": null,
"e": 286,
"s": 171,
"text": "From this article, you will learn about the Markov Chain model and how it can be applied for the music generation."
},
{
"code": null,
"e": 517,
"s": 286,
"text": "Markov chain is a model that describes a sequence of possible events. This sequence needs to satisfied Markov assumption — the probability of the next state depends on a previous state and not on all previous states in a sequence."
},
{
"code": null,
"e": 794,
"s": 517,
"text": "It may sound like a simplification of the real cases. For example to applied Markov chain for the weather prediction, we need to make an assumption that weather tomorrow only depends on current weather and pretend that there are no other factors, like time of the year, e.t.c."
},
{
"code": null,
"e": 995,
"s": 794,
"text": "In spite this simplification in many cases, we will be able to generate useful predictions, but at the same time, we will be able to solve our task faster, by making it less computationally expensive."
},
{
"code": null,
"e": 1124,
"s": 995,
"text": "Markov chain models have many applications in finance, natural language processing and anywhere where you have time series data."
},
{
"code": null,
"e": 1436,
"s": 1124,
"text": "There are plenty of great papers and blog posts explaineing Markov Chain. So without digging into theoretical details, let’s apply this model on practice! The most popular application of the Markov Chain is language and speech, for example, predict next word in a sentence. But what if we try to generate music?"
},
{
"code": null,
"e": 1796,
"s": 1436,
"text": "Same as natural languages we may think about music as a sequence of notes. But because I play guitar I’ll be operating with chords. If we take chords sequence and learn its patternt we may find that certain chords may follow particular chords more often, and other chords rarely follow that chords. We will build our model to find and understand this pattern."
},
{
"code": null,
"e": 2093,
"s": 1796,
"text": "Take corpus of chordsCalculate probability distribution for chords to follow a particular chordDefine the first chord or make a random choiceMake a random choice of the next chord taking into an account probability distributionRepeat steps 4 for the generated chord...Stochastic music is awesome!"
},
{
"code": null,
"e": 2115,
"s": 2093,
"text": "Take corpus of chords"
},
{
"code": null,
"e": 2190,
"s": 2115,
"text": "Calculate probability distribution for chords to follow a particular chord"
},
{
"code": null,
"e": 2237,
"s": 2190,
"text": "Define the first chord or make a random choice"
},
{
"code": null,
"e": 2324,
"s": 2237,
"text": "Make a random choice of the next chord taking into an account probability distribution"
},
{
"code": null,
"e": 2363,
"s": 2324,
"text": "Repeat steps 4 for the generated chord"
},
{
"code": null,
"e": 2367,
"s": 2363,
"text": "..."
},
{
"code": null,
"e": 2396,
"s": 2367,
"text": "Stochastic music is awesome!"
},
{
"code": null,
"e": 2547,
"s": 2396,
"text": "For the data source, I prepared a CSV file with chords sequence that I took from one famous band from Liverpool. You can find this file on the GitHub."
},
{
"code": null,
"e": 2568,
"s": 2547,
"text": "Example of sequence:"
},
{
"code": null,
"e": 2633,
"s": 2568,
"text": "['F', 'Em7', 'A7', 'Dm', 'Dm7', 'Bb', 'C7', 'F', 'C', 'Dm7',...]"
},
{
"code": null,
"e": 2657,
"s": 2633,
"text": "First, we make bigrams:"
},
{
"code": null,
"e": 2720,
"s": 2657,
"text": "['F Em7', 'Em7 A7', 'A7 Dm', 'Dm Dm7', 'Dm7 Bb', 'Bb C7', ...]"
},
{
"code": null,
"e": 2834,
"s": 2720,
"text": "Now if I take chord F as initial chord in a sequence, what will be the probability for other chords to follow it?"
},
{
"code": null,
"e": 2880,
"s": 2834,
"text": "There are 18 bigrams that start with chord F:"
},
{
"code": null,
"e": 2949,
"s": 2880,
"text": "['F Em7', 'F C', 'F F', 'F Em7', 'F C', 'F A7sus4', 'F A7sus4', ...]"
},
{
"code": null,
"e": 3033,
"s": 2949,
"text": "Then we’ll calculate the frequency of each unique bigram to appear in the sequence:"
},
{
"code": null,
"e": 3106,
"s": 3033,
"text": "{'F Em7': 4, 'F C': 4, 'F F': 3, 'F A7sus4': 4, 'F Fsus4': 2, 'F G7': 1}"
},
{
"code": null,
"e": 3151,
"s": 3106,
"text": "If we normalize it, we’ll get probabilities:"
},
{
"code": null,
"e": 3248,
"s": 3151,
"text": "{'F Em7': 0.222, 'F C': 0.222, 'F F': 0.167, 'F A7sus4': 0.222, 'F Fsus4': 0.111, 'F G7': 0.056}"
},
{
"code": null,
"e": 3302,
"s": 3248,
"text": "This often can be interpreted in the form of a graph:"
},
{
"code": null,
"e": 3644,
"s": 3302,
"text": "Each node of this graph, except initial node F in the center, represents possible states that our sequence can achieve, in our case they are chords that may follow F. Some of the chords have higher probabilities than other, some chords can’t follow F chord at all, for example, Am, because there was no bigram than combine this chord with F."
},
{
"code": null,
"e": 3913,
"s": 3644,
"text": "Now, Markov Chain is a stochastic process, or random process is you prefer. In order to move to the next state, we will be choosing chord randomly but according to the probability distribution, in our case, that means that we are more likely to choice chord C than G7."
},
{
"code": null,
"e": 3975,
"s": 3913,
"text": "For a given chord F, we have 6 candidates for the next chord:"
},
{
"code": null,
"e": 4029,
"s": 3975,
"text": "options>>> ['Em7', 'C', 'F', 'A7sus4', 'Fsus4', 'G7']"
},
{
"code": null,
"e": 4083,
"s": 4029,
"text": "And each chord has its own probabilities accordingly:"
},
{
"code": null,
"e": 4143,
"s": 4083,
"text": "probabilities>>> [0.222, 0.222, 0.167, 0.222, 0.111, 0.056]"
},
{
"code": null,
"e": 4265,
"s": 4143,
"text": "Numpy since version 1.7.0 can perform random sampling according to probability distribution it was given, let’s use that:"
},
{
"code": null,
"e": 4335,
"s": 4265,
"text": "import numpy as npchoise = np.random.choice(options, p=probabilities)"
},
{
"code": null,
"e": 4451,
"s": 4335,
"text": "Let’s say our result of this random choice was Em7. Now we have a new state and can repeat the whole process again."
},
{
"code": null,
"e": 4489,
"s": 4451,
"text": "The overall workflow looks like this:"
},
{
"code": null,
"e": 5187,
"s": 4489,
"text": "# Our current statechord = 'F'# create list of bigrams which stats with current chordbigrams_with_current_chord = [bigram for bigram in bigrams if bigram.split(' ')[0]==chord]# count appearance of each bigramcount_appearance = dict(Counter(bigrams_with_current_chord))# convert apperance into probabilitiesfor ngram in count_appearance.keys(): count_appearance[ngram] = count_appearance[ngram]/len(bigrams_with_current_chord)# create list of possible options for the next chordoptions = [key.split(' ')[1] for key in count_appearance.keys()]# create list of probability distributionprobabilities = list(count_appearance.values())# Make random predictionnp.random.choice(options, p=probabilities)"
},
{
"code": null,
"e": 5337,
"s": 5187,
"text": "Because it’s a stochastic process each time you will run this model it will give you different results. For repeatability you can set seed like that:"
},
{
"code": null,
"e": 5356,
"s": 5337,
"text": "np.random.seed(42)"
},
{
"code": null,
"e": 5411,
"s": 5356,
"text": "We can summarize the whole process into two functions:"
},
{
"code": null,
"e": 6645,
"s": 5411,
"text": "def predict_next_state(chord:str, data:list=bigrams): \"\"\"Predict next chord based on current state.\"\"\" # create list of bigrams which stats with current chord bigrams_with_current_chord = [bigram for bigram in bigrams if bigram.split(' ')[0]==chord] # count appearance of each bigram count_appearance = dict(Counter(bigrams_with_current_chord)) # convert apperance into probabilities for ngram in count_appearance.keys(): count_appearance[ngram] = count_appearance[ngram]/len(bigrams_with_current_chord) # create list of possible options for the next chord options = [key.split(' ')[1] for key in count_appearance.keys()] # create list of probability distribution probabilities = list(count_appearance.values()) # return random prediction return np.random.choice(options, p=probabilities)def generate_sequence(chord:str=None, data:list=bigrams, length:int=30): \"\"\"Generate sequence of defined length.\"\"\" # create list to store future chords chords = [] for n in range(length): # append next chord for the list chords.append(predict_next_state(chord, bigrams)) # use last chord in sequence to predict next chord chord = chords[-1] return chords"
},
{
"code": null,
"e": 6699,
"s": 6645,
"text": "Now we can generate a sequence of the length we want:"
},
{
"code": null,
"e": 6722,
"s": 6699,
"text": "generate_sequence('C')"
},
{
"code": null,
"e": 6747,
"s": 6722,
"text": "Example of the sequence:"
},
{
"code": null,
"e": 6832,
"s": 6747,
"text": "['Bb', 'Dm', 'C', 'Bb', 'C7', 'F', 'Em7', 'A7', 'Dm', 'Dm7', 'Bb', 'Dm', 'Gm6' ... ]"
},
{
"code": null,
"e": 7060,
"s": 6832,
"text": "I’ve tried to play it on the guitar and it does sound like a song that band from the Liverpool may write. The only thing that missing is text, but we can use the same model trained on text corpus to generate text for a song :)."
},
{
"code": null,
"e": 7414,
"s": 7060,
"text": "We only touched the tip of the iceberg with simple Markov Chain, the worlds of the stochastic model are so large, including Hidden Markov Chain, Markov Chain Monte Carlo, Hamiltonian Monte Carlo, and many others. But in the essence of each models same Markov assumption — next state depends upon current state and not on the previous sequence of states."
},
{
"code": null,
"e": 7572,
"s": 7414,
"text": "Because of this simple yet powerful rule, Markov chain models found applications in many areas and can be also successfully applied for the music generation."
},
{
"code": null,
"e": 7773,
"s": 7572,
"text": "One of the coolest things here is we will get different results based on a corpus we train our model. Train on a corpus from the Radiohead and model will generate chord sequences in a Radiohead style."
},
{
"code": null,
"e": 7962,
"s": 7773,
"text": "Eugene Seneta. “Markov and the creation of Markov chains” (2006) Original Paper PDFHayes, Brian. “First links in the Markov chain.” American Scientist 101.2 (2013): 252. Original Paper PDF"
},
{
"code": null,
"e": 8046,
"s": 7962,
"text": "Eugene Seneta. “Markov and the creation of Markov chains” (2006) Original Paper PDF"
}
] |
Check for Children Sum Property in a Binary Tree - GeeksforGeeks | 24 Nov, 2021
Given a binary tree, write a function that returns true if the tree satisfies below property. For every node, data value must be equal to sum of data values in left and right children. Consider data value as 0 for NULL children. Below tree is an example
Algorithm: Traverse the given binary tree. For each node check (recursively) if the node and both its children satisfy the Children Sum Property, if so then return true else return false.Implementation:
C++
C
Java
Python3
C#
Javascript
/* Program to check children sum property */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, leftchild and right child */struct node{ int data; struct node* left; struct node* right;}; /* returns 1 if children sum property holdsfor the given node and both of its children*/int isSumProperty(struct node* node){ /* left_data is left child data and right_data is for right child data*/ int sum = 0; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if(node->left != NULL) sum += node->left->data; /* If right child is not present then 0 is used as data of right child */ if(node->right != NULL) sum+ = node->right->data; /* if the node and both of its children satisfy the property return 1 else 0*/ return ((node->data == sum)&& isSumProperty(node->left) && isSumProperty(node->right)) }} /*Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver Codeint main(){ struct node *root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if(isSumProperty(root)) cout << "The given tree satisfies " << "the children sum property "; else cout << "The given tree does not satisfy " << "the children sum property "; getchar(); return 0;}// This code is contributed by Akanksha Rai
/* Program to check children sum property */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* returns 1 if children sum property holds for the given node and both of its children*/int isSumProperty(struct node* node){ /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if(node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if(node->right != NULL) right_data = node->right->data; /* if the node and both of its children satisfy the property return 1 else 0*/ if((node->data == left_data + right_data)&& isSumProperty(node->left) && isSumProperty(node->right)) return 1; else return 0; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if(isSumProperty(root)) printf("The given tree satisfies the children sum property "); else printf("The given tree does not satisfy the children sum property "); getchar(); return 0;}
// Java program to check children sum property /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int d) { data = d; left = right = null; }} class BinaryTree{ Node root; /* returns 1 if children sum property holds for the given node and both of its children*/ int isSumProperty(Node node) { /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left)!=0) && isSumProperty(node.right)!=0) return 1; else return 0; } } /* driver program to test the above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.right = new Node(2); if (tree.isSumProperty(tree.root) != 0) System.out.println("The given tree satisfies children" + " sum property"); else System.out.println("The given tree does not satisfy children" + " sum property"); }}
# Python3 program to check children# sum property # Helper class that allocates a new# node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # returns 1 if children sum property# holds for the given node and both# of its childrendef isSumProperty(node): # left_data is left child data and # right_data is for right child data left_data = 0 right_data = 0 # If node is None or it's a leaf # node then return true if(node == None or (node.left == None and node.right == None)): return 1 else: # If left child is not present then # 0 is used as data of left child if(node.left != None): left_data = node.left.data # If right child is not present then # 0 is used as data of right child if(node.right != None): right_data = node.right.data # if the node and both of its children # satisfy the property return 1 else 0 if((node.data == left_data + right_data) and isSumProperty(node.left) and isSumProperty(node.right)): return 1 else: return 0 # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) root.right.right = newNode(2) if(isSumProperty(root)): print("The given tree satisfies the", "children sum property ") else: print("The given tree does not satisfy", "the children sum property ") # This code is contributed by PranchalK
// C# program to check children sum propertyusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} class GFG{public Node root; /* returns 1 if children sum property holdsfor the given node and both of its children*/public virtual int isSumProperty(Node node){ /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) { return 1; } else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) { left_data = node.left.data; } /* If right child is not present then 0 is used as data of right child */ if (node.right != null) { right_data = node.right.data; } /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left) != 0) && isSumProperty(node.right) != 0) { return 1; } else { return 0; } }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.right = new Node(2); if (tree.isSumProperty(tree.root) != 0) { Console.WriteLine("The given tree satisfies" + " children sum property"); } else { Console.WriteLine("The given tree does not" + " satisfy children sum property"); }}} // This code is contributed by Shrikant13
<script> // JavaScript program to check children sum property class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* returns 1 if children sum property holds for the given node and both of its children*/ function isSumProperty(node) { /* left_data is left child data and right_data is for right child data*/ let left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left)!=0) && isSumProperty(node.right)!=0) return 1; else return 0; } } root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.right = new Node(2); if (isSumProperty(root) != 0) document.write("The given tree satisfies the children" + " sum property"); else document.write("The given tree does not satisfy children" + " sum property"); </script>
Output:
The given tree satisfies the children sum property
Time Complexity: O(n), we are doing a complete traversal of the tree.
YouTubeGeeksforGeeks500K subscribersCheck for Children Sum Property in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=FrLT_RtbbIQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
As an exercise, extend the above question for an n-ary tree.This question was asked by Shekhar.Please write comments if you find any bug in the above algorithm or a better way to solve the same problem.
shrikanth13
PranchalKatiyar
Akanksha_Rai
rameshtravel07
banavath santhosh
Accolite
Amazon
Tree
Accolite
Amazon
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Tree | Set 2 (Properties)
Decision Tree
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
Insertion in a Binary Tree in level order | [
{
"code": null,
"e": 24965,
"s": 24937,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25220,
"s": 24965,
"text": "Given a binary tree, write a function that returns true if the tree satisfies below property. For every node, data value must be equal to sum of data values in left and right children. Consider data value as 0 for NULL children. Below tree is an example "
},
{
"code": null,
"e": 25426,
"s": 25222,
"text": "Algorithm: Traverse the given binary tree. For each node check (recursively) if the node and both its children satisfy the Children Sum Property, if so then return true else return false.Implementation: "
},
{
"code": null,
"e": 25430,
"s": 25426,
"text": "C++"
},
{
"code": null,
"e": 25432,
"s": 25430,
"text": "C"
},
{
"code": null,
"e": 25437,
"s": 25432,
"text": "Java"
},
{
"code": null,
"e": 25445,
"s": 25437,
"text": "Python3"
},
{
"code": null,
"e": 25448,
"s": 25445,
"text": "C#"
},
{
"code": null,
"e": 25459,
"s": 25448,
"text": "Javascript"
},
{
"code": "/* Program to check children sum property */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, leftchild and right child */struct node{ int data; struct node* left; struct node* right;}; /* returns 1 if children sum property holdsfor the given node and both of its children*/int isSumProperty(struct node* node){ /* left_data is left child data and right_data is for right child data*/ int sum = 0; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if(node->left != NULL) sum += node->left->data; /* If right child is not present then 0 is used as data of right child */ if(node->right != NULL) sum+ = node->right->data; /* if the node and both of its children satisfy the property return 1 else 0*/ return ((node->data == sum)&& isSumProperty(node->left) && isSumProperty(node->right)) }} /*Helper function that allocates a new nodewith the given data and NULL left and rightpointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver Codeint main(){ struct node *root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if(isSumProperty(root)) cout << \"The given tree satisfies \" << \"the children sum property \"; else cout << \"The given tree does not satisfy \" << \"the children sum property \"; getchar(); return 0;}// This code is contributed by Akanksha Rai",
"e": 27415,
"s": 25459,
"text": null
},
{
"code": "/* Program to check children sum property */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left; struct node* right;}; /* returns 1 if children sum property holds for the given node and both of its children*/int isSumProperty(struct node* node){ /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if(node == NULL || (node->left == NULL && node->right == NULL)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if(node->left != NULL) left_data = node->left->data; /* If right child is not present then 0 is used as data of right child */ if(node->right != NULL) right_data = node->right->data; /* if the node and both of its children satisfy the property return 1 else 0*/ if((node->data == left_data + right_data)&& isSumProperty(node->left) && isSumProperty(node->right)) return 1; else return 0; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above function */int main(){ struct node *root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if(isSumProperty(root)) printf(\"The given tree satisfies the children sum property \"); else printf(\"The given tree does not satisfy the children sum property \"); getchar(); return 0;}",
"e": 29303,
"s": 27415,
"text": null
},
{
"code": "// Java program to check children sum property /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int d) { data = d; left = right = null; }} class BinaryTree{ Node root; /* returns 1 if children sum property holds for the given node and both of its children*/ int isSumProperty(Node node) { /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left)!=0) && isSumProperty(node.right)!=0) return 1; else return 0; } } /* driver program to test the above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.right = new Node(2); if (tree.isSumProperty(tree.root) != 0) System.out.println(\"The given tree satisfies children\" + \" sum property\"); else System.out.println(\"The given tree does not satisfy children\" + \" sum property\"); }}",
"e": 31453,
"s": 29303,
"text": null
},
{
"code": "# Python3 program to check children# sum property # Helper class that allocates a new# node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None # returns 1 if children sum property# holds for the given node and both# of its childrendef isSumProperty(node): # left_data is left child data and # right_data is for right child data left_data = 0 right_data = 0 # If node is None or it's a leaf # node then return true if(node == None or (node.left == None and node.right == None)): return 1 else: # If left child is not present then # 0 is used as data of left child if(node.left != None): left_data = node.left.data # If right child is not present then # 0 is used as data of right child if(node.right != None): right_data = node.right.data # if the node and both of its children # satisfy the property return 1 else 0 if((node.data == left_data + right_data) and isSumProperty(node.left) and isSumProperty(node.right)): return 1 else: return 0 # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) root.right.right = newNode(2) if(isSumProperty(root)): print(\"The given tree satisfies the\", \"children sum property \") else: print(\"The given tree does not satisfy\", \"the children sum property \") # This code is contributed by PranchalK",
"e": 33241,
"s": 31453,
"text": null
},
{
"code": "// C# program to check children sum propertyusing System; /* A binary tree node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} class GFG{public Node root; /* returns 1 if children sum property holdsfor the given node and both of its children*/public virtual int isSumProperty(Node node){ /* left_data is left child data and right_data is for right child data*/ int left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) { return 1; } else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) { left_data = node.left.data; } /* If right child is not present then 0 is used as data of right child */ if (node.right != null) { right_data = node.right.data; } /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left) != 0) && isSumProperty(node.right) != 0) { return 1; } else { return 0; } }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(5); tree.root.right.right = new Node(2); if (tree.isSumProperty(tree.root) != 0) { Console.WriteLine(\"The given tree satisfies\" + \" children sum property\"); } else { Console.WriteLine(\"The given tree does not\" + \" satisfy children sum property\"); }}} // This code is contributed by Shrikant13",
"e": 35322,
"s": 33241,
"text": null
},
{
"code": "<script> // JavaScript program to check children sum property class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* returns 1 if children sum property holds for the given node and both of its children*/ function isSumProperty(node) { /* left_data is left child data and right_data is for right child data*/ let left_data = 0, right_data = 0; /* If node is NULL or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if (node.left != null) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null) right_data = node.right.data; /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == left_data + right_data) && (isSumProperty(node.left)!=0) && isSumProperty(node.right)!=0) return 1; else return 0; } } root = new Node(10); root.left = new Node(8); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(5); root.right.right = new Node(2); if (isSumProperty(root) != 0) document.write(\"The given tree satisfies the children\" + \" sum property\"); else document.write(\"The given tree does not satisfy children\" + \" sum property\"); </script>",
"e": 37213,
"s": 35322,
"text": null
},
{
"code": null,
"e": 37223,
"s": 37213,
"text": "Output: "
},
{
"code": null,
"e": 37275,
"s": 37223,
"text": "The given tree satisfies the children sum property "
},
{
"code": null,
"e": 37346,
"s": 37275,
"text": "Time Complexity: O(n), we are doing a complete traversal of the tree. "
},
{
"code": null,
"e": 38193,
"s": 37346,
"text": "YouTubeGeeksforGeeks500K subscribersCheck for Children Sum Property in a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=FrLT_RtbbIQ\" 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": 38397,
"s": 38193,
"text": "As an exercise, extend the above question for an n-ary tree.This question was asked by Shekhar.Please write comments if you find any bug in the above algorithm or a better way to solve the same problem. "
},
{
"code": null,
"e": 38409,
"s": 38397,
"text": "shrikanth13"
},
{
"code": null,
"e": 38425,
"s": 38409,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 38438,
"s": 38425,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 38453,
"s": 38438,
"text": "rameshtravel07"
},
{
"code": null,
"e": 38471,
"s": 38453,
"text": "banavath santhosh"
},
{
"code": null,
"e": 38480,
"s": 38471,
"text": "Accolite"
},
{
"code": null,
"e": 38487,
"s": 38480,
"text": "Amazon"
},
{
"code": null,
"e": 38492,
"s": 38487,
"text": "Tree"
},
{
"code": null,
"e": 38501,
"s": 38492,
"text": "Accolite"
},
{
"code": null,
"e": 38508,
"s": 38501,
"text": "Amazon"
},
{
"code": null,
"e": 38513,
"s": 38508,
"text": "Tree"
},
{
"code": null,
"e": 38611,
"s": 38513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38620,
"s": 38611,
"text": "Comments"
},
{
"code": null,
"e": 38633,
"s": 38620,
"text": "Old Comments"
},
{
"code": null,
"e": 38666,
"s": 38633,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 38680,
"s": 38666,
"text": "Decision Tree"
},
{
"code": null,
"e": 38740,
"s": 38680,
"text": "Inorder Tree Traversal without recursion and without stack!"
},
{
"code": null,
"e": 38798,
"s": 38740,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 38881,
"s": 38798,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 38917,
"s": 38881,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38965,
"s": 38917,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 39000,
"s": 38965,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 39027,
"s": 39000,
"text": "BFS vs DFS for Binary Tree"
}
] |
Optimize E-Commerce Last-Mile Delivery with Python | by Samir Saci | Towards Data Science | If you travel to first and second-tier cities of China, you will find on the street many delivery drivers (Chinese: 快递).
They take the parcels from small warehouses called customer service centres (Chinese:客户服务中心) located in each neighbourhood and deliver them to the final customers.
These centres are key elements of the Logistics Network of the major courier companies in China. They provide a large geographical coverage for last-mile delivery and a huge competitive advantage by offering the best service level and delivery lead time in the market.
Before arriving at your door, your parcel will be picked from the vendor’s warehouse, transit through several regional distribution centres and will finally arrive at the service centre of your neighbourhood.
When your parcel arrives at the centre, you will receive a notification on your phone to inform you that a courier will deliver your parcel during the day.
This article will present a solution to optimize the last-mile delivery from these centres to reduce the costs and ensure a uniform distribution of the workload to each driver.
You are a manager in a local service centre with
4 drivers in your team
15 parcel capacity per vehicle
16 destinations to cover in the neighbourhood named Dj with j in [1, 16]
D0 is the centre
1 route per driver
To build your model, you need to provide a distance matrix M as inputs defined by
M(i, j) with i, j in [0, 16]
M(i, j) = distance between Di and Dj
This distance matrix will be loaded from an Excel file. You can find an example for this scenario here: Link
We will use here a python list with the first value at zero (because you don’t deliver anything in the centre)
Demand = [0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8]
Deliver all parcels with a minimum number of drivers
Optimize the routing to minimize the distance covered per route
Results
Route for driver 0 0 Parcels(0) -> 4 Parcels(4) -> 3 Parcels(6) -> 1 Parcels(7) -> 7 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 1 0 Parcels(0) -> 14 Parcels(4) -> 16 Parcels(12) -> 10 Parcels(14) -> 9 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 2 0 Parcels(0) -> 12 Parcels(2) -> 11 Parcels(3) -> 15 Parcels(11) -> 13 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 3 0 Parcels(0) -> 8 Parcels(8) -> 2 Parcels(9) -> 6 Parcels(13) -> 5 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Total distance of all routes: 6,208 (m)Parcels Delivered: 60/60
Based on these results, you can assign each of your four drivers a route that has the same total distance
100% of parcels are delivered with a minimum distance covered
Drivers’ vehicles are loaded to their maximum capacity (15/15)
Using this model helps you to ensure that your drivers, who are paid a fixed amount by delivery, will be fairly assigned to a route. You will avoid the issues of having drivers complaining because they have longer routes than their colleagues.
Moreover, you are using your resources at their maximum capacity.
samirsaci.com
Capacitated vehicle routing problem (CVRP) with Google OR-Tools
OR-Tools is an open-source collection of Google with tools for combinatorial optimization. The objective is to find the best solution out of a very large set of possible solutions.
Let us try to use this library to build the optimal routes.
You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci
This model can help the centre manager to
Optimize his fleet with full utilization of his drivers and vehicles
Ensure that the workload is equally distributed among each driver
Question:
What could be the results with higher capacity (boxes) per driver?
What could be the results if we have a weight or volume constraint?
I let you test it and share your results (or questions) in the comment area.
Have a look at my blog: https://samirsaci.com
[1] Google AI, Google OR-Tools Library, Link | [
{
"code": null,
"e": 292,
"s": 171,
"text": "If you travel to first and second-tier cities of China, you will find on the street many delivery drivers (Chinese: 快递)."
},
{
"code": null,
"e": 456,
"s": 292,
"text": "They take the parcels from small warehouses called customer service centres (Chinese:客户服务中心) located in each neighbourhood and deliver them to the final customers."
},
{
"code": null,
"e": 725,
"s": 456,
"text": "These centres are key elements of the Logistics Network of the major courier companies in China. They provide a large geographical coverage for last-mile delivery and a huge competitive advantage by offering the best service level and delivery lead time in the market."
},
{
"code": null,
"e": 934,
"s": 725,
"text": "Before arriving at your door, your parcel will be picked from the vendor’s warehouse, transit through several regional distribution centres and will finally arrive at the service centre of your neighbourhood."
},
{
"code": null,
"e": 1090,
"s": 934,
"text": "When your parcel arrives at the centre, you will receive a notification on your phone to inform you that a courier will deliver your parcel during the day."
},
{
"code": null,
"e": 1267,
"s": 1090,
"text": "This article will present a solution to optimize the last-mile delivery from these centres to reduce the costs and ensure a uniform distribution of the workload to each driver."
},
{
"code": null,
"e": 1316,
"s": 1267,
"text": "You are a manager in a local service centre with"
},
{
"code": null,
"e": 1339,
"s": 1316,
"text": "4 drivers in your team"
},
{
"code": null,
"e": 1370,
"s": 1339,
"text": "15 parcel capacity per vehicle"
},
{
"code": null,
"e": 1443,
"s": 1370,
"text": "16 destinations to cover in the neighbourhood named Dj with j in [1, 16]"
},
{
"code": null,
"e": 1460,
"s": 1443,
"text": "D0 is the centre"
},
{
"code": null,
"e": 1479,
"s": 1460,
"text": "1 route per driver"
},
{
"code": null,
"e": 1561,
"s": 1479,
"text": "To build your model, you need to provide a distance matrix M as inputs defined by"
},
{
"code": null,
"e": 1590,
"s": 1561,
"text": "M(i, j) with i, j in [0, 16]"
},
{
"code": null,
"e": 1627,
"s": 1590,
"text": "M(i, j) = distance between Di and Dj"
},
{
"code": null,
"e": 1736,
"s": 1627,
"text": "This distance matrix will be loaded from an Excel file. You can find an example for this scenario here: Link"
},
{
"code": null,
"e": 1847,
"s": 1736,
"text": "We will use here a python list with the first value at zero (because you don’t deliver anything in the centre)"
},
{
"code": null,
"e": 1908,
"s": 1847,
"text": "Demand = [0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8]"
},
{
"code": null,
"e": 1961,
"s": 1908,
"text": "Deliver all parcels with a minimum number of drivers"
},
{
"code": null,
"e": 2025,
"s": 1961,
"text": "Optimize the routing to minimize the distance covered per route"
},
{
"code": null,
"e": 2033,
"s": 2025,
"text": "Results"
},
{
"code": null,
"e": 2828,
"s": 2033,
"text": "Route for driver 0 0 Parcels(0) -> 4 Parcels(4) -> 3 Parcels(6) -> 1 Parcels(7) -> 7 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 1 0 Parcels(0) -> 14 Parcels(4) -> 16 Parcels(12) -> 10 Parcels(14) -> 9 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 2 0 Parcels(0) -> 12 Parcels(2) -> 11 Parcels(3) -> 15 Parcels(11) -> 13 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Route for driver 3 0 Parcels(0) -> 8 Parcels(8) -> 2 Parcels(9) -> 6 Parcels(13) -> 5 Parcels(15) -> 0 Parcels(15)Distance of the route: 1552 (m)Parcels Delivered: 15 (parcels)Total distance of all routes: 6,208 (m)Parcels Delivered: 60/60"
},
{
"code": null,
"e": 2934,
"s": 2828,
"text": "Based on these results, you can assign each of your four drivers a route that has the same total distance"
},
{
"code": null,
"e": 2996,
"s": 2934,
"text": "100% of parcels are delivered with a minimum distance covered"
},
{
"code": null,
"e": 3059,
"s": 2996,
"text": "Drivers’ vehicles are loaded to their maximum capacity (15/15)"
},
{
"code": null,
"e": 3303,
"s": 3059,
"text": "Using this model helps you to ensure that your drivers, who are paid a fixed amount by delivery, will be fairly assigned to a route. You will avoid the issues of having drivers complaining because they have longer routes than their colleagues."
},
{
"code": null,
"e": 3369,
"s": 3303,
"text": "Moreover, you are using your resources at their maximum capacity."
},
{
"code": null,
"e": 3383,
"s": 3369,
"text": "samirsaci.com"
},
{
"code": null,
"e": 3447,
"s": 3383,
"text": "Capacitated vehicle routing problem (CVRP) with Google OR-Tools"
},
{
"code": null,
"e": 3628,
"s": 3447,
"text": "OR-Tools is an open-source collection of Google with tools for combinatorial optimization. The objective is to find the best solution out of a very large set of possible solutions."
},
{
"code": null,
"e": 3688,
"s": 3628,
"text": "Let us try to use this library to build the optimal routes."
},
{
"code": null,
"e": 3791,
"s": 3688,
"text": "You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 3833,
"s": 3791,
"text": "This model can help the centre manager to"
},
{
"code": null,
"e": 3902,
"s": 3833,
"text": "Optimize his fleet with full utilization of his drivers and vehicles"
},
{
"code": null,
"e": 3968,
"s": 3902,
"text": "Ensure that the workload is equally distributed among each driver"
},
{
"code": null,
"e": 3978,
"s": 3968,
"text": "Question:"
},
{
"code": null,
"e": 4045,
"s": 3978,
"text": "What could be the results with higher capacity (boxes) per driver?"
},
{
"code": null,
"e": 4113,
"s": 4045,
"text": "What could be the results if we have a weight or volume constraint?"
},
{
"code": null,
"e": 4190,
"s": 4113,
"text": "I let you test it and share your results (or questions) in the comment area."
},
{
"code": null,
"e": 4236,
"s": 4190,
"text": "Have a look at my blog: https://samirsaci.com"
}
] |
Longest Common Prefix in an Array | Practice | GeeksforGeeks | Given a array of N strings, find the longest common prefix among all strings present in the array.
Example 1:
Input:
N = 4
arr[] = {geeksforgeeks, geeks, geek,
geezer}
Output: gee
Explanation: "gee" is the longest common
prefix in all the given strings.
Example 2:
Input:
N = 2
arr[] = {hello, world}
Output: -1
Explanation: There's no common prefix
in the given strings.
Your Task:
You don't need to read input or print anything. Your task is to complete the function longestCommonPrefix() which takes the string array arr[] and its size N as inputs and returns the longest common prefix common in all the strings in the array. If there's no prefix common in all the strings, return "-1".
Expected Time Complexity: O(N*max(|arri|)).
Expected Auxiliary Space: O(max(|arri|)) for result.
Constraints:
1 ≤ N ≤ 103
1 ≤ |arri| ≤ 103
0
abhigyanpatek4 hours ago
Simple C++ Solution:
string longestCommonPrefix (string arr[], int N) { sort(arr, arr+N); string s; for(int i = 0; i<arr[0].length(); i++){ if(arr[0][i] == arr[N-1][i]) s.push_back(arr[0][i]); else break; } if(s.size() == 0) return "-1"; return s; }
+1
harshscode1 day ago
sort(arr,arr+n);
string ans;
for(int i=0;i<arr[0].length();i++)
{
string p=arr[0];
string q=arr[n-1];
if(p[i]==q[i])
ans.push_back(p[i]);
else
break;
}
return ans==""?"-1":ans;
0
kuldeepahirwarmba4 days ago
String longestCommonPrefix(String arr[], int n){ // code here int min = 1000; String s =""; int count = 0; int temp = 1000; for(int i=0;i<n;i++) { int len = arr[i].length(); if(len<min) { min = len; s = arr[i]; } } for(int i =0;i<n;i++) { count =0; for(int j=0;j<min;j++) { if(arr[i].charAt(j)==s.charAt(j)) { count++; }else{ break; } } if(count<temp) { temp= count; }
} if(temp ==0) { return "-1"; }else{ return s.substring(0,temp); } }
0
bhardwajji1 week ago
easy c++
string longestCommonPrefix (string arr[], int n)
{
string pref ="";
if(n==1)
return arr[0];
bool f = true;
int minlen =INT_MAX;
for(int i=0;i<n-1;i++){
string s1=arr[i];
string s2=arr[i+1];
int x = s1.size();
int y = s2.size();
minlen = min(minlen,min(x,y));
string same="";
for(int k=0;k<minlen;k++){
if(s1[k]==s2[k]){
if(f==true){
pref+=s1[k];
}
same+=s1[k];
}
else
f= false;
}
if(same.size() < pref.size())
pref = same;
}
if(pref == "")
return "-1";
return pref;
}
0
amonk
This comment was deleted.
0
vishutyagi72 weeks ago
c++ 0.4 sec solution
string find(string s,string s1) { int m,i; string s2; m=min(s.size(),s1.size()); for(i=0;i<m;i++) { if(s[i]!=s1[i]) { break; } else { s2.push_back(s[i]); } } return s2; } string longestCommonPrefix (string arr[], int N) { if(N!=1) { string str=arr[0]; for(int i=1;i<N;i++) { str=find(str,arr[i]); } if(str.size()>0) { return str; } else { return "-1"; } } else { return arr[0]; } }
0
nikipyati2 weeks ago
class Solution:
def longestCommonPrefix(self, arr, n):
ans=''
for i in zip(*arr):
s="".join(i)
if len(set(s))!=1:
break
else:
ans+=s[0]
if len(ans)==0:
return -1
return ans
0
sachinupreti190
This comment was deleted.
0
ankajarya2752 weeks ago
class Solution{
public static String common(String a,String b)
{
String sol="";
for(int i=0;i<Math.min(a.length(),b.length());i++)
{
if(a.charAt(i)==b.charAt(i))
{
sol+=a.charAt(i);
}
else
{
break;
}
}
return sol;
}
String longestCommonPrefix(String arr[], int n){
// code here
String ans= arr[0];
for(int i=1;i<n;i++)
{
ans=common(ans,arr[i]);
}
if(ans.isEmpty())
return "-1";
return ans;
}
}
-1
mohiteshk2 weeks ago
C++ Total Time Taken: 0.22/1.44
string longestCommonPrefix (string arr[], int N) { // your code here string longestString; if(N == 0) return "-1"; if(N == 1) return arr[0]; string &first = arr[0]; int num_chars = 0, i = 0;; bool matching_till_i = false; while(1) { matching_till_i = true; for(int i = 1; i< N; ++i) { if(first[num_chars] == arr[i][num_chars]) continue; matching_till_i = false; } if(matching_till_i) num_chars++; else break; } if(num_chars == 0) return "-1"; longestString = arr->substr(0, num_chars); return longestString; }
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": 337,
"s": 238,
"text": "Given a array of N strings, find the longest common prefix among all strings present in the array."
},
{
"code": null,
"e": 349,
"s": 337,
"text": "\nExample 1:"
},
{
"code": null,
"e": 503,
"s": 349,
"text": "Input:\nN = 4\narr[] = {geeksforgeeks, geeks, geek,\n geezer}\nOutput: gee\nExplanation: \"gee\" is the longest common\nprefix in all the given strings.\n"
},
{
"code": null,
"e": 514,
"s": 503,
"text": "Example 2:"
},
{
"code": null,
"e": 623,
"s": 514,
"text": "Input: \nN = 2\narr[] = {hello, world}\nOutput: -1\nExplanation: There's no common prefix\nin the given strings.\n"
},
{
"code": null,
"e": 942,
"s": 623,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function longestCommonPrefix() which takes the string array arr[] and its size N as inputs and returns the longest common prefix common in all the strings in the array. If there's no prefix common in all the strings, return \"-1\"."
},
{
"code": null,
"e": 1040,
"s": 942,
"text": "\nExpected Time Complexity: O(N*max(|arri|)).\nExpected Auxiliary Space: O(max(|arri|)) for result."
},
{
"code": null,
"e": 1083,
"s": 1040,
"text": "\nConstraints:\n1 ≤ N ≤ 103\n1 ≤ |arri| ≤ 103"
},
{
"code": null,
"e": 1085,
"s": 1083,
"text": "0"
},
{
"code": null,
"e": 1110,
"s": 1085,
"text": "abhigyanpatek4 hours ago"
},
{
"code": null,
"e": 1131,
"s": 1110,
"text": "Simple C++ Solution:"
},
{
"code": null,
"e": 1434,
"s": 1131,
"text": "string longestCommonPrefix (string arr[], int N) { sort(arr, arr+N); string s; for(int i = 0; i<arr[0].length(); i++){ if(arr[0][i] == arr[N-1][i]) s.push_back(arr[0][i]); else break; } if(s.size() == 0) return \"-1\"; return s; }"
},
{
"code": null,
"e": 1437,
"s": 1434,
"text": "+1"
},
{
"code": null,
"e": 1457,
"s": 1437,
"text": "harshscode1 day ago"
},
{
"code": null,
"e": 1746,
"s": 1457,
"text": "sort(arr,arr+n);\n string ans;\n for(int i=0;i<arr[0].length();i++)\n {\n string p=arr[0];\n string q=arr[n-1];\n if(p[i]==q[i])\n ans.push_back(p[i]);\n else\n break;\n }\n return ans==\"\"?\"-1\":ans;"
},
{
"code": null,
"e": 1748,
"s": 1746,
"text": "0"
},
{
"code": null,
"e": 1776,
"s": 1748,
"text": "kuldeepahirwarmba4 days ago"
},
{
"code": null,
"e": 2463,
"s": 1776,
"text": " String longestCommonPrefix(String arr[], int n){ // code here int min = 1000; String s =\"\"; int count = 0; int temp = 1000; for(int i=0;i<n;i++) { int len = arr[i].length(); if(len<min) { min = len; s = arr[i]; } } for(int i =0;i<n;i++) { count =0; for(int j=0;j<min;j++) { if(arr[i].charAt(j)==s.charAt(j)) { count++; }else{ break; } } if(count<temp) { temp= count; }"
},
{
"code": null,
"e": 2579,
"s": 2463,
"text": " } if(temp ==0) { return \"-1\"; }else{ return s.substring(0,temp); } }"
},
{
"code": null,
"e": 2581,
"s": 2579,
"text": "0"
},
{
"code": null,
"e": 2602,
"s": 2581,
"text": "bhardwajji1 week ago"
},
{
"code": null,
"e": 2611,
"s": 2602,
"text": "easy c++"
},
{
"code": null,
"e": 3551,
"s": 2613,
"text": "string longestCommonPrefix (string arr[], int n)\n {\n string pref =\"\";\n if(n==1)\n return arr[0];\n bool f = true;\n int minlen =INT_MAX;\n \n for(int i=0;i<n-1;i++){\n string s1=arr[i];\n string s2=arr[i+1];\n \n int x = s1.size();\n int y = s2.size();\n minlen = min(minlen,min(x,y));\n \n string same=\"\";\n \n for(int k=0;k<minlen;k++){\n \n if(s1[k]==s2[k]){\n if(f==true){\n pref+=s1[k];\n }\n same+=s1[k];\n }\n else \n f= false;\n }\n \n if(same.size() < pref.size())\n pref = same;\n }\n \n if(pref == \"\")\n return \"-1\";\n \n return pref;\n }"
},
{
"code": null,
"e": 3553,
"s": 3551,
"text": "0"
},
{
"code": null,
"e": 3559,
"s": 3553,
"text": "amonk"
},
{
"code": null,
"e": 3585,
"s": 3559,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3587,
"s": 3585,
"text": "0"
},
{
"code": null,
"e": 3610,
"s": 3587,
"text": "vishutyagi72 weeks ago"
},
{
"code": null,
"e": 3631,
"s": 3610,
"text": "c++ 0.4 sec solution"
},
{
"code": null,
"e": 4285,
"s": 3631,
"text": "string find(string s,string s1) { int m,i; string s2; m=min(s.size(),s1.size()); for(i=0;i<m;i++) { if(s[i]!=s1[i]) { break; } else { s2.push_back(s[i]); } } return s2; } string longestCommonPrefix (string arr[], int N) { if(N!=1) { string str=arr[0]; for(int i=1;i<N;i++) { str=find(str,arr[i]); } if(str.size()>0) { return str; } else { return \"-1\"; } } else { return arr[0]; } }"
},
{
"code": null,
"e": 4287,
"s": 4285,
"text": "0"
},
{
"code": null,
"e": 4308,
"s": 4287,
"text": "nikipyati2 weeks ago"
},
{
"code": null,
"e": 4598,
"s": 4308,
"text": "class Solution:\n def longestCommonPrefix(self, arr, n):\n ans=''\n for i in zip(*arr):\n s=\"\".join(i)\n if len(set(s))!=1:\n break\n else:\n ans+=s[0]\n if len(ans)==0:\n return -1\n return ans "
},
{
"code": null,
"e": 4600,
"s": 4598,
"text": "0"
},
{
"code": null,
"e": 4616,
"s": 4600,
"text": "sachinupreti190"
},
{
"code": null,
"e": 4642,
"s": 4616,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4644,
"s": 4642,
"text": "0"
},
{
"code": null,
"e": 4668,
"s": 4644,
"text": "ankajarya2752 weeks ago"
},
{
"code": null,
"e": 5316,
"s": 4668,
"text": "class Solution{\n \n public static String common(String a,String b)\n {\n String sol=\"\";\n for(int i=0;i<Math.min(a.length(),b.length());i++)\n {\n if(a.charAt(i)==b.charAt(i))\n {\n sol+=a.charAt(i);\n }\n else\n {\n break;\n }\n }\n return sol;\n }\n String longestCommonPrefix(String arr[], int n){\n // code here\n String ans= arr[0];\n for(int i=1;i<n;i++)\n {\n ans=common(ans,arr[i]);\n }\n if(ans.isEmpty())\n return \"-1\";\n \n return ans; \n }\n}"
},
{
"code": null,
"e": 5319,
"s": 5316,
"text": "-1"
},
{
"code": null,
"e": 5340,
"s": 5319,
"text": "mohiteshk2 weeks ago"
},
{
"code": null,
"e": 5373,
"s": 5340,
"text": "C++ Total Time Taken: 0.22/1.44 "
},
{
"code": null,
"e": 6203,
"s": 5375,
"text": " string longestCommonPrefix (string arr[], int N) { // your code here string longestString; if(N == 0) return \"-1\"; if(N == 1) return arr[0]; string &first = arr[0]; int num_chars = 0, i = 0;; bool matching_till_i = false; while(1) { matching_till_i = true; for(int i = 1; i< N; ++i) { if(first[num_chars] == arr[i][num_chars]) continue; matching_till_i = false; } if(matching_till_i) num_chars++; else break; } if(num_chars == 0) return \"-1\"; longestString = arr->substr(0, num_chars); return longestString; }"
},
{
"code": null,
"e": 6349,
"s": 6203,
"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": 6385,
"s": 6349,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6395,
"s": 6385,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6405,
"s": 6395,
"text": "\nContest\n"
},
{
"code": null,
"e": 6468,
"s": 6405,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6616,
"s": 6468,
"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": 6824,
"s": 6616,
"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": 6930,
"s": 6824,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Desktop Notifier Application Using Python in 5 Minutes | Towards Data Science | Have you ever tried to create a desktop notifications application based on your needs? do you know you can do this in a few simple steps using python?
Don't worry, let's do this from scratch, in this article we will be creating a desktop notification application for getting the daily stats of the dreadful coronavirus.
What you learn in this article
Installing required python packages.Reading the coronavirus data from the web.Creating a desktop notifier application.Making your program run in the background.
Installing required python packages.
Reading the coronavirus data from the web.
Creating a desktop notifier application.
Making your program run in the background.
we need to download two important packages for this application.
Note: you need to type this two commands in command prompt if you are using Windows or terminal if you are using Linux
requests (for fetching data from the web)
requests (for fetching data from the web)
pip install requests
2. plyer (for creating notifications on your PC)
pip install plyer
we can fetch the coronavirus data using the URL provided below, you are free to replace the country name with your own country name, for this application we will be using India’s coronavirus data.
https://corona-rest-api.herokuapp.com/Api/india
the website looks like this
By now, we have got all the tools required to build this application, so now let's code this application
Note: It will be easier if you code this in offline compiler than online compiler because in the later stages of this article we will be making this application run as background process in your PC, if you are running in online compiler then you need to download the file which is not necessary in offline compiler. I will suggest to use Visual Studio.
part1 ( importing libraries)
part2 (retrieving the data from the web)
part3 (creating custom notification)
That’s it, we are ready to run our application before we actually run our application you need to know some changes you can make to make your application customized according to your needs.
timeout — tells how much time a notification should show up on thedesktop
time.sleep ()— tells after what interval of time the notification should popup
you can find the icon I used here
Here is how you see your notification after running your application.
So you finally created a python application and it runs fine when you go and run it. But don't you think this is a tedious job, every time running your application to get a notification?
Here is a solution, you can make this automated by running your application as a background process in your PC.
Just follow this simple command to make your application run in the background, note you need to type this command in command prompt in case you are using Windows and terminal in case you are using Linux.
Note: replace the <your-file-name-here> with your file name
pythonw.exe .\<your-file-name-here>example pythonw.exe .\desktopNotifier.py
That's it your application now starts running in the background
open task manager in your pc and you can see that in background process you can see python is running
That’s simple, in the task manager kill the process named python. If you feel any difficulty in stoping the notification please feel free to post your difficulty in the comments section of this article.
Daily notification to take medicine.Hourly notification to drink water.
Daily notification to take medicine.
Hourly notification to drink water.
and many more, it’s completely up to you how to use this application.
I hope this article had created interest in you to create your own customized desktop notification application. This application works for any kind of operating system be it Windows or Linux or Mac. If you want a simpler desktop notification application, please feel free to ask in the comment section of this article | [
{
"code": null,
"e": 323,
"s": 172,
"text": "Have you ever tried to create a desktop notifications application based on your needs? do you know you can do this in a few simple steps using python?"
},
{
"code": null,
"e": 492,
"s": 323,
"text": "Don't worry, let's do this from scratch, in this article we will be creating a desktop notification application for getting the daily stats of the dreadful coronavirus."
},
{
"code": null,
"e": 523,
"s": 492,
"text": "What you learn in this article"
},
{
"code": null,
"e": 684,
"s": 523,
"text": "Installing required python packages.Reading the coronavirus data from the web.Creating a desktop notifier application.Making your program run in the background."
},
{
"code": null,
"e": 721,
"s": 684,
"text": "Installing required python packages."
},
{
"code": null,
"e": 764,
"s": 721,
"text": "Reading the coronavirus data from the web."
},
{
"code": null,
"e": 805,
"s": 764,
"text": "Creating a desktop notifier application."
},
{
"code": null,
"e": 848,
"s": 805,
"text": "Making your program run in the background."
},
{
"code": null,
"e": 913,
"s": 848,
"text": "we need to download two important packages for this application."
},
{
"code": null,
"e": 1032,
"s": 913,
"text": "Note: you need to type this two commands in command prompt if you are using Windows or terminal if you are using Linux"
},
{
"code": null,
"e": 1074,
"s": 1032,
"text": "requests (for fetching data from the web)"
},
{
"code": null,
"e": 1116,
"s": 1074,
"text": "requests (for fetching data from the web)"
},
{
"code": null,
"e": 1138,
"s": 1116,
"text": " pip install requests"
},
{
"code": null,
"e": 1187,
"s": 1138,
"text": "2. plyer (for creating notifications on your PC)"
},
{
"code": null,
"e": 1205,
"s": 1187,
"text": "pip install plyer"
},
{
"code": null,
"e": 1402,
"s": 1205,
"text": "we can fetch the coronavirus data using the URL provided below, you are free to replace the country name with your own country name, for this application we will be using India’s coronavirus data."
},
{
"code": null,
"e": 1450,
"s": 1402,
"text": "https://corona-rest-api.herokuapp.com/Api/india"
},
{
"code": null,
"e": 1478,
"s": 1450,
"text": "the website looks like this"
},
{
"code": null,
"e": 1583,
"s": 1478,
"text": "By now, we have got all the tools required to build this application, so now let's code this application"
},
{
"code": null,
"e": 1936,
"s": 1583,
"text": "Note: It will be easier if you code this in offline compiler than online compiler because in the later stages of this article we will be making this application run as background process in your PC, if you are running in online compiler then you need to download the file which is not necessary in offline compiler. I will suggest to use Visual Studio."
},
{
"code": null,
"e": 1965,
"s": 1936,
"text": "part1 ( importing libraries)"
},
{
"code": null,
"e": 2006,
"s": 1965,
"text": "part2 (retrieving the data from the web)"
},
{
"code": null,
"e": 2043,
"s": 2006,
"text": "part3 (creating custom notification)"
},
{
"code": null,
"e": 2233,
"s": 2043,
"text": "That’s it, we are ready to run our application before we actually run our application you need to know some changes you can make to make your application customized according to your needs."
},
{
"code": null,
"e": 2307,
"s": 2233,
"text": "timeout — tells how much time a notification should show up on thedesktop"
},
{
"code": null,
"e": 2386,
"s": 2307,
"text": "time.sleep ()— tells after what interval of time the notification should popup"
},
{
"code": null,
"e": 2420,
"s": 2386,
"text": "you can find the icon I used here"
},
{
"code": null,
"e": 2490,
"s": 2420,
"text": "Here is how you see your notification after running your application."
},
{
"code": null,
"e": 2677,
"s": 2490,
"text": "So you finally created a python application and it runs fine when you go and run it. But don't you think this is a tedious job, every time running your application to get a notification?"
},
{
"code": null,
"e": 2789,
"s": 2677,
"text": "Here is a solution, you can make this automated by running your application as a background process in your PC."
},
{
"code": null,
"e": 2994,
"s": 2789,
"text": "Just follow this simple command to make your application run in the background, note you need to type this command in command prompt in case you are using Windows and terminal in case you are using Linux."
},
{
"code": null,
"e": 3054,
"s": 2994,
"text": "Note: replace the <your-file-name-here> with your file name"
},
{
"code": null,
"e": 3130,
"s": 3054,
"text": "pythonw.exe .\\<your-file-name-here>example pythonw.exe .\\desktopNotifier.py"
},
{
"code": null,
"e": 3194,
"s": 3130,
"text": "That's it your application now starts running in the background"
},
{
"code": null,
"e": 3296,
"s": 3194,
"text": "open task manager in your pc and you can see that in background process you can see python is running"
},
{
"code": null,
"e": 3499,
"s": 3296,
"text": "That’s simple, in the task manager kill the process named python. If you feel any difficulty in stoping the notification please feel free to post your difficulty in the comments section of this article."
},
{
"code": null,
"e": 3571,
"s": 3499,
"text": "Daily notification to take medicine.Hourly notification to drink water."
},
{
"code": null,
"e": 3608,
"s": 3571,
"text": "Daily notification to take medicine."
},
{
"code": null,
"e": 3644,
"s": 3608,
"text": "Hourly notification to drink water."
},
{
"code": null,
"e": 3714,
"s": 3644,
"text": "and many more, it’s completely up to you how to use this application."
}
] |
Deletion of array of objects in C++ - GeeksforGeeks | 18 Jan, 2021
Need for deletion of the object:
To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section.
If objects are not deleted explicitly then the program will crash during runtime.
Program 1: Create an object of the class which is created dynamically using the new operator and deleting it explicitly using the delete operator:
C++
// C++ program to create an object
// dynamically and delete explicitly
#include <iostream>
using namespace std;
// Class
class Student {
public:
// Constructor
Student()
{
cout << "Constructor is called!\n";
}
// Destructor
~Student()
{
cout << "Destructor is called!\n";
}
// Function to display the message
void write()
{
cout << "Writing!\n";
}
};
// Driver Code
int main()
{
// Create an array of objects
Student* student = new Student();
// Function Call to write()
// using instance
student->write();
// De-allocate the memory
// explicitly
delete student;
return 0;
}
Constructor is called!
Writing!
Destructor is called!
Program 2: Create an array of objects using the new operator dynamically. Whenever an array of the object of a class is created at runtime then it is the programmer’s responsibility to delete it and avoid a memory leak:
C++
// C++ program to create an array of
// objects and deleting it explicitly
#include <iostream>
using namespace std;
// Class
class Student {
public:
// Constructor
Student()
{
cout << "Constructor is called!\n";
}
// Destructor
~Student()
{
cout << "Destructor is called!\n";
}
// Function to display message
void write()
{
cout << "Writing!\n";
}
};
// Driver Code
int main()
{
// Create an array of the object
// dynamically
Student* student = new Student[3];
// Function Call to write()
student[0].write();
student[1].write();
student[2].write();
// De-allocate the memory
// explicitly
delete[] student;
return 0;
}
Constructor is called!
Constructor is called!
Constructor is called!
Writing!
Writing!
Writing!
Destructor is called!
Destructor is called!
Destructor is called!
Program 3:
Below is the program where delete is used to delete an array of objects:
C++
// C++ program to delete array of
// objects
#include <iostream>
using namespace std;
// Class
class Student {
public:
// Constructor
Student()
{
cout << "Constructor is called!\n";
}
// Destructor
~Student()
{
cout << "Destructor is called!\n";
}
// Function to display message
void write()
{
cout << "Writing!\n";
}
};
// Driver Code
int main()
{
// Create an object dynamically
Student* student = new Student[3];
// Function call to write()
student[0].write();
student[1].write();
student[2].write();
// De-allocate the memory
// explicitly
delete student;
return 0;
}
Explanation: This program will crash in runtime. In this program, constructors are working properly but the destructor is executed only for the first object, and after that program is crashing at runtime because of a memory leak. It is because 3 objects are created at runtime but only one object is deleted explicitly and that’s why the remaining two objects are crashing at runtime.
Conclusion:In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.
C Basics
CPP-Basics
new and delete
C++
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 24170,
"s": 24139,
"text": " \n18 Jan, 2021\n"
},
{
"code": null,
"e": 24203,
"s": 24170,
"text": "Need for deletion of the object:"
},
{
"code": null,
"e": 24316,
"s": 24203,
"text": "To avoid memory leak as when an object is created dynamically using new, it occupies memory in the Heap Section."
},
{
"code": null,
"e": 24398,
"s": 24316,
"text": "If objects are not deleted explicitly then the program will crash during runtime."
},
{
"code": null,
"e": 24545,
"s": 24398,
"text": "Program 1: Create an object of the class which is created dynamically using the new operator and deleting it explicitly using the delete operator:"
},
{
"code": null,
"e": 24549,
"s": 24545,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to create an object \n// dynamically and delete explicitly \n#include <iostream> \nusing namespace std; \n \n// Class \nclass Student { \n \npublic: \n // Constructor \n Student() \n { \n cout << \"Constructor is called!\\n\"; \n } \n \n // Destructor \n ~Student() \n { \n cout << \"Destructor is called!\\n\"; \n } \n \n // Function to display the message \n void write() \n { \n cout << \"Writing!\\n\"; \n } \n}; \n \n// Driver Code \nint main() \n{ \n // Create an array of objects \n Student* student = new Student(); \n \n // Function Call to write() \n // using instance \n student->write(); \n \n // De-allocate the memory \n // explicitly \n delete student; \n \n return 0; \n}\n\n\n\n\n\n",
"e": 25316,
"s": 24559,
"text": null
},
{
"code": null,
"e": 25371,
"s": 25316,
"text": "Constructor is called!\nWriting!\nDestructor is called!\n"
},
{
"code": null,
"e": 25591,
"s": 25371,
"text": "Program 2: Create an array of objects using the new operator dynamically. Whenever an array of the object of a class is created at runtime then it is the programmer’s responsibility to delete it and avoid a memory leak:"
},
{
"code": null,
"e": 25595,
"s": 25591,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to create an array of \n// objects and deleting it explicitly \n#include <iostream> \nusing namespace std; \n \n// Class \nclass Student { \n \npublic: \n // Constructor \n Student() \n { \n cout << \"Constructor is called!\\n\"; \n } \n \n // Destructor \n ~Student() \n { \n cout << \"Destructor is called!\\n\"; \n } \n \n // Function to display message \n void write() \n { \n cout << \"Writing!\\n\"; \n } \n}; \n \n// Driver Code \nint main() \n{ \n // Create an array of the object \n // dynamically \n Student* student = new Student[3]; \n \n // Function Call to write() \n student[0].write(); \n student[1].write(); \n student[2].write(); \n \n // De-allocate the memory \n // explicitly \n delete[] student; \n \n return 0; \n}\n\n\n\n\n\n",
"e": 26415,
"s": 25605,
"text": null
},
{
"code": null,
"e": 26578,
"s": 26415,
"text": "Constructor is called!\nConstructor is called!\nConstructor is called!\nWriting!\nWriting!\nWriting!\nDestructor is called!\nDestructor is called!\nDestructor is called!\n"
},
{
"code": null,
"e": 26589,
"s": 26578,
"text": "Program 3:"
},
{
"code": null,
"e": 26662,
"s": 26589,
"text": "Below is the program where delete is used to delete an array of objects:"
},
{
"code": null,
"e": 26666,
"s": 26662,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C++ program to delete array of \n// objects \n#include <iostream> \nusing namespace std; \n \n// Class \nclass Student { \n \npublic: \n // Constructor \n Student() \n { \n cout << \"Constructor is called!\\n\"; \n } \n \n // Destructor \n ~Student() \n { \n cout << \"Destructor is called!\\n\"; \n } \n \n // Function to display message \n void write() \n { \n cout << \"Writing!\\n\"; \n } \n}; \n \n// Driver Code \nint main() \n{ \n // Create an object dynamically \n Student* student = new Student[3]; \n \n // Function call to write() \n student[0].write(); \n student[1].write(); \n student[2].write(); \n \n // De-allocate the memory \n // explicitly \n delete student; \n \n return 0; \n}\n\n\n\n\n\n",
"e": 27433,
"s": 26676,
"text": null
},
{
"code": null,
"e": 27818,
"s": 27433,
"text": "Explanation: This program will crash in runtime. In this program, constructors are working properly but the destructor is executed only for the first object, and after that program is crashing at runtime because of a memory leak. It is because 3 objects are created at runtime but only one object is deleted explicitly and that’s why the remaining two objects are crashing at runtime."
},
{
"code": null,
"e": 28065,
"s": 27818,
"text": "Conclusion:In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak."
},
{
"code": null,
"e": 28076,
"s": 28065,
"text": "\nC Basics\n"
},
{
"code": null,
"e": 28089,
"s": 28076,
"text": "\nCPP-Basics\n"
},
{
"code": null,
"e": 28106,
"s": 28089,
"text": "\nnew and delete\n"
},
{
"code": null,
"e": 28112,
"s": 28106,
"text": "\nC++\n"
},
{
"code": null,
"e": 28127,
"s": 28112,
"text": "\nC++ Programs\n"
},
{
"code": null,
"e": 28332,
"s": 28127,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28360,
"s": 28332,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28380,
"s": 28360,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28404,
"s": 28380,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28437,
"s": 28404,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28481,
"s": 28437,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28516,
"s": 28481,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 28575,
"s": 28516,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 28601,
"s": 28575,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 28645,
"s": 28601,
"text": "Program to print ASCII Value of a character"
}
] |
Whitespaces in Perl | A Perl program does not care about whitespaces. Following program works perfectly fine −
#!/usr/bin/perl
print "Hello, world\n";
But if spaces are inside the quoted strings, then they would be printed as is. For example −
Live Demo
#!/usr/bin/perl
# This would print with a line break in the middle
print "Hello
world\n";
This will produce the following result −
Hello
world
All types of whitespace like spaces, tabs, newlines, etc. are equivalent to the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it. | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "A Perl program does not care about whitespaces. Following program works perfectly fine −"
},
{
"code": null,
"e": 1194,
"s": 1151,
"text": "#!/usr/bin/perl\nprint \"Hello, world\\n\";"
},
{
"code": null,
"e": 1287,
"s": 1194,
"text": "But if spaces are inside the quoted strings, then they would be printed as is. For example −"
},
{
"code": null,
"e": 1298,
"s": 1287,
"text": " Live Demo"
},
{
"code": null,
"e": 1397,
"s": 1298,
"text": "#!/usr/bin/perl\n# This would print with a line break in the middle\nprint \"Hello\n world\\n\";"
},
{
"code": null,
"e": 1438,
"s": 1397,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1456,
"s": 1438,
"text": "Hello\n world"
},
{
"code": null,
"e": 1705,
"s": 1456,
"text": "All types of whitespace like spaces, tabs, newlines, etc. are equivalent to the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it."
}
] |
Trigger a button click and generate alert on form submission in JavaScript | Let’s say the following is our button −
<button id="submitForm">Submit</button>
On the basis of button id, on form submission, generate an alert −
$("#submitForm").click(function() {
alert("The Form has been Submitted.");
});
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>
CollegeId=<input id="collegeId" type="text"><br />
CollegeName= <input id="collegeName" type="text"><br />
<button id="submitForm">Submit</button>
<script>
$("#submitForm").click(function() {
alert("The Form has been Submitted.");
});
</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 −
After clicking the button, you can see the following output − | [
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is our button −"
},
{
"code": null,
"e": 1142,
"s": 1102,
"text": "<button id=\"submitForm\">Submit</button>"
},
{
"code": null,
"e": 1209,
"s": 1142,
"text": "On the basis of button id, on form submission, generate an alert −"
},
{
"code": null,
"e": 1291,
"s": 1209,
"text": "$(\"#submitForm\").click(function() {\n alert(\"The Form has been Submitted.\");\n});"
},
{
"code": null,
"e": 1302,
"s": 1291,
"text": " Live Demo"
},
{
"code": null,
"e": 1968,
"s": 1302,
"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>\nCollegeId=<input id=\"collegeId\" type=\"text\"><br />\nCollegeName= <input id=\"collegeName\" type=\"text\"><br />\n<button id=\"submitForm\">Submit</button>\n<script>\n $(\"#submitForm\").click(function() {\n alert(\"The Form has been Submitted.\");\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2130,
"s": 1968,
"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": 2171,
"s": 2130,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2233,
"s": 2171,
"text": "After clicking the button, you can see the following output −"
}
] |
Check if a Binary Tree (not BST) has duplicate values - GeeksforGeeks | 31 Mar, 2022
Check if a Binary Tree (not BST) has duplicate valuesExamples:
Input : Root of below tree
1
/ \
2 3
\
2
Output : Yes
Explanation : The duplicate value is 2.
Input : Root of below tree
1
/ \
20 3
\
4
Output : No
Explanation : There are no duplicates.
A simple solution is to store inorder traversal of given binary tree in an array. Then check if array has duplicates or not. We can avoid the use of array and solve the problem in O(n) time. The idea is to use hashing. We traverse the given tree, for every node, we check if it already exists in hash table. If exists, we return true (found duplicate). If it does not exist, we insert into hash table.
C++
Java
Python
C#
Javascript
// C++ Program to check duplicates// in Binary Tree#include <bits/stdc++.h>using namespace std; // A binary tree Node has data,// pointer to left child// and a pointer to right childstruct Node { int data; struct Node* left; struct Node* right;}; // Helper function that allocates// a new Node with the given data// and NULL left and right pointers.struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} bool checkDupUtil(Node* root, unordered_set<int> &s){ // If tree is empty, there are no // duplicates. if (root == NULL) return false; // If current node's data is already present. if (s.find(root->data) != s.end()) return true; // Insert current node s.insert(root->data); // Recursively check in left and right // subtrees. return checkDupUtil(root->left, s) || checkDupUtil(root->right, s);} // To check if tree has duplicatesbool checkDup(struct Node* root){ unordered_set<int> s; return checkDupUtil(root, s);} // Driver program to test above functionsint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); if (checkDup(root)) printf("Yes"); else printf("No"); return 0;}
// Java Program to check duplicates// in Binary Treeimport java.util.HashSet;public class CheckDuplicateValues { //Function that used HashSet to find presence of duplicate nodes public static boolean checkDupUtil(Node root, HashSet<Integer> s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.contains(root.data)) return true; // Insert current node s.add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates public static boolean checkDup(Node root) { HashSet<Integer> s=new HashSet<>(); return checkDupUtil(root, s); } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) System.out.print("Yes"); else System.out.print("No"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childclass Node { int data; Node left,right; Node(int data) { this.data=data; }};//This code is contributed by Gaurav Tiwari
""" Program to check duplicates# in Binary Tree """ # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None def checkDupUtil( root, s) : # If tree is empty, there are no # duplicates. if (root == None) : return False # If current node's data is already present. if root.data in s: return True # Insert current node s.add(root.data) # Recursively check in left and right # subtrees. return checkDupUtil(root.left, s) or checkDupUtil(root.right, s) # To check if tree has duplicatesdef checkDup( root) : s=set() return checkDupUtil(root, s) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(2) root.left.left = newNode(3) if (checkDup(root)): print("Yes") else: print("No") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# Program to check duplicates// in Binary Treeusing System;using System.Collections;using System.Collections.Generic; class CheckDuplicateValues{ //Function that used HashSet to // find presence of duplicate nodes public static Boolean checkDupUtil(Node root, HashSet<int> s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.Contains(root.data)) return true; // Insert current node s.Add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates public static Boolean checkDup(Node root) { HashSet<int> s = new HashSet<int>(); return checkDupUtil(root, s); } public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) Console.Write("Yes"); else Console.Write("No"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childpublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; }}; // This code is contributed by Arnab Kundu
<script> // JavaScript Program to check duplicates in Binary Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function that used HashSet to find // presence of duplicate nodes function checkDupUtil(root, s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.has(root.data)) return true; // Insert current node s.add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates function checkDup(root) { let s = new Set(); return checkDupUtil(root, s); } let root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
YouTubeGeeksforGeeks502K subscribersCheck if a Binary Tree (not BST) has duplicate values | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UdhMwtIcw6w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
Aditya Sharma 3
Ankit.19
_Gaurav_Tiwari
SHUBHAMSINGH10
andrew1234
decode2207
surinderdawra388
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Introduction to Tree Data Structure
BFS vs DFS for Binary Tree
Sorted Array to Balanced BST
Expression Tree
Binary Tree (Array implementation)
Deletion in a Binary Tree
Relationship between number of nodes and height of binary tree
Inorder Tree Traversal without recursion and without stack!
How to determine if a binary tree is height-balanced? | [
{
"code": null,
"e": 25229,
"s": 25201,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 25294,
"s": 25229,
"text": "Check if a Binary Tree (not BST) has duplicate valuesExamples: "
},
{
"code": null,
"e": 25591,
"s": 25294,
"text": "Input : Root of below tree\n 1\n / \\\n 2 3\n \\\n 2\nOutput : Yes\nExplanation : The duplicate value is 2.\n\nInput : Root of below tree\n 1\n / \\\n 20 3\n \\\n 4\nOutput : No\nExplanation : There are no duplicates."
},
{
"code": null,
"e": 25996,
"s": 25593,
"text": "A simple solution is to store inorder traversal of given binary tree in an array. Then check if array has duplicates or not. We can avoid the use of array and solve the problem in O(n) time. The idea is to use hashing. We traverse the given tree, for every node, we check if it already exists in hash table. If exists, we return true (found duplicate). If it does not exist, we insert into hash table. "
},
{
"code": null,
"e": 26000,
"s": 25996,
"text": "C++"
},
{
"code": null,
"e": 26005,
"s": 26000,
"text": "Java"
},
{
"code": null,
"e": 26012,
"s": 26005,
"text": "Python"
},
{
"code": null,
"e": 26015,
"s": 26012,
"text": "C#"
},
{
"code": null,
"e": 26026,
"s": 26015,
"text": "Javascript"
},
{
"code": "// C++ Program to check duplicates// in Binary Tree#include <bits/stdc++.h>using namespace std; // A binary tree Node has data,// pointer to left child// and a pointer to right childstruct Node { int data; struct Node* left; struct Node* right;}; // Helper function that allocates// a new Node with the given data// and NULL left and right pointers.struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} bool checkDupUtil(Node* root, unordered_set<int> &s){ // If tree is empty, there are no // duplicates. if (root == NULL) return false; // If current node's data is already present. if (s.find(root->data) != s.end()) return true; // Insert current node s.insert(root->data); // Recursively check in left and right // subtrees. return checkDupUtil(root->left, s) || checkDupUtil(root->right, s);} // To check if tree has duplicatesbool checkDup(struct Node* root){ unordered_set<int> s; return checkDupUtil(root, s);} // Driver program to test above functionsint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); if (checkDup(root)) printf(\"Yes\"); else printf(\"No\"); return 0;}",
"e": 27375,
"s": 26026,
"text": null
},
{
"code": "// Java Program to check duplicates// in Binary Treeimport java.util.HashSet;public class CheckDuplicateValues { //Function that used HashSet to find presence of duplicate nodes public static boolean checkDupUtil(Node root, HashSet<Integer> s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.contains(root.data)) return true; // Insert current node s.add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates public static boolean checkDup(Node root) { HashSet<Integer> s=new HashSet<>(); return checkDupUtil(root, s); } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childclass Node { int data; Node left,right; Node(int data) { this.data=data; }};//This code is contributed by Gaurav Tiwari",
"e": 28767,
"s": 27375,
"text": null
},
{
"code": "\"\"\" Program to check duplicates# in Binary Tree \"\"\" # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None def checkDupUtil( root, s) : # If tree is empty, there are no # duplicates. if (root == None) : return False # If current node's data is already present. if root.data in s: return True # Insert current node s.add(root.data) # Recursively check in left and right # subtrees. return checkDupUtil(root.left, s) or checkDupUtil(root.right, s) # To check if tree has duplicatesdef checkDup( root) : s=set() return checkDupUtil(root, s) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(2) root.left.left = newNode(3) if (checkDup(root)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 29872,
"s": 28767,
"text": null
},
{
"code": "// C# Program to check duplicates// in Binary Treeusing System;using System.Collections;using System.Collections.Generic; class CheckDuplicateValues{ //Function that used HashSet to // find presence of duplicate nodes public static Boolean checkDupUtil(Node root, HashSet<int> s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.Contains(root.data)) return true; // Insert current node s.Add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates public static Boolean checkDup(Node root) { HashSet<int> s = new HashSet<int>(); return checkDupUtil(root, s); } public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childpublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; }}; // This code is contributed by Arnab Kundu",
"e": 31353,
"s": 29872,
"text": null
},
{
"code": "<script> // JavaScript Program to check duplicates in Binary Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function that used HashSet to find // presence of duplicate nodes function checkDupUtil(root, s) { // If tree is empty, there are no // duplicates. if (root == null) return false; // If current node's data is already present. if (s.has(root.data)) return true; // Insert current node s.add(root.data); // Recursively check in left and right // subtrees. return checkDupUtil(root.left, s) || checkDupUtil(root.right, s); } // To check if tree has duplicates function checkDup(root) { let s = new Set(); return checkDupUtil(root, s); } let root = new Node(1); root.left = new Node(2); root.right = new Node(2); root.left.left = new Node(3); if (checkDup(root)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 32498,
"s": 31353,
"text": null
},
{
"code": null,
"e": 32508,
"s": 32498,
"text": "Output: "
},
{
"code": null,
"e": 32512,
"s": 32508,
"text": "Yes"
},
{
"code": null,
"e": 33366,
"s": 32514,
"text": "YouTubeGeeksforGeeks502K subscribersCheck if a Binary Tree (not BST) has duplicate values | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=UdhMwtIcw6w\" 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": 33407,
"s": 33366,
"text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk"
},
{
"code": null,
"e": 33423,
"s": 33407,
"text": "Aditya Sharma 3"
},
{
"code": null,
"e": 33432,
"s": 33423,
"text": "Ankit.19"
},
{
"code": null,
"e": 33447,
"s": 33432,
"text": "_Gaurav_Tiwari"
},
{
"code": null,
"e": 33462,
"s": 33447,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33473,
"s": 33462,
"text": "andrew1234"
},
{
"code": null,
"e": 33484,
"s": 33473,
"text": "decode2207"
},
{
"code": null,
"e": 33501,
"s": 33484,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33506,
"s": 33501,
"text": "Tree"
},
{
"code": null,
"e": 33511,
"s": 33506,
"text": "Tree"
},
{
"code": null,
"e": 33609,
"s": 33511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33623,
"s": 33609,
"text": "Decision Tree"
},
{
"code": null,
"e": 33659,
"s": 33623,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 33686,
"s": 33659,
"text": "BFS vs DFS for Binary Tree"
},
{
"code": null,
"e": 33715,
"s": 33686,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 33731,
"s": 33715,
"text": "Expression Tree"
},
{
"code": null,
"e": 33766,
"s": 33731,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 33792,
"s": 33766,
"text": "Deletion in a Binary Tree"
},
{
"code": null,
"e": 33855,
"s": 33792,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 33915,
"s": 33855,
"text": "Inorder Tree Traversal without recursion and without stack!"
}
] |
Finger command in Linux with Examples - GeeksforGeeks | 10 May, 2020
Finger command is a user information lookup command which gives details of all the users logged in. This tool is generally used by system administrators. It provides details like login name, user name, idle time, login time, and in some cases their email address even. This tool is similar to the Pinky tool but the Pinky tool is just the lightweight version of this tool.
To install finger tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install finger
In case of CentOS/RedHat
$sudo yum install finger
In case of Fedora OS
$sudo dnf install finger
1. To finger or get details of a user.
$finger manav
Note: Here “manav” is the username.
As can be seen, it displays the login name, name, directory, shell, login time, email, and plan of the user.
2. To get idle status and login details of a user.
$finger -s manav
As can be seen, it displays the idle status along with the details of the user.
3. To avoid printing PGP key, plan and project details
$finger -p manav
As can be seen, it displays the login name, name, directory, shell, login time, email, but not the plan, PGP key, and project of the user.
4. To create a plan for a user.
$echo "Plan details" > ~/.plan
Now, after again using finger command it will display a plan for the user.
5. To create a project for a user.
$echo "Project details" > ~/.project
Now, after again using finger command it will display a project for the user.
6. To create a PGP key for a user.
$echo "pgpkey" > ~/.pgpkey
Now, after again using finger command it will display a PGP key for the user.
linux-command
Linux-Unix
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
SED command in Linux | Set 2
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24779,
"s": 24406,
"text": "Finger command is a user information lookup command which gives details of all the users logged in. This tool is generally used by system administrators. It provides details like login name, user name, idle time, login time, and in some cases their email address even. This tool is similar to the Pinky tool but the Pinky tool is just the lightweight version of this tool."
},
{
"code": null,
"e": 24861,
"s": 24779,
"text": "To install finger tool use the following commands as per your Linux distribution."
},
{
"code": null,
"e": 24886,
"s": 24861,
"text": "In case of Debian/Ubuntu"
},
{
"code": null,
"e": 24915,
"s": 24886,
"text": "$sudo apt-get install finger"
},
{
"code": null,
"e": 24940,
"s": 24915,
"text": "In case of CentOS/RedHat"
},
{
"code": null,
"e": 24965,
"s": 24940,
"text": "$sudo yum install finger"
},
{
"code": null,
"e": 24986,
"s": 24965,
"text": "In case of Fedora OS"
},
{
"code": null,
"e": 25011,
"s": 24986,
"text": "$sudo dnf install finger"
},
{
"code": null,
"e": 25050,
"s": 25011,
"text": "1. To finger or get details of a user."
},
{
"code": null,
"e": 25065,
"s": 25050,
"text": "$finger manav\n"
},
{
"code": null,
"e": 25101,
"s": 25065,
"text": "Note: Here “manav” is the username."
},
{
"code": null,
"e": 25210,
"s": 25101,
"text": "As can be seen, it displays the login name, name, directory, shell, login time, email, and plan of the user."
},
{
"code": null,
"e": 25261,
"s": 25210,
"text": "2. To get idle status and login details of a user."
},
{
"code": null,
"e": 25279,
"s": 25261,
"text": "$finger -s manav\n"
},
{
"code": null,
"e": 25359,
"s": 25279,
"text": "As can be seen, it displays the idle status along with the details of the user."
},
{
"code": null,
"e": 25414,
"s": 25359,
"text": "3. To avoid printing PGP key, plan and project details"
},
{
"code": null,
"e": 25432,
"s": 25414,
"text": "$finger -p manav\n"
},
{
"code": null,
"e": 25571,
"s": 25432,
"text": "As can be seen, it displays the login name, name, directory, shell, login time, email, but not the plan, PGP key, and project of the user."
},
{
"code": null,
"e": 25603,
"s": 25571,
"text": "4. To create a plan for a user."
},
{
"code": null,
"e": 25635,
"s": 25603,
"text": "$echo \"Plan details\" > ~/.plan\n"
},
{
"code": null,
"e": 25710,
"s": 25635,
"text": "Now, after again using finger command it will display a plan for the user."
},
{
"code": null,
"e": 25745,
"s": 25710,
"text": "5. To create a project for a user."
},
{
"code": null,
"e": 25783,
"s": 25745,
"text": "$echo \"Project details\" > ~/.project\n"
},
{
"code": null,
"e": 25861,
"s": 25783,
"text": "Now, after again using finger command it will display a project for the user."
},
{
"code": null,
"e": 25896,
"s": 25861,
"text": "6. To create a PGP key for a user."
},
{
"code": null,
"e": 25924,
"s": 25896,
"text": "$echo \"pgpkey\" > ~/.pgpkey\n"
},
{
"code": null,
"e": 26002,
"s": 25924,
"text": "Now, after again using finger command it will display a PGP key for the user."
},
{
"code": null,
"e": 26016,
"s": 26002,
"text": "linux-command"
},
{
"code": null,
"e": 26027,
"s": 26016,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26043,
"s": 26027,
"text": "Write From Home"
},
{
"code": null,
"e": 26141,
"s": 26043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26178,
"s": 26141,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26213,
"s": 26178,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26239,
"s": 26213,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26273,
"s": 26239,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26302,
"s": 26273,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26338,
"s": 26302,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 26374,
"s": 26338,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 26390,
"s": 26374,
"text": "Python infinity"
},
{
"code": null,
"e": 26451,
"s": 26390,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Count pairs with given sum | Set 2 | 07 Jun, 2022
Given an array arr[] and an integer sum, the task is to find the number of pairs of integers in the array whose sum is equal to sum.Examples:
Input: arr[] = {1, 5, 7, -1}, sum = 6 Output: 2 Pairs with sum 6 are (1, 5) and (7, -1)Input: arr[] = {1, 5, 7, -1, 5}, sum = 6 Output: 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input: arr[] = {1, 1, 1, 1}, sum = 2 Output: 6
Approach: Two Different methods have already been discussed here. Here, a method based on sorting will be discussed.
Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1.Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs.
Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1.
Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs.
Greater than the sum then decrement j.
Lesser than the sum then increment i.
Equals to the sum then count such pairs.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs// from arr[] with the given sumint pairs_count(int arr[], int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array sort(arr, arr + n); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while (i < j and arr[i] == x) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while (j >= i and arr[j] == y) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codeint main(){ int arr[] = { 1, 5, 7, 5, -1 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << pairs_count(arr, n, sum); return 0;}
//Java implementation of the approachimport java.util.Arrays;import java.io.*; class GFG{ // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int arr[], int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array Arrays.sort(arr); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while ((i < j ) && (arr[i] == x)) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while ((j >= i )&& (arr[j] == y)) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 5, 7, 5, -1 }; int n = arr.length; int sum = 6; System.out.println (pairs_count(arr, n, sum));}} // The code is contributed by ajit..
# Python3 implementation of the approach # Function to return the count of pairs# from arr with the given sumdef pairs_count(arr, n, sum): # To store the count of pairs ans = 0 # Sort the given array arr = sorted(arr) # Take two pointers i, j = 0, n - 1 while (i < j): # If sum is greater if (arr[i] + arr[j] < sum): i += 1 # If sum is lesser elif (arr[i] + arr[j] > sum): j -= 1 # If sum is equal else: # Find the frequency of arr[i] x = arr[i] xx = i while (i < j and arr[i] == x): i += 1 # Find the frequency of arr[j] y = arr[j] yy = j while (j >= i and arr[j] == y): j -= 1 # If arr[i] and arr[j] are same # then remove the extra number counted if (x == y): temp = i - xx + yy - j - 1 ans += (temp * (temp + 1)) // 2 else: ans += (i - xx) * (yy - j) # Return the required answer return ans # Driver codearr = [1, 5, 7, 5, -1]n = len(arr)sum = 6 print(pairs_count(arr, n, sum)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int []arr, int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array Array.Sort(arr); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while ((i < j) && (arr[i] == x)) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while ((j >= i) && (arr[j] == y)) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 5, 7, 5, -1 }; int n = arr.Length; int sum = 6; Console.WriteLine (pairs_count(arr, n, sum));}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach // Function to return the count of pairs// from arr[] with the given sumfunction pairs_count(arr, n, sum){ // To store the count of pairs let ans = 0; // Sort the given array arr.sort(); // Take two pointers let i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] let x = arr[i], xx = i; while (i < j && arr[i] == x) i++; // Find the frequency of arr[j] let y = arr[j], yy = j; while (j >= i && arr[j] == y) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { let temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver code let arr = [ 1, 5, 7, 5, -1 ]; let n = arr.length; let sum = 6; document.write(pairs_count(arr, n, sum)); // This code is contributed by Mayank Tyagi </script>
3
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
mohit kumar 29
jit_t
princiraj1992
mayanktyagi1709
subham348
Arrays
Mathematical
Sorting
Arrays
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 198,
"s": 54,
"text": "Given an array arr[] and an integer sum, the task is to find the number of pairs of integers in the array whose sum is equal to sum.Examples: "
},
{
"code": null,
"e": 431,
"s": 198,
"text": "Input: arr[] = {1, 5, 7, -1}, sum = 6 Output: 2 Pairs with sum 6 are (1, 5) and (7, -1)Input: arr[] = {1, 5, 7, -1, 5}, sum = 6 Output: 3 Pairs with sum 6 are (1, 5), (7, -1) & (1, 5) Input: arr[] = {1, 1, 1, 1}, sum = 2 Output: 6 "
},
{
"code": null,
"e": 552,
"s": 433,
"text": "Approach: Two Different methods have already been discussed here. Here, a method based on sorting will be discussed. "
},
{
"code": null,
"e": 840,
"s": 552,
"text": "Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1.Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs."
},
{
"code": null,
"e": 1013,
"s": 840,
"text": "Sort the array and take two pointers i and j, one pointer pointing to the start of the array i.e. i = 0 and another pointer pointing to the end of the array i.e. j = n – 1."
},
{
"code": null,
"e": 1129,
"s": 1013,
"text": "Greater than the sum then decrement j.Lesser than the sum then increment i.Equals to the sum then count such pairs."
},
{
"code": null,
"e": 1168,
"s": 1129,
"text": "Greater than the sum then decrement j."
},
{
"code": null,
"e": 1206,
"s": 1168,
"text": "Lesser than the sum then increment i."
},
{
"code": null,
"e": 1247,
"s": 1206,
"text": "Equals to the sum then count such pairs."
},
{
"code": null,
"e": 1300,
"s": 1247,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1304,
"s": 1300,
"text": "C++"
},
{
"code": null,
"e": 1309,
"s": 1304,
"text": "Java"
},
{
"code": null,
"e": 1317,
"s": 1309,
"text": "Python3"
},
{
"code": null,
"e": 1320,
"s": 1317,
"text": "C#"
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs// from arr[] with the given sumint pairs_count(int arr[], int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array sort(arr, arr + n); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while (i < j and arr[i] == x) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while (j >= i and arr[j] == y) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codeint main(){ int arr[] = { 1, 5, 7, 5, -1 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << pairs_count(arr, n, sum); return 0;}",
"e": 2704,
"s": 1331,
"text": null
},
{
"code": "//Java implementation of the approachimport java.util.Arrays;import java.io.*; class GFG{ // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int arr[], int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array Arrays.sort(arr); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while ((i < j ) && (arr[i] == x)) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while ((j >= i )&& (arr[j] == y)) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 5, 7, 5, -1 }; int n = arr.length; int sum = 6; System.out.println (pairs_count(arr, n, sum));}} // The code is contributed by ajit..",
"e": 4196,
"s": 2704,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of pairs# from arr with the given sumdef pairs_count(arr, n, sum): # To store the count of pairs ans = 0 # Sort the given array arr = sorted(arr) # Take two pointers i, j = 0, n - 1 while (i < j): # If sum is greater if (arr[i] + arr[j] < sum): i += 1 # If sum is lesser elif (arr[i] + arr[j] > sum): j -= 1 # If sum is equal else: # Find the frequency of arr[i] x = arr[i] xx = i while (i < j and arr[i] == x): i += 1 # Find the frequency of arr[j] y = arr[j] yy = j while (j >= i and arr[j] == y): j -= 1 # If arr[i] and arr[j] are same # then remove the extra number counted if (x == y): temp = i - xx + yy - j - 1 ans += (temp * (temp + 1)) // 2 else: ans += (i - xx) * (yy - j) # Return the required answer return ans # Driver codearr = [1, 5, 7, 5, -1]n = len(arr)sum = 6 print(pairs_count(arr, n, sum)) # This code is contributed by Mohit Kumar",
"e": 5465,
"s": 4196,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of pairs// from arr[] with the given sumstatic int pairs_count(int []arr, int n, int sum){ // To store the count of pairs int ans = 0; // Sort the given array Array.Sort(arr); // Take two pointers int i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] int x = arr[i], xx = i; while ((i < j) && (arr[i] == x)) i++; // Find the frequency of arr[j] int y = arr[j], yy = j; while ((j >= i) && (arr[j] == y)) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { int temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 5, 7, 5, -1 }; int n = arr.Length; int sum = 6; Console.WriteLine (pairs_count(arr, n, sum));}} // This code is contributed by PrinciRaj1992",
"e": 6959,
"s": 5465,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of pairs// from arr[] with the given sumfunction pairs_count(arr, n, sum){ // To store the count of pairs let ans = 0; // Sort the given array arr.sort(); // Take two pointers let i = 0, j = n - 1; while (i < j) { // If sum is greater if (arr[i] + arr[j] < sum) i++; // If sum is lesser else if (arr[i] + arr[j] > sum) j--; // If sum is equal else { // Find the frequency of arr[i] let x = arr[i], xx = i; while (i < j && arr[i] == x) i++; // Find the frequency of arr[j] let y = arr[j], yy = j; while (j >= i && arr[j] == y) j--; // If arr[i] and arr[j] are same // then remove the extra number counted if (x == y) { let temp = i - xx + yy - j - 1; ans += (temp * (temp + 1)) / 2; } else ans += (i - xx) * (yy - j); } } // Return the required answer return ans;} // Driver code let arr = [ 1, 5, 7, 5, -1 ]; let n = arr.length; let sum = 6; document.write(pairs_count(arr, n, sum)); // This code is contributed by Mayank Tyagi </script>",
"e": 8301,
"s": 6959,
"text": null
},
{
"code": null,
"e": 8303,
"s": 8301,
"text": "3"
},
{
"code": null,
"e": 8335,
"s": 8305,
"text": "Time Complexity: O(n * log n)"
},
{
"code": null,
"e": 8357,
"s": 8335,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8372,
"s": 8357,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8378,
"s": 8372,
"text": "jit_t"
},
{
"code": null,
"e": 8392,
"s": 8378,
"text": "princiraj1992"
},
{
"code": null,
"e": 8408,
"s": 8392,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 8418,
"s": 8408,
"text": "subham348"
},
{
"code": null,
"e": 8425,
"s": 8418,
"text": "Arrays"
},
{
"code": null,
"e": 8438,
"s": 8425,
"text": "Mathematical"
},
{
"code": null,
"e": 8446,
"s": 8438,
"text": "Sorting"
},
{
"code": null,
"e": 8453,
"s": 8446,
"text": "Arrays"
},
{
"code": null,
"e": 8466,
"s": 8453,
"text": "Mathematical"
},
{
"code": null,
"e": 8474,
"s": 8466,
"text": "Sorting"
},
{
"code": null,
"e": 8572,
"s": 8474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8640,
"s": 8572,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8684,
"s": 8640,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8716,
"s": 8684,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8764,
"s": 8716,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8778,
"s": 8764,
"text": "Linear Search"
},
{
"code": null,
"e": 8808,
"s": 8778,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 8851,
"s": 8808,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8911,
"s": 8851,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8926,
"s": 8911,
"text": "C++ Data Types"
}
] |
Java Guava | isPrime() method of IntMath Class | 23 Jan, 2019
The isPrime(int n) method of Guava’s IntMath class is used to check whether the parameter passed to it is a prime number or not. If the parameter passed to it is prime, then it returns True otherwise it returns False.
A number is said to be Prime if it is divisible only by 1 and the number itself.
Syntax :
public static boolean isPrime(int n)
Parameter: The method accepts only one parameter n which is of integer type and is to be checked for primality.
Return Value :
true : if n is a prime number.
false : if n is 0, 1 or composite number.
Exceptions : The method isPrime(int n) throws IllegalArgumentException if n is negative.
Example 1 :
// Java code to show implementation of // isPrime(int n) method of Guava's // IntMath classimport java.math.RoundingMode; import com.google.common.math.IntMath; class GFG { // Driver code public static void main(String args[]) { int a1 = 63; // Using isPrime(int n) // method of Guava's IntMath class if(IntMath.isPrime(a1)) System.out.println(a1 + " is a prime number"); else System.out.println(a1 + " is not a prime number"); int a2 = 17; // Using isPrime(int n) // method of Guava's IntMath class if(IntMath.isPrime(a2)) System.out.println(a2 + " is a prime number"); else System.out.println(a2 + " is not a prime number"); } }
Output :
63 is not a prime number
17 is a prime number
Example 2 :
// Java code to show implementation of // isPrime(int n) method of Guava's // IntMath classimport java.math.RoundingMode; import com.google.common.math.IntMath; class GFG { static boolean findPrime(int n) { try { // Using isPrime(int n) method // of Guava's IntMath class // This should throw "IllegalArgumentException" // as n is negative boolean ans = IntMath.isPrime(n); // Return the answer return ans; } catch (Exception e) { System.out.println(e); return false; } } // Driver code public static void main(String args[]) { int a1 = -7; try { // Using isPrime(int n) method // of Guava's IntMath class // This should throw "IllegalArgumentException" // as a1 is negative findPrime(a1); } catch (Exception e) { System.out.println(e); } } }
Output :
java.lang.IllegalArgumentException: n (-7) must be >= 0
Reference :https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#isPrime-int-
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
HashMap in Java with Examples
Math pow() method in Java with Example
PriorityQueue in Java
Stack Class in Java
List Interface in Java with Examples
Initialize an ArrayList in Java
ArrayList in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 272,
"s": 54,
"text": "The isPrime(int n) method of Guava’s IntMath class is used to check whether the parameter passed to it is a prime number or not. If the parameter passed to it is prime, then it returns True otherwise it returns False."
},
{
"code": null,
"e": 353,
"s": 272,
"text": "A number is said to be Prime if it is divisible only by 1 and the number itself."
},
{
"code": null,
"e": 362,
"s": 353,
"text": "Syntax :"
},
{
"code": null,
"e": 400,
"s": 362,
"text": "public static boolean isPrime(int n)\n"
},
{
"code": null,
"e": 512,
"s": 400,
"text": "Parameter: The method accepts only one parameter n which is of integer type and is to be checked for primality."
},
{
"code": null,
"e": 527,
"s": 512,
"text": "Return Value :"
},
{
"code": null,
"e": 558,
"s": 527,
"text": "true : if n is a prime number."
},
{
"code": null,
"e": 600,
"s": 558,
"text": "false : if n is 0, 1 or composite number."
},
{
"code": null,
"e": 689,
"s": 600,
"text": "Exceptions : The method isPrime(int n) throws IllegalArgumentException if n is negative."
},
{
"code": null,
"e": 701,
"s": 689,
"text": "Example 1 :"
},
{
"code": "// Java code to show implementation of // isPrime(int n) method of Guava's // IntMath classimport java.math.RoundingMode; import com.google.common.math.IntMath; class GFG { // Driver code public static void main(String args[]) { int a1 = 63; // Using isPrime(int n) // method of Guava's IntMath class if(IntMath.isPrime(a1)) System.out.println(a1 + \" is a prime number\"); else System.out.println(a1 + \" is not a prime number\"); int a2 = 17; // Using isPrime(int n) // method of Guava's IntMath class if(IntMath.isPrime(a2)) System.out.println(a2 + \" is a prime number\"); else System.out.println(a2 + \" is not a prime number\"); } } ",
"e": 1487,
"s": 701,
"text": null
},
{
"code": null,
"e": 1496,
"s": 1487,
"text": "Output :"
},
{
"code": null,
"e": 1543,
"s": 1496,
"text": "63 is not a prime number\n17 is a prime number\n"
},
{
"code": null,
"e": 1555,
"s": 1543,
"text": "Example 2 :"
},
{
"code": "// Java code to show implementation of // isPrime(int n) method of Guava's // IntMath classimport java.math.RoundingMode; import com.google.common.math.IntMath; class GFG { static boolean findPrime(int n) { try { // Using isPrime(int n) method // of Guava's IntMath class // This should throw \"IllegalArgumentException\" // as n is negative boolean ans = IntMath.isPrime(n); // Return the answer return ans; } catch (Exception e) { System.out.println(e); return false; } } // Driver code public static void main(String args[]) { int a1 = -7; try { // Using isPrime(int n) method // of Guava's IntMath class // This should throw \"IllegalArgumentException\" // as a1 is negative findPrime(a1); } catch (Exception e) { System.out.println(e); } } } ",
"e": 2609,
"s": 1555,
"text": null
},
{
"code": null,
"e": 2618,
"s": 2609,
"text": "Output :"
},
{
"code": null,
"e": 2675,
"s": 2618,
"text": "java.lang.IllegalArgumentException: n (-7) must be >= 0\n"
},
{
"code": null,
"e": 2789,
"s": 2675,
"text": "Reference :https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#isPrime-int-"
},
{
"code": null,
"e": 2804,
"s": 2789,
"text": "Java-Functions"
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": "java-guava"
},
{
"code": null,
"e": 2820,
"s": 2815,
"text": "Java"
},
{
"code": null,
"e": 2825,
"s": 2820,
"text": "Java"
},
{
"code": null,
"e": 2923,
"s": 2825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2942,
"s": 2923,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2966,
"s": 2942,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 2998,
"s": 2966,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3028,
"s": 2998,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3067,
"s": 3028,
"text": "Math pow() method in Java with Example"
},
{
"code": null,
"e": 3089,
"s": 3067,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 3109,
"s": 3089,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3146,
"s": 3109,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 3178,
"s": 3146,
"text": "Initialize an ArrayList in Java"
}
] |
Linguistic variable And Linguistic hedges | 08 Oct, 2021
Introduction :
To understand the fuzzy logic & fuzzy set theory, it is important to be familiar with the linguistic variable linguistic hedges. Let’s look at both of them one by one to understand the fuzzy set theory better.
Linguistic Variables :Variables in mathematics normally take numeric values, although non-numeric linguistic variables are frequently employed in fuzzy logic to make the expression of rules and facts easier. For instance, the term ‘Age’ can be used to indicate a linguistic variable with a value such as a child, young, old, and so on.
Linguistic variables are variables with a value made up of linguistic concepts (also known as linguistic words) rather than numbers, such as child, young, and so on.Let’s define AGE as a language variable:
AGE = {Child, Young, Old}
Each AGE linguistic phrase has a membership function for a specific age range. The same age value is mapped to multiple membership values in the range of 0 to 1 by each function. These membership values can then be used to identify whether a person is a child, a young person, or an elderly person. The following is the membership function with regard to each fuzzy term:
Representation of Linguistic Terms of Age
For AGE = 11, we will get a membership value of 0.75 (roughly) in the Child set, 0.2 (approx) in the Young set, and 0 in the Old set, as shown in the diagram. So, if a person’s age is 11, it’s safe to assume that he or she is a child, perhaps a little young but certainly not old.
The formal definition for the linguistic variable is written as :
x,T(x), U, G, M), where :
x - Variable name (in this case, AGE)
T(x)- Set of linguistic terms such as {Child, Young, Old}
U - Universe
G - Syntactical rules which generate the modifies value
linguistic term of x
M - Semantic rules associated with each linguistic term of x with its meaning.
Let us consider an example such as (AGE, {Child, Young, Middle-aged, Old} and U – Set of ages of all the people, G, M).The Semantic rules M give meaning to each linguistic term of AGE. Example: M for the linguistic term Old of the linguistic variable AGE is defined as :
M = {(x,μOld(x)| x∈[0,100]}
and
μOld(x) = { 0 ; ≤ 50
= { (x - 50) / 15 ; 50 < x ≤ 65
= { 1 ; x > 65
The syntactical rules: G that generate the modified value of the linguistic terms of x is given as :
G = (Vn, VT, Pr, S)where :
Vn - Non Terminal Symbols
VT - Terminal Symbols
Pr - Production Rules
S - Start Symbol
Example :Let S be start symbol , Vn = {A, B, C, D, E, S} VT = {and, or, very, more or less, not, almost, young......} Pr = Production Rules : S -> A, S -> S or A, A -> A and B etc.
Linguistic hedges : Linguistic hedges can be used to modify linguistic variables, which is an important feature. Linguistic hedges are primarily employed to aid in the more precise communication of the degree of correctness and truth in a particular statement. For example: If a statement John is Young is associated with the value 0.6 then very young is automatically deduced as having the value 0.6 * 0.6 = 0.36. On the other hand, not very young get the value ( 1 – 0.36 ), i.e., 0.64. In this example, the operator very(X) is defined as X*X; however, in general, these operators may be uniformly, but flexible, defined to fit the application; this results in great power for the expression of both rules and fuzzy facts. Linguistic modifiers such as very, more or less, fairly, and extremely rare examples of hedges. They can modify fuzzy predicates and fuzzy truth values.
In general, for a given fuzzy proposition P, such that
P : x is F
And a linguistic hedge H, we can construct a modified proposition as
HP : x is HF
Here, HF denotes the fuzzy predicate obtained by applying hedge H to predicate F. The predicate can be further modified by applying the hedge to a fuzzy truth value in the given proposition. Any hedge H is interpreted as unary operator ‘h’ on the interval [0,1]. For example hedge very is often interpreted as the unary operator :h(a) = a2 ; for a ∈ [0,1]Similarly, hedge fairly interpreted as the unary operator :h(a) = √a ; or a ∈ [0,1]
A strong modifier strengthens a fuzzy predicate to which it is applied and consequently reduces the truth value of the associated proposition. A weak modifier weakens the predicate and consequently increases the truth value of the associated proposition. Example: If Young (25) = 0.8, Then : very Young(25) = 0.8 ×0.8 = 0.64 and fairly young(25) = √0.8 = 0.89
The modifier h should satisfy the following conditions :
- h is a continuous function
- h(0) = 0; h(1) = 1
- If h is strong, then 1/h is weak and vice versa
- If h and g are two modifiers then compositions of these
modifiers are also modifier such as very little.
If both modifiers are strong, then the composition is also strong and vice versa.
singghakshay
simmytarika5
Artificial Intelligence
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Information Retrieval?
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Sequential Covering Algorithm
ML | Expectation-Maximization Algorithm
Regression and Classification | Supervised Machine Learning
Python | Linear Regression using sklearn
k-nearest neighbor algorithm in Python
Difference between K means and Hierarchical Clustering
Markov Decision Process | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 43,
"s": 28,
"text": "Introduction :"
},
{
"code": null,
"e": 253,
"s": 43,
"text": "To understand the fuzzy logic & fuzzy set theory, it is important to be familiar with the linguistic variable linguistic hedges. Let’s look at both of them one by one to understand the fuzzy set theory better."
},
{
"code": null,
"e": 590,
"s": 253,
"text": "Linguistic Variables :Variables in mathematics normally take numeric values, although non-numeric linguistic variables are frequently employed in fuzzy logic to make the expression of rules and facts easier. For instance, the term ‘Age’ can be used to indicate a linguistic variable with a value such as a child, young, old, and so on. "
},
{
"code": null,
"e": 797,
"s": 590,
"text": "Linguistic variables are variables with a value made up of linguistic concepts (also known as linguistic words) rather than numbers, such as child, young, and so on.Let’s define AGE as a language variable: "
},
{
"code": null,
"e": 823,
"s": 797,
"text": "AGE = {Child, Young, Old}"
},
{
"code": null,
"e": 1196,
"s": 823,
"text": "Each AGE linguistic phrase has a membership function for a specific age range. The same age value is mapped to multiple membership values in the range of 0 to 1 by each function. These membership values can then be used to identify whether a person is a child, a young person, or an elderly person. The following is the membership function with regard to each fuzzy term: "
},
{
"code": null,
"e": 1238,
"s": 1196,
"text": "Representation of Linguistic Terms of Age"
},
{
"code": null,
"e": 1519,
"s": 1238,
"text": "For AGE = 11, we will get a membership value of 0.75 (roughly) in the Child set, 0.2 (approx) in the Young set, and 0 in the Old set, as shown in the diagram. So, if a person’s age is 11, it’s safe to assume that he or she is a child, perhaps a little young but certainly not old."
},
{
"code": null,
"e": 1586,
"s": 1519,
"text": "The formal definition for the linguistic variable is written as : "
},
{
"code": null,
"e": 1878,
"s": 1586,
"text": "x,T(x), U, G, M), where : \nx - Variable name (in this case, AGE)\nT(x)- Set of linguistic terms such as {Child, Young, Old}\nU - Universe\nG - Syntactical rules which generate the modifies value\nlinguistic term of x\nM - Semantic rules associated with each linguistic term of x with its meaning."
},
{
"code": null,
"e": 2150,
"s": 1878,
"text": "Let us consider an example such as (AGE, {Child, Young, Middle-aged, Old} and U – Set of ages of all the people, G, M).The Semantic rules M give meaning to each linguistic term of AGE. Example: M for the linguistic term Old of the linguistic variable AGE is defined as :"
},
{
"code": null,
"e": 2179,
"s": 2150,
"text": "M = {(x,μOld(x)| x∈[0,100]} "
},
{
"code": null,
"e": 2184,
"s": 2179,
"text": "and "
},
{
"code": null,
"e": 2271,
"s": 2184,
"text": "μOld(x) = { 0 ; ≤ 50\n = { (x - 50) / 15 ; 50 < x ≤ 65\n = { 1 ; x > 65"
},
{
"code": null,
"e": 2372,
"s": 2271,
"text": "The syntactical rules: G that generate the modified value of the linguistic terms of x is given as :"
},
{
"code": null,
"e": 2486,
"s": 2372,
"text": "G = (Vn, VT, Pr, S)where :\nVn - Non Terminal Symbols\nVT - Terminal Symbols\nPr - Production Rules\nS - Start Symbol"
},
{
"code": null,
"e": 2667,
"s": 2486,
"text": "Example :Let S be start symbol , Vn = {A, B, C, D, E, S} VT = {and, or, very, more or less, not, almost, young......} Pr = Production Rules : S -> A, S -> S or A, A -> A and B etc."
},
{
"code": null,
"e": 3547,
"s": 2667,
"text": "Linguistic hedges : Linguistic hedges can be used to modify linguistic variables, which is an important feature. Linguistic hedges are primarily employed to aid in the more precise communication of the degree of correctness and truth in a particular statement. For example: If a statement John is Young is associated with the value 0.6 then very young is automatically deduced as having the value 0.6 * 0.6 = 0.36. On the other hand, not very young get the value ( 1 – 0.36 ), i.e., 0.64. In this example, the operator very(X) is defined as X*X; however, in general, these operators may be uniformly, but flexible, defined to fit the application; this results in great power for the expression of both rules and fuzzy facts. Linguistic modifiers such as very, more or less, fairly, and extremely rare examples of hedges. They can modify fuzzy predicates and fuzzy truth values."
},
{
"code": null,
"e": 3602,
"s": 3547,
"text": "In general, for a given fuzzy proposition P, such that"
},
{
"code": null,
"e": 3613,
"s": 3602,
"text": "P : x is F"
},
{
"code": null,
"e": 3683,
"s": 3613,
"text": "And a linguistic hedge H, we can construct a modified proposition as "
},
{
"code": null,
"e": 3696,
"s": 3683,
"text": "HP : x is HF"
},
{
"code": null,
"e": 4135,
"s": 3696,
"text": "Here, HF denotes the fuzzy predicate obtained by applying hedge H to predicate F. The predicate can be further modified by applying the hedge to a fuzzy truth value in the given proposition. Any hedge H is interpreted as unary operator ‘h’ on the interval [0,1]. For example hedge very is often interpreted as the unary operator :h(a) = a2 ; for a ∈ [0,1]Similarly, hedge fairly interpreted as the unary operator :h(a) = √a ; or a ∈ [0,1]"
},
{
"code": null,
"e": 4496,
"s": 4135,
"text": "A strong modifier strengthens a fuzzy predicate to which it is applied and consequently reduces the truth value of the associated proposition. A weak modifier weakens the predicate and consequently increases the truth value of the associated proposition. Example: If Young (25) = 0.8, Then : very Young(25) = 0.8 ×0.8 = 0.64 and fairly young(25) = √0.8 = 0.89 "
},
{
"code": null,
"e": 4553,
"s": 4496,
"text": "The modifier h should satisfy the following conditions :"
},
{
"code": null,
"e": 4842,
"s": 4553,
"text": "- h is a continuous function\n- h(0) = 0; h(1) = 1\n- If h is strong, then 1/h is weak and vice versa\n- If h and g are two modifiers then compositions of these\nmodifiers are also modifier such as very little.\nIf both modifiers are strong, then the composition is also strong and vice versa."
},
{
"code": null,
"e": 4855,
"s": 4842,
"text": "singghakshay"
},
{
"code": null,
"e": 4868,
"s": 4855,
"text": "simmytarika5"
},
{
"code": null,
"e": 4892,
"s": 4868,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 4909,
"s": 4892,
"text": "Machine Learning"
},
{
"code": null,
"e": 4926,
"s": 4909,
"text": "Machine Learning"
},
{
"code": null,
"e": 5024,
"s": 4926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5055,
"s": 5024,
"text": "What is Information Retrieval?"
},
{
"code": null,
"e": 5096,
"s": 5055,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 5129,
"s": 5096,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 5159,
"s": 5129,
"text": "Sequential Covering Algorithm"
},
{
"code": null,
"e": 5199,
"s": 5159,
"text": "ML | Expectation-Maximization Algorithm"
},
{
"code": null,
"e": 5259,
"s": 5199,
"text": "Regression and Classification | Supervised Machine Learning"
},
{
"code": null,
"e": 5300,
"s": 5259,
"text": "Python | Linear Regression using sklearn"
},
{
"code": null,
"e": 5339,
"s": 5300,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 5394,
"s": 5339,
"text": "Difference between K means and Hierarchical Clustering"
}
] |
How to randomly select rows from Pandas DataFrame | 23 Jan, 2022
Let’s discuss how to randomly select rows from Pandas DataFrame. A random selection of rows from a DataFrame can be achieved in different ways. Create a simple dataframe with dictionary of lists.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # select all columnsdf
Method #1: Using sample() method
Sample method returns a random sample of items from an axis of object and this object of same type as your caller.
Example 1:
Python3
# Selects one row randomly using sample()# without give any parameters. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Select one row randomly using sample()# without give any parametersdf.sample()
Output:
Example 2: Using parameter n, which selects n numbers of rows randomly.Select n numbers of rows randomly using sample(n) or sample(n=n). Each time you run this, you get n different rows.
Python3
# To get 3 random rows# each time it gives 3 different rows # df.sample(3) ordf.sample(n = 3)
Output:
Example 3: Using frac parameter.One can do fraction of axis items and get rows. For example, if frac= .5 then sample method return 50% of rows.
Python3
# Fraction of rows # here you get .50 % of the rowsdf.sample(frac = 0.5)
Output:
Example 4: First selects 70% rows of whole df dataframe and put in another dataframe df1 after that we select 50% frac from df1.
Python3
# fraction of rows # here you get 70 % row from the df# make put into another dataframe df1df1 = df.sample(frac =.7) # Now select 50 % rows from df1df1.sample(frac =.50)
Output:
Example 5: Select some rows randomly with replace = falseParameter replace give permission to select one rows many time(like). Default value of replace parameter of sample() method is False so you never select more than total number of rows.
Python3
# Dataframe df has only 4 rows # if we try to select more than 4 row then will come error# Cannot take a larger sample than population when 'replace = False'df1.sample(n = 3, replace = False)
Output:
Example 6: Select more than n rows where n is total number of rows with the help of replace.
Python3
# Select more than rows with using replace# default it is Falsedf1.sample(n = 6, replace = True)
Output:
Example 7: Using weights
Python3
# Weights will be re-normalized automaticallytest_weights = [0.2, 0.2, 0.2, 0.4] df1.sample(n = 3, weights = test_weights)
Output:
Example 8: Using axisThe axis accepts number or name. sample() method also allows users to sample columns instead of rows using the axis argument.
Python3
# Accepts axis number or name. # sample also allows users to sample columns# instead of rows using the axis argument.df1.sample(axis = 0)
Output:
Example 9: Using random_stateWith a given DataFrame, the sample will always fetch same rows. If random_state is None or np.random, then a randomly-initialized RandomState object is returned.
Python3
# With a given seed, the sample will always draw the same rows. # If random_state is None or np.random,# then a randomly-initialized# RandomState object is returned.df1.sample(n = 2, random_state = 2)
Output:
Method #2: Using NumPyNumpy choose how many index include for random selection and we can allow replacement.
Python3
# Import pandas & Numpy packageimport numpy as npimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Choose how many index include for random selectionchosen_idx = np.random.choice(4, replace = True, size = 6) df2 = df.iloc[chosen_idx] df2
Output:
anikakapoor
adnanirshad158
saurabh1990aror
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 250,
"s": 52,
"text": "Let’s discuss how to randomly select rows from Pandas DataFrame. A random selection of rows from a DataFrame can be achieved in different ways. Create a simple dataframe with dictionary of lists. "
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # select all columnsdf",
"e": 661,
"s": 258,
"text": null
},
{
"code": null,
"e": 696,
"s": 661,
"text": "Method #1: Using sample() method "
},
{
"code": null,
"e": 812,
"s": 696,
"text": "Sample method returns a random sample of items from an axis of object and this object of same type as your caller. "
},
{
"code": null,
"e": 825,
"s": 812,
"text": "Example 1: "
},
{
"code": null,
"e": 833,
"s": 825,
"text": "Python3"
},
{
"code": "# Selects one row randomly using sample()# without give any parameters. # Import pandas packageimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Select one row randomly using sample()# without give any parametersdf.sample()",
"e": 1366,
"s": 833,
"text": null
},
{
"code": null,
"e": 1376,
"s": 1366,
"text": "Output: "
},
{
"code": null,
"e": 1565,
"s": 1376,
"text": "Example 2: Using parameter n, which selects n numbers of rows randomly.Select n numbers of rows randomly using sample(n) or sample(n=n). Each time you run this, you get n different rows. "
},
{
"code": null,
"e": 1573,
"s": 1565,
"text": "Python3"
},
{
"code": "# To get 3 random rows# each time it gives 3 different rows # df.sample(3) ordf.sample(n = 3)",
"e": 1667,
"s": 1573,
"text": null
},
{
"code": null,
"e": 1677,
"s": 1667,
"text": "Output: "
},
{
"code": null,
"e": 1822,
"s": 1677,
"text": "Example 3: Using frac parameter.One can do fraction of axis items and get rows. For example, if frac= .5 then sample method return 50% of rows. "
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Python3"
},
{
"code": "# Fraction of rows # here you get .50 % of the rowsdf.sample(frac = 0.5)",
"e": 1903,
"s": 1830,
"text": null
},
{
"code": null,
"e": 1913,
"s": 1903,
"text": "Output: "
},
{
"code": null,
"e": 2044,
"s": 1913,
"text": "Example 4: First selects 70% rows of whole df dataframe and put in another dataframe df1 after that we select 50% frac from df1. "
},
{
"code": null,
"e": 2052,
"s": 2044,
"text": "Python3"
},
{
"code": "# fraction of rows # here you get 70 % row from the df# make put into another dataframe df1df1 = df.sample(frac =.7) # Now select 50 % rows from df1df1.sample(frac =.50)",
"e": 2222,
"s": 2052,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2222,
"text": "Output: "
},
{
"code": null,
"e": 2475,
"s": 2232,
"text": "Example 5: Select some rows randomly with replace = falseParameter replace give permission to select one rows many time(like). Default value of replace parameter of sample() method is False so you never select more than total number of rows. "
},
{
"code": null,
"e": 2483,
"s": 2475,
"text": "Python3"
},
{
"code": "# Dataframe df has only 4 rows # if we try to select more than 4 row then will come error# Cannot take a larger sample than population when 'replace = False'df1.sample(n = 3, replace = False)",
"e": 2675,
"s": 2483,
"text": null
},
{
"code": null,
"e": 2685,
"s": 2675,
"text": "Output: "
},
{
"code": null,
"e": 2779,
"s": 2685,
"text": "Example 6: Select more than n rows where n is total number of rows with the help of replace. "
},
{
"code": null,
"e": 2787,
"s": 2779,
"text": "Python3"
},
{
"code": "# Select more than rows with using replace# default it is Falsedf1.sample(n = 6, replace = True)",
"e": 2884,
"s": 2787,
"text": null
},
{
"code": null,
"e": 2894,
"s": 2884,
"text": "Output: "
},
{
"code": null,
"e": 2920,
"s": 2894,
"text": "Example 7: Using weights "
},
{
"code": null,
"e": 2928,
"s": 2920,
"text": "Python3"
},
{
"code": "# Weights will be re-normalized automaticallytest_weights = [0.2, 0.2, 0.2, 0.4] df1.sample(n = 3, weights = test_weights)",
"e": 3051,
"s": 2928,
"text": null
},
{
"code": null,
"e": 3061,
"s": 3051,
"text": "Output: "
},
{
"code": null,
"e": 3209,
"s": 3061,
"text": "Example 8: Using axisThe axis accepts number or name. sample() method also allows users to sample columns instead of rows using the axis argument. "
},
{
"code": null,
"e": 3217,
"s": 3209,
"text": "Python3"
},
{
"code": "# Accepts axis number or name. # sample also allows users to sample columns# instead of rows using the axis argument.df1.sample(axis = 0)",
"e": 3355,
"s": 3217,
"text": null
},
{
"code": null,
"e": 3365,
"s": 3355,
"text": "Output: "
},
{
"code": null,
"e": 3557,
"s": 3365,
"text": "Example 9: Using random_stateWith a given DataFrame, the sample will always fetch same rows. If random_state is None or np.random, then a randomly-initialized RandomState object is returned. "
},
{
"code": null,
"e": 3565,
"s": 3557,
"text": "Python3"
},
{
"code": "# With a given seed, the sample will always draw the same rows. # If random_state is None or np.random,# then a randomly-initialized# RandomState object is returned.df1.sample(n = 2, random_state = 2)",
"e": 3766,
"s": 3565,
"text": null
},
{
"code": null,
"e": 3776,
"s": 3766,
"text": "Output: "
},
{
"code": null,
"e": 3888,
"s": 3776,
"text": " Method #2: Using NumPyNumpy choose how many index include for random selection and we can allow replacement. "
},
{
"code": null,
"e": 3896,
"s": 3888,
"text": "Python3"
},
{
"code": "# Import pandas & Numpy packageimport numpy as npimport pandas as pd # Define a dictionary containing employee datadata = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'], 'Age':[27, 24, 22, 32, 15], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']} # Convert the dictionary into DataFramedf = pd.DataFrame(data) # Choose how many index include for random selectionchosen_idx = np.random.choice(4, replace = True, size = 6) df2 = df.iloc[chosen_idx] df2",
"e": 4443,
"s": 3896,
"text": null
},
{
"code": null,
"e": 4453,
"s": 4443,
"text": "Output: "
},
{
"code": null,
"e": 4467,
"s": 4455,
"text": "anikakapoor"
},
{
"code": null,
"e": 4482,
"s": 4467,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4498,
"s": 4482,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4523,
"s": 4498,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 4530,
"s": 4523,
"text": "Picked"
},
{
"code": null,
"e": 4554,
"s": 4530,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4568,
"s": 4554,
"text": "Python-pandas"
},
{
"code": null,
"e": 4592,
"s": 4568,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4599,
"s": 4592,
"text": "Python"
},
{
"code": null,
"e": 4618,
"s": 4599,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4716,
"s": 4618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4734,
"s": 4716,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4776,
"s": 4734,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4798,
"s": 4776,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4833,
"s": 4798,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4865,
"s": 4833,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4894,
"s": 4865,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4921,
"s": 4894,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4951,
"s": 4921,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4972,
"s": 4951,
"text": "Python OOPs Concepts"
}
] |
Shell Script to Display the Digits which are in Odd Position | 09 Feb, 2022
Here given a list of numbers, our task is to find the odd position from the given number.
Example:
Input: 123456
Output: 135
Explanation: 1, 2, 3 are at odd position.
Input: 34567
Output: 357
Explanation: 3, 5, 7 are at odd position.
We will have to input a number from the user for a dynamic script. After the number input, we need to whether the input is a number or not. We may also accept numbers with signs as well. We’ll have to input from the user until he/she inputs a pure number. Then we may exactly how many digits are there in the variable, we then need to loop through only the odd positioned digits and print the same. Usage of cut, read, and other basic Linux utility tools to make the task simpler and efficient.
Approach:
Take input from users.
Count of the digits.
Select the particular digits.
Handle + and – symbols (sign).
Get the result.
Below is the implementation:
#!/bin/bash
n=0
while ! [[ $n =~ "^[-+]?[0-9]+$" ]]
do
read -p "Enter a number : " n
l=${#n}
if [[ $n =~ ^[+-]?[0-9]+$ ]];then
if [[ $n =~ ^[+-] ]];then
i=2
if
if [[ $n =~ ^[0-9] ]];then
i=1
if
while [ $i -le $l ]
do
d=$(echo $n | cut -c $i)
echo $d
i=$(($i + 2))
done
break
if
done
Output:
anikaseth98
rkbhola5
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 144,
"s": 54,
"text": "Here given a list of numbers, our task is to find the odd position from the given number."
},
{
"code": null,
"e": 153,
"s": 144,
"text": "Example:"
},
{
"code": null,
"e": 289,
"s": 153,
"text": "Input: 123456\nOutput: 135\nExplanation: 1, 2, 3 are at odd position.\n\nInput: 34567\nOutput: 357\nExplanation: 3, 5, 7 are at odd position."
},
{
"code": null,
"e": 786,
"s": 289,
"text": "We will have to input a number from the user for a dynamic script. After the number input, we need to whether the input is a number or not. We may also accept numbers with signs as well. We’ll have to input from the user until he/she inputs a pure number. Then we may exactly how many digits are there in the variable, we then need to loop through only the odd positioned digits and print the same. Usage of cut, read, and other basic Linux utility tools to make the task simpler and efficient."
},
{
"code": null,
"e": 796,
"s": 786,
"text": "Approach:"
},
{
"code": null,
"e": 819,
"s": 796,
"text": "Take input from users."
},
{
"code": null,
"e": 840,
"s": 819,
"text": "Count of the digits."
},
{
"code": null,
"e": 870,
"s": 840,
"text": "Select the particular digits."
},
{
"code": null,
"e": 901,
"s": 870,
"text": "Handle + and – symbols (sign)."
},
{
"code": null,
"e": 917,
"s": 901,
"text": "Get the result."
},
{
"code": null,
"e": 946,
"s": 917,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1377,
"s": 946,
"text": "#!/bin/bash\nn=0\nwhile ! [[ $n =~ \"^[-+]?[0-9]+$\" ]]\ndo\n read -p \"Enter a number : \" n\n l=${#n}\n if [[ $n =~ ^[+-]?[0-9]+$ ]];then\n if [[ $n =~ ^[+-] ]];then\n i=2\n if \n if [[ $n =~ ^[0-9] ]];then\n i=1\n if\n while [ $i -le $l ]\n do\n d=$(echo $n | cut -c $i)\n echo $d \n i=$(($i + 2)) \n done\n break \n if\ndone"
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Output:"
},
{
"code": null,
"e": 1397,
"s": 1385,
"text": "anikaseth98"
},
{
"code": null,
"e": 1406,
"s": 1397,
"text": "rkbhola5"
},
{
"code": null,
"e": 1413,
"s": 1406,
"text": "Picked"
},
{
"code": null,
"e": 1426,
"s": 1413,
"text": "Shell Script"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1535,
"s": 1437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1561,
"s": 1535,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1596,
"s": 1561,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1633,
"s": 1596,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1662,
"s": 1633,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1699,
"s": 1662,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1736,
"s": 1699,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1770,
"s": 1736,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1810,
"s": 1770,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1849,
"s": 1810,
"text": "Introduction to Linux Operating System"
}
] |
Convert a Binary Tree into its Mirror Tree | 15 Jun, 2022
Mirror of a Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Trees in the above figure are mirror of each other
Method 1 (Recursive)
Algorithm – Mirror(tree):
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
(1) Call Mirror for left-subtree i.e., Mirror(left-subtree)
(2) Call Mirror for right-subtree i.e., Mirror(right-subtree)
(3) Swap left and right subtrees.
temp = left-subtree
left-subtree = right-subtree
right-subtree = temp
Implementation:
C++
C
Java
Python3
C#
Javascript
// C++ program to convert a binary tree// to its mirror#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointerto left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node withthe given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \1 3 is changed to... 4 / \ 5 2 / \ 3 1*/void mirror(struct Node* node){ if (node == NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function to printInorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); cout << node->data << " "; inOrder(node->right);} // Driver Codeint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << "Inorder traversal of the constructed" << " tree is" << endl; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << "\nInorder traversal of the mirror tree" << " is \n"; inOrder(root); return 0;} // This code is contributed by Akanksha Rai
// C program to convert a binary tree// to its mirror#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1*/void mirror(struct Node* node){ if (node==NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function to print Inorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); printf("%d ", node->data); inOrder(node->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ printf("Inorder traversal of the constructed" " tree is \n"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ printf("\nInorder traversal of the mirror tree" " is \n"); inOrder(root); return 0; }
// Java program to convert binary tree into its mirror /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void mirror() { root = mirror(root); } Node mirror(Node node) { if (node == null) return node; /* do the subtrees */ Node left = mirror(node.left); Node right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; } void inOrder() { inOrder(root); } /* Helper function to test mirror(). Given a binary search tree, print out its data elements in increasing sorted order.*/ void inOrder(Node node) { if (node == null) return; inOrder(node.left); System.out.print(node.data + " "); inOrder(node.right); } /* testing for example nodes */ public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* print inorder traversal of the input tree */ System.out.println("Inorder traversal of input tree is :"); tree.inOrder(); System.out.println(""); /* convert tree to its mirror */ tree.mirror(); /* print inorder traversal of the minor tree */ System.out.println("Inorder traversal of binary tree is : "); tree.inOrder(); }}
# Python3 program to convert a binary# tree to its mirror # Utility function to create a new# tree nodeclass newNode: def __init__(self,data): self.data = data self.left = self.right = None """ Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1"""def mirror(node): if (node == None): return else: temp = node """ do the subtrees """ mirror(node.left) mirror(node.right) """ swap the pointers in this node """ temp = node.left node.left = node.right node.right = temp """ Helper function to print Inorder traversal."""def inOrder(node) : if (node == None): return inOrder(node.left) print(node.data, end = " ") inOrder(node.right) # Driver codeif __name__ =="__main__": root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) """ Print inorder traversal of the input tree """ print("Inorder traversal of the", "constructed tree is") inOrder(root) """ Convert tree to its mirror """ mirror(root) """ Print inorder traversal of the mirror tree """ print("\nInorder traversal of", "the mirror treeis ") inOrder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to convert binary// tree into its mirrorusing System; // Class containing left and right// child of current node and key valuepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; public virtual void mirror(){ root = mirror(root);} public virtual Node mirror(Node node){ if (node == null) { return node; } /* do the subtrees */ Node left = mirror(node.left); Node right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node;} public virtual void inOrder(){ inOrder(root);} /* Helper function to test mirror().Given a binary search tree, print out itsdata elements in increasing sorted order.*/public virtual void inOrder(Node node){ if (node == null) { return; } inOrder(node.left); Console.Write(node.data + " "); inOrder(node.right);} /* testing for example nodes */public static void Main(string[] args){ /* creating a binary tree and entering the nodes */ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* print inorder traversal of the input tree */ Console.WriteLine("Inorder traversal " + "of input tree is :"); tree.inOrder(); Console.WriteLine(""); /* convert tree to its mirror */ tree.mirror(); /* print inorder traversal of the minor tree */ Console.WriteLine("Inorder traversal " + "of binary tree is : "); tree.inOrder();}} // This code is contributed by Shrikant13
<script> // JavaScript program to convert// binary tree into its mirror /* Class containing left and right child of current node and key value*/ class Node{ constructor(item) { this.data=item; this.left=this.right=null; }} let root; function mirror(node) { if (node == null) return node; /* do the subtrees */ let left = mirror(node.left); let right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; } /* Helper function to test mirror(). Given a binary search tree, print out its data elements in increasing sorted order.*/ function inOrder(node) { if (node == null) return; inOrder(node.left); document.write(node.data + " "); inOrder(node.right); } /* testing for example nodes */ /* creating a binary tree and entering the nodes */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* print inorder traversal of the input tree */ document.write("Inorder traversal of input tree is :<br>"); inOrder(root); document.write("<br>"); /* convert tree to its mirror */ mirror(root); /* print inorder traversal of the minor tree */ document.write( "Inorder traversal of binary tree is : <br>" ); inOrder(root); // This code is contributed by rag2127 </script>
Output:
Inorder traversal of the constructed tree is
4 2 5 1 3
Inorder traversal of the mirror tree is
3 1 5 2 4
Time & Space Complexities: Worst-case Time complexity is O(n) and for space complexity, If we don’t consider the size of the recursive stack for function calls then O(1) otherwise O(h) where h is the height of the tree. This program is similar to traversal of tree space and time complexities will be the same as Tree traversal more for information Please see our Tree Traversal post for details.
Convert a Binary Tree into its Mirror Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersConvert a Binary Tree into its Mirror Tree | 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 / 6:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=FtdyIHBaKjc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Method 2 (Iterative): The idea is to do queue based level order traversal. While doing traversal, swap left and right children of every node.Implementation:
C++
Java
Python3
C#
Javascript
// Iterative CPP program to convert a Binary// Tree to its mirror#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1*/void mirror(Node* root){ if (root == NULL) return; queue<Node*> q; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (!q.empty()) { // pop top node from queue Node* curr = q.front(); q.pop(); // swap left child with right child swap(curr->left, curr->right); // push left and right children if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); }} /* Helper function to print Inorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); cout << node->data << " "; inOrder(node->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << "\n Inorder traversal of the" " constructed tree is \n"; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << "\n Inorder traversal of the " "mirror tree is \n"; inOrder(root); return 0;}
// Iterative Java program to convert a Binary// Tree to its mirrorimport java.util.*; class GFG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node{ int data; Node left; Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node.So the tree... 4 / \ 2 5 / \1 3 is changed to... 4 / \ 5 2 / \ 3 1*/static void mirror(Node root){ if (root == null) return; Queue<Node> q = new LinkedList<>(); q.add(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.size() > 0) { // pop top node from queue Node curr = q.peek(); q.remove(); // swap left child with right child Node temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.add(curr.left); if (curr.right != null) q.add(curr.right); }} /* Helper function to print Inorder traversal.*/static void inOrder( Node node){ if (node == null) return; inOrder(node.left); System.out.print( node.data + " "); inOrder(node.right);} /* Driver code */public static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ System.out.print( "\n Inorder traversal of the" +" coned tree is \n"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ System.out.print( "\n Inorder traversal of the "+ "mirror tree is \n"); inOrder(root);}} // This code is contributed by Arnab Kundu
# Python3 program to convert a Binary# Tree to its mirror # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node# with the given data and None left and# right pointersclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 ''' def mirror( root): if (root == None): return q = [] q.append(root) # Do BFS. While doing BFS, keep swapping # left and right children while (len(q)): # pop top node from queue curr = q[0] q.pop(0) # swap left child with right child curr.left, curr.right = curr.right, curr.left # append left and right children if (curr.left): q.append(curr.left) if (curr.right): q.append(curr.right) """ Helper function to print Inorder traversal."""def inOrder( node): if (node == None): return inOrder(node.left) print(node.data, end = " ") inOrder(node.right) # Driver coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5) """ Print inorder traversal of the input tree """print("Inorder traversal of the constructed tree is")inOrder(root) """ Convert tree to its mirror """mirror(root) """ Print inorder traversal of the mirror tree """print("\nInorder traversal of the mirror tree is")inOrder(root) # This code is contributed by SHUBHAMSINGH10
// C# Iterative Java program to convert a Binary// Tree to its mirrorusing System.Collections.Generic;using System; class GFG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int data; public Node left; public Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node.So the tree... 4 / \ 2 5 / \1 3 is changed to... 4 / \ 5 2 / \ 3 1*/static void mirror(Node root){ if (root == null) return; Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.Count > 0) { // pop top node from queue Node curr = q.Peek(); q.Dequeue(); // swap left child with right child Node temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.Enqueue(curr.left); if (curr.right != null) q.Enqueue(curr.right); }} /* Helper function to print Inorder traversal.*/static void inOrder( Node node){ if (node == null) return; inOrder(node.left); Console.Write( node.data + " "); inOrder(node.right);} /* Driver code */public static void Main(String []args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ Console.Write( "\n Inorder traversal of the" +" coned tree is \n"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ Console.Write( "\n Inorder traversal of the "+ "mirror tree is \n"); inOrder(root);}} // This code is contributed by 29AjayKumar
<script> // Iterative Javascript program to convert a Binary // Tree to its mirror class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function newNode(data) { let node = new Node(data); return(node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 */ function mirror(root) { if (root == null) return; let q = []; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.length > 0) { // pop top node from queue let curr = q[0]; q.shift(); // swap left child with right child let temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.push(curr.left); if (curr.right != null) q.push(curr.right); } } /* Helper function to print Inorder traversal.*/ function inOrder(node) { if (node == null) return; inOrder(node.left); document.write( node.data + " "); inOrder(node.right); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ document.write(" Inorder traversal of the" +" constructed tree is " + "</br>"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ document.write("</br>" + " Inorder traversal of the "+ "mirror tree is " + "</br>"); inOrder(root); </script>
Output:
Inorder traversal of the constructed tree is
4 2 5 1 3
Inorder traversal of the mirror tree is
3 1 5 2 4
shrikanth13
SHUBHAMSINGH10
Akanksha_Rai
andrew1234
29AjayKumar
rag2127
rameshtravel07
jpafymzpbi
hardikkoriintern
Accolite
Adobe
Amazon
Amazon-Question
Belzabar
Belzabar-Question
Convert to Mirror
cpp-queue
eBay
eBay-Question
Get the Mirror
Microsoft
Mirror Tree
Morgan Stanley
Myntra
Myntra-Question
Ola Cabs
OLA-Question
Paytm
Paytm-Question
Prop-Tiger-Question
Samsung
SAP Labs
Snapdeal
Snapdeal-Question
tree-traversal
Trees
VMWare
VMWare-Question
Tree
Paytm
VMWare
Morgan Stanley
Accolite
Amazon
Microsoft
Samsung
Snapdeal
Ola Cabs
Adobe
SAP Labs
Myntra
Belzabar
eBay
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 191,
"s": 52,
"text": "Mirror of a Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. "
},
{
"code": null,
"e": 242,
"s": 191,
"text": "Trees in the above figure are mirror of each other"
},
{
"code": null,
"e": 263,
"s": 242,
"text": "Method 1 (Recursive)"
},
{
"code": null,
"e": 290,
"s": 263,
"text": "Algorithm – Mirror(tree): "
},
{
"code": null,
"e": 299,
"s": 290,
"text": "Chapters"
},
{
"code": null,
"e": 326,
"s": 299,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 376,
"s": 326,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 399,
"s": 376,
"text": "captions off, selected"
},
{
"code": null,
"e": 407,
"s": 399,
"text": "English"
},
{
"code": null,
"e": 431,
"s": 407,
"text": "This is a modal window."
},
{
"code": null,
"e": 500,
"s": 431,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 522,
"s": 500,
"text": "End of dialog window."
},
{
"code": null,
"e": 785,
"s": 522,
"text": "(1) Call Mirror for left-subtree i.e., Mirror(left-subtree)\n(2) Call Mirror for right-subtree i.e., Mirror(right-subtree)\n(3) Swap left and right subtrees.\n temp = left-subtree\n left-subtree = right-subtree\n right-subtree = temp"
},
{
"code": null,
"e": 801,
"s": 785,
"text": "Implementation:"
},
{
"code": null,
"e": 805,
"s": 801,
"text": "C++"
},
{
"code": null,
"e": 807,
"s": 805,
"text": "C"
},
{
"code": null,
"e": 812,
"s": 807,
"text": "Java"
},
{
"code": null,
"e": 820,
"s": 812,
"text": "Python3"
},
{
"code": null,
"e": 823,
"s": 820,
"text": "C#"
},
{
"code": null,
"e": 834,
"s": 823,
"text": "Javascript"
},
{
"code": "// C++ program to convert a binary tree// to its mirror#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointerto left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node withthe given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\1 3 is changed to... 4 / \\ 5 2 / \\ 3 1*/void mirror(struct Node* node){ if (node == NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function to printInorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); cout << node->data << \" \"; inOrder(node->right);} // Driver Codeint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << \"Inorder traversal of the constructed\" << \" tree is\" << endl; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << \"\\nInorder traversal of the mirror tree\" << \" is \\n\"; inOrder(root); return 0;} // This code is contributed by Akanksha Rai",
"e": 2757,
"s": 834,
"text": null
},
{
"code": "// C program to convert a binary tree// to its mirror#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\ 1 3 is changed to... 4 / \\ 5 2 / \\ 3 1*/void mirror(struct Node* node){ if (node==NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function to print Inorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); printf(\"%d \", node->data); inOrder(node->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ printf(\"Inorder traversal of the constructed\" \" tree is \\n\"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ printf(\"\\nInorder traversal of the mirror tree\" \" is \\n\"); inOrder(root); return 0; }",
"e": 4581,
"s": 2757,
"text": null
},
{
"code": "// Java program to convert binary tree into its mirror /* Class containing left and right child of current node and key value*/class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; void mirror() { root = mirror(root); } Node mirror(Node node) { if (node == null) return node; /* do the subtrees */ Node left = mirror(node.left); Node right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; } void inOrder() { inOrder(root); } /* Helper function to test mirror(). Given a binary search tree, print out its data elements in increasing sorted order.*/ void inOrder(Node node) { if (node == null) return; inOrder(node.left); System.out.print(node.data + \" \"); inOrder(node.right); } /* testing for example nodes */ public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* print inorder traversal of the input tree */ System.out.println(\"Inorder traversal of input tree is :\"); tree.inOrder(); System.out.println(\"\"); /* convert tree to its mirror */ tree.mirror(); /* print inorder traversal of the minor tree */ System.out.println(\"Inorder traversal of binary tree is : \"); tree.inOrder(); }}",
"e": 6385,
"s": 4581,
"text": null
},
{
"code": "# Python3 program to convert a binary# tree to its mirror # Utility function to create a new# tree nodeclass newNode: def __init__(self,data): self.data = data self.left = self.right = None \"\"\" Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\ 1 3 is changed to... 4 / \\ 5 2 / \\ 3 1\"\"\"def mirror(node): if (node == None): return else: temp = node \"\"\" do the subtrees \"\"\" mirror(node.left) mirror(node.right) \"\"\" swap the pointers in this node \"\"\" temp = node.left node.left = node.right node.right = temp \"\"\" Helper function to print Inorder traversal.\"\"\"def inOrder(node) : if (node == None): return inOrder(node.left) print(node.data, end = \" \") inOrder(node.right) # Driver codeif __name__ ==\"__main__\": root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) \"\"\" Print inorder traversal of the input tree \"\"\" print(\"Inorder traversal of the\", \"constructed tree is\") inOrder(root) \"\"\" Convert tree to its mirror \"\"\" mirror(root) \"\"\" Print inorder traversal of the mirror tree \"\"\" print(\"\\nInorder traversal of\", \"the mirror treeis \") inOrder(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 7891,
"s": 6385,
"text": null
},
{
"code": "// C# program to convert binary// tree into its mirrorusing System; // Class containing left and right// child of current node and key valuepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class GFG{public Node root; public virtual void mirror(){ root = mirror(root);} public virtual Node mirror(Node node){ if (node == null) { return node; } /* do the subtrees */ Node left = mirror(node.left); Node right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node;} public virtual void inOrder(){ inOrder(root);} /* Helper function to test mirror().Given a binary search tree, print out itsdata elements in increasing sorted order.*/public virtual void inOrder(Node node){ if (node == null) { return; } inOrder(node.left); Console.Write(node.data + \" \"); inOrder(node.right);} /* testing for example nodes */public static void Main(string[] args){ /* creating a binary tree and entering the nodes */ GFG tree = new GFG(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* print inorder traversal of the input tree */ Console.WriteLine(\"Inorder traversal \" + \"of input tree is :\"); tree.inOrder(); Console.WriteLine(\"\"); /* convert tree to its mirror */ tree.mirror(); /* print inorder traversal of the minor tree */ Console.WriteLine(\"Inorder traversal \" + \"of binary tree is : \"); tree.inOrder();}} // This code is contributed by Shrikant13",
"e": 9667,
"s": 7891,
"text": null
},
{
"code": "<script> // JavaScript program to convert// binary tree into its mirror /* Class containing left and right child of current node and key value*/ class Node{ constructor(item) { this.data=item; this.left=this.right=null; }} let root; function mirror(node) { if (node == null) return node; /* do the subtrees */ let left = mirror(node.left); let right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; } /* Helper function to test mirror(). Given a binary search tree, print out its data elements in increasing sorted order.*/ function inOrder(node) { if (node == null) return; inOrder(node.left); document.write(node.data + \" \"); inOrder(node.right); } /* testing for example nodes */ /* creating a binary tree and entering the nodes */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* print inorder traversal of the input tree */ document.write(\"Inorder traversal of input tree is :<br>\"); inOrder(root); document.write(\"<br>\"); /* convert tree to its mirror */ mirror(root); /* print inorder traversal of the minor tree */ document.write( \"Inorder traversal of binary tree is : <br>\" ); inOrder(root); // This code is contributed by rag2127 </script>",
"e": 11328,
"s": 9667,
"text": null
},
{
"code": null,
"e": 11338,
"s": 11328,
"text": "Output: "
},
{
"code": null,
"e": 11447,
"s": 11338,
"text": "Inorder traversal of the constructed tree is \n4 2 5 1 3 \nInorder traversal of the mirror tree is \n3 1 5 2 4 "
},
{
"code": null,
"e": 11845,
"s": 11447,
"text": "Time & Space Complexities: Worst-case Time complexity is O(n) and for space complexity, If we don’t consider the size of the recursive stack for function calls then O(1) otherwise O(h) where h is the height of the tree. This program is similar to traversal of tree space and time complexities will be the same as Tree traversal more for information Please see our Tree Traversal post for details."
},
{
"code": null,
"e": 12747,
"s": 11845,
"text": "Convert a Binary Tree into its Mirror Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersConvert a Binary Tree into its Mirror Tree | 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 / 6:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=FtdyIHBaKjc\" 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": 12904,
"s": 12747,
"text": "Method 2 (Iterative): The idea is to do queue based level order traversal. While doing traversal, swap left and right children of every node.Implementation:"
},
{
"code": null,
"e": 12908,
"s": 12904,
"text": "C++"
},
{
"code": null,
"e": 12913,
"s": 12908,
"text": "Java"
},
{
"code": null,
"e": 12921,
"s": 12913,
"text": "Python3"
},
{
"code": null,
"e": 12924,
"s": 12921,
"text": "C#"
},
{
"code": null,
"e": 12935,
"s": 12924,
"text": "Javascript"
},
{
"code": "// Iterative CPP program to convert a Binary// Tree to its mirror#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left; struct Node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\ 1 3 is changed to... 4 / \\ 5 2 / \\ 3 1*/void mirror(Node* root){ if (root == NULL) return; queue<Node*> q; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (!q.empty()) { // pop top node from queue Node* curr = q.front(); q.pop(); // swap left child with right child swap(curr->left, curr->right); // push left and right children if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); }} /* Helper function to print Inorder traversal.*/void inOrder(struct Node* node){ if (node == NULL) return; inOrder(node->left); cout << node->data << \" \"; inOrder(node->right);} /* Driver program to test mirror() */int main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << \"\\n Inorder traversal of the\" \" constructed tree is \\n\"; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << \"\\n Inorder traversal of the \" \"mirror tree is \\n\"; inOrder(root); return 0;}",
"e": 14979,
"s": 12935,
"text": null
},
{
"code": "// Iterative Java program to convert a Binary// Tree to its mirrorimport java.util.*; class GFG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node{ int data; Node left; Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node.So the tree... 4 / \\ 2 5 / \\1 3 is changed to... 4 / \\ 5 2 / \\ 3 1*/static void mirror(Node root){ if (root == null) return; Queue<Node> q = new LinkedList<>(); q.add(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.size() > 0) { // pop top node from queue Node curr = q.peek(); q.remove(); // swap left child with right child Node temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.add(curr.left); if (curr.right != null) q.add(curr.right); }} /* Helper function to print Inorder traversal.*/static void inOrder( Node node){ if (node == null) return; inOrder(node.left); System.out.print( node.data + \" \"); inOrder(node.right);} /* Driver code */public static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ System.out.print( \"\\n Inorder traversal of the\" +\" coned tree is \\n\"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ System.out.print( \"\\n Inorder traversal of the \"+ \"mirror tree is \\n\"); inOrder(root);}} // This code is contributed by Arnab Kundu",
"e": 17077,
"s": 14979,
"text": null
},
{
"code": "# Python3 program to convert a Binary# Tree to its mirror # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node# with the given data and None left and# right pointersclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\ 1 3 is changed to... 4 / \\ 5 2 / \\ 3 1 ''' def mirror( root): if (root == None): return q = [] q.append(root) # Do BFS. While doing BFS, keep swapping # left and right children while (len(q)): # pop top node from queue curr = q[0] q.pop(0) # swap left child with right child curr.left, curr.right = curr.right, curr.left # append left and right children if (curr.left): q.append(curr.left) if (curr.right): q.append(curr.right) \"\"\" Helper function to print Inorder traversal.\"\"\"def inOrder( node): if (node == None): return inOrder(node.left) print(node.data, end = \" \") inOrder(node.right) # Driver coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5) \"\"\" Print inorder traversal of the input tree \"\"\"print(\"Inorder traversal of the constructed tree is\")inOrder(root) \"\"\" Convert tree to its mirror \"\"\"mirror(root) \"\"\" Print inorder traversal of the mirror tree \"\"\"print(\"\\nInorder traversal of the mirror tree is\")inOrder(root) # This code is contributed by SHUBHAMSINGH10",
"e": 18818,
"s": 17077,
"text": null
},
{
"code": "// C# Iterative Java program to convert a Binary// Tree to its mirrorusing System.Collections.Generic;using System; class GFG{ /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int data; public Node left; public Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return(node);} /* Change a tree so that the roles of the left and right pointers are swapped at every node.So the tree... 4 / \\ 2 5 / \\1 3 is changed to... 4 / \\ 5 2 / \\ 3 1*/static void mirror(Node root){ if (root == null) return; Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.Count > 0) { // pop top node from queue Node curr = q.Peek(); q.Dequeue(); // swap left child with right child Node temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.Enqueue(curr.left); if (curr.right != null) q.Enqueue(curr.right); }} /* Helper function to print Inorder traversal.*/static void inOrder( Node node){ if (node == null) return; inOrder(node.left); Console.Write( node.data + \" \"); inOrder(node.right);} /* Driver code */public static void Main(String []args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ Console.Write( \"\\n Inorder traversal of the\" +\" coned tree is \\n\"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ Console.Write( \"\\n Inorder traversal of the \"+ \"mirror tree is \\n\"); inOrder(root);}} // This code is contributed by 29AjayKumar",
"e": 20973,
"s": 18818,
"text": null
},
{
"code": "<script> // Iterative Javascript program to convert a Binary // Tree to its mirror class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function newNode(data) { let node = new Node(data); return(node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \\ 2 5 / \\ 1 3 is changed to... 4 / \\ 5 2 / \\ 3 1 */ function mirror(root) { if (root == null) return; let q = []; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (q.length > 0) { // pop top node from queue let curr = q[0]; q.shift(); // swap left child with right child let temp = curr.left; curr.left = curr.right; curr.right = temp;; // push left and right children if (curr.left != null) q.push(curr.left); if (curr.right != null) q.push(curr.right); } } /* Helper function to print Inorder traversal.*/ function inOrder(node) { if (node == null) return; inOrder(node.left); document.write( node.data + \" \"); inOrder(node.right); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* Print inorder traversal of the input tree */ document.write(\" Inorder traversal of the\" +\" constructed tree is \" + \"</br>\"); inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ document.write(\"</br>\" + \" Inorder traversal of the \"+ \"mirror tree is \" + \"</br>\"); inOrder(root); </script>",
"e": 23120,
"s": 20973,
"text": null
},
{
"code": null,
"e": 23129,
"s": 23120,
"text": "Output: "
},
{
"code": null,
"e": 23240,
"s": 23129,
"text": " Inorder traversal of the constructed tree is \n4 2 5 1 3 \n Inorder traversal of the mirror tree is \n3 1 5 2 4 "
},
{
"code": null,
"e": 23252,
"s": 23240,
"text": "shrikanth13"
},
{
"code": null,
"e": 23267,
"s": 23252,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 23280,
"s": 23267,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 23291,
"s": 23280,
"text": "andrew1234"
},
{
"code": null,
"e": 23303,
"s": 23291,
"text": "29AjayKumar"
},
{
"code": null,
"e": 23311,
"s": 23303,
"text": "rag2127"
},
{
"code": null,
"e": 23326,
"s": 23311,
"text": "rameshtravel07"
},
{
"code": null,
"e": 23337,
"s": 23326,
"text": "jpafymzpbi"
},
{
"code": null,
"e": 23354,
"s": 23337,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 23363,
"s": 23354,
"text": "Accolite"
},
{
"code": null,
"e": 23369,
"s": 23363,
"text": "Adobe"
},
{
"code": null,
"e": 23376,
"s": 23369,
"text": "Amazon"
},
{
"code": null,
"e": 23392,
"s": 23376,
"text": "Amazon-Question"
},
{
"code": null,
"e": 23401,
"s": 23392,
"text": "Belzabar"
},
{
"code": null,
"e": 23419,
"s": 23401,
"text": "Belzabar-Question"
},
{
"code": null,
"e": 23437,
"s": 23419,
"text": "Convert to Mirror"
},
{
"code": null,
"e": 23447,
"s": 23437,
"text": "cpp-queue"
},
{
"code": null,
"e": 23452,
"s": 23447,
"text": "eBay"
},
{
"code": null,
"e": 23466,
"s": 23452,
"text": "eBay-Question"
},
{
"code": null,
"e": 23481,
"s": 23466,
"text": "Get the Mirror"
},
{
"code": null,
"e": 23491,
"s": 23481,
"text": "Microsoft"
},
{
"code": null,
"e": 23503,
"s": 23491,
"text": "Mirror Tree"
},
{
"code": null,
"e": 23518,
"s": 23503,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 23525,
"s": 23518,
"text": "Myntra"
},
{
"code": null,
"e": 23541,
"s": 23525,
"text": "Myntra-Question"
},
{
"code": null,
"e": 23550,
"s": 23541,
"text": "Ola Cabs"
},
{
"code": null,
"e": 23563,
"s": 23550,
"text": "OLA-Question"
},
{
"code": null,
"e": 23569,
"s": 23563,
"text": "Paytm"
},
{
"code": null,
"e": 23584,
"s": 23569,
"text": "Paytm-Question"
},
{
"code": null,
"e": 23604,
"s": 23584,
"text": "Prop-Tiger-Question"
},
{
"code": null,
"e": 23612,
"s": 23604,
"text": "Samsung"
},
{
"code": null,
"e": 23621,
"s": 23612,
"text": "SAP Labs"
},
{
"code": null,
"e": 23630,
"s": 23621,
"text": "Snapdeal"
},
{
"code": null,
"e": 23648,
"s": 23630,
"text": "Snapdeal-Question"
},
{
"code": null,
"e": 23663,
"s": 23648,
"text": "tree-traversal"
},
{
"code": null,
"e": 23669,
"s": 23663,
"text": "Trees"
},
{
"code": null,
"e": 23676,
"s": 23669,
"text": "VMWare"
},
{
"code": null,
"e": 23692,
"s": 23676,
"text": "VMWare-Question"
},
{
"code": null,
"e": 23697,
"s": 23692,
"text": "Tree"
},
{
"code": null,
"e": 23703,
"s": 23697,
"text": "Paytm"
},
{
"code": null,
"e": 23710,
"s": 23703,
"text": "VMWare"
},
{
"code": null,
"e": 23725,
"s": 23710,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 23734,
"s": 23725,
"text": "Accolite"
},
{
"code": null,
"e": 23741,
"s": 23734,
"text": "Amazon"
},
{
"code": null,
"e": 23751,
"s": 23741,
"text": "Microsoft"
},
{
"code": null,
"e": 23759,
"s": 23751,
"text": "Samsung"
},
{
"code": null,
"e": 23768,
"s": 23759,
"text": "Snapdeal"
},
{
"code": null,
"e": 23777,
"s": 23768,
"text": "Ola Cabs"
},
{
"code": null,
"e": 23783,
"s": 23777,
"text": "Adobe"
},
{
"code": null,
"e": 23792,
"s": 23783,
"text": "SAP Labs"
},
{
"code": null,
"e": 23799,
"s": 23792,
"text": "Myntra"
},
{
"code": null,
"e": 23808,
"s": 23799,
"text": "Belzabar"
},
{
"code": null,
"e": 23813,
"s": 23808,
"text": "eBay"
},
{
"code": null,
"e": 23818,
"s": 23813,
"text": "Tree"
},
{
"code": null,
"e": 23916,
"s": 23818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23948,
"s": 23916,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 23984,
"s": 23948,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 24048,
"s": 23984,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 24091,
"s": 24048,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 24141,
"s": 24091,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 24174,
"s": 24141,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 24200,
"s": 24174,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 24248,
"s": 24200,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 24262,
"s": 24248,
"text": "Decision Tree"
}
] |
Python program to find Tuples with positive elements in List of tuples | 31 Jan, 2022
Given a list of tuples. The task is to get all the tuples that have all positive elements.
Examples:
Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements.
Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple with all positive elements.
Method #1 : Using list comprehension + all()
In this, all() is used to check for all the tuples, list comprehension helps in the iteration of tuples.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using list comprehension + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = [sub for sub in test_list if all(ele >= 0 for ele in sub)] # printing resultprint("Positive elements Tuples : " + str(res))
Method #2 : Using filter() + lambda + all()
In this, the task of filtration is performed using filter() and lambda function.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using filter() + lambda + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list)) # printing resultprint("Positive elements Tuples : " + str(res))
adnanirshad158
Python list-programs
Python tuple-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "Given a list of tuples. The task is to get all the tuples that have all positive elements."
},
{
"code": null,
"e": 129,
"s": 119,
"text": "Examples:"
},
{
"code": null,
"e": 274,
"s": 129,
"text": "Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements."
},
{
"code": null,
"e": 404,
"s": 274,
"text": "Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple with all positive elements. "
},
{
"code": null,
"e": 449,
"s": 404,
"text": "Method #1 : Using list comprehension + all()"
},
{
"code": null,
"e": 554,
"s": 449,
"text": "In this, all() is used to check for all the tuples, list comprehension helps in the iteration of tuples."
},
{
"code": null,
"e": 562,
"s": 554,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Positive Tuples in List# Using list comprehension + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint(\"The original list is : \" + str(test_list)) # all() to check each elementres = [sub for sub in test_list if all(ele >= 0 for ele in sub)] # printing resultprint(\"Positive elements Tuples : \" + str(res))",
"e": 970,
"s": 562,
"text": null
},
{
"code": null,
"e": 1014,
"s": 970,
"text": "Method #2 : Using filter() + lambda + all()"
},
{
"code": null,
"e": 1095,
"s": 1014,
"text": "In this, the task of filtration is performed using filter() and lambda function."
},
{
"code": null,
"e": 1103,
"s": 1095,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Positive Tuples in List# Using filter() + lambda + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint(\"The original list is : \" + str(test_list)) # all() to check each elementres = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list)) # printing resultprint(\"Positive elements Tuples : \" + str(res))",
"e": 1517,
"s": 1103,
"text": null
},
{
"code": null,
"e": 1532,
"s": 1517,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1553,
"s": 1532,
"text": "Python list-programs"
},
{
"code": null,
"e": 1575,
"s": 1553,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1582,
"s": 1575,
"text": "Python"
},
{
"code": null,
"e": 1598,
"s": 1582,
"text": "Python Programs"
},
{
"code": null,
"e": 1696,
"s": 1598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1714,
"s": 1696,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1756,
"s": 1714,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1778,
"s": 1756,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1813,
"s": 1778,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1839,
"s": 1813,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1882,
"s": 1839,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1904,
"s": 1882,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1943,
"s": 1904,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1981,
"s": 1943,
"text": "Python | Convert a list to dictionary"
}
] |
Python | Pandas Series.dt.month | 20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.month attribute return a numpy array containing the month of the datetime in the underlying data of the given series object.
Syntax: Series.dt.month
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# return the monthresult = sr.dt.month # print the resultprint(result)
Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# return the monthresult = sr.dt.month # print the resultprint(result)
Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.month attribute return a numpy array containing the month of the datetime in the underlying data of the given series object."
},
{
"code": null,
"e": 298,
"s": 274,
"text": "Syntax: Series.dt.month"
},
{
"code": null,
"e": 315,
"s": 298,
"text": "Parameter : None"
},
{
"code": null,
"e": 337,
"s": 315,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 466,
"s": 337,
"text": "Example #1: Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 860,
"s": 466,
"text": null
},
{
"code": null,
"e": 869,
"s": 860,
"text": "Output :"
},
{
"code": null,
"e": 998,
"s": 869,
"text": "Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object."
},
{
"code": "# return the monthresult = sr.dt.month # print the resultprint(result)",
"e": 1070,
"s": 998,
"text": null
},
{
"code": null,
"e": 1383,
"s": 1070,
"text": "Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1679,
"s": 1383,
"text": null
},
{
"code": null,
"e": 1688,
"s": 1679,
"text": "Output :"
},
{
"code": null,
"e": 1817,
"s": 1688,
"text": "Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object."
},
{
"code": "# return the monthresult = sr.dt.month # print the resultprint(result)",
"e": 1889,
"s": 1817,
"text": null
},
{
"code": null,
"e": 2072,
"s": 1889,
"text": "Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object."
},
{
"code": null,
"e": 2102,
"s": 2072,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2116,
"s": 2102,
"text": "Python-pandas"
},
{
"code": null,
"e": 2123,
"s": 2116,
"text": "Python"
},
{
"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": 2239,
"s": 2221,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2281,
"s": 2239,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2303,
"s": 2281,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2338,
"s": 2303,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2370,
"s": 2338,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2399,
"s": 2370,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2426,
"s": 2399,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2456,
"s": 2426,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2477,
"s": 2456,
"text": "Python OOPs Concepts"
}
] |
Subsets and Splits