title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
scipy stats.moment() function | Python
|
11 Feb, 2019
scipy.stats.moment(array, axis=0) function calculates the nth moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python).
Its formula –
Parameters :array : Input array or object having the elements to calculate the moment.axis : Axis along which the moment is to be computed. By default axis = 0.moment : Order of central moment that is returned.
Returns : n-th central moment of the array elements based on the set parameters.
Code #1:
# Momentfrom scipy import statsimport numpy as np arr1 = np.array([[1, 31, 27, 13, 21, 9], [8, 12, 8, 4, 7, 10]]) print("Oth moment : \n", stats.moment(arr1, moment = 0))
Output :
Oth moment :
[1. 1. 1. 1. 1. 1.]
Code #2: With multi-dimensional data
# Moment from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print("Oth moment : \n", stats.moment(arr1, moment = 0)) print("\n6th moment : \n", stats.moment(arr1, moment = 6)) print("\n9th moment : \n", stats.moment(arr1, moment = 9, axis = None)) print("\n12th moment : \n", stats.moment(arr1, moment = 12, axis = 1)) print("\n10th moment : \n", stats.moment(arr1, moment = 10, axis = 1))
Output :
Oth moment :
[1. 1. 1.]
6th moment :
[5.20609375e+02 9.13256836e+00 4.26392850e+06]
9th moment :
55265909588.26437
12th moment :
[1.53284936e+14 1.63654317e+02 8.83474172e+03 5.17842143e+04]
10th moment :
[5.53094361e+11 6.10464868e+01 1.64971407e+03 7.65588508e+03]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "scipy.stats.moment(array, axis=0) function calculates the nth moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python)."
},
{
"code": null,
"e": 215,
"s": 201,
"text": "Its formula –"
},
{
"code": null,
"e": 426,
"s": 215,
"text": "Parameters :array : Input array or object having the elements to calculate the moment.axis : Axis along which the moment is to be computed. By default axis = 0.moment : Order of central moment that is returned."
},
{
"code": null,
"e": 507,
"s": 426,
"text": "Returns : n-th central moment of the array elements based on the set parameters."
},
{
"code": null,
"e": 516,
"s": 507,
"text": "Code #1:"
},
{
"code": "# Momentfrom scipy import statsimport numpy as np arr1 = np.array([[1, 31, 27, 13, 21, 9], [8, 12, 8, 4, 7, 10]]) print(\"Oth moment : \\n\", stats.moment(arr1, moment = 0)) ",
"e": 710,
"s": 516,
"text": null
},
{
"code": null,
"e": 719,
"s": 710,
"text": "Output :"
},
{
"code": null,
"e": 754,
"s": 719,
"text": "Oth moment : \n [1. 1. 1. 1. 1. 1.]"
},
{
"code": null,
"e": 792,
"s": 754,
"text": " Code #2: With multi-dimensional data"
},
{
"code": "# Moment from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [3, 4, 6], [7, 6, 3], [3, 6, 8]] print(\"Oth moment : \\n\", stats.moment(arr1, moment = 0)) print(\"\\n6th moment : \\n\", stats.moment(arr1, moment = 6)) print(\"\\n9th moment : \\n\", stats.moment(arr1, moment = 9, axis = None)) print(\"\\n12th moment : \\n\", stats.moment(arr1, moment = 12, axis = 1)) print(\"\\n10th moment : \\n\", stats.moment(arr1, moment = 10, axis = 1))",
"e": 1259,
"s": 792,
"text": null
},
{
"code": null,
"e": 1268,
"s": 1259,
"text": "Output :"
},
{
"code": null,
"e": 1549,
"s": 1268,
"text": "Oth moment : \n [1. 1. 1.]\n\n6th moment : \n [5.20609375e+02 9.13256836e+00 4.26392850e+06]\n\n9th moment : \n 55265909588.26437\n\n12th moment : \n [1.53284936e+14 1.63654317e+02 8.83474172e+03 5.17842143e+04]\n\n10th moment : \n [5.53094361e+11 6.10464868e+01 1.64971407e+03 7.65588508e+03]"
},
{
"code": null,
"e": 1578,
"s": 1549,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 1591,
"s": 1578,
"text": "Python-scipy"
},
{
"code": null,
"e": 1598,
"s": 1591,
"text": "Python"
},
{
"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": 1871,
"s": 1839,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1900,
"s": 1871,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1930,
"s": 1900,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1957,
"s": 1930,
"text": "Python Classes and Objects"
}
] |
Continue Statement in Java
|
23 Jun, 2022
Suppose a person wants code to execute for the values as per the code is designed to be executed but forcefully the same user wants to skip out the execution for which code should have been executed as designed above but will not as per the demand of the user. In simpler words, it is a decision-making problem as per the demand of the user.
Real-Life Example:
Consider a man is climbing up to go to his house in between there are 11 stairs. Being in hurry to climb up he directly stepped onto 3 staircases and then 4, 5, 6, 7, 8, 9 and jumps to last one. During this he missed out staircase 1st, 2nd and 10th and he completed the goal to reach his house. He continued his journey skipping staircase of. his choices.
In computers, it interprets staircases which is/are supposed to be skipped as ‘continue’. The action to miss out execution which are supposed to be executed, is interpreted as continue statement be it any programming language.
Continue statement is often used inside in programming languages inside loops control structures. Inside the loop, when a continue statement is encountered the control directly jumps to the beginning of the loop for the next iteration instead of executing the statements of the current iteration. The continue statement is used when we want to skip a particular condition and continue the rest execution. Java continue statement is used for all type of loops but it is generally used in for, while, and do-while loops.
In the case of for loop, the continue keyword force control to jump immediately to the update statement.
Whereas in the case of a while loop or do-while loop, control immediately jumps to the Boolean expression.
Syntax: continue keyword along with a semicolon
continue;
Flow Chart of Continue Statement
The above flowchart is most important for the understanding of this keyword. Always remember the condition is always placed inside diamond boxes and statements in rectangular boxes. Now jumping onto the implementation part
Case 1: Continue statement inside for loop
In this program, illustration for how to use the continue statement within For loop. When the value of ‘i’ becomes 10 or 12, the continue statement plays its role and skip their execution but for other values of’ ‘i’ the loop will run smoothly.
Java
// Java Program to illustrate the use of continue statement // Importing Classes/Filesimport java.util.*;public class GFG { // Main driver method public static void main(String args[]) { // For loop for iteration for (int i = 0; i <= 15; i++) { // Check condition for continue if (i == 10 || i == 12) { // Using continue statement to skip the // execution of loop when i==10 or i==12 continue; } // Printing elements to show continue statement System.out.print(i + " "); } }}
Output :
0 1 2 3 4 5 6 7 8 9 11 13 14 15
Time Complexity: O(1)
Auxiliary Space : O(1)
Case 2: Continue statement inside while loop
In the below program, we give example, how to use the continue statement within the While loop. When the value of count becomes 7 or 15, the continue statement plays its role and skip their execution but for other values of the count, the loop will run smoothly.
Java
// Java Program to illustrate the use of continue statement// inside the While looppublic class GFG { // Main driver method public static void main(String args[]) { // Initializing a variable say it count to a value // greater than the value greater among the loop // values int count = 20; // While loop for iteration while (count >= 0) { if (count == 7 || count == 15) { count--; // Decrementing variable initialized above // Showing continue execution inside loop // skipping when count==7 or count==15 continue; } // Printing values after continue statement System.out.print(count + " "); // Decrementing the count variable count--; } }}
Output:
20 19 18 17 16 14 13 12 11 10 9 8 6 5 4 3 2 1 0
Time Complexity: O(1)
Auxiliary Space : O(1)
Case 3: Continue statement inside do while loop
In the below program, we give example, of how to use the continue statement within the do-While loop. When the value of I becomes 4 or 18, the continue statement plays its role and skips its execution but for other values of I, the loop will run smoothly.
Java
// Java Program to illustrate the use of continue statement// inside the Do-While loop // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Creating and Initializing a variable int i = 0; // Do-While loop for iteration do { if (i == 4 || i == 18) { // Incrementing loop variable by 2 i += 2; // Illustrating continue statement skipping // the execution when i==7 or i==15 continue; } // Printing to showcase continue affect System.out.println(i); // Incrementing variable by 2 i += 2; // Condition check } while (i <= 35); }}
Output:
0
2
6
8
10
12
14
16
20
22
24
26
28
30
32
34
Time Complexity: O(1)
Auxiliary Space : O(1)
Case 4: Continue statement inside Inner loop(Nested Loop)
In the below program, we give example, how to use the continue statement within Nested loops. When the value of i becomes 3 and j become 2, the continue statement plays its role and skip their execution but for other values of i and j, the loop will run smoothly.
Java
// Java Program to illustrate the use of continue statement// inside an inner loop or simply nested loops // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main drive method public static void main(String[] args) { // Outer loop for iteration for (int i = 1; i <= 4; i++) { // Inner loop for iteration for (int j = 1; j <= 3; j++) { if (i == 3 && j == 2) { // Continue statement in inner loop to // skip the execution when i==3 and j==2 continue; } // Print elements to showcase keyword affect System.out.println(i + " * " + j); } } }}
Output:
1 * 1
1 * 2
1 * 3
2 * 1
2 * 2
2 * 3
3 * 1
3 * 3
4 * 1
4 * 2
4 * 3
Time Complexity: O(1)
Auxiliary Space : O(1)
simmytarika5
sagar0719kumar
rishavnitro
tarunkanade
Java-Control-Flow
Java
Java-Control-Flow
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Generics in Java
Java Programming Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 394,
"s": 52,
"text": "Suppose a person wants code to execute for the values as per the code is designed to be executed but forcefully the same user wants to skip out the execution for which code should have been executed as designed above but will not as per the demand of the user. In simpler words, it is a decision-making problem as per the demand of the user."
},
{
"code": null,
"e": 413,
"s": 394,
"text": "Real-Life Example:"
},
{
"code": null,
"e": 770,
"s": 413,
"text": "Consider a man is climbing up to go to his house in between there are 11 stairs. Being in hurry to climb up he directly stepped onto 3 staircases and then 4, 5, 6, 7, 8, 9 and jumps to last one. During this he missed out staircase 1st, 2nd and 10th and he completed the goal to reach his house. He continued his journey skipping staircase of. his choices. "
},
{
"code": null,
"e": 997,
"s": 770,
"text": "In computers, it interprets staircases which is/are supposed to be skipped as ‘continue’. The action to miss out execution which are supposed to be executed, is interpreted as continue statement be it any programming language."
},
{
"code": null,
"e": 1516,
"s": 997,
"text": "Continue statement is often used inside in programming languages inside loops control structures. Inside the loop, when a continue statement is encountered the control directly jumps to the beginning of the loop for the next iteration instead of executing the statements of the current iteration. The continue statement is used when we want to skip a particular condition and continue the rest execution. Java continue statement is used for all type of loops but it is generally used in for, while, and do-while loops."
},
{
"code": null,
"e": 1621,
"s": 1516,
"text": "In the case of for loop, the continue keyword force control to jump immediately to the update statement."
},
{
"code": null,
"e": 1728,
"s": 1621,
"text": "Whereas in the case of a while loop or do-while loop, control immediately jumps to the Boolean expression."
},
{
"code": null,
"e": 1776,
"s": 1728,
"text": "Syntax: continue keyword along with a semicolon"
},
{
"code": null,
"e": 1786,
"s": 1776,
"text": "continue;"
},
{
"code": null,
"e": 1819,
"s": 1786,
"text": "Flow Chart of Continue Statement"
},
{
"code": null,
"e": 2042,
"s": 1819,
"text": "The above flowchart is most important for the understanding of this keyword. Always remember the condition is always placed inside diamond boxes and statements in rectangular boxes. Now jumping onto the implementation part"
},
{
"code": null,
"e": 2085,
"s": 2042,
"text": "Case 1: Continue statement inside for loop"
},
{
"code": null,
"e": 2330,
"s": 2085,
"text": "In this program, illustration for how to use the continue statement within For loop. When the value of ‘i’ becomes 10 or 12, the continue statement plays its role and skip their execution but for other values of’ ‘i’ the loop will run smoothly."
},
{
"code": null,
"e": 2335,
"s": 2330,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of continue statement // Importing Classes/Filesimport java.util.*;public class GFG { // Main driver method public static void main(String args[]) { // For loop for iteration for (int i = 0; i <= 15; i++) { // Check condition for continue if (i == 10 || i == 12) { // Using continue statement to skip the // execution of loop when i==10 or i==12 continue; } // Printing elements to show continue statement System.out.print(i + \" \"); } }}",
"e": 2947,
"s": 2335,
"text": null
},
{
"code": null,
"e": 2956,
"s": 2947,
"text": "Output :"
},
{
"code": null,
"e": 2989,
"s": 2956,
"text": "0 1 2 3 4 5 6 7 8 9 11 13 14 15 "
},
{
"code": null,
"e": 3011,
"s": 2989,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 3034,
"s": 3011,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 3079,
"s": 3034,
"text": "Case 2: Continue statement inside while loop"
},
{
"code": null,
"e": 3342,
"s": 3079,
"text": "In the below program, we give example, how to use the continue statement within the While loop. When the value of count becomes 7 or 15, the continue statement plays its role and skip their execution but for other values of the count, the loop will run smoothly."
},
{
"code": null,
"e": 3347,
"s": 3342,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of continue statement// inside the While looppublic class GFG { // Main driver method public static void main(String args[]) { // Initializing a variable say it count to a value // greater than the value greater among the loop // values int count = 20; // While loop for iteration while (count >= 0) { if (count == 7 || count == 15) { count--; // Decrementing variable initialized above // Showing continue execution inside loop // skipping when count==7 or count==15 continue; } // Printing values after continue statement System.out.print(count + \" \"); // Decrementing the count variable count--; } }}",
"e": 4197,
"s": 3347,
"text": null
},
{
"code": null,
"e": 4205,
"s": 4197,
"text": "Output:"
},
{
"code": null,
"e": 4254,
"s": 4205,
"text": "20 19 18 17 16 14 13 12 11 10 9 8 6 5 4 3 2 1 0 "
},
{
"code": null,
"e": 4276,
"s": 4254,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 4299,
"s": 4276,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 4347,
"s": 4299,
"text": "Case 3: Continue statement inside do while loop"
},
{
"code": null,
"e": 4603,
"s": 4347,
"text": "In the below program, we give example, of how to use the continue statement within the do-While loop. When the value of I becomes 4 or 18, the continue statement plays its role and skips its execution but for other values of I, the loop will run smoothly."
},
{
"code": null,
"e": 4608,
"s": 4603,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of continue statement// inside the Do-While loop // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // Creating and Initializing a variable int i = 0; // Do-While loop for iteration do { if (i == 4 || i == 18) { // Incrementing loop variable by 2 i += 2; // Illustrating continue statement skipping // the execution when i==7 or i==15 continue; } // Printing to showcase continue affect System.out.println(i); // Incrementing variable by 2 i += 2; // Condition check } while (i <= 35); }}",
"e": 5427,
"s": 4608,
"text": null
},
{
"code": null,
"e": 5435,
"s": 5427,
"text": "Output:"
},
{
"code": null,
"e": 5479,
"s": 5435,
"text": "0\n2\n6\n8\n10\n12\n14\n16\n20\n22\n24\n26\n28\n30\n32\n34"
},
{
"code": null,
"e": 5501,
"s": 5479,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 5524,
"s": 5501,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 5582,
"s": 5524,
"text": "Case 4: Continue statement inside Inner loop(Nested Loop)"
},
{
"code": null,
"e": 5846,
"s": 5582,
"text": "In the below program, we give example, how to use the continue statement within Nested loops. When the value of i becomes 3 and j become 2, the continue statement plays its role and skip their execution but for other values of i and j, the loop will run smoothly."
},
{
"code": null,
"e": 5851,
"s": 5846,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of continue statement// inside an inner loop or simply nested loops // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main drive method public static void main(String[] args) { // Outer loop for iteration for (int i = 1; i <= 4; i++) { // Inner loop for iteration for (int j = 1; j <= 3; j++) { if (i == 3 && j == 2) { // Continue statement in inner loop to // skip the execution when i==3 and j==2 continue; } // Print elements to showcase keyword affect System.out.println(i + \" * \" + j); } } }}",
"e": 6601,
"s": 5851,
"text": null
},
{
"code": null,
"e": 6610,
"s": 6601,
"text": "Output: "
},
{
"code": null,
"e": 6676,
"s": 6610,
"text": "1 * 1\n1 * 2\n1 * 3\n2 * 1\n2 * 2\n2 * 3\n3 * 1\n3 * 3\n4 * 1\n4 * 2\n4 * 3"
},
{
"code": null,
"e": 6698,
"s": 6676,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 6721,
"s": 6698,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 6734,
"s": 6721,
"text": "simmytarika5"
},
{
"code": null,
"e": 6749,
"s": 6734,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6761,
"s": 6749,
"text": "rishavnitro"
},
{
"code": null,
"e": 6773,
"s": 6761,
"text": "tarunkanade"
},
{
"code": null,
"e": 6791,
"s": 6773,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 6796,
"s": 6791,
"text": "Java"
},
{
"code": null,
"e": 6814,
"s": 6796,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 6819,
"s": 6814,
"text": "Java"
},
{
"code": null,
"e": 6917,
"s": 6819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6961,
"s": 6917,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6997,
"s": 6961,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 7022,
"s": 6997,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7053,
"s": 7022,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 7068,
"s": 7053,
"text": "Stream In Java"
},
{
"code": null,
"e": 7092,
"s": 7068,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 7124,
"s": 7092,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 7152,
"s": 7124,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 7169,
"s": 7152,
"text": "Generics in Java"
}
] |
Row Echelon Form
|
22 Jan, 2021
A matrix is in Row Echelon form if it has the following properties:
Any row consisting entirely of zeros occurs at the bottom of the matrix.
For each row that does not contain entirely zeros, the first non-zero entry is 1 (called a leading 1).
For two successive (non-zero) rows, the leading 1 in the higher row is further left than the leading one in the lower row.
For reduced row echelon form, the leading 1 of every row contains 0 below and above its in that column.
Below is an example of row-echelon form:
and reduced row-echelon form:
Any matrix can be transformed to reduced row echelon form, using a technique called Gaussian elimination. This is particularly useful for solving systems of linear equations.
Gaussian Elimination is a way of converting a matrix into the reduced row echelon form. It can also be used as a way of finding a solution to a solution to the system of linear equations. The idea behind this is that we perform some mathematical operations on the row and continue until only one variable is left.
Below are some operations which we can perform:
Interchange any two rows
Add two rows together.
Multiply one row by a non-zero constant (i.e. 1/3, -1/5, 2).
Given the following linear equation:
and the augmented matrix above
Now, we need to convert this into the row-echelon form. To convert this into row-echelon form, we need to perform Gaussian Elimination.
First, we need to subtract 2*r1 from the r2 and 4*r1 from the r3 to get the 0 in the first place of r2 and r3.
Next, we will interchange the rows, r2 and r3 and after that subtract 5*r2 from r3 to get the second 0 in the third row.
Now, we can deduce the value z from r3, i.e 10 z =0 ⇾ z=0. With the help of the value of z =0, we can put it to r2, y = 2. Similarly, we can put the value of y and z in r1 and we get a value of x=3
The rank of the matrix is the number of non-zero rows in the row echelon form. To find the rank, we need to perform the following steps:
Find the row-echelon form of the given matrix
Count the number of non-zero rows.
Let’s take an example matrix:
Now, we reduce the above matrix to row-echelon form
Here, only one row contains non-zero elements. Hence, the rank of the matrix is 2.
To convert a matrix into reduced row-echelon form, we used the Sympy package in python, first, we need to install it.
# install sympy! pip install sympy # import sympyimport sympy # find the reduced row echelon formsympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rref() # find the rank of matrixprint("Rank of matrix :",sympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rank())
Output:
(Matrix([
[1, 0, 0],
[0, 0, 1],
[0, 0, 0]]), (0, 2))
Rank of matrix : 2
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 122,
"s": 54,
"text": "A matrix is in Row Echelon form if it has the following properties:"
},
{
"code": null,
"e": 195,
"s": 122,
"text": "Any row consisting entirely of zeros occurs at the bottom of the matrix."
},
{
"code": null,
"e": 298,
"s": 195,
"text": "For each row that does not contain entirely zeros, the first non-zero entry is 1 (called a leading 1)."
},
{
"code": null,
"e": 421,
"s": 298,
"text": "For two successive (non-zero) rows, the leading 1 in the higher row is further left than the leading one in the lower row."
},
{
"code": null,
"e": 525,
"s": 421,
"text": "For reduced row echelon form, the leading 1 of every row contains 0 below and above its in that column."
},
{
"code": null,
"e": 567,
"s": 525,
"text": "Below is an example of row-echelon form: "
},
{
"code": null,
"e": 597,
"s": 567,
"text": "and reduced row-echelon form:"
},
{
"code": null,
"e": 772,
"s": 597,
"text": "Any matrix can be transformed to reduced row echelon form, using a technique called Gaussian elimination. This is particularly useful for solving systems of linear equations."
},
{
"code": null,
"e": 1086,
"s": 772,
"text": "Gaussian Elimination is a way of converting a matrix into the reduced row echelon form. It can also be used as a way of finding a solution to a solution to the system of linear equations. The idea behind this is that we perform some mathematical operations on the row and continue until only one variable is left."
},
{
"code": null,
"e": 1134,
"s": 1086,
"text": "Below are some operations which we can perform:"
},
{
"code": null,
"e": 1159,
"s": 1134,
"text": "Interchange any two rows"
},
{
"code": null,
"e": 1182,
"s": 1159,
"text": "Add two rows together."
},
{
"code": null,
"e": 1243,
"s": 1182,
"text": "Multiply one row by a non-zero constant (i.e. 1/3, -1/5, 2)."
},
{
"code": null,
"e": 1280,
"s": 1243,
"text": "Given the following linear equation:"
},
{
"code": null,
"e": 1312,
"s": 1280,
"text": "and the augmented matrix above "
},
{
"code": null,
"e": 1448,
"s": 1312,
"text": "Now, we need to convert this into the row-echelon form. To convert this into row-echelon form, we need to perform Gaussian Elimination."
},
{
"code": null,
"e": 1559,
"s": 1448,
"text": "First, we need to subtract 2*r1 from the r2 and 4*r1 from the r3 to get the 0 in the first place of r2 and r3."
},
{
"code": null,
"e": 1680,
"s": 1559,
"text": "Next, we will interchange the rows, r2 and r3 and after that subtract 5*r2 from r3 to get the second 0 in the third row."
},
{
"code": null,
"e": 1878,
"s": 1680,
"text": "Now, we can deduce the value z from r3, i.e 10 z =0 ⇾ z=0. With the help of the value of z =0, we can put it to r2, y = 2. Similarly, we can put the value of y and z in r1 and we get a value of x=3"
},
{
"code": null,
"e": 2015,
"s": 1878,
"text": "The rank of the matrix is the number of non-zero rows in the row echelon form. To find the rank, we need to perform the following steps:"
},
{
"code": null,
"e": 2061,
"s": 2015,
"text": "Find the row-echelon form of the given matrix"
},
{
"code": null,
"e": 2096,
"s": 2061,
"text": "Count the number of non-zero rows."
},
{
"code": null,
"e": 2126,
"s": 2096,
"text": "Let’s take an example matrix:"
},
{
"code": null,
"e": 2178,
"s": 2126,
"text": "Now, we reduce the above matrix to row-echelon form"
},
{
"code": null,
"e": 2261,
"s": 2178,
"text": "Here, only one row contains non-zero elements. Hence, the rank of the matrix is 2."
},
{
"code": null,
"e": 2379,
"s": 2261,
"text": "To convert a matrix into reduced row-echelon form, we used the Sympy package in python, first, we need to install it."
},
{
"code": "# install sympy! pip install sympy # import sympyimport sympy # find the reduced row echelon formsympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rref() # find the rank of matrixprint(\"Rank of matrix :\",sympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rank())",
"e": 2624,
"s": 2379,
"text": null
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "Output:"
},
{
"code": null,
"e": 2710,
"s": 2632,
"text": "(Matrix([\n [1, 0, 0],\n [0, 0, 1],\n [0, 0, 0]]), (0, 2))\n \n Rank of matrix : 2"
},
{
"code": null,
"e": 2727,
"s": 2710,
"text": "Machine Learning"
},
{
"code": null,
"e": 2734,
"s": 2727,
"text": "Python"
},
{
"code": null,
"e": 2751,
"s": 2734,
"text": "Machine Learning"
},
{
"code": null,
"e": 2849,
"s": 2751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2890,
"s": 2849,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 2923,
"s": 2890,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2959,
"s": 2923,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2983,
"s": 2959,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 3034,
"s": 2983,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 3062,
"s": 3034,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3112,
"s": 3062,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3134,
"s": 3112,
"text": "Python map() function"
},
{
"code": null,
"e": 3152,
"s": 3134,
"text": "Python Dictionary"
}
] |
GATE | GATE IT 2005 | Question 71
|
28 Jun, 2021
A network with CSMA/CD protocol in the MAC layer is running at 1 Gbps over a 1 km cable with no repeaters. The signal speed in the cable is 2 x 108 m/sec. The minimum frame size for this network should be
(A) 10000 bits(B) 10000 bytes(C) 5000 bits(D) 5000 bytesAnswer: (A)Explanation:
Frame Size S >= 2BL/P
Where,
Cable Length L = 1KM = 1000M
Propogation Speed P = 2 x 10^8 m/sec
Bandwidth = 1 Gbps = 10^9 bps
See this for details of above formula.
S >= (2 * 10^9 * 1000) / (2 x 10^8)
>= 10000 bits
Quiz of this Question
adnanirshad158
Gate IT 2005
GATE-Gate IT 2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 259,
"s": 54,
"text": "A network with CSMA/CD protocol in the MAC layer is running at 1 Gbps over a 1 km cable with no repeaters. The signal speed in the cable is 2 x 108 m/sec. The minimum frame size for this network should be"
},
{
"code": null,
"e": 340,
"s": 259,
"text": " (A) 10000 bits(B) 10000 bytes(C) 5000 bits(D) 5000 bytesAnswer: (A)Explanation:"
},
{
"code": null,
"e": 563,
"s": 340,
"text": "Frame Size S >= 2BL/P\n\nWhere,\n\nCable Length L = 1KM = 1000M \nPropogation Speed P = 2 x 10^8 m/sec\nBandwidth = 1 Gbps = 10^9 bps\n\nSee this for details of above formula.\n\nS >= (2 * 10^9 * 1000) / (2 x 10^8)\n >= 10000 bits\n"
},
{
"code": null,
"e": 585,
"s": 563,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 600,
"s": 585,
"text": "adnanirshad158"
},
{
"code": null,
"e": 613,
"s": 600,
"text": "Gate IT 2005"
},
{
"code": null,
"e": 631,
"s": 613,
"text": "GATE-Gate IT 2005"
},
{
"code": null,
"e": 636,
"s": 631,
"text": "GATE"
},
{
"code": null,
"e": 734,
"s": 636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 776,
"s": 734,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 838,
"s": 776,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 872,
"s": 838,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 914,
"s": 872,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 956,
"s": 914,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 998,
"s": 956,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1032,
"s": 998,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1074,
"s": 1032,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 1108,
"s": 1074,
"text": "GATE | GATE-CS-2001 | Question 50"
}
] |
Java.net.HttpURLConnection Class in Java
|
20 Apr, 2022
HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.
It is one of the popular choices among Java developers for interacting with web servers and the android developing team has officially suggested using it wherever possible. Later we will be illustrating a simple implementation of an interactive application that uses Microsoft emotion API to retrieve the emotion scores from an image using methods of HttpURLConnection class.
HttpURLConnection(URL u): Constructs the httpurlconnection to specified URL
Tip: It would be good to have understanding of how to read URL using this HttpURLConnection class for better understanding of below implementation.
Illustration: The whole process can be understood in a nutshell as follows:
Connecting to the server of Microsoft emotion API using the below URL
https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize
Setting the properties and methods for firing the request: In this step, we set the methods and properties of our request object. First, we set the method as a request method to be invoked as POST. We also set the User-Agent property to ensure that our request is not blocked by the server because of an unexpected response type which otherwise would work fine on any web browser.
Firing the http get request: After we have created the URL and have created a HttpURLConnection object, we have to actually fire a request. It can explicitly be done by connect() method. It is rather implicitly done whenever we try to use any response message such as getOutputStream() etc.
Writing to Server: Once we obtain the outputstream to the server we upload our image to the server for processing.
Reading the response from the server: After obtaining an inputstream, we use the bufferedreader to output the results from the server.
Implementation:
Java
// Java Program to Illustrate Use// of HttpURLConnection Class// to Retrieve Emotion score of Image// Using Microsoft Emotion API // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import org.json.simple.JSONObject; // Main class// httpconclass classpublic class GFG { // Main driver method public static void main(String args[]) throws IOException { // Reading input via BufferedReader class BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String key = "833921b016964f95905442e0fab0c229"; JSONObject ezm; while (n-- > 0) { String image = br.readLine(); ezm = new JSONObject(); ezm.put("url", image); // Try block to check for exceptions try { // URL for microsoft cognitive server. URL url = new URL( "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Setting the request method and // properties. con.setRequestMethod("POST"); con.setRequestProperty( "Ocp-Apim-Subscription-Key", key); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); // As we know the length of our content, // the following function sets the fixed // streaming mode length 83 bytes. If // content length not known, comment the // below line. con.setFixedLengthStreamingMode(83); // Setting the auto redirection to true HttpURLConnection.setFollowRedirects(true); // Overriding the default value set by // the static method setFollowRedirect above con.setInstanceFollowRedirects(false); // Setting the doOutput to true for now con.setDoOutput(true); OutputStream out = con.getOutputStream(); // System.out.println(ezm.toString().getBytes().length); // Writing on the output stream out.write(ezm.toString().getBytes()); InputStream ip = con.getInputStream(); BufferedReader br1 = new BufferedReader( new InputStreamReader(ip)); // Printing the response code // and response message from server. System.out.println("Response Code:" + con.getResponseCode()); System.out.println( "Response Message:" + con.getResponseMessage()); // Note: Uncomment the following line to // print the status of FollowRedirect // property // System.out.println("FollowRedirects:" // + // HttpURLConnection.getFollowRedirects()); // Printing the status of // instanceFollowRedirect property System.out.println( "InstanceFollowRedirects:" + con.getInstanceFollowRedirects()); // Printing the 1st header field System.out.println("Header field 1:" + con.getHeaderField(1)); // Printing if usingProxy flag set or not System.out.println("Using proxy:" + con.usingProxy()); StringBuilder response = new StringBuilder(); String responseSingle = null; while ((responseSingle = br1.readLine()) != null) { response.append(responseSingle); } String xx = response.toString(); System.out.println(xx); } // Catch block to handle exceptions catch (Exception e) { // Display exception/s on console System.out.println(e.getMessage()); } } }}
Output:
Response Code:200
Response Message:OK
FollowRedirects:true
InstanceFollowRedirects:false
Header field 1:no-cache
Using proxy:false
[{"faceRectangle":{"height":134,"left":62,"top":86,"width":134},"scores":{"anger":4.105452E-
14,"contempt":1.240792E-11,"disgust":2.58925052E-11,"fear":1.82401266E-17,"happiness":1.0,
"neutral":2.487733E-10,"sadness":6.02089044E-14,"surprise":2.665974E-12}}]
Output Explanation: To test this program, one should provide the number of images to process and then provide the URL of the images. You can leave the content length property unset as the server would handle it automatically, but if you know the length, modify it each time accordingly. In the given source code, as the content length is set to 83 bytes, a URL of that size should be used.
Sample URL: https://media.geeksforgeeks.org/wp-content/uploads/Brad_Pitt.jpg
Note: As it is an interactive application, it is advised to run it on offline platforms. JSON library should also be included in the build path of the project to run this application.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
solankimayank
surinderdawra388
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 299,
"s": 28,
"text": "HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol. "
},
{
"code": null,
"e": 675,
"s": 299,
"text": "It is one of the popular choices among Java developers for interacting with web servers and the android developing team has officially suggested using it wherever possible. Later we will be illustrating a simple implementation of an interactive application that uses Microsoft emotion API to retrieve the emotion scores from an image using methods of HttpURLConnection class."
},
{
"code": null,
"e": 751,
"s": 675,
"text": "HttpURLConnection(URL u): Constructs the httpurlconnection to specified URL"
},
{
"code": null,
"e": 899,
"s": 751,
"text": "Tip: It would be good to have understanding of how to read URL using this HttpURLConnection class for better understanding of below implementation."
},
{
"code": null,
"e": 976,
"s": 899,
"text": "Illustration: The whole process can be understood in a nutshell as follows: "
},
{
"code": null,
"e": 1047,
"s": 976,
"text": "Connecting to the server of Microsoft emotion API using the below URL "
},
{
"code": null,
"e": 1113,
"s": 1047,
"text": "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize"
},
{
"code": null,
"e": 1494,
"s": 1113,
"text": "Setting the properties and methods for firing the request: In this step, we set the methods and properties of our request object. First, we set the method as a request method to be invoked as POST. We also set the User-Agent property to ensure that our request is not blocked by the server because of an unexpected response type which otherwise would work fine on any web browser."
},
{
"code": null,
"e": 1785,
"s": 1494,
"text": "Firing the http get request: After we have created the URL and have created a HttpURLConnection object, we have to actually fire a request. It can explicitly be done by connect() method. It is rather implicitly done whenever we try to use any response message such as getOutputStream() etc."
},
{
"code": null,
"e": 1900,
"s": 1785,
"text": "Writing to Server: Once we obtain the outputstream to the server we upload our image to the server for processing."
},
{
"code": null,
"e": 2035,
"s": 1900,
"text": "Reading the response from the server: After obtaining an inputstream, we use the bufferedreader to output the results from the server."
},
{
"code": null,
"e": 2052,
"s": 2035,
"text": "Implementation: "
},
{
"code": null,
"e": 2057,
"s": 2052,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Use// of HttpURLConnection Class// to Retrieve Emotion score of Image// Using Microsoft Emotion API // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import org.json.simple.JSONObject; // Main class// httpconclass classpublic class GFG { // Main driver method public static void main(String args[]) throws IOException { // Reading input via BufferedReader class BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String key = \"833921b016964f95905442e0fab0c229\"; JSONObject ezm; while (n-- > 0) { String image = br.readLine(); ezm = new JSONObject(); ezm.put(\"url\", image); // Try block to check for exceptions try { // URL for microsoft cognitive server. URL url = new URL( \"https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize\"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Setting the request method and // properties. con.setRequestMethod(\"POST\"); con.setRequestProperty( \"Ocp-Apim-Subscription-Key\", key); con.setRequestProperty(\"Content-Type\", \"application/json\"); con.setRequestProperty(\"Accept\", \"application/json\"); // As we know the length of our content, // the following function sets the fixed // streaming mode length 83 bytes. If // content length not known, comment the // below line. con.setFixedLengthStreamingMode(83); // Setting the auto redirection to true HttpURLConnection.setFollowRedirects(true); // Overriding the default value set by // the static method setFollowRedirect above con.setInstanceFollowRedirects(false); // Setting the doOutput to true for now con.setDoOutput(true); OutputStream out = con.getOutputStream(); // System.out.println(ezm.toString().getBytes().length); // Writing on the output stream out.write(ezm.toString().getBytes()); InputStream ip = con.getInputStream(); BufferedReader br1 = new BufferedReader( new InputStreamReader(ip)); // Printing the response code // and response message from server. System.out.println(\"Response Code:\" + con.getResponseCode()); System.out.println( \"Response Message:\" + con.getResponseMessage()); // Note: Uncomment the following line to // print the status of FollowRedirect // property // System.out.println(\"FollowRedirects:\" // + // HttpURLConnection.getFollowRedirects()); // Printing the status of // instanceFollowRedirect property System.out.println( \"InstanceFollowRedirects:\" + con.getInstanceFollowRedirects()); // Printing the 1st header field System.out.println(\"Header field 1:\" + con.getHeaderField(1)); // Printing if usingProxy flag set or not System.out.println(\"Using proxy:\" + con.usingProxy()); StringBuilder response = new StringBuilder(); String responseSingle = null; while ((responseSingle = br1.readLine()) != null) { response.append(responseSingle); } String xx = response.toString(); System.out.println(xx); } // Catch block to handle exceptions catch (Exception e) { // Display exception/s on console System.out.println(e.getMessage()); } } }}",
"e": 6670,
"s": 2057,
"text": null
},
{
"code": null,
"e": 6679,
"s": 6670,
"text": "Output: "
},
{
"code": null,
"e": 7069,
"s": 6679,
"text": "Response Code:200\nResponse Message:OK\nFollowRedirects:true\nInstanceFollowRedirects:false\nHeader field 1:no-cache\nUsing proxy:false\n[{\"faceRectangle\":{\"height\":134,\"left\":62,\"top\":86,\"width\":134},\"scores\":{\"anger\":4.105452E-\n14,\"contempt\":1.240792E-11,\"disgust\":2.58925052E-11,\"fear\":1.82401266E-17,\"happiness\":1.0,\n\"neutral\":2.487733E-10,\"sadness\":6.02089044E-14,\"surprise\":2.665974E-12}}]"
},
{
"code": null,
"e": 7460,
"s": 7069,
"text": "Output Explanation: To test this program, one should provide the number of images to process and then provide the URL of the images. You can leave the content length property unset as the server would handle it automatically, but if you know the length, modify it each time accordingly. In the given source code, as the content length is set to 83 bytes, a URL of that size should be used. "
},
{
"code": null,
"e": 7537,
"s": 7460,
"text": "Sample URL: https://media.geeksforgeeks.org/wp-content/uploads/Brad_Pitt.jpg"
},
{
"code": null,
"e": 7721,
"s": 7537,
"text": "Note: As it is an interactive application, it is advised to run it on offline platforms. JSON library should also be included in the build path of the project to run this application."
},
{
"code": null,
"e": 8145,
"s": 7721,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8158,
"s": 8145,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8172,
"s": 8158,
"text": "solankimayank"
},
{
"code": null,
"e": 8189,
"s": 8172,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8205,
"s": 8189,
"text": "Java-Networking"
},
{
"code": null,
"e": 8210,
"s": 8205,
"text": "Java"
},
{
"code": null,
"e": 8215,
"s": 8210,
"text": "Java"
}
] |
How to operate callback-based fs.mkdir() method with promises in Node.js ?
|
18 Jul, 2020
The fs.mkdir() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The mkdir() method is used to asynchronously create a directory.
The fs.mkdir() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.
Syntax:
fs.mkdir(path, options)
Note: Callback not required since we operate the method with promises.
Parameters: This method accept two parameters as mentioned above and described below:
path: It is a String, Buffer or URL that specifies the path to the directory that has to be created.
options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.mode: It is a string or an integer which used to set the directory permission. By default its value is 0.777recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false.
mode: It is a string or an integer which used to set the directory permission. By default its value is 0.777
recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false.
Approach: The fs.mkdir() method based on callback. To operate it with promises, first, we use promisify() method defined in utilities module to convert it into a promise based method.
Example 1: Filename: index.js
// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) // Create new directorymakeDir(dir='./Test Directory').then(() => { console.log(`Directory '${dir}' is created`)}) // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);})
Implementing the same functionality using async await:
// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) const createDirectory = async path => { await makeDir(path) console.log(`Directory '${path}' is created`)} createDirectory('./TestDirectory') // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);})
Run the index.js file using the following command:
node index.js
File contents before running the program :
File contents after running the program:
Output:
Directory './Test Directory' is created
Example 2: Filename: index.js
// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) console.log(`\nBefore creating new Directory : \n`)readDir(process.cwd()).then(filenames => { // Fetch the contents of current working // directory before creating new directory for(let filename of filenames){ console.log(filename) }}).catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);}) // Create new directorymakeDir('./Test Directory').then(() => { // Fetch the contents of current working // directory after creating new directory console.log(`\nAfter creating new directory : \n`) return readDir(process.cwd())}) .then(filenames => { for(let filename of filenames) { console.log(filename) }}) // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`)})
Implementing same functionality using async await:
// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) const createDirectory = async path => { console.log(`\nBefore creating new Directory : \n`) // Fetch the contents of current working directory // before creating new directory const oldContents = await readDir(process.cwd()) for(let filename of oldContents) { console.log(filename) } // Create new directory await makeDir('./Test Directory') console.log(`\nAfter creating new directory : \n`) // Fetch the contents of current working directory // after creating new directory const newContents = await readDir(process.cwd()) for(let filename of newContents) { console.log(filename) }} createDirectory('./TestDirectory')// If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);});
Run the index.js file using the following command:
node index.js
File contents before running the program:
File contents after running the program:
Output:
Node.js-fs-module
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2020"
},
{
"code": null,
"e": 255,
"s": 28,
"text": "The fs.mkdir() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The mkdir() method is used to asynchronously create a directory."
},
{
"code": null,
"e": 557,
"s": 255,
"text": "The fs.mkdir() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way."
},
{
"code": null,
"e": 565,
"s": 557,
"text": "Syntax:"
},
{
"code": null,
"e": 589,
"s": 565,
"text": "fs.mkdir(path, options)"
},
{
"code": null,
"e": 660,
"s": 589,
"text": "Note: Callback not required since we operate the method with promises."
},
{
"code": null,
"e": 746,
"s": 660,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 847,
"s": 746,
"text": "path: It is a String, Buffer or URL that specifies the path to the directory that has to be created."
},
{
"code": null,
"e": 1215,
"s": 847,
"text": "options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.mode: It is a string or an integer which used to set the directory permission. By default its value is 0.777recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false."
},
{
"code": null,
"e": 1324,
"s": 1215,
"text": "mode: It is a string or an integer which used to set the directory permission. By default its value is 0.777"
},
{
"code": null,
"e": 1457,
"s": 1324,
"text": "recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false."
},
{
"code": null,
"e": 1641,
"s": 1457,
"text": "Approach: The fs.mkdir() method based on callback. To operate it with promises, first, we use promisify() method defined in utilities module to convert it into a promise based method."
},
{
"code": null,
"e": 1671,
"s": 1641,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) // Create new directorymakeDir(dir='./Test Directory').then(() => { console.log(`Directory '${dir}' is created`)}) // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);})",
"e": 2168,
"s": 1671,
"text": null
},
{
"code": null,
"e": 2223,
"s": 2168,
"text": "Implementing the same functionality using async await:"
},
{
"code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) const createDirectory = async path => { await makeDir(path) console.log(`Directory '${path}' is created`)} createDirectory('./TestDirectory') // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);})",
"e": 2749,
"s": 2223,
"text": null
},
{
"code": null,
"e": 2800,
"s": 2749,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 2814,
"s": 2800,
"text": "node index.js"
},
{
"code": null,
"e": 2857,
"s": 2814,
"text": "File contents before running the program :"
},
{
"code": null,
"e": 2898,
"s": 2857,
"text": "File contents after running the program:"
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 2946,
"s": 2906,
"text": "Directory './Test Directory' is created"
},
{
"code": null,
"e": 2976,
"s": 2946,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) console.log(`\\nBefore creating new Directory : \\n`)readDir(process.cwd()).then(filenames => { // Fetch the contents of current working // directory before creating new directory for(let filename of filenames){ console.log(filename) }}).catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);}) // Create new directorymakeDir('./Test Directory').then(() => { // Fetch the contents of current working // directory after creating new directory console.log(`\\nAfter creating new directory : \\n`) return readDir(process.cwd())}) .then(filenames => { for(let filename of filenames) { console.log(filename) }}) // If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`)})",
"e": 4040,
"s": 2976,
"text": null
},
{
"code": null,
"e": 4091,
"s": 4040,
"text": "Implementing same functionality using async await:"
},
{
"code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir) const createDirectory = async path => { console.log(`\\nBefore creating new Directory : \\n`) // Fetch the contents of current working directory // before creating new directory const oldContents = await readDir(process.cwd()) for(let filename of oldContents) { console.log(filename) } // Create new directory await makeDir('./Test Directory') console.log(`\\nAfter creating new directory : \\n`) // Fetch the contents of current working directory // after creating new directory const newContents = await readDir(process.cwd()) for(let filename of newContents) { console.log(filename) }} createDirectory('./TestDirectory')// If promise gets rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);});",
"e": 5119,
"s": 4091,
"text": null
},
{
"code": null,
"e": 5170,
"s": 5119,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 5184,
"s": 5170,
"text": "node index.js"
},
{
"code": null,
"e": 5226,
"s": 5184,
"text": "File contents before running the program:"
},
{
"code": null,
"e": 5267,
"s": 5226,
"text": "File contents after running the program:"
},
{
"code": null,
"e": 5275,
"s": 5267,
"text": "Output:"
},
{
"code": null,
"e": 5293,
"s": 5275,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 5306,
"s": 5293,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 5314,
"s": 5306,
"text": "Node.js"
},
{
"code": null,
"e": 5331,
"s": 5314,
"text": "Web Technologies"
},
{
"code": null,
"e": 5429,
"s": 5331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5461,
"s": 5429,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5496,
"s": 5461,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5566,
"s": 5496,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 5593,
"s": 5566,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 5618,
"s": 5593,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 5680,
"s": 5618,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5741,
"s": 5680,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5791,
"s": 5741,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5834,
"s": 5791,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Open computer drives like C, D or E using Python
|
29 Dec, 2020
Have you ever wondered that you can open your drives by just typing C, D or E and then that drives are open.This can be possible by using Python. So, for performing this task this we are using os.startfile() method of OS library. This Method start a file with its associated program.
Syntax: os.startfile(file_name)
Return: None.
Now let’s see the code:
Python3
# import libraryimport os # take Input from the user query = input("Which drive you have to open ? C , D or E: \n") # Check the condition for # opening the C driveif "C" in query or "c" in query: os.startfile("C:") # Check the condition for # opening the D driveelif "D" in query or "d" in query: os.startfile("D:") # Check the condition for # opening the D driveelif "E" in query or "e" in query: os.startfile("E:") else: print("Wrong Input")
Output:
Python os-module-programs
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "Have you ever wondered that you can open your drives by just typing C, D or E and then that drives are open.This can be possible by using Python. So, for performing this task this we are using os.startfile() method of OS library. This Method start a file with its associated program."
},
{
"code": null,
"e": 344,
"s": 312,
"text": "Syntax: os.startfile(file_name)"
},
{
"code": null,
"e": 358,
"s": 344,
"text": "Return: None."
},
{
"code": null,
"e": 382,
"s": 358,
"text": "Now let’s see the code:"
},
{
"code": null,
"e": 390,
"s": 382,
"text": "Python3"
},
{
"code": "# import libraryimport os # take Input from the user query = input(\"Which drive you have to open ? C , D or E: \\n\") # Check the condition for # opening the C driveif \"C\" in query or \"c\" in query: os.startfile(\"C:\") # Check the condition for # opening the D driveelif \"D\" in query or \"d\" in query: os.startfile(\"D:\") # Check the condition for # opening the D driveelif \"E\" in query or \"e\" in query: os.startfile(\"E:\") else: print(\"Wrong Input\")",
"e": 847,
"s": 390,
"text": null
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Output:"
},
{
"code": null,
"e": 881,
"s": 855,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 898,
"s": 881,
"text": "python-os-module"
},
{
"code": null,
"e": 913,
"s": 898,
"text": "python-utility"
},
{
"code": null,
"e": 920,
"s": 913,
"text": "Python"
},
{
"code": null,
"e": 1018,
"s": 920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1050,
"s": 1018,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1077,
"s": 1050,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1098,
"s": 1077,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1121,
"s": 1098,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1177,
"s": 1121,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1208,
"s": 1177,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1250,
"s": 1208,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1292,
"s": 1250,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1331,
"s": 1292,
"text": "Python | datetime.timedelta() function"
}
] |
Compressing and Decompressing files using GZIP Format in java
|
02 Jun, 2017
The java.util.zip package provides classes compress and decompress the file contents. FileInputStream, FileOutputStream and GZIPOutputStream classes are provided in Java to compress and decompress the files.
Compressing a File using GZIPOutputStream
Methods used in the program
read(): Reads a byte of data. Present in FileInputStream.int read()write(): Writes a byte of data, Present in FileOutputStream.void write(int b)
read(): Reads a byte of data. Present in FileInputStream.int read()
int read()
write(): Writes a byte of data, Present in FileOutputStream.void write(int b)
void write(int b)
In this example, we have a text file in /home/saket/Desktop/GeeksforGeeks/compress.java drive under “GeeksforGeeks” Folder and we are compressing and generating the GZip file in the same folder.
// Java program to compress a File// using GZIPOutputStream classimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPOutputStream; public class GeeksForGeeks{ static final String OUTPUT_FILE = "/home/saket/Desktop/GeeksforGeeks/compress.gz"; static final String INPUT_FILE = "/home/saket/Desktop//GeeksforGeeks/compress.java"; static void compress() { byte[] buffer = new byte[1024]; try { GZIPOutputStream os = new GZIPOutputStream(new FileOutputStream(OUTPUT_FILE)); FileInputStream in = new FileInputStream(INPUT_FILE); int totalSize; while((totalSize = in.read(buffer)) > 0 ) { os.write(buffer, 0, totalSize); } in.close(); os.finish(); os.close(); System.out.println("File Successfully compressed"); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { compress(); }}
Output:
File Successfully compressed
After Running the above program, It will compress the compress.java file:
Decompressing a File using GZIPOutputStream
// Java program to illustrate // Decompressing a File using GZIPOutputStreamimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPInputStream; class GeeksForGeeks{ static final String INPUT_FILE = "/home/saket/Desktop/GeeksforGeeks/compress.gz"; static final String OUTPUT_FILE = "/home/saket/Desktop//GeeksforGeeks/decompress.java"; static void decompress() { byte[] buffer = new byte[1024]; try { GZIPInputStream is = new GZIPInputStream(new FileInputStream(INPUT_FILE)); FileOutputStream out = new FileOutputStream(OUTPUT_FILE); int totalSize; while((totalSize = is.read(buffer)) > 0 ) { out.write(buffer, 0, totalSize); } out.close(); is.close(); System.out.println("File Successfully decompressed"); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { decompress(); }}
Output :
File Successfully decompressed
Current State after compiling:
Note : Here decom.java contains the above code.After Running the above program, It will decompress the compress.gz and a file named decompress.java will be created.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "The java.util.zip package provides classes compress and decompress the file contents. FileInputStream, FileOutputStream and GZIPOutputStream classes are provided in Java to compress and decompress the files."
},
{
"code": null,
"e": 278,
"s": 236,
"text": "Compressing a File using GZIPOutputStream"
},
{
"code": null,
"e": 306,
"s": 278,
"text": "Methods used in the program"
},
{
"code": null,
"e": 452,
"s": 306,
"text": "read(): Reads a byte of data. Present in FileInputStream.int read()write(): Writes a byte of data, Present in FileOutputStream.void write(int b) "
},
{
"code": null,
"e": 520,
"s": 452,
"text": "read(): Reads a byte of data. Present in FileInputStream.int read()"
},
{
"code": null,
"e": 531,
"s": 520,
"text": "int read()"
},
{
"code": null,
"e": 610,
"s": 531,
"text": "write(): Writes a byte of data, Present in FileOutputStream.void write(int b) "
},
{
"code": null,
"e": 629,
"s": 610,
"text": "void write(int b) "
},
{
"code": null,
"e": 824,
"s": 629,
"text": "In this example, we have a text file in /home/saket/Desktop/GeeksforGeeks/compress.java drive under “GeeksforGeeks” Folder and we are compressing and generating the GZip file in the same folder."
},
{
"code": "// Java program to compress a File// using GZIPOutputStream classimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPOutputStream; public class GeeksForGeeks{ static final String OUTPUT_FILE = \"/home/saket/Desktop/GeeksforGeeks/compress.gz\"; static final String INPUT_FILE = \"/home/saket/Desktop//GeeksforGeeks/compress.java\"; static void compress() { byte[] buffer = new byte[1024]; try { GZIPOutputStream os = new GZIPOutputStream(new FileOutputStream(OUTPUT_FILE)); FileInputStream in = new FileInputStream(INPUT_FILE); int totalSize; while((totalSize = in.read(buffer)) > 0 ) { os.write(buffer, 0, totalSize); } in.close(); os.finish(); os.close(); System.out.println(\"File Successfully compressed\"); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { compress(); }}",
"e": 2074,
"s": 824,
"text": null
},
{
"code": null,
"e": 2082,
"s": 2074,
"text": "Output:"
},
{
"code": null,
"e": 2112,
"s": 2082,
"text": "File Successfully compressed\n"
},
{
"code": null,
"e": 2186,
"s": 2112,
"text": "After Running the above program, It will compress the compress.java file:"
},
{
"code": null,
"e": 2230,
"s": 2186,
"text": "Decompressing a File using GZIPOutputStream"
},
{
"code": "// Java program to illustrate // Decompressing a File using GZIPOutputStreamimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPInputStream; class GeeksForGeeks{ static final String INPUT_FILE = \"/home/saket/Desktop/GeeksforGeeks/compress.gz\"; static final String OUTPUT_FILE = \"/home/saket/Desktop//GeeksforGeeks/decompress.java\"; static void decompress() { byte[] buffer = new byte[1024]; try { GZIPInputStream is = new GZIPInputStream(new FileInputStream(INPUT_FILE)); FileOutputStream out = new FileOutputStream(OUTPUT_FILE); int totalSize; while((totalSize = is.read(buffer)) > 0 ) { out.write(buffer, 0, totalSize); } out.close(); is.close(); System.out.println(\"File Successfully decompressed\"); } catch (IOException e) { e.printStackTrace(); } } public static void main (String[] args) { decompress(); }}",
"e": 3471,
"s": 2230,
"text": null
},
{
"code": null,
"e": 3480,
"s": 3471,
"text": "Output :"
},
{
"code": null,
"e": 3512,
"s": 3480,
"text": "File Successfully decompressed\n"
},
{
"code": null,
"e": 3543,
"s": 3512,
"text": "Current State after compiling:"
},
{
"code": null,
"e": 3708,
"s": 3543,
"text": "Note : Here decom.java contains the above code.After Running the above program, It will decompress the compress.gz and a file named decompress.java will be created."
},
{
"code": null,
"e": 4007,
"s": 3708,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4132,
"s": 4007,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4141,
"s": 4132,
"text": "Java-I/O"
},
{
"code": null,
"e": 4146,
"s": 4141,
"text": "Java"
},
{
"code": null,
"e": 4151,
"s": 4146,
"text": "Java"
}
] |
Python | Pandas Series.append()
|
27 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.append() function is used to concatenate two or more series object.
Syntax: Series.append(to_append, ignore_index=False, verify_integrity=False)
Parameter :to_append : Series or list/tuple of Seriesignore_index : If True, do not use the index labels.verify_integrity : If True, raise Exception on creating index with duplicates
Returns : appended : Series
Example #1: Use Series.append() function to append the passed series object at the end of this series object.
# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the first Indexindex_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index of first seriessr1.index = index_1 # Creating the second Seriessr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul']) # Create the second Indexindex_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10'] # set the index of second seriessr2.index = index_2 # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)
Output :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
dtype: object
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
Now we will use Series.append() function to append sr2 at the end of sr1 series.
# append sr2 at the end of sr1result = sr1.append(sr2) # Print the resultprint(result)
Output :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
As we can see in the output, the Series.append() function has successfully append the sr2 object at the end of sr1 object. Example #2: Use Series.append() function to append the passed series object at the end of this series object. Ignore the original index of the two series objects.
# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the first Indexindex_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index of first seriessr1.index = index_1 # Creating the second Seriessr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul']) # Create the second Indexindex_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10'] # set the index of second seriessr2.index = index_2 # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)
Output :
City 1 New York
City 2 Chicago
City 3 Toronto
City 4 Lisbon
City 5 Rio
dtype: object
City 6 Chicage
City 7 Shanghai
City 8 Beijing
City 9 Jakarta
City 10 Seoul
dtype: object
Now we will use Series.append() function to append sr2 at the end of sr1 series. We are going to ignore the index of the given series object.
# append sr2 at the end of sr1# ignore the indexresult = sr1.append(sr2, ignore_index = True) # Print the resultprint(result)
Output :
0 New York
1 Chicago
2 Toronto
3 Lisbon
4 Rio
5 Chicage
6 Shanghai
7 Beijing
8 Jakarta
9 Seoul
dtype: object
As we can see in the output, the Series.append() function has successfully append the sr2 object at the end of sr1 object and it has also ignored the index.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 367,
"s": 285,
"text": "Pandas Series.append() function is used to concatenate two or more series object."
},
{
"code": null,
"e": 444,
"s": 367,
"text": "Syntax: Series.append(to_append, ignore_index=False, verify_integrity=False)"
},
{
"code": null,
"e": 627,
"s": 444,
"text": "Parameter :to_append : Series or list/tuple of Seriesignore_index : If True, do not use the index labels.verify_integrity : If True, raise Exception on creating index with duplicates"
},
{
"code": null,
"e": 655,
"s": 627,
"text": "Returns : appended : Series"
},
{
"code": null,
"e": 765,
"s": 655,
"text": "Example #1: Use Series.append() function to append the passed series object at the end of this series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the first Indexindex_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index of first seriessr1.index = index_1 # Creating the second Seriessr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul']) # Create the second Indexindex_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10'] # set the index of second seriessr2.index = index_2 # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)",
"e": 1361,
"s": 765,
"text": null
},
{
"code": null,
"e": 1370,
"s": 1361,
"text": "Output :"
},
{
"code": null,
"e": 1594,
"s": 1370,
"text": "City 1 New York\nCity 2 Chicago\nCity 3 Toronto\nCity 4 Lisbon\nCity 5 Rio\ndtype: object\n\nCity 6 Chicage\nCity 7 Shanghai\nCity 8 Beijing\nCity 9 Jakarta\nCity 10 Seoul\ndtype: object"
},
{
"code": null,
"e": 1675,
"s": 1594,
"text": "Now we will use Series.append() function to append sr2 at the end of sr1 series."
},
{
"code": "# append sr2 at the end of sr1result = sr1.append(sr2) # Print the resultprint(result)",
"e": 1763,
"s": 1675,
"text": null
},
{
"code": null,
"e": 1772,
"s": 1763,
"text": "Output :"
},
{
"code": null,
"e": 1986,
"s": 1772,
"text": "City 1 New York\nCity 2 Chicago\nCity 3 Toronto\nCity 4 Lisbon\nCity 5 Rio\nCity 6 Chicage\nCity 7 Shanghai\nCity 8 Beijing\nCity 9 Jakarta\nCity 10 Seoul\ndtype: object"
},
{
"code": null,
"e": 2272,
"s": 1986,
"text": "As we can see in the output, the Series.append() function has successfully append the sr2 object at the end of sr1 object. Example #2: Use Series.append() function to append the passed series object at the end of this series object. Ignore the original index of the two series objects."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the first Indexindex_1 = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index of first seriessr1.index = index_1 # Creating the second Seriessr2 = pd.Series(['Chicage', 'Shanghai', 'Beijing', 'Jakarta', 'Seoul']) # Create the second Indexindex_2 = ['City 6', 'City 7', 'City 8', 'City 9', 'City 10'] # set the index of second seriessr2.index = index_2 # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)",
"e": 2868,
"s": 2272,
"text": null
},
{
"code": null,
"e": 2877,
"s": 2868,
"text": "Output :"
},
{
"code": null,
"e": 3101,
"s": 2877,
"text": "City 1 New York\nCity 2 Chicago\nCity 3 Toronto\nCity 4 Lisbon\nCity 5 Rio\ndtype: object\n\nCity 6 Chicage\nCity 7 Shanghai\nCity 8 Beijing\nCity 9 Jakarta\nCity 10 Seoul\ndtype: object"
},
{
"code": null,
"e": 3243,
"s": 3101,
"text": "Now we will use Series.append() function to append sr2 at the end of sr1 series. We are going to ignore the index of the given series object."
},
{
"code": "# append sr2 at the end of sr1# ignore the indexresult = sr1.append(sr2, ignore_index = True) # Print the resultprint(result)",
"e": 3370,
"s": 3243,
"text": null
},
{
"code": null,
"e": 3379,
"s": 3370,
"text": "Output :"
},
{
"code": null,
"e": 3533,
"s": 3379,
"text": "0 New York\n1 Chicago\n2 Toronto\n3 Lisbon\n4 Rio\n5 Chicage\n6 Shanghai\n7 Beijing\n8 Jakarta\n9 Seoul\ndtype: object"
},
{
"code": null,
"e": 3690,
"s": 3533,
"text": "As we can see in the output, the Series.append() function has successfully append the sr2 object at the end of sr1 object and it has also ignored the index."
},
{
"code": null,
"e": 3711,
"s": 3690,
"text": "Python pandas-series"
},
{
"code": null,
"e": 3740,
"s": 3711,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 3754,
"s": 3740,
"text": "Python-pandas"
},
{
"code": null,
"e": 3761,
"s": 3754,
"text": "Python"
}
] |
TreeSet iterator() Method in Java
|
26 Nov, 2018
The Java.util.TreeSet.iterator() method is used to return an iterator of the same elements as that of the TreeSet. The elements are returned in random order from what was present in the Tree set.
Syntax:
Iterator iterate_value = Tree_Set.iterator();
Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the Tree set and returns the values(iterators).
Below program illustrates the use of Java.util.TreeSet.iterator() method:
// Java code to illustrate iterator()import java.util.*;import java.util.TreeSet; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty TreeSet TreeSet<String> set = new TreeSet<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 TreeSet System.out.println("TreeSet: " + set); // Creating an iterator Iterator value = set.iterator(); // Displaying the values after iterating through the set System.out.println("The iterator values are: "); while (value.hasNext()) { System.out.println(value.next()); } }}
TreeSet: [4, Geeks, To, Welcome]
The iterator values are:
4
Geeks
To
Welcome
Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "The Java.util.TreeSet.iterator() method is used to return an iterator of the same elements as that of the TreeSet. The elements are returned in random order from what was present in the Tree set."
},
{
"code": null,
"e": 256,
"s": 248,
"text": "Syntax:"
},
{
"code": null,
"e": 303,
"s": 256,
"text": "Iterator iterate_value = Tree_Set.iterator();\n"
},
{
"code": null,
"e": 357,
"s": 303,
"text": "Parameters: The function does not take any parameter."
},
{
"code": null,
"e": 460,
"s": 357,
"text": "Return Value: The method iterates over the elements of the Tree set and returns the values(iterators)."
},
{
"code": null,
"e": 534,
"s": 460,
"text": "Below program illustrates the use of Java.util.TreeSet.iterator() method:"
},
{
"code": "// Java code to illustrate iterator()import java.util.*;import java.util.TreeSet; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty TreeSet TreeSet<String> set = new TreeSet<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 TreeSet System.out.println(\"TreeSet: \" + set); // Creating an iterator Iterator value = set.iterator(); // Displaying the values after iterating through the set System.out.println(\"The iterator values are: \"); while (value.hasNext()) { System.out.println(value.next()); } }}",
"e": 1326,
"s": 534,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1326,
"text": "TreeSet: [4, Geeks, To, Welcome]\nThe iterator values are: \n4\nGeeks\nTo\nWelcome\n"
},
{
"code": null,
"e": 1425,
"s": 1405,
"text": "Java - util package"
},
{
"code": null,
"e": 1442,
"s": 1425,
"text": "Java-Collections"
},
{
"code": null,
"e": 1457,
"s": 1442,
"text": "Java-Functions"
},
{
"code": null,
"e": 1470,
"s": 1457,
"text": "java-treeset"
},
{
"code": null,
"e": 1475,
"s": 1470,
"text": "Java"
},
{
"code": null,
"e": 1480,
"s": 1475,
"text": "Java"
},
{
"code": null,
"e": 1497,
"s": 1480,
"text": "Java-Collections"
},
{
"code": null,
"e": 1595,
"s": 1497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1610,
"s": 1595,
"text": "Stream In Java"
},
{
"code": null,
"e": 1631,
"s": 1610,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1652,
"s": 1631,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1671,
"s": 1652,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1688,
"s": 1671,
"text": "Generics in Java"
},
{
"code": null,
"e": 1718,
"s": 1688,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1734,
"s": 1718,
"text": "Strings in Java"
},
{
"code": null,
"e": 1760,
"s": 1734,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1780,
"s": 1760,
"text": "Abstraction in Java"
}
] |
Python | How to get unique elements in nested tuple
|
21 Nov, 2019
Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using nested loop + set()The above 2 functionalities can be used to solve this particular problem. In this, we iterate each nested tuple and add to set if element has occurred for first time and check for each element before adding.
# Python3 code to demonstrate working of# Unique elements in nested tuple# Using nested loop + set() # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple# Using nested loop + set()res = []temp = set()for inner in test_list: for ele in inner: if not ele in temp: temp.add(ele) res.append(ele) # printing resultprint("Unique elements in nested tuples are : " + str(res))
The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [3, 4, 5, 7, 1]
Method #2 : Using set() + from_iterable()The combo of above functionalities can be used to solve this. This is done is 2 steps, first, we flatten the nested list and then find distincts using set().
# Python3 code to demonstrate working of# Unique elements in nested tuple# Using from_iterable() + set()from itertools import chain # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print("The original list : " + str(test_list)) # Unique elements in nested tuple# Using from_iterable() + set()res = list(set(chain.from_iterable(test_list))) # printing resultprint("Unique elements in nested tuples are : " + str(res))
The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [1, 3, 4, 5, 7]
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 | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 314,
"s": 28,
"text": "Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 559,
"s": 314,
"text": "Method #1 : Using nested loop + set()The above 2 functionalities can be used to solve this particular problem. In this, we iterate each nested tuple and add to set if element has occurred for first time and check for each element before adding."
},
{
"code": "# Python3 code to demonstrate working of# Unique elements in nested tuple# Using nested loop + set() # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print(\"The original list : \" + str(test_list)) # Unique elements in nested tuple# Using nested loop + set()res = []temp = set()for inner in test_list: for ele in inner: if not ele in temp: temp.add(ele) res.append(ele) # printing resultprint(\"Unique elements in nested tuples are : \" + str(res))",
"e": 1093,
"s": 559,
"text": null
},
{
"code": null,
"e": 1200,
"s": 1093,
"text": "The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]\nUnique elements in nested tuples are : [3, 4, 5, 7, 1]\n"
},
{
"code": null,
"e": 1401,
"s": 1202,
"text": "Method #2 : Using set() + from_iterable()The combo of above functionalities can be used to solve this. This is done is 2 steps, first, we flatten the nested list and then find distincts using set()."
},
{
"code": "# Python3 code to demonstrate working of# Unique elements in nested tuple# Using from_iterable() + set()from itertools import chain # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)] # printing original list print(\"The original list : \" + str(test_list)) # Unique elements in nested tuple# Using from_iterable() + set()res = list(set(chain.from_iterable(test_list))) # printing resultprint(\"Unique elements in nested tuples are : \" + str(res))",
"e": 1858,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1965,
"s": 1858,
"text": "The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]\nUnique elements in nested tuples are : [1, 3, 4, 5, 7]\n"
},
{
"code": null,
"e": 1987,
"s": 1965,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1994,
"s": 1987,
"text": "Python"
},
{
"code": null,
"e": 2010,
"s": 1994,
"text": "Python Programs"
},
{
"code": null,
"e": 2108,
"s": 2010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2126,
"s": 2108,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2168,
"s": 2126,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2190,
"s": 2168,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2225,
"s": 2190,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2251,
"s": 2225,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2294,
"s": 2251,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2316,
"s": 2294,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2355,
"s": 2316,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2393,
"s": 2355,
"text": "Python | Convert a list to dictionary"
}
] |
Shell Script to Count Lines and Words in a File
|
18 May, 2021
Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action in a shell script.
There may be some scenarios where one needs to keep track of the number of lines and number of words in a particular file. In that scenario, any of the following methods can be used to count the number of the lines and the words in a particular file in Linux. Let’s take some examples for better understanding:
Example: Consider this file(demo.txt) with the following content:
This is first line.
This is second line.
This is third line.
Output:
Number of line = 3
Number of words = 12
Let us have a look at all the methods to count the number of lines and words and how they can be used in a shell script.
Method 1: Using WC command
wc stands for word counts. Using wc command the number of words, number of lines, number of white spaces, etc can be determined.
Syntax-
wc [option] [input-file]
Approach:
Create a variable to store the file path.Use wc –lines command to count the number of lines.Use wc –word command to count the number of words.Print the both number of lines and the number of words using the echo command.
Create a variable to store the file path.
Use wc –lines command to count the number of lines.
Use wc –word command to count the number of words.
Print the both number of lines and the number of words using the echo command.
Input file: cat demo.txt
This is first line
This is second line
This is third line
cat command is used to show the content of the file.
Script:
#!/usr/bin/bash
# path to the file
file_path="/home/amninder/Desktop/demo.txt"
# using wc command to count number of lines
number_of_lines=`wc --lines < $file_path`
# using wc command to count number of words
number_of_words=`wc --word < $file_path`
# Displaying number of lines and number of words
echo "Number of lines: $number_of_lines"
echo "Number of words: $number_of_words"
Output:
Using wc command
Explanation:
The first line tells the system that bash will be used as an interpreter.
The wc command is used to find out the number of lines and number of words.
A variable is created to hold the file path.
After that, wc command is used with –lines argument to count the number of lines, and similarly, wc command with –words argument is used to count the number of words in the file.
In the end, the number of words and the number of lines is displayed using the echo command.
NOTE: Lines starting with the “#” symbol are called comments and ignored by the interpreter except for the first line.
Method 2: Using awk commandawk is a scripting language mainly used for text preprocessing and text manipulation. Using awk, we can do pattern search, find and replace, count words, count lines, count special symbols, count white spaces, etc.
Syntax:
awk {action-to-be-performed} [input-file]
Approach 1:
Create a variable to store the file path.
Initialize a counter variable to count the number of lines.
After every line increment the counter variable to count the number of lines.
Display the number of lines using the print command.
Initialize another counter variable to count the number of words.
Use white space as a Record Separator and increment the counter variable to count the number of words separated by space.
After that, display the number of words using the print command.
Script:
#!/usr/bin/bash
# path to the file
file_path="/home/amninder/Desktop/demo.txt"
# Method 1
echo "Using method 1"
# using awk command to count number of lines
awk 'BEGIN{c1=0} //{c1++} END{print "Number of lines: ",c1}' $file_path
#using awk command to count number of words
awk 'BEGIN{c=0} //{c++} END{print "Number of words: ",c}' RS="[[:space:]]" $file_path
Output:
Using method 1
Explanation:
In the first line, a variable file_path is created to hold the path of the text file.The awk command statement can be divided into the following parts.BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line.END{print “Number of lines: “, c} will print the number of lines.Similarly, the number of words are counted by separating each word by space using RS=”[[:space:]]. Here, RS is a Record Separator, and space is used as a separator in this example.
In the first line, a variable file_path is created to hold the path of the text file.
The awk command statement can be divided into the following parts.BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line.END{print “Number of lines: “, c} will print the number of lines.
BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line.
END{print “Number of lines: “, c} will print the number of lines.
Similarly, the number of words are counted by separating each word by space using RS=”[[:space:]]. Here, RS is a Record Separator, and space is used as a separator in this example.
Note: Lines starting with the “#” symbol are called comments and ignored by the interpreter except for the first line.
Approach 2:
Create a variable to store the file path.Use a special NR variable to find out the number of lines. NR means the number of records, and it holds the number of processed records.Use NF(Number of fields in the current record) to find out the number of words in each line.Then use a while loop to traverse through all the lines and sum up the NF from each line.Display the number of lines.
Create a variable to store the file path.
Use a special NR variable to find out the number of lines. NR means the number of records, and it holds the number of processed records.
Use NF(Number of fields in the current record) to find out the number of words in each line.
Then use a while loop to traverse through all the lines and sum up the NF from each line.
Display the number of lines.
Example for NF: Let’s file be-
First line is on top
Second line is on second last position
NF means the number of fields in the current record i.e. number of words in the current line.
command:
awk '{print NF}' demo.txt
Output:
5
7
Here, 5 represents that there are 5 words in the first line, and 7 means there are 7 words in the second line.
Script:
#!/usr/bin/bash
# path to the file
file_path="/home/amninder/Desktop/demo.txt"
# Method 2
echo "Using method 2"
# using NR to count number of lines
awk 'END{print "Number of lines:",NR}' $file_path
#using awk command to count number of words
awk '{i=0; count=0; while (i<NR) { count+=NF; i++;}}
END {print "Number of words are: " count}' $file_path
Output:
Using method 2
Explanation:
In the first line, a variable file_path is created to hold the path of the text file.
Then, the number of lines is printed using ‘END{print “Number of lines:”,NR}’.
Here, END represents that we are interested in the last values of the NR variable as NR variable holds the count of the processed records.
To count the number of lines, a while loop is used till the number of processed records.
Adding the value of the NF i.e. count of words in each line.
In the end, the number of words is printed that is stored in the count variable.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
TCP Server-Client implementation in C
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 372,
"s": 53,
"text": "Linux provides users a great cool feature of the command-line tool along with a graphical user interface where they can perform tasks via ruining command. All of this command returns a status according to their execution. Its execution value can be used for showing errors or take some other action in a shell script. "
},
{
"code": null,
"e": 683,
"s": 372,
"text": "There may be some scenarios where one needs to keep track of the number of lines and number of words in a particular file. In that scenario, any of the following methods can be used to count the number of the lines and the words in a particular file in Linux. Let’s take some examples for better understanding:"
},
{
"code": null,
"e": 749,
"s": 683,
"text": "Example: Consider this file(demo.txt) with the following content:"
},
{
"code": null,
"e": 810,
"s": 749,
"text": "This is first line.\nThis is second line.\nThis is third line."
},
{
"code": null,
"e": 818,
"s": 810,
"text": "Output:"
},
{
"code": null,
"e": 858,
"s": 818,
"text": "Number of line = 3\nNumber of words = 12"
},
{
"code": null,
"e": 979,
"s": 858,
"text": "Let us have a look at all the methods to count the number of lines and words and how they can be used in a shell script."
},
{
"code": null,
"e": 1006,
"s": 979,
"text": "Method 1: Using WC command"
},
{
"code": null,
"e": 1135,
"s": 1006,
"text": "wc stands for word counts. Using wc command the number of words, number of lines, number of white spaces, etc can be determined."
},
{
"code": null,
"e": 1143,
"s": 1135,
"text": "Syntax-"
},
{
"code": null,
"e": 1168,
"s": 1143,
"text": "wc [option] [input-file]"
},
{
"code": null,
"e": 1178,
"s": 1168,
"text": "Approach:"
},
{
"code": null,
"e": 1399,
"s": 1178,
"text": "Create a variable to store the file path.Use wc –lines command to count the number of lines.Use wc –word command to count the number of words.Print the both number of lines and the number of words using the echo command."
},
{
"code": null,
"e": 1441,
"s": 1399,
"text": "Create a variable to store the file path."
},
{
"code": null,
"e": 1493,
"s": 1441,
"text": "Use wc –lines command to count the number of lines."
},
{
"code": null,
"e": 1544,
"s": 1493,
"text": "Use wc –word command to count the number of words."
},
{
"code": null,
"e": 1623,
"s": 1544,
"text": "Print the both number of lines and the number of words using the echo command."
},
{
"code": null,
"e": 1648,
"s": 1623,
"text": "Input file: cat demo.txt"
},
{
"code": null,
"e": 1706,
"s": 1648,
"text": "This is first line\nThis is second line\nThis is third line"
},
{
"code": null,
"e": 1759,
"s": 1706,
"text": "cat command is used to show the content of the file."
},
{
"code": null,
"e": 1767,
"s": 1759,
"text": "Script:"
},
{
"code": null,
"e": 2152,
"s": 1767,
"text": "#!/usr/bin/bash\n\n# path to the file\nfile_path=\"/home/amninder/Desktop/demo.txt\"\n\n# using wc command to count number of lines\nnumber_of_lines=`wc --lines < $file_path`\n\n# using wc command to count number of words\nnumber_of_words=`wc --word < $file_path`\n\n# Displaying number of lines and number of words\necho \"Number of lines: $number_of_lines\"\necho \"Number of words: $number_of_words\""
},
{
"code": null,
"e": 2160,
"s": 2152,
"text": "Output:"
},
{
"code": null,
"e": 2177,
"s": 2160,
"text": "Using wc command"
},
{
"code": null,
"e": 2190,
"s": 2177,
"text": "Explanation:"
},
{
"code": null,
"e": 2264,
"s": 2190,
"text": "The first line tells the system that bash will be used as an interpreter."
},
{
"code": null,
"e": 2340,
"s": 2264,
"text": "The wc command is used to find out the number of lines and number of words."
},
{
"code": null,
"e": 2385,
"s": 2340,
"text": "A variable is created to hold the file path."
},
{
"code": null,
"e": 2564,
"s": 2385,
"text": "After that, wc command is used with –lines argument to count the number of lines, and similarly, wc command with –words argument is used to count the number of words in the file."
},
{
"code": null,
"e": 2657,
"s": 2564,
"text": "In the end, the number of words and the number of lines is displayed using the echo command."
},
{
"code": null,
"e": 2776,
"s": 2657,
"text": "NOTE: Lines starting with the “#” symbol are called comments and ignored by the interpreter except for the first line."
},
{
"code": null,
"e": 3018,
"s": 2776,
"text": "Method 2: Using awk commandawk is a scripting language mainly used for text preprocessing and text manipulation. Using awk, we can do pattern search, find and replace, count words, count lines, count special symbols, count white spaces, etc."
},
{
"code": null,
"e": 3026,
"s": 3018,
"text": "Syntax:"
},
{
"code": null,
"e": 3068,
"s": 3026,
"text": "awk {action-to-be-performed} [input-file]"
},
{
"code": null,
"e": 3080,
"s": 3068,
"text": "Approach 1:"
},
{
"code": null,
"e": 3122,
"s": 3080,
"text": "Create a variable to store the file path."
},
{
"code": null,
"e": 3182,
"s": 3122,
"text": "Initialize a counter variable to count the number of lines."
},
{
"code": null,
"e": 3260,
"s": 3182,
"text": "After every line increment the counter variable to count the number of lines."
},
{
"code": null,
"e": 3313,
"s": 3260,
"text": "Display the number of lines using the print command."
},
{
"code": null,
"e": 3379,
"s": 3313,
"text": "Initialize another counter variable to count the number of words."
},
{
"code": null,
"e": 3501,
"s": 3379,
"text": "Use white space as a Record Separator and increment the counter variable to count the number of words separated by space."
},
{
"code": null,
"e": 3566,
"s": 3501,
"text": "After that, display the number of words using the print command."
},
{
"code": null,
"e": 3574,
"s": 3566,
"text": "Script:"
},
{
"code": null,
"e": 3936,
"s": 3574,
"text": "#!/usr/bin/bash\n\n# path to the file\nfile_path=\"/home/amninder/Desktop/demo.txt\"\n\n# Method 1\necho \"Using method 1\"\n# using awk command to count number of lines\nawk 'BEGIN{c1=0} //{c1++} END{print \"Number of lines: \",c1}' $file_path\n\n#using awk command to count number of words\nawk 'BEGIN{c=0} //{c++} END{print \"Number of words: \",c}' RS=\"[[:space:]]\" $file_path"
},
{
"code": null,
"e": 3944,
"s": 3936,
"text": "Output:"
},
{
"code": null,
"e": 3959,
"s": 3944,
"text": "Using method 1"
},
{
"code": null,
"e": 3972,
"s": 3959,
"text": "Explanation:"
},
{
"code": null,
"e": 4506,
"s": 3972,
"text": "In the first line, a variable file_path is created to hold the path of the text file.The awk command statement can be divided into the following parts.BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line.END{print “Number of lines: “, c} will print the number of lines.Similarly, the number of words are counted by separating each word by space using RS=”[[:space:]]. Here, RS is a Record Separator, and space is used as a separator in this example."
},
{
"code": null,
"e": 4592,
"s": 4506,
"text": "In the first line, a variable file_path is created to hold the path of the text file."
},
{
"code": null,
"e": 4861,
"s": 4592,
"text": "The awk command statement can be divided into the following parts.BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line.END{print “Number of lines: “, c} will print the number of lines."
},
{
"code": null,
"e": 4999,
"s": 4861,
"text": "BEGIN{c=0} will initialize a count variable called. //{c++} will increment the count variable c by 1, whenever it encountered a new line."
},
{
"code": null,
"e": 5065,
"s": 4999,
"text": "END{print “Number of lines: “, c} will print the number of lines."
},
{
"code": null,
"e": 5246,
"s": 5065,
"text": "Similarly, the number of words are counted by separating each word by space using RS=”[[:space:]]. Here, RS is a Record Separator, and space is used as a separator in this example."
},
{
"code": null,
"e": 5365,
"s": 5246,
"text": "Note: Lines starting with the “#” symbol are called comments and ignored by the interpreter except for the first line."
},
{
"code": null,
"e": 5377,
"s": 5365,
"text": "Approach 2:"
},
{
"code": null,
"e": 5764,
"s": 5377,
"text": "Create a variable to store the file path.Use a special NR variable to find out the number of lines. NR means the number of records, and it holds the number of processed records.Use NF(Number of fields in the current record) to find out the number of words in each line.Then use a while loop to traverse through all the lines and sum up the NF from each line.Display the number of lines."
},
{
"code": null,
"e": 5806,
"s": 5764,
"text": "Create a variable to store the file path."
},
{
"code": null,
"e": 5943,
"s": 5806,
"text": "Use a special NR variable to find out the number of lines. NR means the number of records, and it holds the number of processed records."
},
{
"code": null,
"e": 6036,
"s": 5943,
"text": "Use NF(Number of fields in the current record) to find out the number of words in each line."
},
{
"code": null,
"e": 6126,
"s": 6036,
"text": "Then use a while loop to traverse through all the lines and sum up the NF from each line."
},
{
"code": null,
"e": 6155,
"s": 6126,
"text": "Display the number of lines."
},
{
"code": null,
"e": 6186,
"s": 6155,
"text": "Example for NF: Let’s file be-"
},
{
"code": null,
"e": 6246,
"s": 6186,
"text": "First line is on top\nSecond line is on second last position"
},
{
"code": null,
"e": 6340,
"s": 6246,
"text": "NF means the number of fields in the current record i.e. number of words in the current line."
},
{
"code": null,
"e": 6389,
"s": 6340,
"text": "command: \nawk '{print NF}' demo.txt\n\nOutput:\n5\n7"
},
{
"code": null,
"e": 6500,
"s": 6389,
"text": "Here, 5 represents that there are 5 words in the first line, and 7 means there are 7 words in the second line."
},
{
"code": null,
"e": 6508,
"s": 6500,
"text": "Script:"
},
{
"code": null,
"e": 6863,
"s": 6508,
"text": "#!/usr/bin/bash\n\n# path to the file\nfile_path=\"/home/amninder/Desktop/demo.txt\"\n\n# Method 2\necho \"Using method 2\"\n\n# using NR to count number of lines\nawk 'END{print \"Number of lines:\",NR}' $file_path \n\n#using awk command to count number of words\nawk '{i=0; count=0; while (i<NR) { count+=NF; i++;}} \nEND {print \"Number of words are: \" count}' $file_path"
},
{
"code": null,
"e": 6871,
"s": 6863,
"text": "Output:"
},
{
"code": null,
"e": 6886,
"s": 6871,
"text": "Using method 2"
},
{
"code": null,
"e": 6899,
"s": 6886,
"text": "Explanation:"
},
{
"code": null,
"e": 6985,
"s": 6899,
"text": "In the first line, a variable file_path is created to hold the path of the text file."
},
{
"code": null,
"e": 7065,
"s": 6985,
"text": "Then, the number of lines is printed using ‘END{print “Number of lines:”,NR}’. "
},
{
"code": null,
"e": 7204,
"s": 7065,
"text": "Here, END represents that we are interested in the last values of the NR variable as NR variable holds the count of the processed records."
},
{
"code": null,
"e": 7293,
"s": 7204,
"text": "To count the number of lines, a while loop is used till the number of processed records."
},
{
"code": null,
"e": 7354,
"s": 7293,
"text": "Adding the value of the NF i.e. count of words in each line."
},
{
"code": null,
"e": 7435,
"s": 7354,
"text": "In the end, the number of words is printed that is stored in the count variable."
},
{
"code": null,
"e": 7442,
"s": 7435,
"text": "Picked"
},
{
"code": null,
"e": 7455,
"s": 7442,
"text": "Shell Script"
},
{
"code": null,
"e": 7466,
"s": 7455,
"text": "Linux-Unix"
},
{
"code": null,
"e": 7564,
"s": 7466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7599,
"s": 7564,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 7635,
"s": 7599,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 7673,
"s": 7635,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 7709,
"s": 7673,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 7747,
"s": 7709,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 7773,
"s": 7747,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 7811,
"s": 7773,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7846,
"s": 7811,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 7882,
"s": 7846,
"text": "echo command in Linux with Examples"
}
] |
rm - Unix, Linux Command
|
rm - remove files or directories
rm [OPTION]... FILE...
rm removes each specified file. By default, it does not remove directories.
If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted.
Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped.
Example-1:
Remove the file myfile.txt. If the file is write-protected, you will be prompted to confirm that you really want to delete it:
$ rm myfile.txt
Example-2:
Remove the file myfile.txt. You will not be prompted, even if the file is write-protected; if rm can delete the file, it will:
$ rm -f myfile.txt
Example-3:
Remove all files in the working directory. If it is write-protected, you will be prompted before rm removes it:
$ rm *
Example-4:
Remove all files in the working directory. rm will not prompt you for any reason before deleting them:
$ rm -f *
Example-5:
Attempt to remove every file in the working directory, but prompt before each file to confirm:
$ rm -i *
Example-6:
Remove every file in the working directory; prompt for confirmation if more than three files are being deleted:
$ rm -I *
Example-7:
Remove the directory mydirectory, and any files and directories it contains. If a file or directory that rm tries to delete
is write-protected, you will be prompted to make sure that you really want to delete it:
$ rm -r mydirectory
Example-8:
Same as the above command, but you will never be prompted; if rm can delete the files, it will:
$ rm -rf mydirectory
|
[
{
"code": null,
"e": 10744,
"s": 10711,
"text": "rm - remove files or directories"
},
{
"code": null,
"e": 10767,
"s": 10744,
"text": "rm [OPTION]... FILE..."
},
{
"code": null,
"e": 10843,
"s": 10767,
"text": "rm removes each specified file. By default, it does not remove directories."
},
{
"code": null,
"e": 11111,
"s": 10843,
"text": "If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted."
},
{
"code": null,
"e": 11380,
"s": 11111,
"text": "Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped."
},
{
"code": null,
"e": 11391,
"s": 11380,
"text": "Example-1:"
},
{
"code": null,
"e": 11518,
"s": 11391,
"text": "Remove the file myfile.txt. If the file is write-protected, you will be prompted to confirm that you really want to delete it:"
},
{
"code": null,
"e": 11534,
"s": 11518,
"text": "$ rm myfile.txt"
},
{
"code": null,
"e": 11545,
"s": 11534,
"text": "Example-2:"
},
{
"code": null,
"e": 11672,
"s": 11545,
"text": "Remove the file myfile.txt. You will not be prompted, even if the file is write-protected; if rm can delete the file, it will:"
},
{
"code": null,
"e": 11691,
"s": 11672,
"text": "$ rm -f myfile.txt"
},
{
"code": null,
"e": 11702,
"s": 11691,
"text": "Example-3:"
},
{
"code": null,
"e": 11814,
"s": 11702,
"text": "Remove all files in the working directory. If it is write-protected, you will be prompted before rm removes it:"
},
{
"code": null,
"e": 11821,
"s": 11814,
"text": "$ rm *"
},
{
"code": null,
"e": 11832,
"s": 11821,
"text": "Example-4:"
},
{
"code": null,
"e": 11935,
"s": 11832,
"text": "Remove all files in the working directory. rm will not prompt you for any reason before deleting them:"
},
{
"code": null,
"e": 11945,
"s": 11935,
"text": "$ rm -f *"
},
{
"code": null,
"e": 11956,
"s": 11945,
"text": "Example-5:"
},
{
"code": null,
"e": 12051,
"s": 11956,
"text": "Attempt to remove every file in the working directory, but prompt before each file to confirm:"
},
{
"code": null,
"e": 12061,
"s": 12051,
"text": "$ rm -i *"
},
{
"code": null,
"e": 12072,
"s": 12061,
"text": "Example-6:"
},
{
"code": null,
"e": 12184,
"s": 12072,
"text": "Remove every file in the working directory; prompt for confirmation if more than three files are being deleted:"
},
{
"code": null,
"e": 12194,
"s": 12184,
"text": "$ rm -I *"
},
{
"code": null,
"e": 12205,
"s": 12194,
"text": "Example-7:"
},
{
"code": null,
"e": 12419,
"s": 12205,
"text": "Remove the directory mydirectory, and any files and directories it contains. If a file or directory that rm tries to delete \nis write-protected, you will be prompted to make sure that you really want to delete it:"
},
{
"code": null,
"e": 12440,
"s": 12419,
"text": "$ rm -r mydirectory "
},
{
"code": null,
"e": 12451,
"s": 12440,
"text": "Example-8:"
},
{
"code": null,
"e": 12547,
"s": 12451,
"text": "Same as the above command, but you will never be prompted; if rm can delete the files, it will:"
}
] |
numpy.sin() in Python
|
04 Jul, 2021
numpy.sin(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate trigonometric sine for all x(being the array elements). Parameters :
array : [array_like]elements are in radians.
2pi Radians = 36o degrees
Return :
An array with trigonometric sine of
x for all x i.e. array elements
Code #1 : Working
Python
# Python program explaining# sin() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array) Sin_Values = np.sin(in_array)print ("\nSine values : \n", Sin_Values)
Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]
Sine values :
[ 0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]
Code #2 : Graphical representation
Python
# Python program showing# Graphical representation of# sin() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.sin(in_array) print("in_array : ", in_array)print("\nout_array : ", out_array) # red for numpy.sin()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.sin()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output :
in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933
0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]
out_array : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01
-7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01
9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.sin.html#numpy.sin .
akshaysingh98088
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "numpy.sin(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate trigonometric sine for all x(being the array elements). Parameters : "
},
{
"code": null,
"e": 260,
"s": 211,
"text": "array : [array_like]elements are in radians. "
},
{
"code": null,
"e": 288,
"s": 262,
"text": "2pi Radians = 36o degrees"
},
{
"code": null,
"e": 299,
"s": 288,
"text": "Return : "
},
{
"code": null,
"e": 368,
"s": 299,
"text": "An array with trigonometric sine of\nx for all x i.e. array elements "
},
{
"code": null,
"e": 390,
"s": 368,
"text": " Code #1 : Working "
},
{
"code": null,
"e": 397,
"s": 390,
"text": "Python"
},
{
"code": "# Python program explaining# sin() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Input array : \\n\", in_array) Sin_Values = np.sin(in_array)print (\"\\nSine values : \\n\", Sin_Values)",
"e": 623,
"s": 397,
"text": null
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Output : "
},
{
"code": null,
"e": 800,
"s": 634,
"text": "Input array : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nSine values : \n [ 0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]"
},
{
"code": null,
"e": 839,
"s": 800,
"text": " Code #2 : Graphical representation "
},
{
"code": null,
"e": 846,
"s": 839,
"text": "Python"
},
{
"code": "# Python program showing# Graphical representation of# sin() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.sin(in_array) print(\"in_array : \", in_array)print(\"\\nout_array : \", out_array) # red for numpy.sin()plt.plot(in_array, out_array, color = 'red', marker = \"o\")plt.title(\"numpy.sin()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()",
"e": 1245,
"s": 846,
"text": null
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": "Output : "
},
{
"code": null,
"e": 1637,
"s": 1256,
"text": "in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01\n -7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01\n 9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16]"
},
{
"code": null,
"e": 1737,
"s": 1639,
"text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.sin.html#numpy.sin . "
},
{
"code": null,
"e": 1754,
"s": 1737,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1789,
"s": 1754,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 1802,
"s": 1789,
"text": "Python-numpy"
},
{
"code": null,
"e": 1809,
"s": 1802,
"text": "Python"
},
{
"code": null,
"e": 1907,
"s": 1809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1925,
"s": 1907,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1967,
"s": 1925,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1989,
"s": 1967,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2024,
"s": 1989,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2050,
"s": 2024,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2082,
"s": 2050,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2111,
"s": 2082,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2138,
"s": 2111,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2168,
"s": 2138,
"text": "Iterate over a list in Python"
}
] |
Intermediate Coding Problems in Python
|
17 Dec, 2021
Python, being a very dynamic and versatile programming language, is used in almost every field. From software development to machine learning, it covers them all. This article will focus on some interesting coding problems which can be used to sharpen our skills a bit more and at the same time, have fun solving this list of specially curated problems. Although this article will focus on solving these problems using Python, one can feel free to use any other language of their choice. So let’s head right into it!
The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long would it take for a Python function to generate just one sentence? The sentence we will go for is: “a computer science portal for geeks”. The way we will simulate this is to write a function that generates a string that is 35 characters long by choosing random letters from the 26 letters in the alphabet plus space. We will write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow, our program should keep track of the best string generated so far.
Example:
Python3
import random # function to generate # a random string def generateOne(strlen): # string with all the alphabets # and a space alphabet = "abcdefghijklmnopqrstuvwxyz " res ="" for i in range(strlen): res+= alphabet[random.randrange(27)] return res # function to determine the # score of the generated stringdef score(goal, testString): numSame = 0 for i in range(len(goal)): if goal[i] == testString[i]: numSame+= 1 return numSame / len(goal) # main function to call the previous# two functions until the goal is achieveddef main(): goalString = "a computer science portal for geeks" newString = generateOne(35) best = 0 newScore = score(goalString, newString) while newScore<1: if newScore>best: print(newString) best = newScore newString = generateOne(35) newScore = score(goalString, newString) # Driver codemain()
Output:
pxwvkdfwpbzneycy rifcrnczxqtsfowgjm
wfgytnakffjty ggfy trylljfhurazyxow
docujzolvswarzqszridmejyluhwviujlkj
qbtvqanrbwsximmnlhjgkaacufhskiooxm
w jnlhvvinzrlimtesllsroqqqf wwteela
mjcevludro yoigewqudxjsad bxrl qnlv
f pomksbzrjizegcjwyoqftjz wwx ges
Here, we wrote three functions. One will generate a random string using the 26 characters of the alphabet and space. The second function will then score the generated string by comparing each letter of it with the goalString. The third function will repeatedly call the first two functions until the task is completed. It will also take note of the best string generated so far by comparing their scores. The one with the highest score will be the best one. Finally, we run this program in our IDE and see it work.
This is a really interesting program as it generates some really funny outputs. It is also a healthy practice problem for beginners who want to understand the “string” type more clearly. Let’s look into the problem.Given a string, find a substring based on the following conditions:
The substring must be the longest one of all the possible substring in the given string.
There must not be any repeating characters in the substring.
If there is more than one substring satisfying the above two conditions, then print the substring which occurs first.
If there is no substring satisfying all the aforementioned conditions then print -1.
Although there can be many methods of approach to this problem, we will look at the most basic one.
Example:
Python3
def test_1(string =""): # initializing the substring substring = "" testList = [] initial = 0 for char in string: for i in range(initial, len(string)): substring+= string[i] # checking conditions if substring.count(string[i])>1: testList.append(substring[:-1]) initial+= 1 substring = "" break maxi ="" for word in testList: if len(word)>len(maxi): maxi = word if len(maxi)<3: return "-1" else: return maxi # Driver codeprint(test_1("character"))print(test_1("standfan"))print(test_1("class"))
Here, we write a single function that will carry out the entire task. First it will initialize variables called substring and testList to store the substring and a list of possible outputs respectively. Then it will loop over the entire string provided and break every time it finds a repetition and appends that word to testList. Finally, the longest word out of the possible outputs is returned.
Output:
racte
standf
clas
A low-level implementation of the classic game “Mastermind”. We need to write a program that generates a four-digit random code and the user needs to guess the code in 10 tries or less. If any digit out of the guessed four-digit code is wrong, the computer should print out “B”. If the digit is correct but at the wrong place, the computer should print “Y”. If both the digit and position is correct, the computer should print “R”. Example:
Example:
Python3
import random # generates a four-digit codedef gen_code(): set_code = [] for i in range(4): val = random.randint(0, 9) set_code.append(val) return set_code # asks for input from the userdef input_code(): code = input("Enter your four digit guess code: ") return code # plays the gamedef mastermind(): genCode = gen_code() i = 0 while i < 10: result = "" inputCode = [int(c) for c in input_code()] if len(inputCode) != 4: print("Enter only 4 digit number") continue if inputCode == genCode: print("You guessed it !", genCode) break for element in inputCode: if element in genCode: if inputCode.index(element) == genCode.index(element): result+="R" else: result+="Y" else: result+="B" print(result) i += 1 else: print("You ran out of trys !", genCode) # Driver Codemastermind()
First, we write a function to generate a random four-digit code using Python’s random module. Next, we define a function that asks for user input. Finally, we write a function that compares the generated code to the guessed code and gives appropriate results.
A very simple problem with many different solutions, but the main aim is to solve it in the most efficient way. A man was given directions to go from point A to point B. The directions were: “SOUTH”, “NORTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too. Going to one direction and coming back in the opposite direction is a waste of time and energy. So, we need to help the man by writing a program that will eliminate the useless steps and will contain only the necessary directions. For example: The directions [“NORTH”, “SOUTH”, “SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”] should be reduced to [“WEST”]. This is because going “NORTH” and then immediately “SOUTH” means coming back to the same place. So we cancel them and we have [“SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”]. Next, we go “SOUTH”, take “EAST” and then immediately take “WEST”, which again means coming back to the same point. Hence we cancel “EAST” and “WEST” to giving us [“SOUTH”, “NORTH”, “WEST”]. It’s clear that “SOUTH” and “NORTH” are opposites hence canceled and finally we are left with [“WEST”].
Example:
Python3
opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} # Function to find the reduced# directiondef dirReduc(givenDirections): finalDirections = [] for d in range(0, len(givenDirections)): if finalDirections: if finalDirections[-1] == opposite[givenDirections[d]]: finalDirections.pop() else: finalDirections.append(givenDirections[d]) else: finalDirections.append(givenDirections[d]) return finalDirections # Driver Codeprint(dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
In the above solution, we create a dictionary of opposites to help us determine if a given direction is opposite to the other. Next, we initialize a variable called finalDirections which will be our output. If the direction which is in the givenDirections is opposite of the last element in finalDirections, we pop it out of finalDirections otherwise we append it to finalDirections.
Output:
['WEST']
This problem helps one to understand the key concepts of an array(list) in Python. Two arrays are said to be the same if they contain the same elements and in the same order. However, in this problem, we will compare two arrays to see if they are same, but with a slight twist. Here, two arrays are the same if the elements of one array are squares of elements of other arrays and regardless of the order. Consider two arrays a and b.
a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
Here b can be written as:
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
which is a square of every element of a. Hence, they are same. If a or b are None, our program should written False
Example:
Python3
# function to compare the arraysdef comp(array1, array2): # checking if any array is None if array1 is None or array2 is None: return False # checking if any of the array # is a square of the other if (sorted(array1) == sorted([i ** 2 for i in array2])) or (sorted(array2) == sorted([i ** 2 for i in array1])): return True return False # Driver Codecomp([1,2,3,4], [1,4,9,16])
Output:
True
user_2pui
avtarkumar719
python-basics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 571,
"s": 54,
"text": "Python, being a very dynamic and versatile programming language, is used in almost every field. From software development to machine learning, it covers them all. This article will focus on some interesting coding problems which can be used to sharpen our skills a bit more and at the same time, have fun solving this list of specially curated problems. Although this article will focus on solving these problems using Python, one can feel free to use any other language of their choice. So let’s head right into it!"
},
{
"code": null,
"e": 1561,
"s": 571,
"text": "The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long would it take for a Python function to generate just one sentence? The sentence we will go for is: “a computer science portal for geeks”. The way we will simulate this is to write a function that generates a string that is 35 characters long by choosing random letters from the 26 letters in the alphabet plus space. We will write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow, our program should keep track of the best string generated so far."
},
{
"code": null,
"e": 1571,
"s": 1561,
"text": "Example: "
},
{
"code": null,
"e": 1579,
"s": 1571,
"text": "Python3"
},
{
"code": "import random # function to generate # a random string def generateOne(strlen): # string with all the alphabets # and a space alphabet = \"abcdefghijklmnopqrstuvwxyz \" res =\"\" for i in range(strlen): res+= alphabet[random.randrange(27)] return res # function to determine the # score of the generated stringdef score(goal, testString): numSame = 0 for i in range(len(goal)): if goal[i] == testString[i]: numSame+= 1 return numSame / len(goal) # main function to call the previous# two functions until the goal is achieveddef main(): goalString = \"a computer science portal for geeks\" newString = generateOne(35) best = 0 newScore = score(goalString, newString) while newScore<1: if newScore>best: print(newString) best = newScore newString = generateOne(35) newScore = score(goalString, newString) # Driver codemain()",
"e": 2574,
"s": 1579,
"text": null
},
{
"code": null,
"e": 2582,
"s": 2574,
"text": "Output:"
},
{
"code": null,
"e": 2834,
"s": 2582,
"text": "pxwvkdfwpbzneycy rifcrnczxqtsfowgjm\nwfgytnakffjty ggfy trylljfhurazyxow\ndocujzolvswarzqszridmejyluhwviujlkj\n qbtvqanrbwsximmnlhjgkaacufhskiooxm\nw jnlhvvinzrlimtesllsroqqqf wwteela\nmjcevludro yoigewqudxjsad bxrl qnlv\nf pomksbzrjizegcjwyoqftjz wwx ges"
},
{
"code": null,
"e": 3350,
"s": 2834,
"text": "Here, we wrote three functions. One will generate a random string using the 26 characters of the alphabet and space. The second function will then score the generated string by comparing each letter of it with the goalString. The third function will repeatedly call the first two functions until the task is completed. It will also take note of the best string generated so far by comparing their scores. The one with the highest score will be the best one. Finally, we run this program in our IDE and see it work. "
},
{
"code": null,
"e": 3634,
"s": 3350,
"text": "This is a really interesting program as it generates some really funny outputs. It is also a healthy practice problem for beginners who want to understand the “string” type more clearly. Let’s look into the problem.Given a string, find a substring based on the following conditions: "
},
{
"code": null,
"e": 3724,
"s": 3634,
"text": "The substring must be the longest one of all the possible substring in the given string. "
},
{
"code": null,
"e": 3786,
"s": 3724,
"text": "There must not be any repeating characters in the substring. "
},
{
"code": null,
"e": 3905,
"s": 3786,
"text": "If there is more than one substring satisfying the above two conditions, then print the substring which occurs first. "
},
{
"code": null,
"e": 3991,
"s": 3905,
"text": "If there is no substring satisfying all the aforementioned conditions then print -1. "
},
{
"code": null,
"e": 4091,
"s": 3991,
"text": "Although there can be many methods of approach to this problem, we will look at the most basic one."
},
{
"code": null,
"e": 4101,
"s": 4091,
"text": "Example: "
},
{
"code": null,
"e": 4109,
"s": 4101,
"text": "Python3"
},
{
"code": "def test_1(string =\"\"): # initializing the substring substring = \"\" testList = [] initial = 0 for char in string: for i in range(initial, len(string)): substring+= string[i] # checking conditions if substring.count(string[i])>1: testList.append(substring[:-1]) initial+= 1 substring = \"\" break maxi =\"\" for word in testList: if len(word)>len(maxi): maxi = word if len(maxi)<3: return \"-1\" else: return maxi # Driver codeprint(test_1(\"character\"))print(test_1(\"standfan\"))print(test_1(\"class\"))",
"e": 4842,
"s": 4109,
"text": null
},
{
"code": null,
"e": 5240,
"s": 4842,
"text": "Here, we write a single function that will carry out the entire task. First it will initialize variables called substring and testList to store the substring and a list of possible outputs respectively. Then it will loop over the entire string provided and break every time it finds a repetition and appends that word to testList. Finally, the longest word out of the possible outputs is returned."
},
{
"code": null,
"e": 5249,
"s": 5240,
"text": "Output: "
},
{
"code": null,
"e": 5268,
"s": 5249,
"text": "racte\nstandf\nclas "
},
{
"code": null,
"e": 5709,
"s": 5268,
"text": "A low-level implementation of the classic game “Mastermind”. We need to write a program that generates a four-digit random code and the user needs to guess the code in 10 tries or less. If any digit out of the guessed four-digit code is wrong, the computer should print out “B”. If the digit is correct but at the wrong place, the computer should print “Y”. If both the digit and position is correct, the computer should print “R”. Example:"
},
{
"code": null,
"e": 5719,
"s": 5709,
"text": "Example: "
},
{
"code": null,
"e": 5727,
"s": 5719,
"text": "Python3"
},
{
"code": "import random # generates a four-digit codedef gen_code(): set_code = [] for i in range(4): val = random.randint(0, 9) set_code.append(val) return set_code # asks for input from the userdef input_code(): code = input(\"Enter your four digit guess code: \") return code # plays the gamedef mastermind(): genCode = gen_code() i = 0 while i < 10: result = \"\" inputCode = [int(c) for c in input_code()] if len(inputCode) != 4: print(\"Enter only 4 digit number\") continue if inputCode == genCode: print(\"You guessed it !\", genCode) break for element in inputCode: if element in genCode: if inputCode.index(element) == genCode.index(element): result+=\"R\" else: result+=\"Y\" else: result+=\"B\" print(result) i += 1 else: print(\"You ran out of trys !\", genCode) # Driver Codemastermind()",
"e": 6913,
"s": 5727,
"text": null
},
{
"code": null,
"e": 7174,
"s": 6913,
"text": "First, we write a function to generate a random four-digit code using Python’s random module. Next, we define a function that asks for user input. Finally, we write a function that compares the generated code to the guessed code and gives appropriate results. "
},
{
"code": null,
"e": 8280,
"s": 7174,
"text": "A very simple problem with many different solutions, but the main aim is to solve it in the most efficient way. A man was given directions to go from point A to point B. The directions were: “SOUTH”, “NORTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too. Going to one direction and coming back in the opposite direction is a waste of time and energy. So, we need to help the man by writing a program that will eliminate the useless steps and will contain only the necessary directions. For example: The directions [“NORTH”, “SOUTH”, “SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”] should be reduced to [“WEST”]. This is because going “NORTH” and then immediately “SOUTH” means coming back to the same place. So we cancel them and we have [“SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”]. Next, we go “SOUTH”, take “EAST” and then immediately take “WEST”, which again means coming back to the same point. Hence we cancel “EAST” and “WEST” to giving us [“SOUTH”, “NORTH”, “WEST”]. It’s clear that “SOUTH” and “NORTH” are opposites hence canceled and finally we are left with [“WEST”]."
},
{
"code": null,
"e": 8290,
"s": 8280,
"text": "Example: "
},
{
"code": null,
"e": 8298,
"s": 8290,
"text": "Python3"
},
{
"code": "opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} # Function to find the reduced# directiondef dirReduc(givenDirections): finalDirections = [] for d in range(0, len(givenDirections)): if finalDirections: if finalDirections[-1] == opposite[givenDirections[d]]: finalDirections.pop() else: finalDirections.append(givenDirections[d]) else: finalDirections.append(givenDirections[d]) return finalDirections # Driver Codeprint(dirReduc([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"]))",
"e": 9014,
"s": 8298,
"text": null
},
{
"code": null,
"e": 9399,
"s": 9014,
"text": "In the above solution, we create a dictionary of opposites to help us determine if a given direction is opposite to the other. Next, we initialize a variable called finalDirections which will be our output. If the direction which is in the givenDirections is opposite of the last element in finalDirections, we pop it out of finalDirections otherwise we append it to finalDirections. "
},
{
"code": null,
"e": 9407,
"s": 9399,
"text": "Output:"
},
{
"code": null,
"e": 9417,
"s": 9407,
"text": "['WEST'] "
},
{
"code": null,
"e": 9852,
"s": 9417,
"text": "This problem helps one to understand the key concepts of an array(list) in Python. Two arrays are said to be the same if they contain the same elements and in the same order. However, in this problem, we will compare two arrays to see if they are same, but with a slight twist. Here, two arrays are the same if the elements of one array are squares of elements of other arrays and regardless of the order. Consider two arrays a and b."
},
{
"code": null,
"e": 9946,
"s": 9852,
"text": "a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]"
},
{
"code": null,
"e": 9973,
"s": 9946,
"text": "Here b can be written as: "
},
{
"code": null,
"e": 10042,
"s": 9973,
"text": "b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]"
},
{
"code": null,
"e": 10158,
"s": 10042,
"text": "which is a square of every element of a. Hence, they are same. If a or b are None, our program should written False"
},
{
"code": null,
"e": 10168,
"s": 10158,
"text": "Example: "
},
{
"code": null,
"e": 10176,
"s": 10168,
"text": "Python3"
},
{
"code": "# function to compare the arraysdef comp(array1, array2): # checking if any array is None if array1 is None or array2 is None: return False # checking if any of the array # is a square of the other if (sorted(array1) == sorted([i ** 2 for i in array2])) or (sorted(array2) == sorted([i ** 2 for i in array1])): return True return False # Driver Codecomp([1,2,3,4], [1,4,9,16])",
"e": 10611,
"s": 10176,
"text": null
},
{
"code": null,
"e": 10619,
"s": 10611,
"text": "Output:"
},
{
"code": null,
"e": 10624,
"s": 10619,
"text": "True"
},
{
"code": null,
"e": 10636,
"s": 10626,
"text": "user_2pui"
},
{
"code": null,
"e": 10650,
"s": 10636,
"text": "avtarkumar719"
},
{
"code": null,
"e": 10664,
"s": 10650,
"text": "python-basics"
},
{
"code": null,
"e": 10671,
"s": 10664,
"text": "Python"
},
{
"code": null,
"e": 10687,
"s": 10671,
"text": "Python Programs"
}
] |
Print * in place of characters for reading passwords in C
|
20 Sep, 2018
While writing a C program, if you want to type password and it should not be visible on screen or an * symbol is to be printed.
Examples:
Input : abcdefg
Output : *******
Note : Below solution uses getch() which may not work on all compilers as this is a non-standard function.
// C program to print * // in place of characters#include<stdio.h>#include<conio.h>int main(void){ char password[55]; printf("password:\n"); int p=0; do{ password[p]=getch(); if(password[p]!='\r'){ printf("*"); } p++; }while(password[p-1]!='\r'); password[p-1]='\0'; printf("\nYou have entered %s as password.",password); getch();}
Explanation: Basically it is taking the characters we enter through getch() function and print * instead of it for every letter we type.
Remark: It doesn’t run in this IDE, download this file and run in your terminal.
This article is contributed by Pavan Gopal Rayapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
imdpkmr
C Language
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Sep, 2018"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "While writing a C program, if you want to type password and it should not be visible on screen or an * symbol is to be printed."
},
{
"code": null,
"e": 190,
"s": 180,
"text": "Examples:"
},
{
"code": null,
"e": 224,
"s": 190,
"text": "Input : abcdefg\nOutput : *******\n"
},
{
"code": null,
"e": 331,
"s": 224,
"text": "Note : Below solution uses getch() which may not work on all compilers as this is a non-standard function."
},
{
"code": "// C program to print * // in place of characters#include<stdio.h>#include<conio.h>int main(void){ char password[55]; printf(\"password:\\n\"); int p=0; do{ password[p]=getch(); if(password[p]!='\\r'){ printf(\"*\"); } p++; }while(password[p-1]!='\\r'); password[p-1]='\\0'; printf(\"\\nYou have entered %s as password.\",password); getch();}",
"e": 728,
"s": 331,
"text": null
},
{
"code": null,
"e": 865,
"s": 728,
"text": "Explanation: Basically it is taking the characters we enter through getch() function and print * instead of it for every letter we type."
},
{
"code": null,
"e": 946,
"s": 865,
"text": "Remark: It doesn’t run in this IDE, download this file and run in your terminal."
},
{
"code": null,
"e": 1254,
"s": 946,
"text": "This article is contributed by Pavan Gopal Rayapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1379,
"s": 1254,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "imdpkmr"
},
{
"code": null,
"e": 1398,
"s": 1387,
"text": "C Language"
},
{
"code": null,
"e": 1417,
"s": 1398,
"text": "School Programming"
},
{
"code": null,
"e": 1515,
"s": 1417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1563,
"s": 1515,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1584,
"s": 1563,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1610,
"s": 1584,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 1655,
"s": 1610,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1693,
"s": 1655,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1711,
"s": 1693,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1736,
"s": 1711,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 1759,
"s": 1736,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1778,
"s": 1759,
"text": "Interfaces in Java"
}
] |
Python Program for BogoSort or Permutation Sort
|
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of permutation sort.
BogoSort also is known as permutation sort, is based on generating and testing paradigms.
Now let’s observe the solution in the implementation below−
Live Demo
# random module
import random
# Sort
def bogoSort(a):
n = len(a)
while (is_sorted(a)== False):
shuffle(a)
# check
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
# permutation
def shuffle(a):
n = len(a)
for i in range (0,n):
r = random.randint(0,n-1)
a[i], a[r] = a[r], a[i]
# main
a = [1,5,3,4,8,6,3,4,5]
bogoSort(a)
print("Sorted array :")
for i in range(len(a)):
print (a[i],end=" ")
Sorted array is :
1 3 3 4 4 5 5 6 8
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for BogoSort or Permutation Sort
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1251,
"s": 1150,
"text": "Problem statement − We are given an array, we need to sort it using the concept of permutation sort."
},
{
"code": null,
"e": 1341,
"s": 1251,
"text": "BogoSort also is known as permutation sort, is based on generating and testing paradigms."
},
{
"code": null,
"e": 1401,
"s": 1341,
"text": "Now let’s observe the solution in the implementation below−"
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": " Live Demo"
},
{
"code": null,
"e": 1907,
"s": 1412,
"text": "# random module\nimport random\n# Sort\ndef bogoSort(a):\n n = len(a)\n while (is_sorted(a)== False):\n shuffle(a)\n# check\ndef is_sorted(a):\n n = len(a)\n for i in range(0, n-1):\n if (a[i] > a[i+1] ):\n return False\n return True\n# permutation\ndef shuffle(a):\n n = len(a)\n for i in range (0,n):\n r = random.randint(0,n-1)\n a[i], a[r] = a[r], a[i]\n# main\na = [1,5,3,4,8,6,3,4,5]\nbogoSort(a)\nprint(\"Sorted array :\")\nfor i in range(len(a)):\n print (a[i],end=\" \")"
},
{
"code": null,
"e": 1943,
"s": 1907,
"text": "Sorted array is :\n1 3 3 4 4 5 5 6 8"
},
{
"code": null,
"e": 2044,
"s": 1943,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 2149,
"s": 2044,
"text": "In this article, we have learned about how we can make a Python Program for BogoSort or Permutation Sort"
}
] |
Scala - Quick Guide
|
Scala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky. Scala smoothly integrates the features of object-oriented and functional languages. Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability.
Here we have presented a few points that makes Scala the first choice of application developers.
Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits which will be explained in subsequent chapters.
Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.
Scala is also a functional language in the sense that every function is a value and every value is an object so ultimately every function is an object.
Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. These concepts will be explained in subsequent chapters.
Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect you to provide redundant type information. You don't have to specify a type in most cases, and you certainly don't have to repeat it.
Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM). This means that Scala and Java have a common runtime platform. You can easily move from Java to Scala.
The Scala compiler compiles your Scala code into Java Byte Code, which can then be executed by the 'scala' command. The 'scala' command is similar to the java command, in that it executes your compiled Scala code.
Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects.
Scala allows you to express general programming patterns in an effective way. It reduces the number of lines and helps the programmer to code in a type-safe way. It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism (Synchronize).
Scala has a set of features that completely differ from Java. Some of these are −
All types are objects
Type inference
Nested Functions
Functions are objects
Domain specific language (DSL) support
Traits
Closures
Concurrency support inspired by Erlang
Scala is being used everywhere and importantly in enterprise web applications. You can check a few of the most popular Scala web frameworks −
The Lift Framework
The Lift Framework
The Play framework
The Play framework
The Bowler framework
The Bowler framework
Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer.
Follow the steps given below to install Scala.
First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on.
If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.
Open Command Console and type −
\>java –version
Java version "1.8.0_31"
Java (TM) SE Run Time
Environment (build 1.8.0_31-b31)
Java Hotspot (TM) 64-bit Server
VM (build 25.31-b07, mixed mode)
Open Command terminal and type −
$java –version
Java version "1.8.0_31"
Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64)
Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode)
We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system.
In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it.
Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,
Windows
Set JAVA_HOME to C:\ProgramFiles\java\jdk1.7.0_60
Linux
Export JAVA_HOME=/usr/local/java-current
Append the full path of Java compiler location to the System Path.
Windows
Append the String "C:\Program Files\Java\jdk1.7.0_60\bin" to the end of the system variable PATH.
Linux
Export PATH=$PATH:$JAVA_HOME/bin/
Execute the command java -version from the command prompt as explained above.
You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt −
\>java –jar scala-2.11.5-installer.jar\>
This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:\Program Files\Scala”, you can select a suitable path as per your convenience.
Command −
$java –jar scala-2.9.0.1-installer.jar
Output −
Welcome to the installation of Scala 2.9.0.1!
The homepage is at − http://Scala-lang.org/
press 1 to continue, 2 to quit, 3 to redisplay
1................................................
[ Starting to unpack ]
[ Processing package: Software Package Installation (1/1) ]
[ Unpacking finished ]
[ Console installation done ]
During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience.
Finally, open a new command prompt and type Scala -version and press Enter. You should see the following −
\>scala -version
Scala code runner version 2.11.5 -- Copyright 2002-2013, LAMP/EPFL
$scala -version
Scala code runner version 2.9.0.1 – Copyright 2002-2013, LAMP/EPFL
If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ';' line end character is optional.
When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean.
Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating.
Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields.
Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields.
Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function.
Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function.
Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods.
Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods.
We can execute a Scala program in two modes: one is interactive mode and another is script mode.
Open the command prompt and use the following command to open Scala.
\>scala
If Scala is installed in your system, the following output will be displayed −
Welcome to Scala version 2.9.0.1
Type in expressions to have them evaluated.
Type :help for more information.
Type the following text to the right of the Scala prompt and press the Enter key −
scala> println("Hello, Scala!");
It will produce the following result −
Hello, Scala!
Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it.
object HelloWorld {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
def main(args: Array[String]) {
println("Hello, world!") // prints Hello World
}
}
Save the file as − HelloWorld.scala.
Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command.
Use the following command to compile and execute your Scala program.
\> scalac HelloWorld.scala
\> scala HelloWorld
Hello, World!
The following are the basic syntaxes and coding conventions in Scala programming.
Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala.
Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala.
Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example − class MyFirstScalaClass.
Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example − class MyFirstScalaClass.
Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example − def myMethodName()
Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example − def myMethodName()
Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile).
Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'.
Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile).
Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'.
def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program.
def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program.
All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers.
An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers.
Following are legal alphanumeric identifiers −
age, salary, _value, __1_value
Following are illegal identifiers −
$salary, 123abc, -salary
An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #.
Following are legal operator identifiers −
+ ++ ::: <?> :>
The Scala compiler will internally "mangle" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater.
A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier.
Following are legal mixed identifiers −
unary_+, myvar_=
Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator (operator overloading).
A literal identifier is an arbitrary string enclosed in back ticks (` . . . `).
Following are legal literal identifiers −
`x` `<clinit>` `yield`
The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names.
Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler.
object HelloWorld {
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
def main(args: Array[String]) {
// Prints Hello World
// This is also an example of single line comment.
println("Hello, world!")
}
}
A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments.
Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is usually optional. You can type one if you want but you don't have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line. Below syntax is the usage of multiple statements.
val s = "hello"; println(s)
A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows −
package com.liftcode.stuff
Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package −
import scala.xml._
You can import a single class and object, for example, HashMap from the scala.collection.mutable package −
import scala.collection.mutable.HashMap
You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package −
import scala.collection.immutable.{TreeMap, TreeSet}
A marker trait that enables dynamic invocations. Instances x of this trait allow method invocations x.meth(args) for arbitrary method names meth and argument lists args as well as field accesses x.field for arbitrary field namesfield. This feature is introduced in Scala-2.10.
If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules −
foo.method("blah") ~~> foo.applyDynamic("method")("blah")
foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah"))
foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2))
foo.field ~~> foo.selectDynamic("field")
foo.varia = 10 ~~> foo.updateDynamic("varia")(10)
foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13)
foo.arr(10) ~~> foo.applyDynamic("arr")(10)
Scala has all the same data types as Java, with the same memory footprint and precision. Following is the table giving details about all the data types available in Scala −
Byte
8 bit signed value. Range from -128 to 127
Short
16 bit signed value. Range -32768 to 32767
Int
32 bit signed value. Range -2147483648 to 2147483647
Long
64 bit signed value. -9223372036854775808 to 9223372036854775807
Float
32 bit IEEE 754 single-precision float
Double
64 bit IEEE 754 double-precision float
Char
16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
String
A sequence of Chars
Boolean
Either the literal true or the literal false
Unit
Corresponds to no value
Null
null or empty reference
Nothing
The subtype of every other type; includes no values
Any
The supertype of any type; any object is of type Any
AnyRef
The supertype of any reference type
All the data types listed above are objects. There are no primitive types like in Java. This means that you can call methods on an Int, Long, etc.
The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala Literals.
Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Here are some integer literals −
0
035
21
0xFFFFFFFF
0777L
Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. Here are some floating point literals −
0.0
1e30f
3.14159f
1.0e100
.1
The Boolean literals true and false are members of type Boolean.
A symbol literal 'x is a shorthand for the expression scala.Symbol("x"). Symbol is a case class, which is defined as follows.
package scala
final case class Symbol private (name: String) {
override def toString: String = "'" + name
}
A character literal is a single character enclosed in quotes. The character is either a printable Unicode character or is described by an escape sequence. Here are some character literals −
'a'
'\u0041'
'\n'
'\t'
A string literal is a sequence of characters in double quotes. The characters are either printable Unicode character or are described by escape sequences. Here are some string literals −
"Hello,\nWorld!"
"This string contains a \" character."
A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The sequence of characters is arbitrary, except that it may contain three or more consecutive quote characters only at the very end.
Characters must not necessarily be printable; newlines or other control characters are also permitted. Here is a multi-line string literal −
"""the present string
spans three
lines."""
The null value is of type scala.Null and is thus compatible with every reference type. It denotes a reference value which refers to a special "null" object.
The following escape sequences are recognized in character and string literals.
A character with Unicode between 0 and 255 may also be represented by an octal escape, i.e., a backslash '\' followed by a sequence of up to three octal characters. Following is the example to show few escape sequence characters −
object Test {
def main(args: Array[String]) {
println("Hello\tWorld\n\n" );
}
}
When the above code is compiled and executed, it produces the following result −
Hello World
Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory.
Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword −
var myVar : String = "Foo"
Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −
val myVal : String = "Foo"
The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −
val or val VariableName : DataType = [Initial Value]
If you do not assign any initial value to a variable, then it is valid as follows −
var myVar :Int;
val myVal :String;
When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −
var myVar = 10;
val myVal = "Hello, Scala!";
Here, by default, myVar will be Int type and myVal will become String type variable.
Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.]
val (myVar1: Int, myVar2: String) = Pair(40, "Foo")
And the type inference gets it right −
val (myVar1, myVar2) = Pair(40, "Foo")
The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration.
object Demo {
def main(args: Array[String]) {
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar); println(myVal); println(myVar1);
println(myVal1);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10
Hello Scala with datatype declaration.
20
Hello Scala without datatype declaration.
Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope.
Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val.
Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword.
Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable and immutable types and can be defined using either var or val.
This chapter takes you through how to use classes and objects in Scala programming. A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class.
The following diagram demonstrates the class and object by taking an example of class student, which contains the member variables (name and roll no) and member methods (setName() and setRollNo()). Finally all are members of the class. Class is a blue print and objects are real here. In the following diagram, Student is a class and Harini, John, and Maria are the objects of Student class, those are having name and roll-number.
Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods.
The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class.
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
As mentioned earlier in this chapter, you can create objects using a keyword new and then you can access class fields and methods as shown below in the example −
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
object Demo {
def main(args: Array[String]) {
val pt = new Point(10, 20);
// Move to a new location
pt.move(10, 10);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Point x location : 20
Point y location : 30
You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method.
Let us take an example of two classes Point class (as same example as above) and Location class is inherited class using extends keyword. Such an ‘extends’ clause has two effects: it makes Location class inherit all non-private members from Point class, and it makes the type Location a subtype of the type Point class. So here the Point class is called superclass and the class Location is called subclass. Extending a class and inheriting all the features of a parent class is called inheritance but Scala allows the inheritance from just one class only.
Note − Methods move() method in Point class and move() method in Location class do not override the corresponding definitions of move since they are different definitions (for example, the former take two arguments while the latter take three arguments).
Try the following example program to implement inheritance.
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}
class Location(override val xc: Int, override val yc: Int,
val zc :Int) extends Point(xc, yc){
var z: Int = zc
def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
println ("Point y location : " + y);
println ("Point z location : " + z);
}
}
object Demo {
def main(args: Array[String]) {
val loc = new Location(10, 20, 15);
// Move to a new location
loc.move(10, 10, 5);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Point x location : 20
Point y location : 30
Point z location : 20
Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10.
Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class.
object <object name> {
implicit class <class name>(<Variable>: Data type) {
def <method>(): Unit =
}
}
Let us take an example of an implicit class named IntTimes with the method times(). It means the times () contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println (“Hello”)” means the println (“”Hello”) statement will execute 4 times.
The following is the program for the given example. In this example two object classes are used (Run and Demo) so that we have to save those two classes in different files with their respective names as follows.
Run.scala − Save the following program in Run.scala.
object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =
if(current > 0){
f
loop(current - 1)
}
loop(x)
}
}
}
Demo.scala − Save the following program in Demo.scala.
import Run._
object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}
The following commands are used to compile and execute these two programs.
\>scalac Run.scala
\>scalac Demo.scala
\>scala Demo
Hello
Hello
Hello
Hello
Note −
Implicit classes must be defined inside another class/object/trait (not in top level).
Implicit classes must be defined inside another class/object/trait (not in top level).
Implicit classes may only take one non –implicit argument in their constructor.
Implicit classes may only take one non –implicit argument in their constructor.
Implicit classes may not be any method, member or object in scope with the same name as the implicit class.
Implicit classes may not be any method, member or object in scope with the same name as the implicit class.
Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor. You already have seen all the examples using singleton objects where you called Scala's main method.
Following is the same example program to implement singleton.
import java.io._
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
}
}
object Demo {
def main(args: Array[String]) {
val point = new Point(10, 20)
printPoint
def printPoint{
println ("Point x location : " + point.x);
println ("Point y location : " + point.y);
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Point x location : 10
Point y location : 20
This chapter takes you through the Scala access modifiers. Members of packages, classes or objects can be labeled with the access modifiers private and protected, and if we are not using either of these two keywords, then access will be assumed as public. These modifiers restrict accesses to the members to certain regions of code. To use an access modifier, you include its keyword in the definition of members of package, class or object as we will see in the following section.
A private member is visible only inside the class or object that contains the member definition.
Following is the example code snippet to explain Private member −
class Outer {
class Inner {
private def f() { println("f") }
class InnerMost {
f() // OK
}
}
(new Inner).f() // Error: f is not accessible
}
In Scala, the access (new Inner). f() is illegal because f is declared private in Inner and the access is not from within class Inner. By contrast, the first access to f in class Innermost is OK, because that access is contained in the body of class Inner. Java would permit both accesses because it lets an outer class access private members of its inner classes.
A protected member is only accessible from subclasses of the class in which the member is defined.
Following is the example code snippet to explain protected member −
package p {
class Super {
protected def f() { println("f") }
}
class Sub extends Super {
f()
}
class Other {
(new Super).f() // Error: f is not accessible
}
}
The access to f in class Sub is OK because f is declared protected in ‘Super’ class and ‘Sub’ class is a subclass of Super. By contrast the access to f in ‘Other’ class is not permitted, because class ‘Other’ does not inherit from class ‘Super’. In Java, the latter access would be still permitted because ‘Other’ class is in the same package as ‘Sub’ class.
Unlike private and protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from anywhere.
Following is the example code snippet to explain public member −
class Outer {
class Inner {
def f() { println("f") }
class InnerMost {
f() // OK
}
}
(new Inner).f() // OK because now f() is public
}
Access modifiers in Scala can be augmented with qualifiers. A modifier of the form private[X] or protected[X] means that access is private or protected "up to" X, where X designates some enclosing package, class or singleton object.
Consider the following example −
package society {
package professional {
class Executive {
private[professional] var workDetails = null
private[society] var friends = null
private[this] var secrets = null
def help(another : Executive) {
println(another.workDetails)
println(another.secrets) //ERROR
}
}
}
}
Note − the following points from the above example −
Variable workDetails will be accessible to any class within the enclosing package professional.
Variable workDetails will be accessible to any class within the enclosing package professional.
Variable friends will be accessible to any class within the enclosing package society.
Variable friends will be accessible to any class within the enclosing package society.
Variable secrets will be accessible only on the implicit object within instance methods (this).
Variable secrets will be accessible only on the implicit object within instance methods (this).
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.
The following arithmetic operators are supported by Scala language. For example, let us assume variable A holds 10 and variable B holds 20, then −
Show Examples
The following relational operators are supported by Scala language. For example let us assume variable A holds 10 and variable B holds 20, then −
Show Examples
The following logical operators are supported by Scala language. For example, assume variable A holds 1 and variable B holds 0, then −
Show Examples
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by Scala language is listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Show Examples
There are following assignment operators supported by Scala language −
Show Examples
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Take a look at the following table. Operators with the highest precedence appear at the top of the table and those with the lowest precedence appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
This chapter takes you through the conditional construction statements in Scala programming. Following is the general form of a typical decision making IF...ELSE structure found in most of the programming languages.
The following is a flow chart diagram for conditional statement.
‘if’ statement consists of a Boolean expression followed by one or more statements.
The syntax of an ‘if’ statement is as follows.
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the ‘if’ expression will be executed. If not, the first set of code after the end of the ‘if’ expression (after the closing curly brace) will be executed.
Try the following example program to understand conditional expressions (if expression) in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var x = 10;
if( x < 20 ){
println("This is if statement");
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
This is if statement
An ‘if’ statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The syntax of a if...else is −
if(Boolean_expression){
//Executes when the Boolean expression is true
} else{
//Executes when the Boolean expression is false
}
Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var x = 30;
if( x < 20 ){
println("This is if statement");
} else {
println("This is else statement");
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
This is else statement
An 'if' statement can be followed by an optional 'else if...else' statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero or one else's and it must come after any else if's.
An 'if' can have zero to many else if's and they must come before the else.
An 'if' can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
The following is the syntax of an ‘if...else if...else’ is as follows −
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
} else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
} else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
} else {
//Executes when the none of the above condition is true.
}
Try the following example program to understand conditional statements (if- else- if- else statement) in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var x = 30;
if( x == 10 ){
println("Value of X is 10");
} else if( x == 20 ){
println("Value of X is 20");
} else if( x == 30 ){
println("Value of X is 30");
} else{
println("This is else statement");
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Value of X is 30
It is always legal to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement.
The syntax for a nested if-else is as follows −
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
Try the following example program to understand conditional statements (nested- if statement) in Scala Programming Language.
object Demo {
def main(args: Array[String]) {
var x = 30;
var y = 10;
if( x == 30 ){
if( y == 10 ){
println("X = 30 and Y = 10");
}
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
X = 30 and Y = 10
This chapter takes you through the loop control structures in Scala programming languages.
There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Scala programming language provides the following types of loops to handle looping requirements. Click the following links in the table to check their detail.
while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
do-while loop
Like a while statement, except that it tests the condition at the end of the loop body.
for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. As such Scala does not support break or continue statement like Java does but starting from Scala version 2.8, there is a way to break the loops. Click the following links to check the detail.
break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.
A loop becomes an infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement infinite loop.
The following program implements infinite loop.
object Demo {
def main(args: Array[String]) {
var a = 10;
// An infinite loop.
while( true ){
println( "Value of a: " + a );
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
If you will execute above code, it will go in infinite loop which you can terminate by pressing Ctrl + C keys.
Value of a: 10
Value of a: 10
Value of a: 10
Value of a: 10
................
A function is a group of statements that perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically, the division usually is so that each function performs a specific task.
Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference. A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode where as a function in Scala is a complete object which can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method.
A function definition can appear anywhere in a source file and Scala permits nested function definitions, that is, function definitions inside other function definitions. Most important point to note is that Scala function's name can have characters like +, ++, ~, &,-, --, \, /, :, etc.
A Scala function declaration has the following form −
def functionName ([list of parameters]) : [return type]
Methods are implicitly declared abstract if you don’t use the equals sign and the method body.
A Scala function definition has the following form −
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional. Very similar to Java, a return statement can be used along with an expression in case function returns a value. Following is the function which will add two integers and return their sum −
object add {
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
A function, that does not return anything can return a Unit that is equivalent to void in Java and indicates that function does not return anything. The functions which do not return anything in Scala, they are called procedures.
Here is the syntax −
object Hello{
def printMe( ) : Unit = {
println("Hello, Scala!")
}
}
Scala provides a number of syntactic variations for invoking methods. Following is the standard way to call a method −
functionName( list of parameters )
If a function is being called using an instance of the object, then we would use dot notation similar to Java as follows −
[instance.]functionName( list of parameters )
Try the following example program to define and then call the same function.
object Demo {
def main(args: Array[String]) {
println( "Returned Value : " + addInt(5,7) );
}
def addInt( a:Int, b:Int ) : Int = {
var sum:Int = 0
sum = a + b
return sum
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Returned Value : 12
Scala functions are the heart of Scala programming and that's why Scala is assumed as a functional programming language. Following are few important concepts related to Scala functions which should be understood by a Scala programmer.
A closure is a function, whose return value depends on the value of one or more variables declared outside this function.
The following piece of code with anonymous function.
val multiplier = (i:Int) => i * 10
Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function. Try the following code −
val multiplier = (i:Int) => i * factor
There are two free variables in multiplier: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multiplier is called. However, factor is not a formal parameter, then what is this? Let us add one more line of code.
var factor = 3
val multiplier = (i:Int) => i * factor
Now factor has a reference to a variable outside the function but in the enclosing scope. The function references factor and reads its current value each time. If a function has no external references, then it is trivially closed over itself. No external context is required.
Try the following example program.
object Demo {
def main(args: Array[String]) {
println( "multiplier(1) value = " + multiplier(1) )
println( "multiplier(2) value = " + multiplier(2) )
}
var factor = 3
val multiplier = (i:Int) => i * factor
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
multiplier(1) value = 3
multiplier(2) value = 6
This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class.
The following code can be used to create a String −
var greeting = "Hello world!";
or
var greeting:String = "Hello world!";
Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above.
Try the following example program.
object Demo {
val greeting: String = "Hello, world!"
def main(args: Array[String]) {
println( greeting )
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Hello, world!
As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!.
Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object.
Use the following code segment to find the length of a string −
object Demo {
def main(args: Array[String]) {
var palindrome = "Dot saw I was Tod";
var len = palindrome.length();
println( "String Length is : " + len );
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
String Length is : 17
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
Which results in −
"Hello, world!"
The following lines of code to find string length.
object Demo {
def main(args: Array[String]) {
var str1 = "Dot saw I was ";
var str2 = "Tod";
println("Dot " + str1 + str2);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Dot Dot saw I was Tod
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Try the following example program, which makes use of printf() method −
object Demo {
def main(args: Array[String]) {
var floatVar = 12.456
var intVar = 2000
var stringVar = "Hello, Scala!"
var fs = printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string" + "is %s", floatVar, intVar, stringVar);
println(fs)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
The value of the float variable is 12.456000,
while the value of the integer variable is 2000,
and the string is Hello, Scala!()
String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal.
There are three types (interpolators) of implementations in String Interpolation.
The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator.
The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement.
val name = “James”
println(s “Hello, $name”) //output: Hello, James
String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’.
println(s “1 + 1 = ${1 + 1}”) //output: 1 + 1 = 2
Try the following example program of implementing ‘s’ interpolator.
object Demo {
def main(args: Array[String]) {
val name = "James"
println(s"Hello, $name")
println(s"1 + 1 = ${1 + 1}")
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Hello, James
1 + 1 = 2
The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc.
Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90.
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") //James is 1.90 meters tall
It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is no % character after variable reference. It will assume as %s (String).
The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string. The following code snippets in a table will differ the usage of ‘s’ and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\n’ effects as new line and in output of ‘raw’ usage the ‘\n’ will not effect. It will print the complete string with escape letters.
Program −
object Demo {
def main(args: Array[String]) {
println(s"Result = \n a \n b")
}
}
Program −
object Demo {
def main(args: Array[String]) {
println(raw"Result = \n a \n b")
}
}
Output −
Result =
a
b
Output −
Result = \n a \n b
Following is the list of methods defined by java.lang.String class and can be used directly in your Scala programs −
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
int compareTo(String anotherString)
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern()
Returns a canonical representation for the string object.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length()
Returns the length of this string.
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int offset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.
Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one.
To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference.
The following is the syntax for declaring an array variable.
var z:Array[String] = new Array[String](3)
or
var z = new Array[String](3)
Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following −
z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"
Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array −
var z = Array("Zara", "Nuha", "Ayan")
Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known.
Below is an example program of showing how to create, initialize and process arrays −
object Demo {
def main(args: Array[String]) {
var myList = Array(1.9, 2.9, 3.4, 3.5)
// Print all the array elements
for ( x <- myList ) {
println( x )
}
// Summing all elements
var total = 0.0;
for ( i <- 0 to (myList.length - 1)) {
total += myList(i);
}
println("Total is " + total);
// Finding the largest element
var max = myList(0);
for ( i <- 1 to (myList.length - 1) ) {
if (myList(i) > max) max = myList(i);
}
println("Max is " + max);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package.
There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays.
The following is the example of defining a two-dimensional array −
var myMatrix = ofDim[Int](3,3)
This is an array that has three elements each being an array of integers that has three elements.
Try the following example program to process a multi-dimensional array −
import Array._
object Demo {
def main(args: Array[String]) {
var myMatrix = ofDim[Int](3,3)
// build a matrix
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
myMatrix(i)(j) = j;
}
}
// Print two dimensional array
for (i <- 0 to 2) {
for ( j <- 0 to 2) {
print(" " + myMatrix(i)(j));
}
println();
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
0 1 2
0 1 2
0 1 2
Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method.
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)
var myList3 = concat( myList1, myList2)
// Print all the array elements
for ( x <- myList3 ) {
println( x )
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
1.9
2.9
3.4
3.5
8.9
7.9
0.4
1.5
Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1.
Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18.
Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19.
The following example program shows how to create an array with ranges.
import Array._
object Demo {
def main(args: Array[String]) {
var myList1 = range(10, 20, 2)
var myList2 = range(10,20)
// Print all the array elements
for ( x <- myList1 ) {
print( " " + x )
}
println()
for ( x <- myList2 ) {
print( " " + x )
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10 12 14 16 18
10 11 12 13 14 15 16 17 18 19
Following are the important methods, which you can use while playing with array. As shown above, you would have to import Array._ package before using any of the mentioned methods. For a complete list of methods available, please check official documentation of Scala.
def apply( x: T, xs: T* ): Array[T]
Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean.
def concat[T]( xss: Array[T]* ): Array[T]
Concatenates all arrays into a single array.
def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit
Copy one array to another. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos, length).
def empty[T]: Array[T]
Returns an array of length 0
def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]
Returns an array containing repeated applications of a function to a start value.
def fill[T]( n: Int )(elem: => T): Array[T]
Returns an array that contains the results of some element computation a number of times.
def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]
Returns a two-dimensional array that contains the results of some element computation a number of times.
def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]
Returns an array containing repeated applications of a function to a start value.
def ofDim[T]( n1: Int ): Array[T]
Creates array with given dimensions.
def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]
Creates a 2-dimensional array
def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]
Creates a 3-dimensional array
def range( start: Int, end: Int, step: Int ): Array[Int]
Returns an array containing equally spaced values in some integer interval.
def range( start: Int, end: Int ): Array[Int]
Returns an array containing a sequence of increasing integers in a range.
def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]
Returns an array containing values of a given function over a range of integer values starting from 0.
def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]
Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0.
Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).
Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items.
For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones.
This chapter throws light on the most commonly used collection types and most frequently used operations over those collections.
Scala Lists
Scala's List[T] is a linked list of type T.
Scala Sets
A set is a collection of pairwise different elements of the same type.
Scala Maps
A Map is a collection of key/value pairs. Any value can be retrieved based on its key.
Scala Tuples
Unlike an array or list, a tuple can hold objects with different types.
Scala Options
Option[T] provides a container for zero or one element of a given type.
Scala Iterators
An iterator is not a collection, but rather a way to access the elements of a collection one by one.
A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters.
A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait.
trait Equal {
def isEqual(x: Any): Boolean
def isNotEqual(x: Any): Boolean = !isEqual(x)
}
This trait consists of two methods isEqual and isNotEqual. Here, we have not given any implementation for isEqual where as another method has its implementation. Child classes extending a trait can give implementation for the un-implemented methods. So a trait is very similar to what we have abstract classes in Java.
Let us assume an example of trait Equal contain two methods isEqual() and isNotEqual(). The trait Equal contain one implemented method that is isEqual() so when user defined class Point extends the trait Equal, implementation to isEqual() method in Point class should be provided.
Here it is required to know two important method of Scala, which are used in the following example.
obj.isInstanceOf [Point] To check Type of obj and Point are same are not.
obj.isInstanceOf [Point] To check Type of obj and Point are same are not.
obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type.
obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type.
Try the following example program to implement traits.
trait Equal {
def isEqual(x: Any): Boolean
def isNotEqual(x: Any): Boolean = !isEqual(x)
}
class Point(xc: Int, yc: Int) extends Equal {
var x: Int = xc
var y: Int = yc
def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y
}
object Demo {
def main(args: Array[String]) {
val p1 = new Point(2, 3)
val p2 = new Point(2, 4)
val p3 = new Point(3, 3)
println(p1.isNotEqual(p2))
println(p1.isNotEqual(p3))
println(p1.isNotEqual(2))
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
true
false
true
Value classes are new mechanism in Scala to avoid allocating runtime objects. It contains a primary constructor with exactly one val parameter. It contains only methods (def) not allowed var, val, nested classes, traits, or objects. Value class cannot be extended by another class. This can be possible by extending your value class with AnyVal. The typesafety of custom datatypes without the runtime overhead.
Let us take an examples of value classes Weight, Height, Email, Age, etc. For all these examples it is not required to allocate memory in the application.
A value class not allowed to extend traits. To permit value classes to extend traits, universal traits are introduced which extends for Any.
trait Printable extends Any {
def print(): Unit = println(this)
}
class Wrapper(val underlying: Int) extends AnyVal with Printable
object Demo {
def main(args: Array[String]) {
val w = new Wrapper(3)
w.print() // actually requires instantiating a Wrapper instance
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
It will give you the hash code of Wrapper class.
Wrapper@13
There is no firm rule, but here are few guidelines to consider −
If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.
If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.
If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy.
If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy.
If you want to inherit from it in Java code, use an abstract class.
If you want to inherit from it in Java code, use an abstract class.
If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class.
If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class.
If efficiency is very important, lean towards using a class.
If efficiency is very important, lean towards using a class.
Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages.
A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.
Try the following example program, which shows how to match against an integer value.
object Demo {
def main(args: Array[String]) {
println(matchTest(3))
}
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
many
The block with the case statements defines a function, which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.
Try the following example program, which matches a value against patterns of different types.
object Demo {
def main(args: Array[String]) {
println(matchTest("two"))
println(matchTest("test"))
println(matchTest(1))
}
def matchTest(x: Any): Any = x match {
case 1 => "one"
case "two" => 2
case y: Int => "scala.Int"
case _ => "many"
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
2
many
one
The case classes are special classes that are used in pattern matching with case expressions. Syntactically, these are standard classes with a special modifier: case.
Try the following, it is a simple pattern matching example using case class.
object Demo {
def main(args: Array[String]) {
val alice = new Person("Alice", 25)
val bob = new Person("Bob", 32)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, bob, charlie)) {
person match {
case Person("Alice", 25) => println("Hi Alice!")
case Person("Bob", 32) => println("Hi Bob!")
case Person(name, age) => println(
"Age: " + age + " year, name: " + name + "?")
}
}
}
case class Person(name: String, age: Int)
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?
Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching.
First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional. If you want mutable fields, use the var keyword. So, our constructor argument lists are now shorter.
Second, the compiler automatically implements equals, hashCode, and toString methods to the class, which use the fields specified as constructor arguments. So, we no longer need our own toString() methods.
Finally, also, the body of Person class becomes empty because there are no methods that we need to define!
This chapter explains how Scala supports regular expressions through Regex class available in the scala.util.matching package.
Try the following example program where we will try to find out word Scala from a statement.
import scala.util.matching.Regex
object Demo {
def main(args: Array[String]) {
val pattern = "Scala".r
val str = "Scala is Scalable and cool"
println(pattern findFirstIn str)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Some(Scala)
We create a String and call the r( ) method on it. Scala implicitly converts the String to a RichString and invokes that method to get an instance of Regex. To find a first match of the regular expression, simply call the findFirstIn() method. If instead of finding only the first occurrence we would like to find all occurrences of the matching word, we can use the findAllIn( ) method and in case there are multiple Scala words available in the target string, this will return a collection of all matching words.
You can make use of the mkString( ) method to concatenate the resulting list and you can use a pipe (|) to search small and capital case of Scala and you can use Regex constructor instead or r() method to create a pattern.
Try the following example program.
import scala.util.matching.Regex
object Demo {
def main(args: Array[String]) {
val pattern = new Regex("(S|s)cala")
val str = "Scala is scalable and cool"
println((pattern findAllIn str).mkString(","))
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Scala,scala
If you would like to replace matching text, we can use replaceFirstIn( ) to replace the first match or replaceAllIn( ) to replace all occurrences.
object Demo {
def main(args: Array[String]) {
val pattern = "(S|s)cala".r
val str = "Scala is scalable and cool"
println(pattern replaceFirstIn(str, "Java"))
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Java is scalable and cool
Scala inherits its regular expression syntax from Java, which in turn inherits most of the features of Perl. Here are just some examples that should be enough as refreshers −
Following is the table listing down all the regular expression Meta character syntax available in Java.
Note − that every backslash appears twice in the string above. This is because in Java and Scala a single backslash is an escape character in a string literal, not a regular character that shows up in the string. So instead of ‘\’, you need to write ‘\\’ to get a single backslash in the string.
Try the following example program.
import scala.util.matching.Regex
object Demo {
def main(args: Array[String]) {
val pattern = new Regex("abl[ae]\\d+")
val str = "ablaw is able1 and cool"
println((pattern findAllIn str).mkString(","))
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
able1
Scala's exceptions work like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn't actually have checked exceptions.
When you want to handle exceptions, you use a try{...}catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.
Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows.
throw new IllegalArgumentException
Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle exception.
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException =>{
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Missing file exception
The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn.
You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates. Try the following program.
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Demo {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
} finally {
println("Exiting finally...")
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Missing file exception
Exiting finally...
An extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match a value and take it apart. Often, the extractor object also defines a dual method apply for building values, but this is not required.
Let us take an example of object defines both apply and unapply methods. The apply method has the same meaning as always: it turns Test into an object that can be applied to arguments in parentheses in the same way a method is applied. So you can write Test ("Zara", "gmail.com") to construct the string "Zara@gmail.com".
The unapply method is what turns Test class into an extractor and it reverses the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply takes an email address and returns potentially two strings: the user and the domain of the address.
The unapply must also handle the case where the given string is not an email address. That's why unapply returns an Option-type over pairs of strings. Its result is either Some (user, domain) if the string str is an email address with the given user and domain parts, or None, if str is not an email address. Here are some examples as follows.
unapply("Zara@gmail.com") equals Some("Zara", "gmail.com")
unapply("Zara Ali") equals None
Following example program shows an extractor object for email addresses.
object Demo {
def main(args: Array[String]) {
println ("Apply method : " + apply("Zara", "gmail.com"));
println ("Unapply method : " + unapply("Zara@gmail.com"));
println ("Unapply method : " + unapply("Zara Ali"));
}
// The injection method (optional)
def apply(user: String, domain: String) = {
user +"@"+ domain
}
// The extraction method (mandatory)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2){
Some(parts(0), parts(1))
} else {
None
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Apply method : Zara@gmail.com
Unapply method : Some((Zara,gmail.com))
Unapply method : None
When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method on that instance. We can define apply both in objects and in classes.
As mentioned above, the purpose of the unapply method is to extract a specific value we are looking for. It does the opposite operation apply does. When comparing an extractor object using the match statement the unapply method will be automatically executed.
Try the following example program.
object Demo {
def main(args: Array[String]) {
val x = Demo(5)
println(x)
x match {
case Demo(num) => println(x+" is bigger two times than "+num)
//unapply is invoked
case _ => println("i cannot calculate")
}
}
def apply(x: Int) = x*2
def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10
10 is bigger two times than 5
Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files.
The following is an example program to writing to a file.
import java.io._
object Demo {
def main(args: Array[String]) {
val writer = new PrintWriter(new File("test.txt" ))
writer.write("Hello Scala")
writer.close()
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file.
Hello Scala
Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line.
object Demo {
def main(args: Array[String]) {
print("Please enter your input : " )
val line = Console.readLine
println("Thanks, you just typed: " + line)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Please enter your input : Scala is great
Thanks, you just typed: Scala is great
Reading from files is really simple. You can use Scala's Source class and its companion object to read files. Following is the example which shows you how to read from "Demo.txt" file which we created earlier.
import scala.io.Source
object Demo {
def main(args: Array[String]) {
println("Following is the content read:" )
Source.fromFile("Demo.txt" ).foreach {
print
}
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Following is the content read:
Hello Scala
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2443,
"s": 1998,
"text": "Scala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky. Scala smoothly integrates the features of object-oriented and functional languages. Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability."
},
{
"code": null,
"e": 2540,
"s": 2443,
"text": "Here we have presented a few points that makes Scala the first choice of application developers."
},
{
"code": null,
"e": 2739,
"s": 2540,
"text": "Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits which will be explained in subsequent chapters."
},
{
"code": null,
"e": 2873,
"s": 2739,
"text": "Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance."
},
{
"code": null,
"e": 3025,
"s": 2873,
"text": "Scala is also a functional language in the sense that every function is a value and every value is an object so ultimately every function is an object."
},
{
"code": null,
"e": 3245,
"s": 3025,
"text": "Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. These concepts will be explained in subsequent chapters."
},
{
"code": null,
"e": 3479,
"s": 3245,
"text": "Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect you to provide redundant type information. You don't have to specify a type in most cases, and you certainly don't have to repeat it."
},
{
"code": null,
"e": 3673,
"s": 3479,
"text": "Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM). This means that Scala and Java have a common runtime platform. You can easily move from Java to Scala."
},
{
"code": null,
"e": 3887,
"s": 3673,
"text": "The Scala compiler compiles your Scala code into Java Byte Code, which can then be executed by the 'scala' command. The 'scala' command is similar to the java command, in that it executes your compiled Scala code."
},
{
"code": null,
"e": 4027,
"s": 3887,
"text": "Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects."
},
{
"code": null,
"e": 4314,
"s": 4027,
"text": "Scala allows you to express general programming patterns in an effective way. It reduces the number of lines and helps the programmer to code in a type-safe way. It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism (Synchronize)."
},
{
"code": null,
"e": 4396,
"s": 4314,
"text": "Scala has a set of features that completely differ from Java. Some of these are −"
},
{
"code": null,
"e": 4418,
"s": 4396,
"text": "All types are objects"
},
{
"code": null,
"e": 4433,
"s": 4418,
"text": "Type inference"
},
{
"code": null,
"e": 4450,
"s": 4433,
"text": "Nested Functions"
},
{
"code": null,
"e": 4472,
"s": 4450,
"text": "Functions are objects"
},
{
"code": null,
"e": 4511,
"s": 4472,
"text": "Domain specific language (DSL) support"
},
{
"code": null,
"e": 4518,
"s": 4511,
"text": "Traits"
},
{
"code": null,
"e": 4527,
"s": 4518,
"text": "Closures"
},
{
"code": null,
"e": 4566,
"s": 4527,
"text": "Concurrency support inspired by Erlang"
},
{
"code": null,
"e": 4708,
"s": 4566,
"text": "Scala is being used everywhere and importantly in enterprise web applications. You can check a few of the most popular Scala web frameworks −"
},
{
"code": null,
"e": 4727,
"s": 4708,
"text": "The Lift Framework"
},
{
"code": null,
"e": 4746,
"s": 4727,
"text": "The Lift Framework"
},
{
"code": null,
"e": 4765,
"s": 4746,
"text": "The Play framework"
},
{
"code": null,
"e": 4784,
"s": 4765,
"text": "The Play framework"
},
{
"code": null,
"e": 4805,
"s": 4784,
"text": "The Bowler framework"
},
{
"code": null,
"e": 4826,
"s": 4805,
"text": "The Bowler framework"
},
{
"code": null,
"e": 5008,
"s": 4826,
"text": "Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer."
},
{
"code": null,
"e": 5055,
"s": 5008,
"text": "Follow the steps given below to install Scala."
},
{
"code": null,
"e": 5252,
"s": 5055,
"text": "First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on."
},
{
"code": null,
"e": 5436,
"s": 5252,
"text": "If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table."
},
{
"code": null,
"e": 5468,
"s": 5436,
"text": "Open Command Console and type −"
},
{
"code": null,
"e": 5484,
"s": 5468,
"text": "\\>java –version"
},
{
"code": null,
"e": 5508,
"s": 5484,
"text": "Java version \"1.8.0_31\""
},
{
"code": null,
"e": 5530,
"s": 5508,
"text": "Java (TM) SE Run Time"
},
{
"code": null,
"e": 5563,
"s": 5530,
"text": "Environment (build 1.8.0_31-b31)"
},
{
"code": null,
"e": 5595,
"s": 5563,
"text": "Java Hotspot (TM) 64-bit Server"
},
{
"code": null,
"e": 5628,
"s": 5595,
"text": "VM (build 25.31-b07, mixed mode)"
},
{
"code": null,
"e": 5661,
"s": 5628,
"text": "Open Command terminal and type −"
},
{
"code": null,
"e": 5676,
"s": 5661,
"text": "$java –version"
},
{
"code": null,
"e": 5700,
"s": 5676,
"text": "Java version \"1.8.0_31\""
},
{
"code": null,
"e": 5758,
"s": 5700,
"text": "Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64)"
},
{
"code": null,
"e": 5814,
"s": 5758,
"text": "Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode)"
},
{
"code": null,
"e": 5916,
"s": 5814,
"text": "We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system."
},
{
"code": null,
"e": 6067,
"s": 5916,
"text": "In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it."
},
{
"code": null,
"e": 6200,
"s": 6067,
"text": "Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,"
},
{
"code": null,
"e": 6208,
"s": 6200,
"text": "Windows"
},
{
"code": null,
"e": 6258,
"s": 6208,
"text": "Set JAVA_HOME to C:\\ProgramFiles\\java\\jdk1.7.0_60"
},
{
"code": null,
"e": 6264,
"s": 6258,
"text": "Linux"
},
{
"code": null,
"e": 6305,
"s": 6264,
"text": "Export JAVA_HOME=/usr/local/java-current"
},
{
"code": null,
"e": 6372,
"s": 6305,
"text": "Append the full path of Java compiler location to the System Path."
},
{
"code": null,
"e": 6380,
"s": 6372,
"text": "Windows"
},
{
"code": null,
"e": 6478,
"s": 6380,
"text": "Append the String \"C:\\Program Files\\Java\\jdk1.7.0_60\\bin\" to the end of the system variable PATH."
},
{
"code": null,
"e": 6484,
"s": 6478,
"text": "Linux"
},
{
"code": null,
"e": 6518,
"s": 6484,
"text": "Export PATH=$PATH:$JAVA_HOME/bin/"
},
{
"code": null,
"e": 6596,
"s": 6518,
"text": "Execute the command java -version from the command prompt as explained above."
},
{
"code": null,
"e": 6848,
"s": 6596,
"text": "You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt −"
},
{
"code": null,
"e": 6889,
"s": 6848,
"text": "\\>java –jar scala-2.11.5-installer.jar\\>"
},
{
"code": null,
"e": 7249,
"s": 6889,
"text": "This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:\\Program Files\\Scala”, you can select a suitable path as per your convenience."
},
{
"code": null,
"e": 7259,
"s": 7249,
"text": "Command −"
},
{
"code": null,
"e": 7298,
"s": 7259,
"text": "$java –jar scala-2.9.0.1-installer.jar"
},
{
"code": null,
"e": 7307,
"s": 7298,
"text": "Output −"
},
{
"code": null,
"e": 7353,
"s": 7307,
"text": "Welcome to the installation of Scala 2.9.0.1!"
},
{
"code": null,
"e": 7397,
"s": 7353,
"text": "The homepage is at − http://Scala-lang.org/"
},
{
"code": null,
"e": 7444,
"s": 7397,
"text": "press 1 to continue, 2 to quit, 3 to redisplay"
},
{
"code": null,
"e": 7494,
"s": 7444,
"text": "1................................................"
},
{
"code": null,
"e": 7517,
"s": 7494,
"text": "[ Starting to unpack ]"
},
{
"code": null,
"e": 7577,
"s": 7517,
"text": "[ Processing package: Software Package Installation (1/1) ]"
},
{
"code": null,
"e": 7600,
"s": 7577,
"text": "[ Unpacking finished ]"
},
{
"code": null,
"e": 7630,
"s": 7600,
"text": "[ Console installation done ]"
},
{
"code": null,
"e": 7844,
"s": 7630,
"text": "During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience."
},
{
"code": null,
"e": 7951,
"s": 7844,
"text": "Finally, open a new command prompt and type Scala -version and press Enter. You should see the following −"
},
{
"code": null,
"e": 7968,
"s": 7951,
"text": "\\>scala -version"
},
{
"code": null,
"e": 8035,
"s": 7968,
"text": "Scala code runner version 2.11.5 -- Copyright 2002-2013, LAMP/EPFL"
},
{
"code": null,
"e": 8051,
"s": 8035,
"text": "$scala -version"
},
{
"code": null,
"e": 8118,
"s": 8051,
"text": "Scala code runner version 2.9.0.1 – Copyright 2002-2013, LAMP/EPFL"
},
{
"code": null,
"e": 8314,
"s": 8118,
"text": "If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ';' line end character is optional."
},
{
"code": null,
"e": 8534,
"s": 8314,
"text": "When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean."
},
{
"code": null,
"e": 8716,
"s": 8534,
"text": "Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating."
},
{
"code": null,
"e": 8898,
"s": 8716,
"text": "Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating."
},
{
"code": null,
"e": 9021,
"s": 8898,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class."
},
{
"code": null,
"e": 9144,
"s": 9021,
"text": "Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class."
},
{
"code": null,
"e": 9323,
"s": 9144,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 9502,
"s": 9323,
"text": "Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed."
},
{
"code": null,
"e": 9659,
"s": 9502,
"text": "Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields."
},
{
"code": null,
"e": 9816,
"s": 9659,
"text": "Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields."
},
{
"code": null,
"e": 9948,
"s": 9816,
"text": "Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function."
},
{
"code": null,
"e": 10080,
"s": 9948,
"text": "Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function."
},
{
"code": null,
"e": 10287,
"s": 10080,
"text": "Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods."
},
{
"code": null,
"e": 10494,
"s": 10287,
"text": "Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods."
},
{
"code": null,
"e": 10591,
"s": 10494,
"text": "We can execute a Scala program in two modes: one is interactive mode and another is script mode."
},
{
"code": null,
"e": 10660,
"s": 10591,
"text": "Open the command prompt and use the following command to open Scala."
},
{
"code": null,
"e": 10669,
"s": 10660,
"text": "\\>scala\n"
},
{
"code": null,
"e": 10748,
"s": 10669,
"text": "If Scala is installed in your system, the following output will be displayed −"
},
{
"code": null,
"e": 10859,
"s": 10748,
"text": "Welcome to Scala version 2.9.0.1\nType in expressions to have them evaluated.\nType :help for more information.\n"
},
{
"code": null,
"e": 10942,
"s": 10859,
"text": "Type the following text to the right of the Scala prompt and press the Enter key −"
},
{
"code": null,
"e": 10976,
"s": 10942,
"text": "scala> println(\"Hello, Scala!\");\n"
},
{
"code": null,
"e": 11015,
"s": 10976,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 11030,
"s": 11015,
"text": "Hello, Scala!\n"
},
{
"code": null,
"e": 11151,
"s": 11030,
"text": "Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it."
},
{
"code": null,
"e": 11360,
"s": 11151,
"text": "object HelloWorld {\n /* This is my first java program. \n * This will print 'Hello World' as the output\n */\n def main(args: Array[String]) {\n println(\"Hello, world!\") // prints Hello World\n }\n}"
},
{
"code": null,
"e": 11397,
"s": 11360,
"text": "Save the file as − HelloWorld.scala."
},
{
"code": null,
"e": 11740,
"s": 11397,
"text": "Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command."
},
{
"code": null,
"e": 11809,
"s": 11740,
"text": "Use the following command to compile and execute your Scala program."
},
{
"code": null,
"e": 11857,
"s": 11809,
"text": "\\> scalac HelloWorld.scala\n\\> scala HelloWorld\n"
},
{
"code": null,
"e": 11872,
"s": 11857,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 11954,
"s": 11872,
"text": "The following are the basic syntaxes and coding conventions in Scala programming."
},
{
"code": null,
"e": 12076,
"s": 11954,
"text": "Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala."
},
{
"code": null,
"e": 12198,
"s": 12076,
"text": "Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala."
},
{
"code": null,
"e": 12421,
"s": 12198,
"text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.\nExample − class MyFirstScalaClass."
},
{
"code": null,
"e": 12609,
"s": 12421,
"text": "Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case."
},
{
"code": null,
"e": 12644,
"s": 12609,
"text": "Example − class MyFirstScalaClass."
},
{
"code": null,
"e": 12864,
"s": 12644,
"text": "Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case.\nExample − def myMethodName()"
},
{
"code": null,
"e": 13055,
"s": 12864,
"text": "Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case."
},
{
"code": null,
"e": 13084,
"s": 13055,
"text": "Example − def myMethodName()"
},
{
"code": null,
"e": 13494,
"s": 13084,
"text": "Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile).\nExample − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'."
},
{
"code": null,
"e": 13801,
"s": 13494,
"text": "Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile)."
},
{
"code": null,
"e": 13904,
"s": 13801,
"text": "Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'."
},
{
"code": null,
"e": 14041,
"s": 13904,
"text": "def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program."
},
{
"code": null,
"e": 14178,
"s": 14041,
"text": "def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program."
},
{
"code": null,
"e": 14413,
"s": 14178,
"text": "All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers."
},
{
"code": null,
"e": 14633,
"s": 14413,
"text": "An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers."
},
{
"code": null,
"e": 14680,
"s": 14633,
"text": "Following are legal alphanumeric identifiers −"
},
{
"code": null,
"e": 14713,
"s": 14680,
"text": "age, salary, _value, __1_value\n"
},
{
"code": null,
"e": 14749,
"s": 14713,
"text": "Following are illegal identifiers −"
},
{
"code": null,
"e": 14775,
"s": 14749,
"text": "$salary, 123abc, -salary\n"
},
{
"code": null,
"e": 14919,
"s": 14775,
"text": "An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #."
},
{
"code": null,
"e": 14962,
"s": 14919,
"text": "Following are legal operator identifiers −"
},
{
"code": null,
"e": 14978,
"s": 14962,
"text": "+ ++ ::: <?> :>"
},
{
"code": null,
"e": 15202,
"s": 14978,
"text": "The Scala compiler will internally \"mangle\" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater."
},
{
"code": null,
"e": 15324,
"s": 15202,
"text": "A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier."
},
{
"code": null,
"e": 15364,
"s": 15324,
"text": "Following are legal mixed identifiers −"
},
{
"code": null,
"e": 15383,
"s": 15364,
"text": "unary_+, myvar_=\n"
},
{
"code": null,
"e": 15533,
"s": 15383,
"text": "Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator (operator overloading)."
},
{
"code": null,
"e": 15613,
"s": 15533,
"text": "A literal identifier is an arbitrary string enclosed in back ticks (` . . . `)."
},
{
"code": null,
"e": 15655,
"s": 15613,
"text": "Following are legal literal identifiers −"
},
{
"code": null,
"e": 15679,
"s": 15655,
"text": "`x` `<clinit>` `yield`\n"
},
{
"code": null,
"e": 15825,
"s": 15679,
"text": "The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names."
},
{
"code": null,
"e": 16048,
"s": 15825,
"text": "Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler."
},
{
"code": null,
"e": 16372,
"s": 16048,
"text": "object HelloWorld {\n /* This is my first java program. \n * This will print 'Hello World' as the output\n * This is an example of multi-line comments.\n */\n def main(args: Array[String]) {\n // Prints Hello World\n // This is also an example of single line comment.\n println(\"Hello, world!\") \n }\n}"
},
{
"code": null,
"e": 16554,
"s": 16372,
"text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments."
},
{
"code": null,
"e": 16961,
"s": 16554,
"text": "Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is usually optional. You can type one if you want but you don't have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line. Below syntax is the usage of multiple statements."
},
{
"code": null,
"e": 16989,
"s": 16961,
"text": "val s = \"hello\"; println(s)"
},
{
"code": null,
"e": 17171,
"s": 16989,
"text": "A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows −"
},
{
"code": null,
"e": 17199,
"s": 17171,
"text": "package com.liftcode.stuff\n"
},
{
"code": null,
"e": 17367,
"s": 17199,
"text": "Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package −"
},
{
"code": null,
"e": 17387,
"s": 17367,
"text": "import scala.xml._\n"
},
{
"code": null,
"e": 17494,
"s": 17387,
"text": "You can import a single class and object, for example, HashMap from the scala.collection.mutable package −"
},
{
"code": null,
"e": 17535,
"s": 17494,
"text": "import scala.collection.mutable.HashMap\n"
},
{
"code": null,
"e": 17682,
"s": 17535,
"text": "You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package −"
},
{
"code": null,
"e": 17735,
"s": 17682,
"text": "import scala.collection.immutable.{TreeMap, TreeSet}"
},
{
"code": null,
"e": 18012,
"s": 17735,
"text": "A marker trait that enables dynamic invocations. Instances x of this trait allow method invocations x.meth(args) for arbitrary method names meth and argument lists args as well as field accesses x.field for arbitrary field namesfield. This feature is introduced in Scala-2.10."
},
{
"code": null,
"e": 18135,
"s": 18012,
"text": "If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules −"
},
{
"code": null,
"e": 18540,
"s": 18135,
"text": "foo.method(\"blah\") ~~> foo.applyDynamic(\"method\")(\"blah\")\nfoo.method(x = \"blah\") ~~> foo.applyDynamicNamed(\"method\")((\"x\", \"blah\"))\nfoo.method(x = 1, 2) ~~> foo.applyDynamicNamed(\"method\")((\"x\", 1), (\"\", 2))\nfoo.field ~~> foo.selectDynamic(\"field\")\nfoo.varia = 10 ~~> foo.updateDynamic(\"varia\")(10)\nfoo.arr(10) = 13 ~~> foo.selectDynamic(\"arr\").update(10, 13)\nfoo.arr(10) ~~> foo.applyDynamic(\"arr\")(10)\n"
},
{
"code": null,
"e": 18713,
"s": 18540,
"text": "Scala has all the same data types as Java, with the same memory footprint and precision. Following is the table giving details about all the data types available in Scala −"
},
{
"code": null,
"e": 18718,
"s": 18713,
"text": "Byte"
},
{
"code": null,
"e": 18761,
"s": 18718,
"text": "8 bit signed value. Range from -128 to 127"
},
{
"code": null,
"e": 18767,
"s": 18761,
"text": "Short"
},
{
"code": null,
"e": 18810,
"s": 18767,
"text": "16 bit signed value. Range -32768 to 32767"
},
{
"code": null,
"e": 18814,
"s": 18810,
"text": "Int"
},
{
"code": null,
"e": 18867,
"s": 18814,
"text": "32 bit signed value. Range -2147483648 to 2147483647"
},
{
"code": null,
"e": 18872,
"s": 18867,
"text": "Long"
},
{
"code": null,
"e": 18937,
"s": 18872,
"text": "64 bit signed value. -9223372036854775808 to 9223372036854775807"
},
{
"code": null,
"e": 18943,
"s": 18937,
"text": "Float"
},
{
"code": null,
"e": 18982,
"s": 18943,
"text": "32 bit IEEE 754 single-precision float"
},
{
"code": null,
"e": 18989,
"s": 18982,
"text": "Double"
},
{
"code": null,
"e": 19028,
"s": 18989,
"text": "64 bit IEEE 754 double-precision float"
},
{
"code": null,
"e": 19033,
"s": 19028,
"text": "Char"
},
{
"code": null,
"e": 19096,
"s": 19033,
"text": "16 bit unsigned Unicode character. Range from U+0000 to U+FFFF"
},
{
"code": null,
"e": 19103,
"s": 19096,
"text": "String"
},
{
"code": null,
"e": 19123,
"s": 19103,
"text": "A sequence of Chars"
},
{
"code": null,
"e": 19131,
"s": 19123,
"text": "Boolean"
},
{
"code": null,
"e": 19176,
"s": 19131,
"text": "Either the literal true or the literal false"
},
{
"code": null,
"e": 19181,
"s": 19176,
"text": "Unit"
},
{
"code": null,
"e": 19205,
"s": 19181,
"text": "Corresponds to no value"
},
{
"code": null,
"e": 19210,
"s": 19205,
"text": "Null"
},
{
"code": null,
"e": 19234,
"s": 19210,
"text": "null or empty reference"
},
{
"code": null,
"e": 19242,
"s": 19234,
"text": "Nothing"
},
{
"code": null,
"e": 19294,
"s": 19242,
"text": "The subtype of every other type; includes no values"
},
{
"code": null,
"e": 19298,
"s": 19294,
"text": "Any"
},
{
"code": null,
"e": 19351,
"s": 19298,
"text": "The supertype of any type; any object is of type Any"
},
{
"code": null,
"e": 19358,
"s": 19351,
"text": "AnyRef"
},
{
"code": null,
"e": 19394,
"s": 19358,
"text": "The supertype of any reference type"
},
{
"code": null,
"e": 19541,
"s": 19394,
"text": "All the data types listed above are objects. There are no primitive types like in Java. This means that you can call methods on an Int, Long, etc."
},
{
"code": null,
"e": 19649,
"s": 19541,
"text": "The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala Literals."
},
{
"code": null,
"e": 19774,
"s": 19649,
"text": "Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Here are some integer literals −"
},
{
"code": null,
"e": 19803,
"s": 19774,
"text": "0\n035\n21 \n0xFFFFFFFF \n0777L\n"
},
{
"code": null,
"e": 19973,
"s": 19803,
"text": "Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. Here are some floating point literals −"
},
{
"code": null,
"e": 20007,
"s": 19973,
"text": "0.0 \n1e30f \n3.14159f \n1.0e100\n.1\n"
},
{
"code": null,
"e": 20072,
"s": 20007,
"text": "The Boolean literals true and false are members of type Boolean."
},
{
"code": null,
"e": 20198,
"s": 20072,
"text": "A symbol literal 'x is a shorthand for the expression scala.Symbol(\"x\"). Symbol is a case class, which is defined as follows."
},
{
"code": null,
"e": 20310,
"s": 20198,
"text": "package scala\nfinal case class Symbol private (name: String) {\n override def toString: String = \"'\" + name\n}\n"
},
{
"code": null,
"e": 20500,
"s": 20310,
"text": "A character literal is a single character enclosed in quotes. The character is either a printable Unicode character or is described by an escape sequence. Here are some character literals −"
},
{
"code": null,
"e": 20525,
"s": 20500,
"text": "'a' \n'\\u0041'\n'\\n'\n'\\t'\n"
},
{
"code": null,
"e": 20712,
"s": 20525,
"text": "A string literal is a sequence of characters in double quotes. The characters are either printable Unicode character or are described by escape sequences. Here are some string literals −"
},
{
"code": null,
"e": 20769,
"s": 20712,
"text": "\"Hello,\\nWorld!\"\n\"This string contains a \\\" character.\"\n"
},
{
"code": null,
"e": 20997,
"s": 20769,
"text": "A multi-line string literal is a sequence of characters enclosed in triple quotes \"\"\" ... \"\"\". The sequence of characters is arbitrary, except that it may contain three or more consecutive quote characters only at the very end."
},
{
"code": null,
"e": 21138,
"s": 20997,
"text": "Characters must not necessarily be printable; newlines or other control characters are also permitted. Here is a multi-line string literal −"
},
{
"code": null,
"e": 21183,
"s": 21138,
"text": "\"\"\"the present string\nspans three\nlines.\"\"\"\n"
},
{
"code": null,
"e": 21340,
"s": 21183,
"text": "The null value is of type scala.Null and is thus compatible with every reference type. It denotes a reference value which refers to a special \"null\" object."
},
{
"code": null,
"e": 21420,
"s": 21340,
"text": "The following escape sequences are recognized in character and string literals."
},
{
"code": null,
"e": 21651,
"s": 21420,
"text": "A character with Unicode between 0 and 255 may also be represented by an octal escape, i.e., a backslash '\\' followed by a sequence of up to three octal characters. Following is the example to show few escape sequence characters −"
},
{
"code": null,
"e": 21744,
"s": 21651,
"text": "object Test {\n def main(args: Array[String]) {\n println(\"Hello\\tWorld\\n\\n\" );\n }\n} "
},
{
"code": null,
"e": 21825,
"s": 21744,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 21840,
"s": 21825,
"text": "Hello World\n"
},
{
"code": null,
"e": 21987,
"s": 21840,
"text": "Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory."
},
{
"code": null,
"e": 22237,
"s": 21987,
"text": "Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables."
},
{
"code": null,
"e": 22539,
"s": 22237,
"text": "Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword −"
},
{
"code": null,
"e": 22567,
"s": 22539,
"text": "var myVar : String = \"Foo\"\n"
},
{
"code": null,
"e": 22774,
"s": 22567,
"text": "Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −"
},
{
"code": null,
"e": 22802,
"s": 22774,
"text": "val myVal : String = \"Foo\"\n"
},
{
"code": null,
"e": 22969,
"s": 22802,
"text": "The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −"
},
{
"code": null,
"e": 23023,
"s": 22969,
"text": "val or val VariableName : DataType = [Initial Value]\n"
},
{
"code": null,
"e": 23107,
"s": 23023,
"text": "If you do not assign any initial value to a variable, then it is valid as follows −"
},
{
"code": null,
"e": 23143,
"s": 23107,
"text": "var myVar :Int;\nval myVal :String;\n"
},
{
"code": null,
"e": 23392,
"s": 23143,
"text": "When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −"
},
{
"code": null,
"e": 23438,
"s": 23392,
"text": "var myVar = 10;\nval myVal = \"Hello, Scala!\";\n"
},
{
"code": null,
"e": 23523,
"s": 23438,
"text": "Here, by default, myVar will be Int type and myVal will become String type variable."
},
{
"code": null,
"e": 23759,
"s": 23523,
"text": "Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.]"
},
{
"code": null,
"e": 23812,
"s": 23759,
"text": "val (myVar1: Int, myVar2: String) = Pair(40, \"Foo\")\n"
},
{
"code": null,
"e": 23851,
"s": 23812,
"text": "And the type inference gets it right −"
},
{
"code": null,
"e": 23891,
"s": 23851,
"text": "val (myVar1, myVar2) = Pair(40, \"Foo\")\n"
},
{
"code": null,
"e": 24122,
"s": 23891,
"text": "The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration."
},
{
"code": null,
"e": 24450,
"s": 24122,
"text": "object Demo {\n def main(args: Array[String]) {\n var myVar :Int = 10;\n val myVal :String = \"Hello Scala with datatype declaration.\";\n var myVar1 = 20;\n val myVal1 = \"Hello Scala new without datatype declaration.\";\n \n println(myVar); println(myVal); println(myVar1); \n println(myVal1);\n }\n}"
},
{
"code": null,
"e": 24557,
"s": 24450,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 24591,
"s": 24557,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 24679,
"s": 24591,
"text": "10\nHello Scala with datatype declaration.\n20\nHello Scala without datatype declaration.\n"
},
{
"code": null,
"e": 24899,
"s": 24679,
"text": "Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope."
},
{
"code": null,
"e": 25222,
"s": 24899,
"text": "Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val."
},
{
"code": null,
"e": 25591,
"s": 25222,
"text": "Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword."
},
{
"code": null,
"e": 25892,
"s": 25591,
"text": "Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable and immutable types and can be defined using either var or val."
},
{
"code": null,
"e": 26180,
"s": 25892,
"text": "This chapter takes you through how to use classes and objects in Scala programming. A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class."
},
{
"code": null,
"e": 26611,
"s": 26180,
"text": "The following diagram demonstrates the class and object by taking an example of class student, which contains the member variables (name and roll no) and member methods (setName() and setRollNo()). Finally all are members of the class. Class is a blue print and objects are real here. In the following diagram, Student is a class and Harini, John, and Maria are the objects of Student class, those are having name and roll-number."
},
{
"code": null,
"e": 26852,
"s": 26611,
"text": "Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods."
},
{
"code": null,
"e": 27050,
"s": 26852,
"text": "The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class."
},
{
"code": null,
"e": 27281,
"s": 27050,
"text": "class Point(xc: Int, yc: Int) {\n var x: Int = xc\n var y: Int = yc\n\n def move(dx: Int, dy: Int) {\n x = x + dx\n y = y + dy\n println (\"Point x location : \" + x);\n println (\"Point y location : \" + y);\n }\n}\n"
},
{
"code": null,
"e": 27443,
"s": 27281,
"text": "As mentioned earlier in this chapter, you can create objects using a keyword new and then you can access class fields and methods as shown below in the example −"
},
{
"code": null,
"e": 27849,
"s": 27443,
"text": "import java.io._\n\nclass Point(val xc: Int, val yc: Int) {\n var x: Int = xc\n var y: Int = yc\n \n def move(dx: Int, dy: Int) {\n x = x + dx\n y = y + dy\n println (\"Point x location : \" + x);\n println (\"Point y location : \" + y);\n }\n}\n\nobject Demo {\n def main(args: Array[String]) {\n val pt = new Point(10, 20);\n\n // Move to a new location\n pt.move(10, 10);\n }\n}"
},
{
"code": null,
"e": 27956,
"s": 27849,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 27990,
"s": 27956,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 28035,
"s": 27990,
"text": "Point x location : 20\nPoint y location : 30\n"
},
{
"code": null,
"e": 28385,
"s": 28035,
"text": "You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method."
},
{
"code": null,
"e": 28942,
"s": 28385,
"text": "Let us take an example of two classes Point class (as same example as above) and Location class is inherited class using extends keyword. Such an ‘extends’ clause has two effects: it makes Location class inherit all non-private members from Point class, and it makes the type Location a subtype of the type Point class. So here the Point class is called superclass and the class Location is called subclass. Extending a class and inheriting all the features of a parent class is called inheritance but Scala allows the inheritance from just one class only."
},
{
"code": null,
"e": 29197,
"s": 28942,
"text": "Note − Methods move() method in Point class and move() method in Location class do not override the corresponding definitions of move since they are different definitions (for example, the former take two arguments while the latter take three arguments)."
},
{
"code": null,
"e": 29257,
"s": 29197,
"text": "Try the following example program to implement inheritance."
},
{
"code": null,
"e": 30022,
"s": 29257,
"text": "import java.io._\n\nclass Point(val xc: Int, val yc: Int) {\n var x: Int = xc\n var y: Int = yc\n \n def move(dx: Int, dy: Int) {\n x = x + dx\n y = y + dy\n println (\"Point x location : \" + x);\n println (\"Point y location : \" + y);\n }\n}\n\nclass Location(override val xc: Int, override val yc: Int,\n val zc :Int) extends Point(xc, yc){\n var z: Int = zc\n\n def move(dx: Int, dy: Int, dz: Int) {\n x = x + dx\n y = y + dy\n z = z + dz\n println (\"Point x location : \" + x);\n println (\"Point y location : \" + y);\n println (\"Point z location : \" + z);\n }\n}\n\nobject Demo {\n def main(args: Array[String]) {\n val loc = new Location(10, 20, 15);\n\n // Move to a new location\n loc.move(10, 10, 5);\n }\n}"
},
{
"code": null,
"e": 30129,
"s": 30022,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 30163,
"s": 30129,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 30230,
"s": 30163,
"text": "Point x location : 20\nPoint y location : 30\nPoint z location : 20\n"
},
{
"code": null,
"e": 30437,
"s": 30230,
"text": "Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10."
},
{
"code": null,
"e": 30639,
"s": 30437,
"text": "Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class."
},
{
"code": null,
"e": 30754,
"s": 30639,
"text": "object <object name> {\n implicit class <class name>(<Variable>: Data type) {\n def <method>(): Unit =\n }\n}"
},
{
"code": null,
"e": 31084,
"s": 30754,
"text": "Let us take an example of an implicit class named IntTimes with the method times(). It means the times () contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println (“Hello”)” means the println (“”Hello”) statement will execute 4 times."
},
{
"code": null,
"e": 31296,
"s": 31084,
"text": "The following is the program for the given example. In this example two object classes are used (Run and Demo) so that we have to save those two classes in different files with their respective names as follows."
},
{
"code": null,
"e": 31349,
"s": 31296,
"text": "Run.scala − Save the following program in Run.scala."
},
{
"code": null,
"e": 31600,
"s": 31349,
"text": "object Run {\n implicit class IntTimes(x: Int) {\n def times [A](f: =>A): Unit = {\n def loop(current: Int): Unit =\n \n if(current > 0){\n f\n loop(current - 1)\n }\n loop(x)\n }\n }\n}"
},
{
"code": null,
"e": 31655,
"s": 31600,
"text": "Demo.scala − Save the following program in Demo.scala."
},
{
"code": null,
"e": 31756,
"s": 31655,
"text": "import Run._\n\nobject Demo {\n def main(args: Array[String]) {\n 4 times println(\"hello\")\n }\n}"
},
{
"code": null,
"e": 31831,
"s": 31756,
"text": "The following commands are used to compile and execute these two programs."
},
{
"code": null,
"e": 31884,
"s": 31831,
"text": "\\>scalac Run.scala\n\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 31909,
"s": 31884,
"text": "Hello\nHello\nHello\nHello\n"
},
{
"code": null,
"e": 31916,
"s": 31909,
"text": "Note −"
},
{
"code": null,
"e": 32003,
"s": 31916,
"text": "Implicit classes must be defined inside another class/object/trait (not in top level)."
},
{
"code": null,
"e": 32090,
"s": 32003,
"text": "Implicit classes must be defined inside another class/object/trait (not in top level)."
},
{
"code": null,
"e": 32170,
"s": 32090,
"text": "Implicit classes may only take one non –implicit argument in their constructor."
},
{
"code": null,
"e": 32250,
"s": 32170,
"text": "Implicit classes may only take one non –implicit argument in their constructor."
},
{
"code": null,
"e": 32358,
"s": 32250,
"text": "Implicit classes may not be any method, member or object in scope with the same name as the implicit class."
},
{
"code": null,
"e": 32466,
"s": 32358,
"text": "Implicit classes may not be any method, member or object in scope with the same name as the implicit class."
},
{
"code": null,
"e": 32938,
"s": 32466,
"text": "Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword. Since you can't instantiate a singleton object, you can't pass parameters to the primary constructor. You already have seen all the examples using singleton objects where you called Scala's main method."
},
{
"code": null,
"e": 33000,
"s": 32938,
"text": "Following is the same example program to implement singleton."
},
{
"code": null,
"e": 33418,
"s": 33000,
"text": "import java.io._\n\nclass Point(val xc: Int, val yc: Int) {\n var x: Int = xc\n var y: Int = yc\n \n def move(dx: Int, dy: Int) {\n x = x + dx\n y = y + dy\n }\n}\n\nobject Demo {\n def main(args: Array[String]) {\n val point = new Point(10, 20)\n printPoint\n\n def printPoint{\n println (\"Point x location : \" + point.x);\n println (\"Point y location : \" + point.y);\n }\n }\n}"
},
{
"code": null,
"e": 33525,
"s": 33418,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 33558,
"s": 33525,
"text": "\\>scalac Demo.scala\n\\>scala Demo"
},
{
"code": null,
"e": 33603,
"s": 33558,
"text": "Point x location : 10\nPoint y location : 20\n"
},
{
"code": null,
"e": 34085,
"s": 33603,
"text": "This chapter takes you through the Scala access modifiers. Members of packages, classes or objects can be labeled with the access modifiers private and protected, and if we are not using either of these two keywords, then access will be assumed as public. These modifiers restrict accesses to the members to certain regions of code. To use an access modifier, you include its keyword in the definition of members of package, class or object as we will see in the following section."
},
{
"code": null,
"e": 34182,
"s": 34085,
"text": "A private member is visible only inside the class or object that contains the member definition."
},
{
"code": null,
"e": 34248,
"s": 34182,
"text": "Following is the example code snippet to explain Private member −"
},
{
"code": null,
"e": 34432,
"s": 34248,
"text": "class Outer {\n class Inner {\n private def f() { println(\"f\") }\n \n class InnerMost {\n f() // OK\n }\n }\n (new Inner).f() // Error: f is not accessible\n}"
},
{
"code": null,
"e": 34797,
"s": 34432,
"text": "In Scala, the access (new Inner). f() is illegal because f is declared private in Inner and the access is not from within class Inner. By contrast, the first access to f in class Innermost is OK, because that access is contained in the body of class Inner. Java would permit both accesses because it lets an outer class access private members of its inner classes."
},
{
"code": null,
"e": 34896,
"s": 34797,
"text": "A protected member is only accessible from subclasses of the class in which the member is defined."
},
{
"code": null,
"e": 34964,
"s": 34896,
"text": "Following is the example code snippet to explain protected member −"
},
{
"code": null,
"e": 35167,
"s": 34964,
"text": "package p {\n class Super {\n protected def f() { println(\"f\") }\n }\n \n class Sub extends Super {\n f()\n }\n \n class Other {\n (new Super).f() // Error: f is not accessible\n }\n}"
},
{
"code": null,
"e": 35526,
"s": 35167,
"text": "The access to f in class Sub is OK because f is declared protected in ‘Super’ class and ‘Sub’ class is a subclass of Super. By contrast the access to f in ‘Other’ class is not permitted, because class ‘Other’ does not inherit from class ‘Super’. In Java, the latter access would be still permitted because ‘Other’ class is in the same package as ‘Sub’ class."
},
{
"code": null,
"e": 35723,
"s": 35526,
"text": "Unlike private and protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from anywhere."
},
{
"code": null,
"e": 35788,
"s": 35723,
"text": "Following is the example code snippet to explain public member −"
},
{
"code": null,
"e": 35966,
"s": 35788,
"text": "class Outer {\n class Inner {\n def f() { println(\"f\") }\n \n class InnerMost {\n f() // OK\n }\n }\n (new Inner).f() // OK because now f() is public\n}"
},
{
"code": null,
"e": 36199,
"s": 35966,
"text": "Access modifiers in Scala can be augmented with qualifiers. A modifier of the form private[X] or protected[X] means that access is private or protected \"up to\" X, where X designates some enclosing package, class or singleton object."
},
{
"code": null,
"e": 36232,
"s": 36199,
"text": "Consider the following example −"
},
{
"code": null,
"e": 36595,
"s": 36232,
"text": "package society {\n package professional {\n class Executive {\n private[professional] var workDetails = null\n private[society] var friends = null\n private[this] var secrets = null\n\n def help(another : Executive) {\n println(another.workDetails)\n println(another.secrets) //ERROR\n }\n }\n }\n}"
},
{
"code": null,
"e": 36648,
"s": 36595,
"text": "Note − the following points from the above example −"
},
{
"code": null,
"e": 36744,
"s": 36648,
"text": "Variable workDetails will be accessible to any class within the enclosing package professional."
},
{
"code": null,
"e": 36840,
"s": 36744,
"text": "Variable workDetails will be accessible to any class within the enclosing package professional."
},
{
"code": null,
"e": 36927,
"s": 36840,
"text": "Variable friends will be accessible to any class within the enclosing package society."
},
{
"code": null,
"e": 37014,
"s": 36927,
"text": "Variable friends will be accessible to any class within the enclosing package society."
},
{
"code": null,
"e": 37110,
"s": 37014,
"text": "Variable secrets will be accessible only on the implicit object within instance methods (this)."
},
{
"code": null,
"e": 37206,
"s": 37110,
"text": "Variable secrets will be accessible only on the implicit object within instance methods (this)."
},
{
"code": null,
"e": 37397,
"s": 37206,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides the following types of operators −"
},
{
"code": null,
"e": 37418,
"s": 37397,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 37439,
"s": 37418,
"text": "Relational Operators"
},
{
"code": null,
"e": 37457,
"s": 37439,
"text": "Logical Operators"
},
{
"code": null,
"e": 37475,
"s": 37457,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 37496,
"s": 37475,
"text": "Assignment Operators"
},
{
"code": null,
"e": 37611,
"s": 37496,
"text": "This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one."
},
{
"code": null,
"e": 37758,
"s": 37611,
"text": "The following arithmetic operators are supported by Scala language. For example, let us assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 37772,
"s": 37758,
"text": "Show Examples"
},
{
"code": null,
"e": 37918,
"s": 37772,
"text": "The following relational operators are supported by Scala language. For example let us assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 37932,
"s": 37918,
"text": "Show Examples"
},
{
"code": null,
"e": 38067,
"s": 37932,
"text": "The following logical operators are supported by Scala language. For example, assume variable A holds 1 and variable B holds 0, then −"
},
{
"code": null,
"e": 38081,
"s": 38067,
"text": "Show Examples"
},
{
"code": null,
"e": 38196,
"s": 38081,
"text": "Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows −"
},
{
"code": null,
"e": 38273,
"s": 38196,
"text": "Assume if A = 60; and B = 13; now in binary format they will be as follows −"
},
{
"code": null,
"e": 38389,
"s": 38273,
"text": "A = 0011 1100\nB = 0000 1101\n-----------------------\nA&B = 0000 1100\nA|B = 0011 1101\nA^B = 0011 0001\n~A = 1100 0011\n"
},
{
"code": null,
"e": 38532,
"s": 38389,
"text": "The Bitwise operators supported by Scala language is listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 38546,
"s": 38532,
"text": "Show Examples"
},
{
"code": null,
"e": 38617,
"s": 38546,
"text": "There are following assignment operators supported by Scala language −"
},
{
"code": null,
"e": 38631,
"s": 38617,
"text": "Show Examples"
},
{
"code": null,
"e": 38893,
"s": 38631,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −"
},
{
"code": null,
"e": 39060,
"s": 38893,
"text": "For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7."
},
{
"code": null,
"e": 39299,
"s": 39060,
"text": "Take a look at the following table. Operators with the highest precedence appear at the top of the table and those with the lowest precedence appear at the bottom. Within an expression, higher precedence operators will be evaluated first."
},
{
"code": null,
"e": 39515,
"s": 39299,
"text": "This chapter takes you through the conditional construction statements in Scala programming. Following is the general form of a typical decision making IF...ELSE structure found in most of the programming languages."
},
{
"code": null,
"e": 39580,
"s": 39515,
"text": "The following is a flow chart diagram for conditional statement."
},
{
"code": null,
"e": 39664,
"s": 39580,
"text": "‘if’ statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 39711,
"s": 39664,
"text": "The syntax of an ‘if’ statement is as follows."
},
{
"code": null,
"e": 39803,
"s": 39711,
"text": "if(Boolean_expression) {\n // Statements will execute if the Boolean expression is true\n}\n"
},
{
"code": null,
"e": 40032,
"s": 39803,
"text": "If the Boolean expression evaluates to true then the block of code inside the ‘if’ expression will be executed. If not, the first set of code after the end of the ‘if’ expression (after the closing curly brace) will be executed."
},
{
"code": null,
"e": 40151,
"s": 40032,
"text": "Try the following example program to understand conditional expressions (if expression) in Scala Programming Language."
},
{
"code": null,
"e": 40296,
"s": 40151,
"text": "object Demo {\n def main(args: Array[String]) {\n var x = 10;\n\n if( x < 20 ){\n println(\"This is if statement\");\n }\n }\n}"
},
{
"code": null,
"e": 40403,
"s": 40296,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 40437,
"s": 40403,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 40459,
"s": 40437,
"text": "This is if statement\n"
},
{
"code": null,
"e": 40577,
"s": 40459,
"text": "An ‘if’ statement can be followed by an optional else statement, which executes when the Boolean expression is false."
},
{
"code": null,
"e": 40608,
"s": 40577,
"text": "The syntax of a if...else is −"
},
{
"code": null,
"e": 40744,
"s": 40608,
"text": "if(Boolean_expression){\n //Executes when the Boolean expression is true\n} else{\n //Executes when the Boolean expression is false\n}\n"
},
{
"code": null,
"e": 40867,
"s": 40744,
"text": "Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language."
},
{
"code": null,
"e": 41071,
"s": 40867,
"text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n\n if( x < 20 ){\n println(\"This is if statement\");\n } else {\n println(\"This is else statement\");\n }\n }\n}"
},
{
"code": null,
"e": 41178,
"s": 41071,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 41212,
"s": 41178,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 41236,
"s": 41212,
"text": "This is else statement\n"
},
{
"code": null,
"e": 41398,
"s": 41236,
"text": "An 'if' statement can be followed by an optional 'else if...else' statement, which is very useful to test various conditions using single if...else if statement."
},
{
"code": null,
"e": 41478,
"s": 41398,
"text": "When using if , else if , else statements there are few points to keep in mind."
},
{
"code": null,
"e": 41552,
"s": 41478,
"text": "An 'if' can have zero or one else's and it must come after any else if's."
},
{
"code": null,
"e": 41626,
"s": 41552,
"text": "An 'if' can have zero or one else's and it must come after any else if's."
},
{
"code": null,
"e": 41702,
"s": 41626,
"text": "An 'if' can have zero to many else if's and they must come before the else."
},
{
"code": null,
"e": 41778,
"s": 41702,
"text": "An 'if' can have zero to many else if's and they must come before the else."
},
{
"code": null,
"e": 41861,
"s": 41778,
"text": "Once an else if succeeds, none of he remaining else if's or else's will be tested."
},
{
"code": null,
"e": 41944,
"s": 41861,
"text": "Once an else if succeeds, none of he remaining else if's or else's will be tested."
},
{
"code": null,
"e": 42016,
"s": 41944,
"text": "The following is the syntax of an ‘if...else if...else’ is as follows −"
},
{
"code": null,
"e": 42336,
"s": 42016,
"text": "if(Boolean_expression 1){\n //Executes when the Boolean expression 1 is true\n} else if(Boolean_expression 2){\n //Executes when the Boolean expression 2 is true\n} else if(Boolean_expression 3){\n //Executes when the Boolean expression 3 is true\n} else {\n //Executes when the none of the above condition is true.\n}\n"
},
{
"code": null,
"e": 42469,
"s": 42336,
"text": "Try the following example program to understand conditional statements (if- else- if- else statement) in Scala Programming Language."
},
{
"code": null,
"e": 42801,
"s": 42469,
"text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n\n if( x == 10 ){\n println(\"Value of X is 10\");\n } else if( x == 20 ){\n println(\"Value of X is 20\");\n } else if( x == 30 ){\n println(\"Value of X is 30\");\n } else{\n println(\"This is else statement\");\n }\n }\n}"
},
{
"code": null,
"e": 42908,
"s": 42801,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 42942,
"s": 42908,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 42960,
"s": 42942,
"text": "Value of X is 30\n"
},
{
"code": null,
"e": 43099,
"s": 42960,
"text": "It is always legal to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement."
},
{
"code": null,
"e": 43147,
"s": 43099,
"text": "The syntax for a nested if-else is as follows −"
},
{
"code": null,
"e": 43321,
"s": 43147,
"text": "if(Boolean_expression 1){\n //Executes when the Boolean expression 1 is true\n \n if(Boolean_expression 2){\n //Executes when the Boolean expression 2 is true\n }\n}\n"
},
{
"code": null,
"e": 43446,
"s": 43321,
"text": "Try the following example program to understand conditional statements (nested- if statement) in Scala Programming Language."
},
{
"code": null,
"e": 43651,
"s": 43446,
"text": "object Demo {\n def main(args: Array[String]) {\n var x = 30;\n var y = 10;\n \n if( x == 30 ){\n if( y == 10 ){\n println(\"X = 30 and Y = 10\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 43758,
"s": 43651,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 43792,
"s": 43758,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 43811,
"s": 43792,
"text": "X = 30 and Y = 10\n"
},
{
"code": null,
"e": 43902,
"s": 43811,
"text": "This chapter takes you through the loop control structures in Scala programming languages."
},
{
"code": null,
"e": 44132,
"s": 43902,
"text": "There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 44238,
"s": 44132,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 44419,
"s": 44238,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 44578,
"s": 44419,
"text": "Scala programming language provides the following types of loops to handle looping requirements. Click the following links in the table to check their detail."
},
{
"code": null,
"e": 44589,
"s": 44578,
"text": "while loop"
},
{
"code": null,
"e": 44720,
"s": 44589,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 44734,
"s": 44720,
"text": "do-while loop"
},
{
"code": null,
"e": 44822,
"s": 44734,
"text": "Like a while statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 44831,
"s": 44822,
"text": "for loop"
},
{
"code": null,
"e": 44937,
"s": 44831,
"text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 45297,
"s": 44937,
"text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. As such Scala does not support break or continue statement like Java does but starting from Scala version 2.8, there is a way to break the loops. Click the following links to check the detail."
},
{
"code": null,
"e": 45313,
"s": 45297,
"text": "break statement"
},
{
"code": null,
"e": 45416,
"s": 45313,
"text": "Terminates the loop statement and transfers execution to the statement immediately following the loop."
},
{
"code": null,
"e": 45567,
"s": 45416,
"text": "A loop becomes an infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement infinite loop."
},
{
"code": null,
"e": 45615,
"s": 45567,
"text": "The following program implements infinite loop."
},
{
"code": null,
"e": 45792,
"s": 45615,
"text": "object Demo {\n def main(args: Array[String]) {\n var a = 10;\n \n // An infinite loop.\n while( true ){\n println( \"Value of a: \" + a );\n }\n }\n}"
},
{
"code": null,
"e": 45899,
"s": 45792,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 45933,
"s": 45899,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 46044,
"s": 45933,
"text": "If you will execute above code, it will go in infinite loop which you can terminate by pressing Ctrl + C keys."
},
{
"code": null,
"e": 46122,
"s": 46044,
"text": "Value of a: 10\nValue of a: 10\nValue of a: 10\nValue of a: 10\n................\n"
},
{
"code": null,
"e": 46387,
"s": 46122,
"text": "A function is a group of statements that perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically, the division usually is so that each function performs a specific task."
},
{
"code": null,
"e": 46800,
"s": 46387,
"text": "Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference. A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode where as a function in Scala is a complete object which can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method."
},
{
"code": null,
"e": 47088,
"s": 46800,
"text": "A function definition can appear anywhere in a source file and Scala permits nested function definitions, that is, function definitions inside other function definitions. Most important point to note is that Scala function's name can have characters like +, ++, ~, &,-, --, \\, /, :, etc."
},
{
"code": null,
"e": 47142,
"s": 47088,
"text": "A Scala function declaration has the following form −"
},
{
"code": null,
"e": 47198,
"s": 47142,
"text": "def functionName ([list of parameters]) : [return type]"
},
{
"code": null,
"e": 47293,
"s": 47198,
"text": "Methods are implicitly declared abstract if you don’t use the equals sign and the method body."
},
{
"code": null,
"e": 47346,
"s": 47293,
"text": "A Scala function definition has the following form −"
},
{
"code": null,
"e": 47443,
"s": 47346,
"text": "def functionName ([list of parameters]) : [return type] = {\n function body\n return [expr]\n}\n"
},
{
"code": null,
"e": 47808,
"s": 47443,
"text": "Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional. Very similar to Java, a return statement can be used along with an expression in case function returns a value. Following is the function which will add two integers and return their sum −"
},
{
"code": null,
"e": 47926,
"s": 47808,
"text": "object add {\n def addInt( a:Int, b:Int ) : Int = {\n var sum:Int = 0\n sum = a + b\n return sum\n }\n}\n"
},
{
"code": null,
"e": 48156,
"s": 47926,
"text": "A function, that does not return anything can return a Unit that is equivalent to void in Java and indicates that function does not return anything. The functions which do not return anything in Scala, they are called procedures."
},
{
"code": null,
"e": 48177,
"s": 48156,
"text": "Here is the syntax −"
},
{
"code": null,
"e": 48259,
"s": 48177,
"text": "object Hello{\n def printMe( ) : Unit = {\n println(\"Hello, Scala!\")\n }\n}\n"
},
{
"code": null,
"e": 48378,
"s": 48259,
"text": "Scala provides a number of syntactic variations for invoking methods. Following is the standard way to call a method −"
},
{
"code": null,
"e": 48414,
"s": 48378,
"text": "functionName( list of parameters )\n"
},
{
"code": null,
"e": 48537,
"s": 48414,
"text": "If a function is being called using an instance of the object, then we would use dot notation similar to Java as follows −"
},
{
"code": null,
"e": 48584,
"s": 48537,
"text": "[instance.]functionName( list of parameters )\n"
},
{
"code": null,
"e": 48661,
"s": 48584,
"text": "Try the following example program to define and then call the same function."
},
{
"code": null,
"e": 48876,
"s": 48661,
"text": "object Demo {\n def main(args: Array[String]) {\n println( \"Returned Value : \" + addInt(5,7) );\n }\n \n def addInt( a:Int, b:Int ) : Int = {\n var sum:Int = 0\n sum = a + b\n\n return sum\n }\n}"
},
{
"code": null,
"e": 48983,
"s": 48876,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 49017,
"s": 48983,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 49038,
"s": 49017,
"text": "Returned Value : 12\n"
},
{
"code": null,
"e": 49273,
"s": 49038,
"text": "Scala functions are the heart of Scala programming and that's why Scala is assumed as a functional programming language. Following are few important concepts related to Scala functions which should be understood by a Scala programmer."
},
{
"code": null,
"e": 49395,
"s": 49273,
"text": "A closure is a function, whose return value depends on the value of one or more variables declared outside this function."
},
{
"code": null,
"e": 49448,
"s": 49395,
"text": "The following piece of code with anonymous function."
},
{
"code": null,
"e": 49484,
"s": 49448,
"text": "val multiplier = (i:Int) => i * 10\n"
},
{
"code": null,
"e": 49623,
"s": 49484,
"text": "Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function. Try the following code −"
},
{
"code": null,
"e": 49663,
"s": 49623,
"text": "val multiplier = (i:Int) => i * factor\n"
},
{
"code": null,
"e": 49938,
"s": 49663,
"text": "There are two free variables in multiplier: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multiplier is called. However, factor is not a formal parameter, then what is this? Let us add one more line of code."
},
{
"code": null,
"e": 49993,
"s": 49938,
"text": "var factor = 3\nval multiplier = (i:Int) => i * factor\n"
},
{
"code": null,
"e": 50269,
"s": 49993,
"text": "Now factor has a reference to a variable outside the function but in the enclosing scope. The function references factor and reads its current value each time. If a function has no external references, then it is trivially closed over itself. No external context is required."
},
{
"code": null,
"e": 50304,
"s": 50269,
"text": "Try the following example program."
},
{
"code": null,
"e": 50538,
"s": 50304,
"text": "object Demo {\n def main(args: Array[String]) {\n println( \"multiplier(1) value = \" + multiplier(1) )\n println( \"multiplier(2) value = \" + multiplier(2) )\n }\n var factor = 3\n val multiplier = (i:Int) => i * factor\n}"
},
{
"code": null,
"e": 50645,
"s": 50538,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 50679,
"s": 50645,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 50728,
"s": 50679,
"text": "multiplier(1) value = 3\nmultiplier(2) value = 6\n"
},
{
"code": null,
"e": 51085,
"s": 50728,
"text": "This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class."
},
{
"code": null,
"e": 51137,
"s": 51085,
"text": "The following code can be used to create a String −"
},
{
"code": null,
"e": 51212,
"s": 51137,
"text": "var greeting = \"Hello world!\";\n\nor\n\nvar greeting:String = \"Hello world!\";\n"
},
{
"code": null,
"e": 51418,
"s": 51212,
"text": "Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above."
},
{
"code": null,
"e": 51453,
"s": 51418,
"text": "Try the following example program."
},
{
"code": null,
"e": 51578,
"s": 51453,
"text": "object Demo {\n val greeting: String = \"Hello, world!\"\n\n def main(args: Array[String]) {\n println( greeting )\n }\n}"
},
{
"code": null,
"e": 51685,
"s": 51578,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 51719,
"s": 51685,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 51734,
"s": 51719,
"text": "Hello, world!\n"
},
{
"code": null,
"e": 51960,
"s": 51734,
"text": "As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!."
},
{
"code": null,
"e": 52187,
"s": 51960,
"text": "Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object."
},
{
"code": null,
"e": 52251,
"s": 52187,
"text": "Use the following code segment to find the length of a string −"
},
{
"code": null,
"e": 52441,
"s": 52251,
"text": "object Demo {\n def main(args: Array[String]) {\n var palindrome = \"Dot saw I was Tod\";\n var len = palindrome.length();\n \n println( \"String Length is : \" + len );\n }\n}"
},
{
"code": null,
"e": 52548,
"s": 52441,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 52582,
"s": 52548,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 52605,
"s": 52582,
"text": "String Length is : 17\n"
},
{
"code": null,
"e": 52672,
"s": 52605,
"text": "The String class includes a method for concatenating two strings −"
},
{
"code": null,
"e": 52698,
"s": 52672,
"text": "string1.concat(string2);\n"
},
{
"code": null,
"e": 52844,
"s": 52698,
"text": "This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −"
},
{
"code": null,
"e": 52875,
"s": 52844,
"text": "\"My name is \".concat(\"Zara\");\n"
},
{
"code": null,
"e": 52943,
"s": 52875,
"text": "Strings are more commonly concatenated with the + operator, as in −"
},
{
"code": null,
"e": 52970,
"s": 52943,
"text": "\"Hello,\" + \" world\" + \"!\"\n"
},
{
"code": null,
"e": 52989,
"s": 52970,
"text": "Which results in −"
},
{
"code": null,
"e": 53006,
"s": 52989,
"text": "\"Hello, world!\"\n"
},
{
"code": null,
"e": 53057,
"s": 53006,
"text": "The following lines of code to find string length."
},
{
"code": null,
"e": 53217,
"s": 53057,
"text": "object Demo {\n def main(args: Array[String]) {\n var str1 = \"Dot saw I was \";\n var str2 = \"Tod\";\n \n println(\"Dot \" + str1 + str2);\n }\n}"
},
{
"code": null,
"e": 53324,
"s": 53217,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 53358,
"s": 53324,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 53381,
"s": 53358,
"text": "Dot Dot saw I was Tod\n"
},
{
"code": null,
"e": 53582,
"s": 53381,
"text": "You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object."
},
{
"code": null,
"e": 53654,
"s": 53582,
"text": "Try the following example program, which makes use of printf() method −"
},
{
"code": null,
"e": 54008,
"s": 53654,
"text": "object Demo {\n def main(args: Array[String]) {\n var floatVar = 12.456\n var intVar = 2000\n var stringVar = \"Hello, Scala!\"\n \n var fs = printf(\"The value of the float variable is \" + \"%f, while the value of the integer \" + \"variable is %d, and the string\" + \"is %s\", floatVar, intVar, stringVar);\n \n println(fs)\n }\n}"
},
{
"code": null,
"e": 54115,
"s": 54008,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 54149,
"s": 54115,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 54281,
"s": 54149,
"text": "The value of the float variable is 12.456000, \nwhile the value of the integer variable is 2000, \nand the string is Hello, Scala!()\n"
},
{
"code": null,
"e": 54527,
"s": 54281,
"text": "String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal."
},
{
"code": null,
"e": 54609,
"s": 54527,
"text": "There are three types (interpolators) of implementations in String Interpolation."
},
{
"code": null,
"e": 54853,
"s": 54609,
"text": "The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator."
},
{
"code": null,
"e": 55017,
"s": 54853,
"text": "The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement."
},
{
"code": null,
"e": 55086,
"s": 55017,
"text": "val name = “James”\nprintln(s “Hello, $name”) //output: Hello, James\n"
},
{
"code": null,
"e": 55324,
"s": 55086,
"text": "String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’."
},
{
"code": null,
"e": 55375,
"s": 55324,
"text": "println(s “1 + 1 = ${1 + 1}”) //output: 1 + 1 = 2\n"
},
{
"code": null,
"e": 55443,
"s": 55375,
"text": "Try the following example program of implementing ‘s’ interpolator."
},
{
"code": null,
"e": 55597,
"s": 55443,
"text": "object Demo {\n def main(args: Array[String]) {\n val name = \"James\"\n \n println(s\"Hello, $name\")\n println(s\"1 + 1 = ${1 + 1}\")\n }\n}"
},
{
"code": null,
"e": 55704,
"s": 55597,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 55738,
"s": 55704,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 55762,
"s": 55738,
"text": "Hello, James\n1 + 1 = 2\n"
},
{
"code": null,
"e": 55997,
"s": 55762,
"text": "The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc."
},
{
"code": null,
"e": 56286,
"s": 55997,
"text": "Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90."
},
{
"code": null,
"e": 56400,
"s": 56286,
"text": "val height = 1.9d\nval name = \"James\"\nprintln(f\"$name%s is $height%2.2f meters tall\") //James is 1.90 meters tall\n"
},
{
"code": null,
"e": 56723,
"s": 56400,
"text": "It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is no % character after variable reference. It will assume as %s (String)."
},
{
"code": null,
"e": 57094,
"s": 56723,
"text": "The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string. The following code snippets in a table will differ the usage of ‘s’ and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\\n’ effects as new line and in output of ‘raw’ usage the ‘\\n’ will not effect. It will print the complete string with escape letters."
},
{
"code": null,
"e": 57104,
"s": 57094,
"text": "Program −"
},
{
"code": null,
"e": 57197,
"s": 57104,
"text": "object Demo {\n def main(args: Array[String]) {\n println(s\"Result = \\n a \\n b\")\n }\n}"
},
{
"code": null,
"e": 57207,
"s": 57197,
"text": "Program −"
},
{
"code": null,
"e": 57302,
"s": 57207,
"text": "object Demo {\n def main(args: Array[String]) {\n println(raw\"Result = \\n a \\n b\")\n }\n}"
},
{
"code": null,
"e": 57311,
"s": 57302,
"text": "Output −"
},
{
"code": null,
"e": 57325,
"s": 57311,
"text": "Result =\na\nb\n"
},
{
"code": null,
"e": 57334,
"s": 57325,
"text": "Output −"
},
{
"code": null,
"e": 57354,
"s": 57334,
"text": "Result = \\n a \\n b\n"
},
{
"code": null,
"e": 57471,
"s": 57354,
"text": "Following is the list of methods defined by java.lang.String class and can be used directly in your Scala programs −"
},
{
"code": null,
"e": 57494,
"s": 57471,
"text": "char charAt(int index)"
},
{
"code": null,
"e": 57540,
"s": 57494,
"text": "Returns the character at the specified index."
},
{
"code": null,
"e": 57564,
"s": 57540,
"text": "int compareTo(Object o)"
},
{
"code": null,
"e": 57604,
"s": 57564,
"text": "Compares this String to another Object."
},
{
"code": null,
"e": 57640,
"s": 57604,
"text": "int compareTo(String anotherString)"
},
{
"code": null,
"e": 57680,
"s": 57640,
"text": "Compares two strings lexicographically."
},
{
"code": null,
"e": 57716,
"s": 57680,
"text": "int compareToIgnoreCase(String str)"
},
{
"code": null,
"e": 57783,
"s": 57716,
"text": "Compares two strings lexicographically, ignoring case differences."
},
{
"code": null,
"e": 57809,
"s": 57783,
"text": "String concat(String str)"
},
{
"code": null,
"e": 57870,
"s": 57809,
"text": "Concatenates the specified string to the end of this string."
},
{
"code": null,
"e": 57909,
"s": 57870,
"text": "boolean contentEquals(StringBuffer sb)"
},
{
"code": null,
"e": 58023,
"s": 57909,
"text": "Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer."
},
{
"code": null,
"e": 58062,
"s": 58023,
"text": "static String copyValueOf(char[] data)"
},
{
"code": null,
"e": 58142,
"s": 58062,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 58204,
"s": 58142,
"text": "static String copyValueOf(char[] data, int offset, int count)"
},
{
"code": null,
"e": 58284,
"s": 58204,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 58316,
"s": 58284,
"text": "boolean endsWith(String suffix)"
},
{
"code": null,
"e": 58369,
"s": 58316,
"text": "Tests if this string ends with the specified suffix."
},
{
"code": null,
"e": 58401,
"s": 58369,
"text": "boolean equals(Object anObject)"
},
{
"code": null,
"e": 58447,
"s": 58401,
"text": "Compares this string to the specified object."
},
{
"code": null,
"e": 58494,
"s": 58447,
"text": "boolean equalsIgnoreCase(String anotherString)"
},
{
"code": null,
"e": 58564,
"s": 58494,
"text": "Compares this String to another String, ignoring case considerations."
},
{
"code": null,
"e": 58580,
"s": 58564,
"text": "byte getBytes()"
},
{
"code": null,
"e": 58705,
"s": 58580,
"text": "Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array."
},
{
"code": null,
"e": 58741,
"s": 58705,
"text": "byte[] getBytes(String charsetName)"
},
{
"code": null,
"e": 58853,
"s": 58741,
"text": "Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array."
},
{
"code": null,
"e": 58919,
"s": 58853,
"text": "void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)"
},
{
"code": null,
"e": 58992,
"s": 58919,
"text": "Copies characters from this string into the destination character array."
},
{
"code": null,
"e": 59007,
"s": 58992,
"text": "int hashCode()"
},
{
"code": null,
"e": 59044,
"s": 59007,
"text": "Returns a hash code for this string."
},
{
"code": null,
"e": 59064,
"s": 59044,
"text": "int indexOf(int ch)"
},
{
"code": null,
"e": 59153,
"s": 59064,
"text": "Returns the index within this string of the first occurrence of the specified character."
},
{
"code": null,
"e": 59188,
"s": 59153,
"text": "int indexOf(int ch, int fromIndex)"
},
{
"code": null,
"e": 59321,
"s": 59188,
"text": "Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index."
},
{
"code": null,
"e": 59345,
"s": 59321,
"text": "int indexOf(String str)"
},
{
"code": null,
"e": 59434,
"s": 59345,
"text": "Returns the index within this string of the first occurrence of the specified substring."
},
{
"code": null,
"e": 59473,
"s": 59434,
"text": "int indexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 59595,
"s": 59473,
"text": "Returns the index within this string of the first occurrence of the specified substring, starting at the specified index."
},
{
"code": null,
"e": 59611,
"s": 59595,
"text": "String intern()"
},
{
"code": null,
"e": 59669,
"s": 59611,
"text": "Returns a canonical representation for the string object."
},
{
"code": null,
"e": 59693,
"s": 59669,
"text": "int lastIndexOf(int ch)"
},
{
"code": null,
"e": 59781,
"s": 59693,
"text": "Returns the index within this string of the last occurrence of the specified character."
},
{
"code": null,
"e": 59820,
"s": 59781,
"text": "int lastIndexOf(int ch, int fromIndex)"
},
{
"code": null,
"e": 59960,
"s": 59820,
"text": "Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index."
},
{
"code": null,
"e": 59988,
"s": 59960,
"text": "int lastIndexOf(String str)"
},
{
"code": null,
"e": 60081,
"s": 59988,
"text": "Returns the index within this string of the rightmost occurrence of the specified substring."
},
{
"code": null,
"e": 60124,
"s": 60081,
"text": "int lastIndexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 60264,
"s": 60124,
"text": "Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index."
},
{
"code": null,
"e": 60277,
"s": 60264,
"text": "int length()"
},
{
"code": null,
"e": 60312,
"s": 60277,
"text": "Returns the length of this string."
},
{
"code": null,
"e": 60342,
"s": 60312,
"text": "boolean matches(String regex)"
},
{
"code": null,
"e": 60413,
"s": 60342,
"text": "Tells whether or not this string matches the given regular expression."
},
{
"code": null,
"e": 60503,
"s": 60413,
"text": "boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)"
},
{
"code": null,
"e": 60542,
"s": 60503,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 60612,
"s": 60542,
"text": "boolean regionMatches(int toffset, String other, int offset, int len)"
},
{
"code": null,
"e": 60651,
"s": 60612,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 60694,
"s": 60651,
"text": "String replace(char oldChar, char newChar)"
},
{
"code": null,
"e": 60796,
"s": 60694,
"text": "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
},
{
"code": null,
"e": 60847,
"s": 60796,
"text": "String replaceAll(String regex, String replacement"
},
{
"code": null,
"e": 60956,
"s": 60847,
"text": "Replaces each substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 61010,
"s": 60956,
"text": "String replaceFirst(String regex, String replacement)"
},
{
"code": null,
"e": 61124,
"s": 61010,
"text": "Replaces the first substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 61153,
"s": 61124,
"text": "String[] split(String regex)"
},
{
"code": null,
"e": 61220,
"s": 61153,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 61260,
"s": 61220,
"text": "String[] split(String regex, int limit)"
},
{
"code": null,
"e": 61327,
"s": 61260,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 61361,
"s": 61327,
"text": "boolean startsWith(String prefix)"
},
{
"code": null,
"e": 61416,
"s": 61361,
"text": "Tests if this string starts with the specified prefix."
},
{
"code": null,
"e": 61463,
"s": 61416,
"text": "boolean startsWith(String prefix, int toffset)"
},
{
"code": null,
"e": 61546,
"s": 61463,
"text": "Tests if this string starts with the specified prefix beginning a specified index."
},
{
"code": null,
"e": 61601,
"s": 61546,
"text": "CharSequence subSequence(int beginIndex, int endIndex)"
},
{
"code": null,
"e": 61674,
"s": 61601,
"text": "Returns a new character sequence that is a subsequence of this sequence."
},
{
"code": null,
"e": 61707,
"s": 61674,
"text": "String substring(int beginIndex)"
},
{
"code": null,
"e": 61764,
"s": 61707,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 61811,
"s": 61764,
"text": "String substring(int beginIndex, int endIndex)"
},
{
"code": null,
"e": 61868,
"s": 61811,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 61889,
"s": 61868,
"text": "char[] toCharArray()"
},
{
"code": null,
"e": 61936,
"s": 61889,
"text": "Converts this string to a new character array."
},
{
"code": null,
"e": 61957,
"s": 61936,
"text": "String toLowerCase()"
},
{
"code": null,
"e": 62056,
"s": 61957,
"text": "Converts all of the characters in this String to lower case using the rules of the default locale."
},
{
"code": null,
"e": 62090,
"s": 62056,
"text": "String toLowerCase(Locale locale)"
},
{
"code": null,
"e": 62187,
"s": 62090,
"text": "Converts all of the characters in this String to lower case using the rules of the given Locale."
},
{
"code": null,
"e": 62205,
"s": 62187,
"text": "String toString()"
},
{
"code": null,
"e": 62266,
"s": 62205,
"text": "This object (which is already a string!) is itself returned."
},
{
"code": null,
"e": 62287,
"s": 62266,
"text": "String toUpperCase()"
},
{
"code": null,
"e": 62386,
"s": 62287,
"text": "Converts all of the characters in this String to upper case using the rules of the default locale."
},
{
"code": null,
"e": 62420,
"s": 62386,
"text": "String toUpperCase(Locale locale)"
},
{
"code": null,
"e": 62517,
"s": 62420,
"text": "Converts all of the characters in this String to upper case using the rules of the given Locale."
},
{
"code": null,
"e": 62531,
"s": 62517,
"text": "String trim()"
},
{
"code": null,
"e": 62607,
"s": 62531,
"text": "Returns a copy of the string, with leading and trailing whitespace omitted."
},
{
"code": null,
"e": 62652,
"s": 62607,
"text": "static String valueOf(primitive data type x)"
},
{
"code": null,
"e": 62720,
"s": 62652,
"text": "Returns the string representation of the passed data type argument."
},
{
"code": null,
"e": 62986,
"s": 62720,
"text": "Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 63464,
"s": 62986,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one."
},
{
"code": null,
"e": 63612,
"s": 63464,
"text": "To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference."
},
{
"code": null,
"e": 63673,
"s": 63612,
"text": "The following is the syntax for declaring an array variable."
},
{
"code": null,
"e": 63751,
"s": 63673,
"text": "var z:Array[String] = new Array[String](3)\n\nor\n\nvar z = new Array[String](3)\n"
},
{
"code": null,
"e": 63968,
"s": 63751,
"text": "Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following −"
},
{
"code": null,
"e": 64015,
"s": 63968,
"text": "z(0) = \"Zara\"; z(1) = \"Nuha\"; z(4/2) = \"Ayan\"\n"
},
{
"code": null,
"e": 64165,
"s": 64015,
"text": "Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array −"
},
{
"code": null,
"e": 64204,
"s": 64165,
"text": "var z = Array(\"Zara\", \"Nuha\", \"Ayan\")\n"
},
{
"code": null,
"e": 64320,
"s": 64204,
"text": "Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9."
},
{
"code": null,
"e": 64485,
"s": 64320,
"text": "When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known."
},
{
"code": null,
"e": 64571,
"s": 64485,
"text": "Below is an example program of showing how to create, initialize and process arrays −"
},
{
"code": null,
"e": 65166,
"s": 64571,
"text": "object Demo {\n def main(args: Array[String]) {\n var myList = Array(1.9, 2.9, 3.4, 3.5)\n \n // Print all the array elements\n for ( x <- myList ) {\n println( x )\n }\n\n // Summing all elements\n var total = 0.0;\n \n for ( i <- 0 to (myList.length - 1)) {\n total += myList(i);\n }\n println(\"Total is \" + total);\n\n // Finding the largest element\n var max = myList(0);\n \n for ( i <- 1 to (myList.length - 1) ) {\n if (myList(i) > max) max = myList(i);\n }\n \n println(\"Max is \" + max);\n }\n}"
},
{
"code": null,
"e": 65273,
"s": 65166,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 65307,
"s": 65273,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 65349,
"s": 65307,
"text": "1.9\n2.9\n3.4\n3.5\nTotal is 11.7\nMax is 3.5\n"
},
{
"code": null,
"e": 65559,
"s": 65349,
"text": "Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package."
},
{
"code": null,
"e": 65799,
"s": 65559,
"text": "There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays."
},
{
"code": null,
"e": 65866,
"s": 65799,
"text": "The following is the example of defining a two-dimensional array −"
},
{
"code": null,
"e": 65897,
"s": 65866,
"text": "var myMatrix = ofDim[Int](3,3)"
},
{
"code": null,
"e": 65995,
"s": 65897,
"text": "This is an array that has three elements each being an array of integers that has three elements."
},
{
"code": null,
"e": 66068,
"s": 65995,
"text": "Try the following example program to process a multi-dimensional array −"
},
{
"code": null,
"e": 66495,
"s": 66068,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myMatrix = ofDim[Int](3,3)\n \n // build a matrix\n for (i <- 0 to 2) {\n for ( j <- 0 to 2) {\n myMatrix(i)(j) = j;\n }\n }\n \n // Print two dimensional array\n for (i <- 0 to 2) {\n for ( j <- 0 to 2) {\n print(\" \" + myMatrix(i)(j));\n }\n println();\n }\n }\n}"
},
{
"code": null,
"e": 66602,
"s": 66495,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 66636,
"s": 66602,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 66655,
"s": 66636,
"text": "0 1 2\n0 1 2\n0 1 2\n"
},
{
"code": null,
"e": 66809,
"s": 66655,
"text": "Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method."
},
{
"code": null,
"e": 67125,
"s": 66809,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myList1 = Array(1.9, 2.9, 3.4, 3.5)\n var myList2 = Array(8.9, 7.9, 0.4, 1.5)\n\n var myList3 = concat( myList1, myList2)\n \n // Print all the array elements\n for ( x <- myList3 ) {\n println( x )\n }\n }\n}"
},
{
"code": null,
"e": 67232,
"s": 67125,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 67266,
"s": 67232,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 67299,
"s": 67266,
"text": "1.9\n2.9\n3.4\n3.5\n8.9\n7.9\n0.4\n1.5\n"
},
{
"code": null,
"e": 67531,
"s": 67299,
"text": "Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1."
},
{
"code": null,
"e": 67730,
"s": 67531,
"text": "Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18."
},
{
"code": null,
"e": 67972,
"s": 67730,
"text": "Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19."
},
{
"code": null,
"e": 68044,
"s": 67972,
"text": "The following example program shows how to create an array with ranges."
},
{
"code": null,
"e": 68374,
"s": 68044,
"text": "import Array._\n\nobject Demo {\n def main(args: Array[String]) {\n var myList1 = range(10, 20, 2)\n var myList2 = range(10,20)\n\n // Print all the array elements\n for ( x <- myList1 ) {\n print( \" \" + x )\n }\n \n println()\n for ( x <- myList2 ) {\n print( \" \" + x )\n }\n }\n}"
},
{
"code": null,
"e": 68481,
"s": 68374,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 68515,
"s": 68481,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 68561,
"s": 68515,
"text": "10 12 14 16 18\n10 11 12 13 14 15 16 17 18 19\n"
},
{
"code": null,
"e": 68830,
"s": 68561,
"text": "Following are the important methods, which you can use while playing with array. As shown above, you would have to import Array._ package before using any of the mentioned methods. For a complete list of methods available, please check official documentation of Scala."
},
{
"code": null,
"e": 68866,
"s": 68830,
"text": "def apply( x: T, xs: T* ): Array[T]"
},
{
"code": null,
"e": 68972,
"s": 68866,
"text": "Creates an array of T objects, where T can be Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean."
},
{
"code": null,
"e": 69014,
"s": 68972,
"text": "def concat[T]( xss: Array[T]* ): Array[T]"
},
{
"code": null,
"e": 69059,
"s": 69014,
"text": "Concatenates all arrays into a single array."
},
{
"code": null,
"e": 69143,
"s": 69059,
"text": "def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit"
},
{
"code": null,
"e": 69245,
"s": 69143,
"text": "Copy one array to another. Equivalent to Java's System.arraycopy(src, srcPos, dest, destPos, length)."
},
{
"code": null,
"e": 69268,
"s": 69245,
"text": "def empty[T]: Array[T]"
},
{
"code": null,
"e": 69297,
"s": 69268,
"text": "Returns an array of length 0"
},
{
"code": null,
"e": 69359,
"s": 69297,
"text": "def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]"
},
{
"code": null,
"e": 69441,
"s": 69359,
"text": "Returns an array containing repeated applications of a function to a start value."
},
{
"code": null,
"e": 69486,
"s": 69441,
"text": "def fill[T]( n: Int )(elem: => T): Array[T]"
},
{
"code": null,
"e": 69576,
"s": 69486,
"text": "Returns an array that contains the results of some element computation a number of times."
},
{
"code": null,
"e": 69639,
"s": 69576,
"text": "def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]"
},
{
"code": null,
"e": 69744,
"s": 69639,
"text": "Returns a two-dimensional array that contains the results of some element computation a number of times."
},
{
"code": null,
"e": 69805,
"s": 69744,
"text": "def iterate[T]( start: T, len: Int)( f: (T) => T ): Array[T]"
},
{
"code": null,
"e": 69887,
"s": 69805,
"text": "Returns an array containing repeated applications of a function to a start value."
},
{
"code": null,
"e": 69921,
"s": 69887,
"text": "def ofDim[T]( n1: Int ): Array[T]"
},
{
"code": null,
"e": 69958,
"s": 69921,
"text": "Creates array with given dimensions."
},
{
"code": null,
"e": 70008,
"s": 69958,
"text": "def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]"
},
{
"code": null,
"e": 70038,
"s": 70008,
"text": "Creates a 2-dimensional array"
},
{
"code": null,
"e": 70104,
"s": 70038,
"text": "def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]"
},
{
"code": null,
"e": 70134,
"s": 70104,
"text": "Creates a 3-dimensional array"
},
{
"code": null,
"e": 70191,
"s": 70134,
"text": "def range( start: Int, end: Int, step: Int ): Array[Int]"
},
{
"code": null,
"e": 70267,
"s": 70191,
"text": "Returns an array containing equally spaced values in some integer interval."
},
{
"code": null,
"e": 70313,
"s": 70267,
"text": "def range( start: Int, end: Int ): Array[Int]"
},
{
"code": null,
"e": 70387,
"s": 70313,
"text": "Returns an array containing a sequence of increasing integers in a range."
},
{
"code": null,
"e": 70437,
"s": 70387,
"text": "def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]"
},
{
"code": null,
"e": 70540,
"s": 70437,
"text": "Returns an array containing values of a given function over a range of integer values starting from 0."
},
{
"code": null,
"e": 70615,
"s": 70540,
"text": "def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]"
},
{
"code": null,
"e": 70732,
"s": 70615,
"text": "Returns a two-dimensional array containing values of a given function over ranges of integer values starting from 0."
},
{
"code": null,
"e": 71016,
"s": 70732,
"text": "Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option)."
},
{
"code": null,
"e": 71361,
"s": 71016,
"text": "Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items."
},
{
"code": null,
"e": 71576,
"s": 71361,
"text": "For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones."
},
{
"code": null,
"e": 71705,
"s": 71576,
"text": "This chapter throws light on the most commonly used collection types and most frequently used operations over those collections."
},
{
"code": null,
"e": 71717,
"s": 71705,
"text": "Scala Lists"
},
{
"code": null,
"e": 71761,
"s": 71717,
"text": "Scala's List[T] is a linked list of type T."
},
{
"code": null,
"e": 71772,
"s": 71761,
"text": "Scala Sets"
},
{
"code": null,
"e": 71843,
"s": 71772,
"text": "A set is a collection of pairwise different elements of the same type."
},
{
"code": null,
"e": 71854,
"s": 71843,
"text": "Scala Maps"
},
{
"code": null,
"e": 71941,
"s": 71854,
"text": "A Map is a collection of key/value pairs. Any value can be retrieved based on its key."
},
{
"code": null,
"e": 71954,
"s": 71941,
"text": "Scala Tuples"
},
{
"code": null,
"e": 72026,
"s": 71954,
"text": "Unlike an array or list, a tuple can hold objects with different types."
},
{
"code": null,
"e": 72040,
"s": 72026,
"text": "Scala Options"
},
{
"code": null,
"e": 72112,
"s": 72040,
"text": "Option[T] provides a container for zero or one element of a given type."
},
{
"code": null,
"e": 72128,
"s": 72112,
"text": "Scala Iterators"
},
{
"code": null,
"e": 72229,
"s": 72128,
"text": "An iterator is not a collection, but rather a way to access the elements of a collection one by one."
},
{
"code": null,
"e": 72460,
"s": 72229,
"text": "A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits."
},
{
"code": null,
"e": 72654,
"s": 72460,
"text": "Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters."
},
{
"code": null,
"e": 72799,
"s": 72654,
"text": "A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait."
},
{
"code": null,
"e": 72897,
"s": 72799,
"text": "trait Equal {\n def isEqual(x: Any): Boolean\n def isNotEqual(x: Any): Boolean = !isEqual(x)\n}\n"
},
{
"code": null,
"e": 73216,
"s": 72897,
"text": "This trait consists of two methods isEqual and isNotEqual. Here, we have not given any implementation for isEqual where as another method has its implementation. Child classes extending a trait can give implementation for the un-implemented methods. So a trait is very similar to what we have abstract classes in Java."
},
{
"code": null,
"e": 73497,
"s": 73216,
"text": "Let us assume an example of trait Equal contain two methods isEqual() and isNotEqual(). The trait Equal contain one implemented method that is isEqual() so when user defined class Point extends the trait Equal, implementation to isEqual() method in Point class should be provided."
},
{
"code": null,
"e": 73597,
"s": 73497,
"text": "Here it is required to know two important method of Scala, which are used in the following example."
},
{
"code": null,
"e": 73671,
"s": 73597,
"text": "obj.isInstanceOf [Point] To check Type of obj and Point are same are not."
},
{
"code": null,
"e": 73745,
"s": 73671,
"text": "obj.isInstanceOf [Point] To check Type of obj and Point are same are not."
},
{
"code": null,
"e": 73860,
"s": 73745,
"text": "obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type."
},
{
"code": null,
"e": 73975,
"s": 73860,
"text": "obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type."
},
{
"code": null,
"e": 74030,
"s": 73975,
"text": "Try the following example program to implement traits."
},
{
"code": null,
"e": 74552,
"s": 74030,
"text": "trait Equal {\n def isEqual(x: Any): Boolean\n def isNotEqual(x: Any): Boolean = !isEqual(x)\n}\n\nclass Point(xc: Int, yc: Int) extends Equal {\n var x: Int = xc\n var y: Int = yc\n \n def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y\n}\n\nobject Demo {\n def main(args: Array[String]) {\n val p1 = new Point(2, 3)\n val p2 = new Point(2, 4)\n val p3 = new Point(3, 3)\n\n println(p1.isNotEqual(p2))\n println(p1.isNotEqual(p3))\n println(p1.isNotEqual(2))\n }\n}"
},
{
"code": null,
"e": 74659,
"s": 74552,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 74693,
"s": 74659,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 74710,
"s": 74693,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 75121,
"s": 74710,
"text": "Value classes are new mechanism in Scala to avoid allocating runtime objects. It contains a primary constructor with exactly one val parameter. It contains only methods (def) not allowed var, val, nested classes, traits, or objects. Value class cannot be extended by another class. This can be possible by extending your value class with AnyVal. The typesafety of custom datatypes without the runtime overhead."
},
{
"code": null,
"e": 75276,
"s": 75121,
"text": "Let us take an examples of value classes Weight, Height, Email, Age, etc. For all these examples it is not required to allocate memory in the application."
},
{
"code": null,
"e": 75417,
"s": 75276,
"text": "A value class not allowed to extend traits. To permit value classes to extend traits, universal traits are introduced which extends for Any."
},
{
"code": null,
"e": 75707,
"s": 75417,
"text": "trait Printable extends Any {\n def print(): Unit = println(this)\n}\nclass Wrapper(val underlying: Int) extends AnyVal with Printable\n\nobject Demo {\n def main(args: Array[String]) {\n val w = new Wrapper(3)\n w.print() // actually requires instantiating a Wrapper instance\n }\n}"
},
{
"code": null,
"e": 75814,
"s": 75707,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 75848,
"s": 75814,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 75897,
"s": 75848,
"text": "It will give you the hash code of Wrapper class."
},
{
"code": null,
"e": 75909,
"s": 75897,
"text": "Wrapper@13\n"
},
{
"code": null,
"e": 75974,
"s": 75909,
"text": "There is no firm rule, but here are few guidelines to consider −"
},
{
"code": null,
"e": 76080,
"s": 75974,
"text": "If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all."
},
{
"code": null,
"e": 76186,
"s": 76080,
"text": "If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all."
},
{
"code": null,
"e": 76327,
"s": 76186,
"text": "If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy."
},
{
"code": null,
"e": 76468,
"s": 76327,
"text": "If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy."
},
{
"code": null,
"e": 76536,
"s": 76468,
"text": "If you want to inherit from it in Java code, use an abstract class."
},
{
"code": null,
"e": 76604,
"s": 76536,
"text": "If you want to inherit from it in Java code, use an abstract class."
},
{
"code": null,
"e": 76766,
"s": 76604,
"text": "If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class."
},
{
"code": null,
"e": 76928,
"s": 76766,
"text": "If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class."
},
{
"code": null,
"e": 76989,
"s": 76928,
"text": "If efficiency is very important, lean towards using a class."
},
{
"code": null,
"e": 77050,
"s": 76989,
"text": "If efficiency is very important, lean towards using a class."
},
{
"code": null,
"e": 77231,
"s": 77050,
"text": "Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages."
},
{
"code": null,
"e": 77497,
"s": 77231,
"text": "A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions."
},
{
"code": null,
"e": 77583,
"s": 77497,
"text": "Try the following example program, which shows how to match against an integer value."
},
{
"code": null,
"e": 77788,
"s": 77583,
"text": "object Demo {\n def main(args: Array[String]) {\n println(matchTest(3))\n }\n \n def matchTest(x: Int): String = x match {\n case 1 => \"one\"\n case 2 => \"two\"\n case _ => \"many\"\n }\n}"
},
{
"code": null,
"e": 77895,
"s": 77788,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 77929,
"s": 77895,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 77935,
"s": 77929,
"text": "many\n"
},
{
"code": null,
"e": 78146,
"s": 77935,
"text": "The block with the case statements defines a function, which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object."
},
{
"code": null,
"e": 78240,
"s": 78146,
"text": "Try the following example program, which matches a value against patterns of different types."
},
{
"code": null,
"e": 78540,
"s": 78240,
"text": "object Demo {\n def main(args: Array[String]) {\n println(matchTest(\"two\"))\n println(matchTest(\"test\"))\n println(matchTest(1))\n }\n \n def matchTest(x: Any): Any = x match {\n case 1 => \"one\"\n case \"two\" => 2\n case y: Int => \"scala.Int\"\n case _ => \"many\"\n }\n}"
},
{
"code": null,
"e": 78647,
"s": 78540,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 78681,
"s": 78647,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 78693,
"s": 78681,
"text": "2\nmany\none\n"
},
{
"code": null,
"e": 78860,
"s": 78693,
"text": "The case classes are special classes that are used in pattern matching with case expressions. Syntactically, these are standard classes with a special modifier: case."
},
{
"code": null,
"e": 78937,
"s": 78860,
"text": "Try the following, it is a simple pattern matching example using case class."
},
{
"code": null,
"e": 79487,
"s": 78937,
"text": "object Demo {\n def main(args: Array[String]) {\n val alice = new Person(\"Alice\", 25)\n val bob = new Person(\"Bob\", 32)\n val charlie = new Person(\"Charlie\", 32)\n \n for (person <- List(alice, bob, charlie)) {\n person match {\n case Person(\"Alice\", 25) => println(\"Hi Alice!\")\n case Person(\"Bob\", 32) => println(\"Hi Bob!\")\n case Person(name, age) => println(\n \"Age: \" + age + \" year, name: \" + name + \"?\")\n }\n }\n }\n case class Person(name: String, age: Int)\n}"
},
{
"code": null,
"e": 79594,
"s": 79487,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 79628,
"s": 79594,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 79676,
"s": 79628,
"text": "Hi Alice!\nHi Bob!\nAge: 32 year, name: Charlie?\n"
},
{
"code": null,
"e": 79849,
"s": 79676,
"text": "Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching."
},
{
"code": null,
"e": 80078,
"s": 79849,
"text": "First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional. If you want mutable fields, use the var keyword. So, our constructor argument lists are now shorter."
},
{
"code": null,
"e": 80284,
"s": 80078,
"text": "Second, the compiler automatically implements equals, hashCode, and toString methods to the class, which use the fields specified as constructor arguments. So, we no longer need our own toString() methods."
},
{
"code": null,
"e": 80391,
"s": 80284,
"text": "Finally, also, the body of Person class becomes empty because there are no methods that we need to define!"
},
{
"code": null,
"e": 80518,
"s": 80391,
"text": "This chapter explains how Scala supports regular expressions through Regex class available in the scala.util.matching package."
},
{
"code": null,
"e": 80611,
"s": 80518,
"text": "Try the following example program where we will try to find out word Scala from a statement."
},
{
"code": null,
"e": 80822,
"s": 80611,
"text": "import scala.util.matching.Regex\n\nobject Demo {\n def main(args: Array[String]) {\n val pattern = \"Scala\".r\n val str = \"Scala is Scalable and cool\"\n \n println(pattern findFirstIn str)\n }\n}"
},
{
"code": null,
"e": 80929,
"s": 80822,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 80963,
"s": 80929,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 80976,
"s": 80963,
"text": "Some(Scala)\n"
},
{
"code": null,
"e": 81491,
"s": 80976,
"text": "We create a String and call the r( ) method on it. Scala implicitly converts the String to a RichString and invokes that method to get an instance of Regex. To find a first match of the regular expression, simply call the findFirstIn() method. If instead of finding only the first occurrence we would like to find all occurrences of the matching word, we can use the findAllIn( ) method and in case there are multiple Scala words available in the target string, this will return a collection of all matching words."
},
{
"code": null,
"e": 81714,
"s": 81491,
"text": "You can make use of the mkString( ) method to concatenate the resulting list and you can use a pipe (|) to search small and capital case of Scala and you can use Regex constructor instead or r() method to create a pattern."
},
{
"code": null,
"e": 81749,
"s": 81714,
"text": "Try the following example program."
},
{
"code": null,
"e": 81987,
"s": 81749,
"text": "import scala.util.matching.Regex\n\nobject Demo {\n def main(args: Array[String]) {\n val pattern = new Regex(\"(S|s)cala\")\n val str = \"Scala is scalable and cool\"\n \n println((pattern findAllIn str).mkString(\",\"))\n }\n}"
},
{
"code": null,
"e": 82094,
"s": 81987,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 82128,
"s": 82094,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 82141,
"s": 82128,
"text": "Scala,scala\n"
},
{
"code": null,
"e": 82289,
"s": 82141,
"text": "If you would like to replace matching text, we can use replaceFirstIn( ) to replace the first match or replaceAllIn( ) to replace all occurrences."
},
{
"code": null,
"e": 82482,
"s": 82289,
"text": "object Demo {\n def main(args: Array[String]) {\n val pattern = \"(S|s)cala\".r\n val str = \"Scala is scalable and cool\"\n \n println(pattern replaceFirstIn(str, \"Java\"))\n }\n}"
},
{
"code": null,
"e": 82589,
"s": 82482,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 82623,
"s": 82589,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 82650,
"s": 82623,
"text": "Java is scalable and cool\n"
},
{
"code": null,
"e": 82825,
"s": 82650,
"text": "Scala inherits its regular expression syntax from Java, which in turn inherits most of the features of Perl. Here are just some examples that should be enough as refreshers −"
},
{
"code": null,
"e": 82929,
"s": 82825,
"text": "Following is the table listing down all the regular expression Meta character syntax available in Java."
},
{
"code": null,
"e": 83225,
"s": 82929,
"text": "Note − that every backslash appears twice in the string above. This is because in Java and Scala a single backslash is an escape character in a string literal, not a regular character that shows up in the string. So instead of ‘\\’, you need to write ‘\\\\’ to get a single backslash in the string."
},
{
"code": null,
"e": 83260,
"s": 83225,
"text": "Try the following example program."
},
{
"code": null,
"e": 83497,
"s": 83260,
"text": "import scala.util.matching.Regex\n\nobject Demo {\n def main(args: Array[String]) {\n val pattern = new Regex(\"abl[ae]\\\\d+\")\n val str = \"ablaw is able1 and cool\"\n \n println((pattern findAllIn str).mkString(\",\"))\n }\n}"
},
{
"code": null,
"e": 83604,
"s": 83497,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 83638,
"s": 83604,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 83645,
"s": 83638,
"text": "able1\n"
},
{
"code": null,
"e": 83874,
"s": 83645,
"text": "Scala's exceptions work like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn't actually have checked exceptions."
},
{
"code": null,
"e": 84049,
"s": 83874,
"text": "When you want to handle exceptions, you use a try{...}catch{...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions."
},
{
"code": null,
"e": 84186,
"s": 84049,
"text": "Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows."
},
{
"code": null,
"e": 84222,
"s": 84186,
"text": "throw new IllegalArgumentException\n"
},
{
"code": null,
"e": 84403,
"s": 84222,
"text": "Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle exception."
},
{
"code": null,
"e": 84824,
"s": 84403,
"text": "import java.io.FileReader\nimport java.io.FileNotFoundException\nimport java.io.IOException\n\nobject Demo {\n def main(args: Array[String]) {\n try {\n val f = new FileReader(\"input.txt\")\n } catch {\n case ex: FileNotFoundException =>{\n println(\"Missing file exception\")\n }\n \n case ex: IOException => {\n println(\"IO Exception\")\n }\n }\n }\n}"
},
{
"code": null,
"e": 84931,
"s": 84824,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 84965,
"s": 84931,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 84989,
"s": 84965,
"text": "Missing file exception\n"
},
{
"code": null,
"e": 85171,
"s": 84989,
"text": "The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn."
},
{
"code": null,
"e": 85330,
"s": 85171,
"text": "You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates. Try the following program."
},
{
"code": null,
"e": 85809,
"s": 85330,
"text": "import java.io.FileReader\nimport java.io.FileNotFoundException\nimport java.io.IOException\n\nobject Demo {\n def main(args: Array[String]) {\n try {\n val f = new FileReader(\"input.txt\")\n } catch {\n case ex: FileNotFoundException => {\n println(\"Missing file exception\")\n }\n \n case ex: IOException => {\n println(\"IO Exception\")\n }\n } finally {\n println(\"Exiting finally...\")\n }\n }\n}"
},
{
"code": null,
"e": 85916,
"s": 85809,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 85950,
"s": 85916,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 85993,
"s": 85950,
"text": "Missing file exception\nExiting finally...\n"
},
{
"code": null,
"e": 86266,
"s": 85993,
"text": "An extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match a value and take it apart. Often, the extractor object also defines a dual method apply for building values, but this is not required."
},
{
"code": null,
"e": 86588,
"s": 86266,
"text": "Let us take an example of object defines both apply and unapply methods. The apply method has the same meaning as always: it turns Test into an object that can be applied to arguments in parentheses in the same way a method is applied. So you can write Test (\"Zara\", \"gmail.com\") to construct the string \"Zara@gmail.com\"."
},
{
"code": null,
"e": 86886,
"s": 86588,
"text": "The unapply method is what turns Test class into an extractor and it reverses the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply takes an email address and returns potentially two strings: the user and the domain of the address."
},
{
"code": null,
"e": 87230,
"s": 86886,
"text": "The unapply must also handle the case where the given string is not an email address. That's why unapply returns an Option-type over pairs of strings. Its result is either Some (user, domain) if the string str is an email address with the given user and domain parts, or None, if str is not an email address. Here are some examples as follows."
},
{
"code": null,
"e": 87322,
"s": 87230,
"text": "unapply(\"Zara@gmail.com\") equals Some(\"Zara\", \"gmail.com\")\nunapply(\"Zara Ali\") equals None\n"
},
{
"code": null,
"e": 87395,
"s": 87322,
"text": "Following example program shows an extractor object for email addresses."
},
{
"code": null,
"e": 88002,
"s": 87395,
"text": "object Demo {\n def main(args: Array[String]) {\n println (\"Apply method : \" + apply(\"Zara\", \"gmail.com\"));\n println (\"Unapply method : \" + unapply(\"Zara@gmail.com\"));\n println (\"Unapply method : \" + unapply(\"Zara Ali\"));\n }\n \n // The injection method (optional)\n def apply(user: String, domain: String) = {\n user +\"@\"+ domain\n }\n\n // The extraction method (mandatory)\n def unapply(str: String): Option[(String, String)] = {\n val parts = str split \"@\"\n \n if (parts.length == 2){\n Some(parts(0), parts(1)) \n } else {\n None\n }\n }\n}"
},
{
"code": null,
"e": 88109,
"s": 88002,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 88143,
"s": 88109,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 88236,
"s": 88143,
"text": "Apply method : Zara@gmail.com\nUnapply method : Some((Zara,gmail.com))\nUnapply method : None\n"
},
{
"code": null,
"e": 88439,
"s": 88236,
"text": "When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method on that instance. We can define apply both in objects and in classes."
},
{
"code": null,
"e": 88699,
"s": 88439,
"text": "As mentioned above, the purpose of the unapply method is to extract a specific value we are looking for. It does the opposite operation apply does. When comparing an extractor object using the match statement the unapply method will be automatically executed."
},
{
"code": null,
"e": 88734,
"s": 88699,
"text": "Try the following example program."
},
{
"code": null,
"e": 89111,
"s": 88734,
"text": "object Demo {\n def main(args: Array[String]) {\n val x = Demo(5)\n println(x)\n\n x match {\n case Demo(num) => println(x+\" is bigger two times than \"+num)\n \n //unapply is invoked\n case _ => println(\"i cannot calculate\")\n }\n }\n def apply(x: Int) = x*2\n def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None\n}"
},
{
"code": null,
"e": 89218,
"s": 89111,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 89252,
"s": 89218,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 89286,
"s": 89252,
"text": "10\n10 is bigger two times than 5\n"
},
{
"code": null,
"e": 89435,
"s": 89286,
"text": "Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files."
},
{
"code": null,
"e": 89493,
"s": 89435,
"text": "The following is an example program to writing to a file."
},
{
"code": null,
"e": 89681,
"s": 89493,
"text": "import java.io._\n\nobject Demo {\n def main(args: Array[String]) {\n val writer = new PrintWriter(new File(\"test.txt\" ))\n\n writer.write(\"Hello Scala\")\n writer.close()\n }\n}"
},
{
"code": null,
"e": 89788,
"s": 89681,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 89822,
"s": 89788,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 89957,
"s": 89822,
"text": "It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file."
},
{
"code": null,
"e": 89970,
"s": 89957,
"text": "Hello Scala\n"
},
{
"code": null,
"e": 90146,
"s": 89970,
"text": "Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line."
},
{
"code": null,
"e": 90335,
"s": 90146,
"text": "object Demo {\n def main(args: Array[String]) {\n print(\"Please enter your input : \" )\n val line = Console.readLine\n \n println(\"Thanks, you just typed: \" + line)\n }\n}"
},
{
"code": null,
"e": 90442,
"s": 90335,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 90476,
"s": 90442,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 90557,
"s": 90476,
"text": "Please enter your input : Scala is great\nThanks, you just typed: Scala is great\n"
},
{
"code": null,
"e": 90767,
"s": 90557,
"text": "Reading from files is really simple. You can use Scala's Source class and its companion object to read files. Following is the example which shows you how to read from \"Demo.txt\" file which we created earlier."
},
{
"code": null,
"e": 90967,
"s": 90767,
"text": "import scala.io.Source\n\nobject Demo {\n def main(args: Array[String]) {\n println(\"Following is the content read:\" )\n\n Source.fromFile(\"Demo.txt\" ).foreach { \n print \n }\n }\n}"
},
{
"code": null,
"e": 91074,
"s": 90967,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 91108,
"s": 91074,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 91152,
"s": 91108,
"text": "Following is the content read:\nHello Scala\n"
},
{
"code": null,
"e": 91185,
"s": 91152,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 91204,
"s": 91185,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 91239,
"s": 91204,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 91260,
"s": 91239,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 91295,
"s": 91260,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 91313,
"s": 91295,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 91348,
"s": 91313,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 91366,
"s": 91348,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 91401,
"s": 91366,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 91419,
"s": 91401,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 91454,
"s": 91419,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 91477,
"s": 91454,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 91484,
"s": 91477,
"text": " Print"
},
{
"code": null,
"e": 91495,
"s": 91484,
"text": " Add Notes"
}
] |
Modernize Your Sinful Python Code with Beautiful Type Hints | by Eirik Berge | Towards Data Science
|
Setting the StageUnderstanding Dynamic Types and Static TypesPython Type Hints for VariablesChecking Type Hints with MypyPython Type Hints for FunctionsHow to Add Lists as Type HintsFive Awesome Type Hints to Power Up Your CodeWhy All The Cool Kids Use Python 3.9+Wrapping Up and Further Resources
Setting the Stage
Understanding Dynamic Types and Static Types
Python Type Hints for Variables
Checking Type Hints with Mypy
Python Type Hints for Functions
How to Add Lists as Type Hints
Five Awesome Type Hints to Power Up Your Code
Why All The Cool Kids Use Python 3.9+
Wrapping Up and Further Resources
In the 2020 Developer Survey by Stack Overflow, Python took the top spot in the category “programming languages developers want to learn”. In spite of this, Python has drawbacks that annoy supporters and feed critics. One of the drawbacks that are often mentioned is the following:
Python has dynamic types. This increases debugging time and makes the behaviour of variables and functions unpredictable.
Although dynamic types are convenient for rapid prototyping, they can become an annoyance in larger projects. This is where type hinting comes into play: It is possible since the release of Python 3.5 to emulate static types in Python by writing type hints! ❤️
Another advantage of writing type hints is that they improve code quality. When I say code quality, most people think of descriptive variable names and well-written docstrings. Writing type hints is a modern addition for improving your code quality in Python.
In this article, I will show YOU how to use type hints to supercharge your Python code!
Goals: I will teach you the basics of type hinting in Python. After the basics, I will show you five more awesome type hints to power up your Python code. Finally, I will explain how type hints recently became less of a hassle with the introduction of Python 3.9.
Prerequisites: You should be familiar with the basics of Python. Make sure that the Python version you are running is higher than Python 3.5. No prerequisites on dynamic types, static types, or type hints are necessary.
First of all, I should explain the terms dynamic types and static types. In Python, you can change the data type of a variable as many times as you want throughout the program:
Notice from the code snippet above that:
I don’t specify the data type of the variable my_variable when defining it.
I can change the data type of the variable my_variable throughout the Python program.
In short, Python has dynamic types.
In some programming languages (for example Java) you need to specify the data type of a variable at creation. Moreover, the data type of a variable can not change later in the program. We say that such programming languages have static types.
Programming in a language with static types might seem like a burden. Yet, debugging a programming language with static types is often less cumbersome. With static types, you can find errors earlier and fix them with minimal effort.
To put it simply:
This is your face when debugging with dynamic types 😢
This is your face when debugging with static types 😎
I will show you how to emulate static types in Python with type hints!
Fun fact: Dynamic typing is sometimes called duck typing. The terminology comes from the well-known saying: “If it walks like a duck and it quacks like a duck, then it must be a duck.”
I will begin with the following application of type hints:
Type hints allow you to specify data types for variables.
Since code snippets speak louder than words, take a look at the following example:
I have, with the power of type hints, specified that my_variable should be an integer. That was not too bad! 😃
You can use standard data types such as float, bool, and string for type hints as well. The following code snippet records some useful features of a car:
If you try to run the above code snippet in a script, then Python has no complaints. Everything seems peachy! However, this does not tell you that Python checks that the assigned types are correct. In fact, try to run the following code:
What!? Python does not give any errors with the wrong type hint 😧
This is because Python, although it understands the syntax of type hints, does not care about it at all.
You will need to use an external type checker to check that the type hints match the provided variables. An external type checker is often an external Python module. I will show you how to use the mypy module for external type checking. Don’t worry, mypy is easy to use!
The one-line description of mypy is as follows:
If you sprinkle your code with type hints, mypy can type check your code and find common bugs.
To install mypy, use PIP (Package Installer for Python) with the command:
pip install mypy
If this did not work, then check out the documentation for installation help. Create a file called simple_type_hint.py with the following line of code:
Open up your terminal and navigate to the folder where you created the file simple_type_hint.py. Then run the command:
python -m mypy simple_type_hint.py
This should display the message:
Success: no issues found in 1 source file
It seems like mypy is okay with everything written so far. I now want to intentionally break the type hint to see what happens 😈
Add the following line of code to simple_type_hint.py:
In the above code snippet, I have specified with a type hint that my_variable should be an integer. Even so, I later break the type hint by assigning a string to my_variable.
If you run the file simple_type_hint.py as a Python program, then there is no error displayed as usual. However, try to use mypy with the command:
python -m mypy simple_type_hint.py
This should display something like the following message:
simple_type_hint.py:5: error: Incompatible types in assignment (expression has type “str”, variable has type “int”)Found 1 error in 1 file (checked 1 source file)
Unlike Python, mypy detects what is wrong. The error message above specifies both the line number (in my case 5) and the precise problem that occurs.
It feels great to have a working example, no matter how simple 🔥
Fun Fact: At mypy’s GitHub Page, there is an issue from 2019 (Issue #6740) suggesting that mypy should stop referring to itself as alpha software. The term alpha software refers to software in the pre-release/early version stage. The creator of Python, Guido van Rossum, steps into the discussion to set things straight:
“We're being very self-deprecating here. I would not hesitate calling mypy production quality, i.e. beyond beta.” — Guide van Rossum
Most Python programs have plenty of functions in them. I will now show you how to work with type hints for functions.
In an empty file with the name simple_function.py I wrote the following simple function:
The function both_divisible_by_two accepts two integers as inputs. It then checks whether both of them are divisible by two. Pretty straightforward, right? Now I add type hints to the function both_divisible_by_two:
Notice that only the first line of both_divisible_by_two has changed:
I wrote a: int and b: int to indicate that the inputs a and b of both_divisible_by_two should be integers.
To indicate that the output of both_divisible_by_two is a Boolean value I use the syntax -> bool.
If you now run the usual command
python -m mypy simple_funciton.py
then you should get the pleasant output
Success: no issues found in 1 source file.
Look great! It is always a good sanity check to see whether mypy reacts if you intentionally make a wrong type hint. To try this out, I alter both_divisible_by_two as follows:
If you again run the command
python -m mypy simple_funciton.py
then you should roughly get the error message
simple_function.py:4: error: Incompatible return value type (got "bool", expected "str")Found 1 error in 1 file (checked 1 source file)
It works! 😃
Hint: If you change the type hint for the output to int in both_divisible_by_two then mypy would give no errors. Do you understand why? It has to due with a subtle implementation detail in Python: The Boolean class bool is a subclass of the integer class int under the identification
0 <-> False and 1 <-> True.
Hence Boolean values “are” integers in Python. Keep this detail in mind when you are working with type hints!
We’ve seen how to add basic type hints to a function. How would you type hint that a variable should be a list? Unfortunately, the obvious approach (to write list) is not valid in Python version 3.8 and lower 😒
You actually need to reach into the built-in module typing to grab the type hint for a list. Let me open a new file called list_type_hints.py and start the file with the line:
Notice that List is capitalized. Create a function called append_element that appends a value to a given list:
So far, so good. The function append_element would crash if passed a dictionary for the data parameter. To ensure this, you can add type hints as follows:
If you run mypy on the file list_type_hints.py with the command
python -m mypy list_type_hints.py
then mypy reports the following:
list_type_hints.py:5: error: “append” of “list” does not return a valueFound 1 error in 1 file (checked 1 source file)
What is this? It seems like mypy has found an error in our code 😱
What is the problem? Scrutinize mypy’s response above before continuing.
Solution: The list method append modifies lists in place but returns None. Hence the statement
return data.append(value)
will always return the same as
return None
To fix the code, you should make the following simple edit:
It is awesome to find the problem right away! Here type hints found an error that the usual Python interpreter would not alert you about 😎
The type hints have the added benefit that they document the code better. It is now clear in append_element that data should be a list. I could also have used a more descriptive variable name than data. Descriptive variable names and type hints can both improve the quality of the code.
So far, the elements in the list passed into append_element can be of any type. It can for instance be a list of integers, a list of strings, or a list consisting of both integers and strings. If I only want to accept a list of integers, then I can change the code as follows:
Notice that I have exchanged the type hint List with the more specific type hint List[int]. Now the list input and list output can only contain integers!
Hint: In the typing module, there are other container data types like dictionaries Dict and tuples Tuple. I invite you to check these out whenever you need them.
You are now familiar with the basics of type hinting in Python. It is hence time to learn some more advanced features. I will show you five awesome type hints that will supercharge your Python code 🐍
It is sometimes too restrictive to require that a variable or function argument should be a List. In fact, as long as iteration is possible, the type is often acceptable. For this situation, you can use the Iterable type hint. Consider the following print_everything function:
Calling the function print_everything on anything that supports iteration (for example lists, tuples, strings) is now possible.
Hint: In Python, a function that does not have an explicit return statement returns by default None. This is the reason why I have added the -> None type hint for the output of the function print_everything.
Python is a programming language that supports higher-order functions. A consequence of this is that you can pass functions as arguments to other functions. Consider the following wrapper_print function:
The attribute __name__ gives the name of the function. Notice that both the input and the output of wrapper_print are functions. I can specify this as a type hint by using the Callable type hint:
When trying to understand what a callable is, you frequently run into the saying “A callable is anything that can be called.” 😑
If you are unsure, then Python has the built-in function callable to the rescue. The function callable checks whether something is callable or not. In everyday coding, it’s for the most part functions you should have in mind when specifying Callable as a type hint.
Hint: Rest assured that functions (both stand-alone functions and class methods) are callable. Conversely, rest assured that none of the data types int, float, bool, str, None, list, dict, tuple, or set are callable. An interesting example of a callable is an instance of a class that has the dunder method __call__.
Sometimes, requiring that a variable or function argument could only be of a single type is too restrictive. A common example is a variable that could be both an integer and a floating-point number. Consider the type hint
It is conceivable that hourly_wage could also be an integer. You can use the Union type hint to specify many type hints:
Inside Union, specify each appropriate type for the variable separated by commas. Notice that there is a trade-off situation here: By adding many type hints with Union you get more flexibility. However, as your type hints get more flexible they also become less useful.
Hint: In Python 3.10, there is a brand new syntax that is available: Instead of Union you can use the operator | to separate different type hints. Hence we can exchange Union[int, float] with int | float in Python 3.10+.
Most companies as of today are not yet using Python 3.10. Hence I would recommend getting familiar with the classical syntax by using Union.
Commonly, certain arguments in functions are by default set to None. Consider, as an example, the following lowercase_playlist function:
In lowercase_playlist the songs parameter is set to None by default. If no value is provided for songs, then songs is set to a list containing the single song “Everything is awesome!”. Finally, we return the lowercase versions of the songs by using a list comprehension.
You could write Union[List, None] to provide an input type hint for lowercase_playlist. However, this is so common that there is the special shorthand syntax Optional[List]:
Hint: You should NOT use mutable objects (such as a list) for default arguments in functions. Doing this often leads to annoying bugs. I recommend Chapter 8 of Al Sweigart’s new book Beyond the Basic Stuff with Python for more on this problem.
Finally, you can provide a catch-all type hint with Any. The Python documentation simply states:
Any — Special type indicating an unconstrained type. Every type is compatible with Any. Any is compatible with every type.
Why do you need Any when you can omit type hints? 😕
The main use for Any is, in my opinion, to show to other developers that the lack of a restrictive type hint is a conscious choice. If you simply did not specify a type hint, then other developers could start to wonder:
Did Mark forget to add a type hint here? Is he being sloppy? Hm...
Be attentive to your fellow developers and use the Any type hint whenever appropriate.
Before Python 3.9, you needed to import List and Dict from the typing module if you wanted to provide those type hints.
In Python 3.9 there is finally native support for lists and dictionary type hints. That means that you DON’T need to use the typing module to import List and Dict for type hinting. In Python 3.9+ you can use the lowercase list and dict for type hints:
Hint: Before Python 3.9, you had to capitalize List and Dict when importing them from the typing module. This is to avoid overriding the built-in list() and dict() constructor functions. In Python 3.9+ you can safely use the lowercase versions list and dict for type hints without overwriting anything.
Ahh! The only thing better than fewer imports is syntax consistency 😍
In this article, I have gone through type hints in Python. Type hints are a modern way to sneak in some of that sweet static typing into your Python code.
There is no better place for the knowledge-hungry Pythonista to start than PEP484. Moreover, the cool people at mypy have made an awesome cheat sheet.
Hint: You can incorporate type hints bit by bit in your projects. There is no problem having part of the code statically typed, while the rest is dynamically typed.
If you like my writing, then check out my other blog posts such as Learn Some Front-End Web Development as a Data Scientist and 5 Awesome NumPy Functions That Can Save You in a Pinch. If you are interested in data science, programming, or anything in between, feel free to add me on LinkedIn and say hi ✋
|
[
{
"code": null,
"e": 470,
"s": 172,
"text": "Setting the StageUnderstanding Dynamic Types and Static TypesPython Type Hints for VariablesChecking Type Hints with MypyPython Type Hints for FunctionsHow to Add Lists as Type HintsFive Awesome Type Hints to Power Up Your CodeWhy All The Cool Kids Use Python 3.9+Wrapping Up and Further Resources"
},
{
"code": null,
"e": 488,
"s": 470,
"text": "Setting the Stage"
},
{
"code": null,
"e": 533,
"s": 488,
"text": "Understanding Dynamic Types and Static Types"
},
{
"code": null,
"e": 565,
"s": 533,
"text": "Python Type Hints for Variables"
},
{
"code": null,
"e": 595,
"s": 565,
"text": "Checking Type Hints with Mypy"
},
{
"code": null,
"e": 627,
"s": 595,
"text": "Python Type Hints for Functions"
},
{
"code": null,
"e": 658,
"s": 627,
"text": "How to Add Lists as Type Hints"
},
{
"code": null,
"e": 704,
"s": 658,
"text": "Five Awesome Type Hints to Power Up Your Code"
},
{
"code": null,
"e": 742,
"s": 704,
"text": "Why All The Cool Kids Use Python 3.9+"
},
{
"code": null,
"e": 776,
"s": 742,
"text": "Wrapping Up and Further Resources"
},
{
"code": null,
"e": 1058,
"s": 776,
"text": "In the 2020 Developer Survey by Stack Overflow, Python took the top spot in the category “programming languages developers want to learn”. In spite of this, Python has drawbacks that annoy supporters and feed critics. One of the drawbacks that are often mentioned is the following:"
},
{
"code": null,
"e": 1180,
"s": 1058,
"text": "Python has dynamic types. This increases debugging time and makes the behaviour of variables and functions unpredictable."
},
{
"code": null,
"e": 1441,
"s": 1180,
"text": "Although dynamic types are convenient for rapid prototyping, they can become an annoyance in larger projects. This is where type hinting comes into play: It is possible since the release of Python 3.5 to emulate static types in Python by writing type hints! ❤️"
},
{
"code": null,
"e": 1701,
"s": 1441,
"text": "Another advantage of writing type hints is that they improve code quality. When I say code quality, most people think of descriptive variable names and well-written docstrings. Writing type hints is a modern addition for improving your code quality in Python."
},
{
"code": null,
"e": 1789,
"s": 1701,
"text": "In this article, I will show YOU how to use type hints to supercharge your Python code!"
},
{
"code": null,
"e": 2053,
"s": 1789,
"text": "Goals: I will teach you the basics of type hinting in Python. After the basics, I will show you five more awesome type hints to power up your Python code. Finally, I will explain how type hints recently became less of a hassle with the introduction of Python 3.9."
},
{
"code": null,
"e": 2273,
"s": 2053,
"text": "Prerequisites: You should be familiar with the basics of Python. Make sure that the Python version you are running is higher than Python 3.5. No prerequisites on dynamic types, static types, or type hints are necessary."
},
{
"code": null,
"e": 2450,
"s": 2273,
"text": "First of all, I should explain the terms dynamic types and static types. In Python, you can change the data type of a variable as many times as you want throughout the program:"
},
{
"code": null,
"e": 2491,
"s": 2450,
"text": "Notice from the code snippet above that:"
},
{
"code": null,
"e": 2567,
"s": 2491,
"text": "I don’t specify the data type of the variable my_variable when defining it."
},
{
"code": null,
"e": 2653,
"s": 2567,
"text": "I can change the data type of the variable my_variable throughout the Python program."
},
{
"code": null,
"e": 2689,
"s": 2653,
"text": "In short, Python has dynamic types."
},
{
"code": null,
"e": 2932,
"s": 2689,
"text": "In some programming languages (for example Java) you need to specify the data type of a variable at creation. Moreover, the data type of a variable can not change later in the program. We say that such programming languages have static types."
},
{
"code": null,
"e": 3165,
"s": 2932,
"text": "Programming in a language with static types might seem like a burden. Yet, debugging a programming language with static types is often less cumbersome. With static types, you can find errors earlier and fix them with minimal effort."
},
{
"code": null,
"e": 3183,
"s": 3165,
"text": "To put it simply:"
},
{
"code": null,
"e": 3237,
"s": 3183,
"text": "This is your face when debugging with dynamic types 😢"
},
{
"code": null,
"e": 3290,
"s": 3237,
"text": "This is your face when debugging with static types 😎"
},
{
"code": null,
"e": 3361,
"s": 3290,
"text": "I will show you how to emulate static types in Python with type hints!"
},
{
"code": null,
"e": 3546,
"s": 3361,
"text": "Fun fact: Dynamic typing is sometimes called duck typing. The terminology comes from the well-known saying: “If it walks like a duck and it quacks like a duck, then it must be a duck.”"
},
{
"code": null,
"e": 3605,
"s": 3546,
"text": "I will begin with the following application of type hints:"
},
{
"code": null,
"e": 3663,
"s": 3605,
"text": "Type hints allow you to specify data types for variables."
},
{
"code": null,
"e": 3746,
"s": 3663,
"text": "Since code snippets speak louder than words, take a look at the following example:"
},
{
"code": null,
"e": 3857,
"s": 3746,
"text": "I have, with the power of type hints, specified that my_variable should be an integer. That was not too bad! 😃"
},
{
"code": null,
"e": 4011,
"s": 3857,
"text": "You can use standard data types such as float, bool, and string for type hints as well. The following code snippet records some useful features of a car:"
},
{
"code": null,
"e": 4249,
"s": 4011,
"text": "If you try to run the above code snippet in a script, then Python has no complaints. Everything seems peachy! However, this does not tell you that Python checks that the assigned types are correct. In fact, try to run the following code:"
},
{
"code": null,
"e": 4315,
"s": 4249,
"text": "What!? Python does not give any errors with the wrong type hint 😧"
},
{
"code": null,
"e": 4420,
"s": 4315,
"text": "This is because Python, although it understands the syntax of type hints, does not care about it at all."
},
{
"code": null,
"e": 4691,
"s": 4420,
"text": "You will need to use an external type checker to check that the type hints match the provided variables. An external type checker is often an external Python module. I will show you how to use the mypy module for external type checking. Don’t worry, mypy is easy to use!"
},
{
"code": null,
"e": 4739,
"s": 4691,
"text": "The one-line description of mypy is as follows:"
},
{
"code": null,
"e": 4834,
"s": 4739,
"text": "If you sprinkle your code with type hints, mypy can type check your code and find common bugs."
},
{
"code": null,
"e": 4908,
"s": 4834,
"text": "To install mypy, use PIP (Package Installer for Python) with the command:"
},
{
"code": null,
"e": 4925,
"s": 4908,
"text": "pip install mypy"
},
{
"code": null,
"e": 5077,
"s": 4925,
"text": "If this did not work, then check out the documentation for installation help. Create a file called simple_type_hint.py with the following line of code:"
},
{
"code": null,
"e": 5196,
"s": 5077,
"text": "Open up your terminal and navigate to the folder where you created the file simple_type_hint.py. Then run the command:"
},
{
"code": null,
"e": 5231,
"s": 5196,
"text": "python -m mypy simple_type_hint.py"
},
{
"code": null,
"e": 5264,
"s": 5231,
"text": "This should display the message:"
},
{
"code": null,
"e": 5306,
"s": 5264,
"text": "Success: no issues found in 1 source file"
},
{
"code": null,
"e": 5435,
"s": 5306,
"text": "It seems like mypy is okay with everything written so far. I now want to intentionally break the type hint to see what happens 😈"
},
{
"code": null,
"e": 5490,
"s": 5435,
"text": "Add the following line of code to simple_type_hint.py:"
},
{
"code": null,
"e": 5665,
"s": 5490,
"text": "In the above code snippet, I have specified with a type hint that my_variable should be an integer. Even so, I later break the type hint by assigning a string to my_variable."
},
{
"code": null,
"e": 5812,
"s": 5665,
"text": "If you run the file simple_type_hint.py as a Python program, then there is no error displayed as usual. However, try to use mypy with the command:"
},
{
"code": null,
"e": 5847,
"s": 5812,
"text": "python -m mypy simple_type_hint.py"
},
{
"code": null,
"e": 5905,
"s": 5847,
"text": "This should display something like the following message:"
},
{
"code": null,
"e": 6068,
"s": 5905,
"text": "simple_type_hint.py:5: error: Incompatible types in assignment (expression has type “str”, variable has type “int”)Found 1 error in 1 file (checked 1 source file)"
},
{
"code": null,
"e": 6218,
"s": 6068,
"text": "Unlike Python, mypy detects what is wrong. The error message above specifies both the line number (in my case 5) and the precise problem that occurs."
},
{
"code": null,
"e": 6283,
"s": 6218,
"text": "It feels great to have a working example, no matter how simple 🔥"
},
{
"code": null,
"e": 6604,
"s": 6283,
"text": "Fun Fact: At mypy’s GitHub Page, there is an issue from 2019 (Issue #6740) suggesting that mypy should stop referring to itself as alpha software. The term alpha software refers to software in the pre-release/early version stage. The creator of Python, Guido van Rossum, steps into the discussion to set things straight:"
},
{
"code": null,
"e": 6737,
"s": 6604,
"text": "“We're being very self-deprecating here. I would not hesitate calling mypy production quality, i.e. beyond beta.” — Guide van Rossum"
},
{
"code": null,
"e": 6855,
"s": 6737,
"text": "Most Python programs have plenty of functions in them. I will now show you how to work with type hints for functions."
},
{
"code": null,
"e": 6944,
"s": 6855,
"text": "In an empty file with the name simple_function.py I wrote the following simple function:"
},
{
"code": null,
"e": 7160,
"s": 6944,
"text": "The function both_divisible_by_two accepts two integers as inputs. It then checks whether both of them are divisible by two. Pretty straightforward, right? Now I add type hints to the function both_divisible_by_two:"
},
{
"code": null,
"e": 7230,
"s": 7160,
"text": "Notice that only the first line of both_divisible_by_two has changed:"
},
{
"code": null,
"e": 7337,
"s": 7230,
"text": "I wrote a: int and b: int to indicate that the inputs a and b of both_divisible_by_two should be integers."
},
{
"code": null,
"e": 7435,
"s": 7337,
"text": "To indicate that the output of both_divisible_by_two is a Boolean value I use the syntax -> bool."
},
{
"code": null,
"e": 7468,
"s": 7435,
"text": "If you now run the usual command"
},
{
"code": null,
"e": 7502,
"s": 7468,
"text": "python -m mypy simple_funciton.py"
},
{
"code": null,
"e": 7542,
"s": 7502,
"text": "then you should get the pleasant output"
},
{
"code": null,
"e": 7585,
"s": 7542,
"text": "Success: no issues found in 1 source file."
},
{
"code": null,
"e": 7761,
"s": 7585,
"text": "Look great! It is always a good sanity check to see whether mypy reacts if you intentionally make a wrong type hint. To try this out, I alter both_divisible_by_two as follows:"
},
{
"code": null,
"e": 7790,
"s": 7761,
"text": "If you again run the command"
},
{
"code": null,
"e": 7824,
"s": 7790,
"text": "python -m mypy simple_funciton.py"
},
{
"code": null,
"e": 7870,
"s": 7824,
"text": "then you should roughly get the error message"
},
{
"code": null,
"e": 8006,
"s": 7870,
"text": "simple_function.py:4: error: Incompatible return value type (got \"bool\", expected \"str\")Found 1 error in 1 file (checked 1 source file)"
},
{
"code": null,
"e": 8018,
"s": 8006,
"text": "It works! 😃"
},
{
"code": null,
"e": 8302,
"s": 8018,
"text": "Hint: If you change the type hint for the output to int in both_divisible_by_two then mypy would give no errors. Do you understand why? It has to due with a subtle implementation detail in Python: The Boolean class bool is a subclass of the integer class int under the identification"
},
{
"code": null,
"e": 8330,
"s": 8302,
"text": "0 <-> False and 1 <-> True."
},
{
"code": null,
"e": 8440,
"s": 8330,
"text": "Hence Boolean values “are” integers in Python. Keep this detail in mind when you are working with type hints!"
},
{
"code": null,
"e": 8651,
"s": 8440,
"text": "We’ve seen how to add basic type hints to a function. How would you type hint that a variable should be a list? Unfortunately, the obvious approach (to write list) is not valid in Python version 3.8 and lower 😒"
},
{
"code": null,
"e": 8827,
"s": 8651,
"text": "You actually need to reach into the built-in module typing to grab the type hint for a list. Let me open a new file called list_type_hints.py and start the file with the line:"
},
{
"code": null,
"e": 8938,
"s": 8827,
"text": "Notice that List is capitalized. Create a function called append_element that appends a value to a given list:"
},
{
"code": null,
"e": 9093,
"s": 8938,
"text": "So far, so good. The function append_element would crash if passed a dictionary for the data parameter. To ensure this, you can add type hints as follows:"
},
{
"code": null,
"e": 9157,
"s": 9093,
"text": "If you run mypy on the file list_type_hints.py with the command"
},
{
"code": null,
"e": 9191,
"s": 9157,
"text": "python -m mypy list_type_hints.py"
},
{
"code": null,
"e": 9224,
"s": 9191,
"text": "then mypy reports the following:"
},
{
"code": null,
"e": 9343,
"s": 9224,
"text": "list_type_hints.py:5: error: “append” of “list” does not return a valueFound 1 error in 1 file (checked 1 source file)"
},
{
"code": null,
"e": 9409,
"s": 9343,
"text": "What is this? It seems like mypy has found an error in our code 😱"
},
{
"code": null,
"e": 9482,
"s": 9409,
"text": "What is the problem? Scrutinize mypy’s response above before continuing."
},
{
"code": null,
"e": 9577,
"s": 9482,
"text": "Solution: The list method append modifies lists in place but returns None. Hence the statement"
},
{
"code": null,
"e": 9603,
"s": 9577,
"text": "return data.append(value)"
},
{
"code": null,
"e": 9634,
"s": 9603,
"text": "will always return the same as"
},
{
"code": null,
"e": 9646,
"s": 9634,
"text": "return None"
},
{
"code": null,
"e": 9706,
"s": 9646,
"text": "To fix the code, you should make the following simple edit:"
},
{
"code": null,
"e": 9845,
"s": 9706,
"text": "It is awesome to find the problem right away! Here type hints found an error that the usual Python interpreter would not alert you about 😎"
},
{
"code": null,
"e": 10132,
"s": 9845,
"text": "The type hints have the added benefit that they document the code better. It is now clear in append_element that data should be a list. I could also have used a more descriptive variable name than data. Descriptive variable names and type hints can both improve the quality of the code."
},
{
"code": null,
"e": 10409,
"s": 10132,
"text": "So far, the elements in the list passed into append_element can be of any type. It can for instance be a list of integers, a list of strings, or a list consisting of both integers and strings. If I only want to accept a list of integers, then I can change the code as follows:"
},
{
"code": null,
"e": 10563,
"s": 10409,
"text": "Notice that I have exchanged the type hint List with the more specific type hint List[int]. Now the list input and list output can only contain integers!"
},
{
"code": null,
"e": 10725,
"s": 10563,
"text": "Hint: In the typing module, there are other container data types like dictionaries Dict and tuples Tuple. I invite you to check these out whenever you need them."
},
{
"code": null,
"e": 10925,
"s": 10725,
"text": "You are now familiar with the basics of type hinting in Python. It is hence time to learn some more advanced features. I will show you five awesome type hints that will supercharge your Python code 🐍"
},
{
"code": null,
"e": 11202,
"s": 10925,
"text": "It is sometimes too restrictive to require that a variable or function argument should be a List. In fact, as long as iteration is possible, the type is often acceptable. For this situation, you can use the Iterable type hint. Consider the following print_everything function:"
},
{
"code": null,
"e": 11330,
"s": 11202,
"text": "Calling the function print_everything on anything that supports iteration (for example lists, tuples, strings) is now possible."
},
{
"code": null,
"e": 11538,
"s": 11330,
"text": "Hint: In Python, a function that does not have an explicit return statement returns by default None. This is the reason why I have added the -> None type hint for the output of the function print_everything."
},
{
"code": null,
"e": 11742,
"s": 11538,
"text": "Python is a programming language that supports higher-order functions. A consequence of this is that you can pass functions as arguments to other functions. Consider the following wrapper_print function:"
},
{
"code": null,
"e": 11938,
"s": 11742,
"text": "The attribute __name__ gives the name of the function. Notice that both the input and the output of wrapper_print are functions. I can specify this as a type hint by using the Callable type hint:"
},
{
"code": null,
"e": 12066,
"s": 11938,
"text": "When trying to understand what a callable is, you frequently run into the saying “A callable is anything that can be called.” 😑"
},
{
"code": null,
"e": 12332,
"s": 12066,
"text": "If you are unsure, then Python has the built-in function callable to the rescue. The function callable checks whether something is callable or not. In everyday coding, it’s for the most part functions you should have in mind when specifying Callable as a type hint."
},
{
"code": null,
"e": 12649,
"s": 12332,
"text": "Hint: Rest assured that functions (both stand-alone functions and class methods) are callable. Conversely, rest assured that none of the data types int, float, bool, str, None, list, dict, tuple, or set are callable. An interesting example of a callable is an instance of a class that has the dunder method __call__."
},
{
"code": null,
"e": 12871,
"s": 12649,
"text": "Sometimes, requiring that a variable or function argument could only be of a single type is too restrictive. A common example is a variable that could be both an integer and a floating-point number. Consider the type hint"
},
{
"code": null,
"e": 12992,
"s": 12871,
"text": "It is conceivable that hourly_wage could also be an integer. You can use the Union type hint to specify many type hints:"
},
{
"code": null,
"e": 13262,
"s": 12992,
"text": "Inside Union, specify each appropriate type for the variable separated by commas. Notice that there is a trade-off situation here: By adding many type hints with Union you get more flexibility. However, as your type hints get more flexible they also become less useful."
},
{
"code": null,
"e": 13483,
"s": 13262,
"text": "Hint: In Python 3.10, there is a brand new syntax that is available: Instead of Union you can use the operator | to separate different type hints. Hence we can exchange Union[int, float] with int | float in Python 3.10+."
},
{
"code": null,
"e": 13624,
"s": 13483,
"text": "Most companies as of today are not yet using Python 3.10. Hence I would recommend getting familiar with the classical syntax by using Union."
},
{
"code": null,
"e": 13761,
"s": 13624,
"text": "Commonly, certain arguments in functions are by default set to None. Consider, as an example, the following lowercase_playlist function:"
},
{
"code": null,
"e": 14032,
"s": 13761,
"text": "In lowercase_playlist the songs parameter is set to None by default. If no value is provided for songs, then songs is set to a list containing the single song “Everything is awesome!”. Finally, we return the lowercase versions of the songs by using a list comprehension."
},
{
"code": null,
"e": 14206,
"s": 14032,
"text": "You could write Union[List, None] to provide an input type hint for lowercase_playlist. However, this is so common that there is the special shorthand syntax Optional[List]:"
},
{
"code": null,
"e": 14450,
"s": 14206,
"text": "Hint: You should NOT use mutable objects (such as a list) for default arguments in functions. Doing this often leads to annoying bugs. I recommend Chapter 8 of Al Sweigart’s new book Beyond the Basic Stuff with Python for more on this problem."
},
{
"code": null,
"e": 14547,
"s": 14450,
"text": "Finally, you can provide a catch-all type hint with Any. The Python documentation simply states:"
},
{
"code": null,
"e": 14670,
"s": 14547,
"text": "Any — Special type indicating an unconstrained type. Every type is compatible with Any. Any is compatible with every type."
},
{
"code": null,
"e": 14722,
"s": 14670,
"text": "Why do you need Any when you can omit type hints? 😕"
},
{
"code": null,
"e": 14942,
"s": 14722,
"text": "The main use for Any is, in my opinion, to show to other developers that the lack of a restrictive type hint is a conscious choice. If you simply did not specify a type hint, then other developers could start to wonder:"
},
{
"code": null,
"e": 15009,
"s": 14942,
"text": "Did Mark forget to add a type hint here? Is he being sloppy? Hm..."
},
{
"code": null,
"e": 15096,
"s": 15009,
"text": "Be attentive to your fellow developers and use the Any type hint whenever appropriate."
},
{
"code": null,
"e": 15216,
"s": 15096,
"text": "Before Python 3.9, you needed to import List and Dict from the typing module if you wanted to provide those type hints."
},
{
"code": null,
"e": 15468,
"s": 15216,
"text": "In Python 3.9 there is finally native support for lists and dictionary type hints. That means that you DON’T need to use the typing module to import List and Dict for type hinting. In Python 3.9+ you can use the lowercase list and dict for type hints:"
},
{
"code": null,
"e": 15771,
"s": 15468,
"text": "Hint: Before Python 3.9, you had to capitalize List and Dict when importing them from the typing module. This is to avoid overriding the built-in list() and dict() constructor functions. In Python 3.9+ you can safely use the lowercase versions list and dict for type hints without overwriting anything."
},
{
"code": null,
"e": 15841,
"s": 15771,
"text": "Ahh! The only thing better than fewer imports is syntax consistency 😍"
},
{
"code": null,
"e": 15996,
"s": 15841,
"text": "In this article, I have gone through type hints in Python. Type hints are a modern way to sneak in some of that sweet static typing into your Python code."
},
{
"code": null,
"e": 16147,
"s": 15996,
"text": "There is no better place for the knowledge-hungry Pythonista to start than PEP484. Moreover, the cool people at mypy have made an awesome cheat sheet."
},
{
"code": null,
"e": 16312,
"s": 16147,
"text": "Hint: You can incorporate type hints bit by bit in your projects. There is no problem having part of the code statically typed, while the rest is dynamically typed."
}
] |
HTML <del> Tag - GeeksforGeeks
|
17 Mar, 2022
The <del> tag in HTML stands for delete and is used to mark a portion of text which has been deleted from the document. The deleted text is rendered as strike-through text by the web browsers although this property can be changed using CSS text-decoration property. The <del> tag requires a starting and ending tag.
Attributes: The <del> tag contains two attributes which are listed below:
cite: It is used to specify the URL of the document or message which denotes the reason for deleting the text.
datetime: It is used to specify the date and time of the deleted text.
Syntax:
<del> Contents... </del>
Example 1: Below example illustrate the <del> element in HTML:
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML del Tag</h2> <!-- HTML del tag is used in paragraph Tag --> <p>GeeksforGeeks is a <del>mathematical</del> science portal</p> </body></html>
Output:
Example 2: This example use the <del> tag with the datetime attribute.
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML del Tag</h2> <!-- HTML del tag is used in paragraph Tag --> <p>GeeksforGeeks is a <del>mathematical</del> science portal</p> </body></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox 1 and above
Opera
Safari
Edge
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubhamyadav4
ManasChhabra2
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
|
[
{
"code": null,
"e": 22720,
"s": 22692,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 23036,
"s": 22720,
"text": "The <del> tag in HTML stands for delete and is used to mark a portion of text which has been deleted from the document. The deleted text is rendered as strike-through text by the web browsers although this property can be changed using CSS text-decoration property. The <del> tag requires a starting and ending tag."
},
{
"code": null,
"e": 23111,
"s": 23036,
"text": "Attributes: The <del> tag contains two attributes which are listed below: "
},
{
"code": null,
"e": 23222,
"s": 23111,
"text": "cite: It is used to specify the URL of the document or message which denotes the reason for deleting the text."
},
{
"code": null,
"e": 23293,
"s": 23222,
"text": "datetime: It is used to specify the date and time of the deleted text."
},
{
"code": null,
"e": 23301,
"s": 23293,
"text": "Syntax:"
},
{
"code": null,
"e": 23326,
"s": 23301,
"text": "<del> Contents... </del>"
},
{
"code": null,
"e": 23389,
"s": 23326,
"text": "Example 1: Below example illustrate the <del> element in HTML:"
},
{
"code": null,
"e": 23394,
"s": 23389,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML del Tag</h2> <!-- HTML del tag is used in paragraph Tag --> <p>GeeksforGeeks is a <del>mathematical</del> science portal</p> </body></html> ",
"e": 23664,
"s": 23394,
"text": null
},
{
"code": null,
"e": 23674,
"s": 23664,
"text": "Output: "
},
{
"code": null,
"e": 23747,
"s": 23674,
"text": "Example 2: This example use the <del> tag with the datetime attribute. "
},
{
"code": null,
"e": 23752,
"s": 23747,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML del Tag</h2> <!-- HTML del tag is used in paragraph Tag --> <p>GeeksforGeeks is a <del>mathematical</del> science portal</p> </body></html> ",
"e": 24022,
"s": 23752,
"text": null
},
{
"code": null,
"e": 24032,
"s": 24022,
"text": "Output: "
},
{
"code": null,
"e": 24053,
"s": 24032,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 24068,
"s": 24053,
"text": "Google Chrome "
},
{
"code": null,
"e": 24086,
"s": 24068,
"text": "Internet Explorer"
},
{
"code": null,
"e": 24106,
"s": 24086,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 24113,
"s": 24106,
"text": "Opera "
},
{
"code": null,
"e": 24121,
"s": 24113,
"text": "Safari "
},
{
"code": null,
"e": 24127,
"s": 24121,
"text": "Edge "
},
{
"code": null,
"e": 24264,
"s": 24127,
"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": 24278,
"s": 24264,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 24292,
"s": 24278,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 24302,
"s": 24292,
"text": "HTML-Tags"
},
{
"code": null,
"e": 24307,
"s": 24302,
"text": "HTML"
},
{
"code": null,
"e": 24312,
"s": 24307,
"text": "HTML"
},
{
"code": null,
"e": 24410,
"s": 24312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24419,
"s": 24410,
"text": "Comments"
},
{
"code": null,
"e": 24432,
"s": 24419,
"text": "Old Comments"
},
{
"code": null,
"e": 24494,
"s": 24432,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 24544,
"s": 24494,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 24604,
"s": 24544,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 24652,
"s": 24604,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 24713,
"s": 24652,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 24766,
"s": 24713,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 24803,
"s": 24766,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 24853,
"s": 24803,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 24903,
"s": 24853,
"text": "CSS to put icon inside an input element in a form"
}
] |
Concurrency in Python - Multiprocessing
|
In this chapter, we will focus more on the comparison between multiprocessing and multithreading.
It is the use of two or more CPUs units within a single computer system. It is the best approach to get the full potential from our hardware by utilizing full number of CPU cores available in our computer system.
It is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads.
The following table shows some of the important differences between them −
While working with concurrent applications, there is a limitation present in Python called the GIL (Global Interpreter Lock). GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. GIL is the mutex – mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first.
With the use of multiprocessing, we can effectively bypass the limitation caused by GIL −
By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL.
By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL.
Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time.
Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time.
The following three methods can be used to start a process in Python within the multiprocessing module −
Fork
Spawn
Forkserver
Fork command is a standard command found in UNIX. It is used to create new processes called child processes. This child process runs concurrently with the process called the parent process. These child processes are also identical to their parent processes and inherit all of the resources available to the parent. The following system calls are used while creating a process with Fork −
fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>
fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>
getpid() − This system call returns the process ID(PID) of the calling process.
getpid() − This system call returns the process ID(PID) of the calling process.
The following Python script example will help you understabd how to create a new child process and get the PIDs of child and parent processes −
import os
def child():
n = os.fork()
if n > 0:
print("PID of Parent process is : ", os.getpid())
else:
print("PID of Child process is : ", os.getpid())
child()
PID of Parent process is : 25989
PID of Child process is : 25990
Spawn means to start something new. Hence, spawning a process means the creation of a new process by a parent process. The parent process continues its execution asynchronously or waits until the child process ends its execution. Follow these steps for spawning a process −
Importing multiprocessing module.
Importing multiprocessing module.
Creating the object process.
Creating the object process.
Starting the process activity by calling start() method.
Starting the process activity by calling start() method.
Waiting until the process has finished its work and exit by calling join() method.
Waiting until the process has finished its work and exit by calling join() method.
The following example of Python script helps in spawning three processes
import multiprocessing
def spawn_process(i):
print ('This is process: %s' %i)
return
if __name__ == '__main__':
Process_jobs = []
for i in range(3):
p = multiprocessing.Process(target = spawn_process, args = (i,))
Process_jobs.append(p)
p.start()
p.join()
This is process: 0
This is process: 1
This is process: 2
Forkserver mechanism is only available on those selected UNIX platforms that support passing the file descriptors over Unix Pipes. Consider the following points to understand the working of Forkserver mechanism −
A server is instantiated on using Forkserver mechanism for starting new process.
A server is instantiated on using Forkserver mechanism for starting new process.
The server then receives the command and handles all the requests for creating new processes.
The server then receives the command and handles all the requests for creating new processes.
For creating a new process, our python program will send a request to Forkserver and it will create a process for us.
For creating a new process, our python program will send a request to Forkserver and it will create a process for us.
At last, we can use this new created process in our programs.
At last, we can use this new created process in our programs.
Python multiprocessing module allows us to have daemon processes through its daemonic option. Daemon processes or the processes that are running in the background follow similar concept as the daemon threads. To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.
Here, we are using the same example as used in the daemon threads. The only difference is the change of module from multithreading to multiprocessing and setting the daemonic flag to true. However, there would be a change in output as shown below −
import multiprocessing
import time
def nondaemonProcess():
print("starting my Process")
time.sleep(8)
print("ending my Process")
def daemonProcess():
while True:
print("Hello")
time.sleep(2)
if __name__ == '__main__':
nondaemonProcess = multiprocessing.Process(target = nondaemonProcess)
daemonProcess = multiprocessing.Process(target = daemonProcess)
daemonProcess.daemon = True
nondaemonProcess.daemon = False
daemonProcess.start()
nondaemonProcess.start()
starting my Process
ending my Process
The output is different when compared to the one generated by daemon threads, because the process in no daemon mode have an output. Hence, the daemonic process ends automatically after the main programs end to avoid the persistence of running processes.
We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution.
import multiprocessing
import time
def Child_process():
print ('Starting function')
time.sleep(5)
print ('Finished function')
P = multiprocessing.Process(target = Child_process)
P.start()
print("My Process has terminated, terminating main thread")
print("Terminating Child Process")
P.terminate()
print("Child Process successfully terminated")
My Process has terminated, terminating main thread
Terminating Child Process
Child Process successfully terminated
The output shows that the program terminates before the execution of child process that has been created with the help of the Child_process() function. This implies that the child process has been terminated successfully.
Every process in the operating system is having process identity known as PID. In Python, we can find out the PID of current process with the help of the following command −
import multiprocessing
print(multiprocessing.current_process().pid)
The following example of Python script helps find out the PID of main process as well as PID of child process −
import multiprocessing
import time
def Child_process():
print("PID of Child Process is: {}".format(multiprocessing.current_process().pid))
print("PID of Main process is: {}".format(multiprocessing.current_process().pid))
P = multiprocessing.Process(target=Child_process)
P.start()
P.join()
PID of Main process is: 9401
PID of Child Process is: 9402
We can create threads by sub-classing the threading.Thread class. In addition, we can also create processes by sub-classing the multiprocessing.Process class. For using a process in subclass, we need to consider the following points −
We need to define a new subclass of the Process class.
We need to define a new subclass of the Process class.
We need to override the _init_(self [,args] ) class.
We need to override the _init_(self [,args] ) class.
We need to override the of the run(self [,args] ) method to implement what Process
We need to override the of the run(self [,args] ) method to implement what Process
We need to start the process by invoking thestart() method.
We need to start the process by invoking thestart() method.
import multiprocessing
class MyProcess(multiprocessing.Process):
def run(self):
print ('called run method in process: %s' %self.name)
return
if __name__ == '__main__':
jobs = []
for i in range(5):
P = MyProcess()
jobs.append(P)
P.start()
P.join()
called run method in process: MyProcess-1
called run method in process: MyProcess-2
called run method in process: MyProcess-3
called run method in process: MyProcess-4
called run method in process: MyProcess-5
If we talk about simple parallel processing tasks in our Python applications, then multiprocessing module provide us the Pool class. The following methods of Pool class can be used to spin up number of child processes within our main program
This method is similar to the.submit()method of .ThreadPoolExecutor.It blocks until the result is ready.
When we need parallel execution of our tasks then we need to use theapply_async()method to submit tasks to the pool. It is an asynchronous operation that will not lock the main thread until all the child processes are executed.
Just like the apply() method, it also blocks until the result is ready. It is equivalent to the built-in map() function that splits the iterable data in a number of chunks and submits to the process pool as separate tasks.
It is a variant of the map() method as apply_async() is to the apply() method. It returns a result object. When the result becomes ready, a callable is applied to it. The callable must be completed immediately; otherwise, the thread that handles the results will get blocked.
The following example will help you implement a process pool for performing parallel execution. A simple calculation of square of number has been performed by applying the square() function through the multiprocessing.Pool method. Then pool.map() has been used to submit the 5, because input is a list of integers from 0 to 4. The result would be stored in p_outputs and it is printed.
def square(n):
result = n*n
return result
if __name__ == '__main__':
inputs = list(range(5))
p = multiprocessing.Pool(processes = 4)
p_outputs = pool.map(function_square, inputs)
p.close()
p.join()
print ('Pool :', p_outputs)
Pool : [0, 1, 4, 9, 16]
57 Lectures
8 hours
Denis Tishkov
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2020,
"s": 1922,
"text": "In this chapter, we will focus more on the comparison between multiprocessing and multithreading."
},
{
"code": null,
"e": 2233,
"s": 2020,
"text": "It is the use of two or more CPUs units within a single computer system. It is the best approach to get the full potential from our hardware by utilizing full number of CPU cores available in our computer system."
},
{
"code": null,
"e": 2445,
"s": 2233,
"text": "It is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads."
},
{
"code": null,
"e": 2520,
"s": 2445,
"text": "The following table shows some of the important differences between them −"
},
{
"code": null,
"e": 3060,
"s": 2520,
"text": "While working with concurrent applications, there is a limitation present in Python called the GIL (Global Interpreter Lock). GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. GIL is the mutex – mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first."
},
{
"code": null,
"e": 3150,
"s": 3060,
"text": "With the use of multiprocessing, we can effectively bypass the limitation caused by GIL −"
},
{
"code": null,
"e": 3288,
"s": 3150,
"text": "By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL."
},
{
"code": null,
"e": 3426,
"s": 3288,
"text": "By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL."
},
{
"code": null,
"e": 3540,
"s": 3426,
"text": "Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time."
},
{
"code": null,
"e": 3654,
"s": 3540,
"text": "Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time."
},
{
"code": null,
"e": 3759,
"s": 3654,
"text": "The following three methods can be used to start a process in Python within the multiprocessing module −"
},
{
"code": null,
"e": 3764,
"s": 3759,
"text": "Fork"
},
{
"code": null,
"e": 3770,
"s": 3764,
"text": "Spawn"
},
{
"code": null,
"e": 3781,
"s": 3770,
"text": "Forkserver"
},
{
"code": null,
"e": 4169,
"s": 3781,
"text": "Fork command is a standard command found in UNIX. It is used to create new processes called child processes. This child process runs concurrently with the process called the parent process. These child processes are also identical to their parent processes and inherit all of the resources available to the parent. The following system calls are used while creating a process with Fork −"
},
{
"code": null,
"e": 4277,
"s": 4169,
"text": "fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>"
},
{
"code": null,
"e": 4385,
"s": 4277,
"text": "fork() − It is a system call generally implemented in kernel. It is used to create a copy of the process.p>"
},
{
"code": null,
"e": 4465,
"s": 4385,
"text": "getpid() − This system call returns the process ID(PID) of the calling process."
},
{
"code": null,
"e": 4545,
"s": 4465,
"text": "getpid() − This system call returns the process ID(PID) of the calling process."
},
{
"code": null,
"e": 4689,
"s": 4545,
"text": "The following Python script example will help you understabd how to create a new child process and get the PIDs of child and parent processes −"
},
{
"code": null,
"e": 4876,
"s": 4689,
"text": "import os\n\ndef child():\n n = os.fork()\n \n if n > 0:\n print(\"PID of Parent process is : \", os.getpid())\n\n else:\n print(\"PID of Child process is : \", os.getpid())\nchild()"
},
{
"code": null,
"e": 4942,
"s": 4876,
"text": "PID of Parent process is : 25989\nPID of Child process is : 25990\n"
},
{
"code": null,
"e": 5216,
"s": 4942,
"text": "Spawn means to start something new. Hence, spawning a process means the creation of a new process by a parent process. The parent process continues its execution asynchronously or waits until the child process ends its execution. Follow these steps for spawning a process −"
},
{
"code": null,
"e": 5250,
"s": 5216,
"text": "Importing multiprocessing module."
},
{
"code": null,
"e": 5284,
"s": 5250,
"text": "Importing multiprocessing module."
},
{
"code": null,
"e": 5313,
"s": 5284,
"text": "Creating the object process."
},
{
"code": null,
"e": 5342,
"s": 5313,
"text": "Creating the object process."
},
{
"code": null,
"e": 5399,
"s": 5342,
"text": "Starting the process activity by calling start() method."
},
{
"code": null,
"e": 5456,
"s": 5399,
"text": "Starting the process activity by calling start() method."
},
{
"code": null,
"e": 5539,
"s": 5456,
"text": "Waiting until the process has finished its work and exit by calling join() method."
},
{
"code": null,
"e": 5622,
"s": 5539,
"text": "Waiting until the process has finished its work and exit by calling join() method."
},
{
"code": null,
"e": 5695,
"s": 5622,
"text": "The following example of Python script helps in spawning three processes"
},
{
"code": null,
"e": 5980,
"s": 5695,
"text": "import multiprocessing\n\ndef spawn_process(i):\n print ('This is process: %s' %i)\n return\n\nif __name__ == '__main__':\n Process_jobs = []\n for i in range(3):\n p = multiprocessing.Process(target = spawn_process, args = (i,))\n Process_jobs.append(p)\n p.start()\n p.join()"
},
{
"code": null,
"e": 6038,
"s": 5980,
"text": "This is process: 0\nThis is process: 1\nThis is process: 2\n"
},
{
"code": null,
"e": 6251,
"s": 6038,
"text": "Forkserver mechanism is only available on those selected UNIX platforms that support passing the file descriptors over Unix Pipes. Consider the following points to understand the working of Forkserver mechanism −"
},
{
"code": null,
"e": 6332,
"s": 6251,
"text": "A server is instantiated on using Forkserver mechanism for starting new process."
},
{
"code": null,
"e": 6413,
"s": 6332,
"text": "A server is instantiated on using Forkserver mechanism for starting new process."
},
{
"code": null,
"e": 6507,
"s": 6413,
"text": "The server then receives the command and handles all the requests for creating new processes."
},
{
"code": null,
"e": 6601,
"s": 6507,
"text": "The server then receives the command and handles all the requests for creating new processes."
},
{
"code": null,
"e": 6719,
"s": 6601,
"text": "For creating a new process, our python program will send a request to Forkserver and it will create a process for us."
},
{
"code": null,
"e": 6837,
"s": 6719,
"text": "For creating a new process, our python program will send a request to Forkserver and it will create a process for us."
},
{
"code": null,
"e": 6899,
"s": 6837,
"text": "At last, we can use this new created process in our programs."
},
{
"code": null,
"e": 6961,
"s": 6899,
"text": "At last, we can use this new created process in our programs."
},
{
"code": null,
"e": 7429,
"s": 6961,
"text": "Python multiprocessing module allows us to have daemon processes through its daemonic option. Daemon processes or the processes that are running in the background follow similar concept as the daemon threads. To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed."
},
{
"code": null,
"e": 7678,
"s": 7429,
"text": "Here, we are using the same example as used in the daemon threads. The only difference is the change of module from multithreading to multiprocessing and setting the daemonic flag to true. However, there would be a change in output as shown below −"
},
{
"code": null,
"e": 8174,
"s": 7678,
"text": "import multiprocessing\nimport time\n\ndef nondaemonProcess():\n print(\"starting my Process\")\n time.sleep(8)\n print(\"ending my Process\")\ndef daemonProcess():\n while True:\n print(\"Hello\")\n time.sleep(2)\nif __name__ == '__main__':\n nondaemonProcess = multiprocessing.Process(target = nondaemonProcess)\n daemonProcess = multiprocessing.Process(target = daemonProcess)\n daemonProcess.daemon = True\n nondaemonProcess.daemon = False\n daemonProcess.start()\n nondaemonProcess.start()"
},
{
"code": null,
"e": 8213,
"s": 8174,
"text": "starting my Process\nending my Process\n"
},
{
"code": null,
"e": 8467,
"s": 8213,
"text": "The output is different when compared to the one generated by daemon threads, because the process in no daemon mode have an output. Hence, the daemonic process ends automatically after the main programs end to avoid the persistence of running processes."
},
{
"code": null,
"e": 8698,
"s": 8467,
"text": "We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution."
},
{
"code": null,
"e": 9051,
"s": 8698,
"text": "import multiprocessing\nimport time\ndef Child_process():\n print ('Starting function')\n time.sleep(5)\n print ('Finished function')\nP = multiprocessing.Process(target = Child_process)\nP.start()\nprint(\"My Process has terminated, terminating main thread\")\nprint(\"Terminating Child Process\")\nP.terminate()\nprint(\"Child Process successfully terminated\")"
},
{
"code": null,
"e": 9167,
"s": 9051,
"text": "My Process has terminated, terminating main thread\nTerminating Child Process\nChild Process successfully terminated\n"
},
{
"code": null,
"e": 9389,
"s": 9167,
"text": "The output shows that the program terminates before the execution of child process that has been created with the help of the Child_process() function. This implies that the child process has been terminated successfully."
},
{
"code": null,
"e": 9563,
"s": 9389,
"text": "Every process in the operating system is having process identity known as PID. In Python, we can find out the PID of current process with the help of the following command −"
},
{
"code": null,
"e": 9631,
"s": 9563,
"text": "import multiprocessing\nprint(multiprocessing.current_process().pid)"
},
{
"code": null,
"e": 9743,
"s": 9631,
"text": "The following example of Python script helps find out the PID of main process as well as PID of child process −"
},
{
"code": null,
"e": 10036,
"s": 9743,
"text": "import multiprocessing\nimport time\ndef Child_process():\n print(\"PID of Child Process is: {}\".format(multiprocessing.current_process().pid))\nprint(\"PID of Main process is: {}\".format(multiprocessing.current_process().pid))\nP = multiprocessing.Process(target=Child_process)\nP.start()\nP.join()"
},
{
"code": null,
"e": 10096,
"s": 10036,
"text": "PID of Main process is: 9401\nPID of Child Process is: 9402\n"
},
{
"code": null,
"e": 10331,
"s": 10096,
"text": "We can create threads by sub-classing the threading.Thread class. In addition, we can also create processes by sub-classing the multiprocessing.Process class. For using a process in subclass, we need to consider the following points −"
},
{
"code": null,
"e": 10386,
"s": 10331,
"text": "We need to define a new subclass of the Process class."
},
{
"code": null,
"e": 10441,
"s": 10386,
"text": "We need to define a new subclass of the Process class."
},
{
"code": null,
"e": 10494,
"s": 10441,
"text": "We need to override the _init_(self [,args] ) class."
},
{
"code": null,
"e": 10547,
"s": 10494,
"text": "We need to override the _init_(self [,args] ) class."
},
{
"code": null,
"e": 10630,
"s": 10547,
"text": "We need to override the of the run(self [,args] ) method to implement what Process"
},
{
"code": null,
"e": 10713,
"s": 10630,
"text": "We need to override the of the run(self [,args] ) method to implement what Process"
},
{
"code": null,
"e": 10773,
"s": 10713,
"text": "We need to start the process by invoking thestart() method."
},
{
"code": null,
"e": 10833,
"s": 10773,
"text": "We need to start the process by invoking thestart() method."
},
{
"code": null,
"e": 11107,
"s": 10833,
"text": "import multiprocessing\nclass MyProcess(multiprocessing.Process):\n def run(self):\n print ('called run method in process: %s' %self.name)\n return\nif __name__ == '__main__':\n jobs = []\n for i in range(5):\n P = MyProcess()\n jobs.append(P)\n P.start()\n P.join()"
},
{
"code": null,
"e": 11318,
"s": 11107,
"text": "called run method in process: MyProcess-1\ncalled run method in process: MyProcess-2\ncalled run method in process: MyProcess-3\ncalled run method in process: MyProcess-4\ncalled run method in process: MyProcess-5\n"
},
{
"code": null,
"e": 11560,
"s": 11318,
"text": "If we talk about simple parallel processing tasks in our Python applications, then multiprocessing module provide us the Pool class. The following methods of Pool class can be used to spin up number of child processes within our main program"
},
{
"code": null,
"e": 11665,
"s": 11560,
"text": "This method is similar to the.submit()method of .ThreadPoolExecutor.It blocks until the result is ready."
},
{
"code": null,
"e": 11893,
"s": 11665,
"text": "When we need parallel execution of our tasks then we need to use theapply_async()method to submit tasks to the pool. It is an asynchronous operation that will not lock the main thread until all the child processes are executed."
},
{
"code": null,
"e": 12116,
"s": 11893,
"text": "Just like the apply() method, it also blocks until the result is ready. It is equivalent to the built-in map() function that splits the iterable data in a number of chunks and submits to the process pool as separate tasks."
},
{
"code": null,
"e": 12392,
"s": 12116,
"text": "It is a variant of the map() method as apply_async() is to the apply() method. It returns a result object. When the result becomes ready, a callable is applied to it. The callable must be completed immediately; otherwise, the thread that handles the results will get blocked."
},
{
"code": null,
"e": 12778,
"s": 12392,
"text": "The following example will help you implement a process pool for performing parallel execution. A simple calculation of square of number has been performed by applying the square() function through the multiprocessing.Pool method. Then pool.map() has been used to submit the 5, because input is a list of integers from 0 to 4. The result would be stored in p_outputs and it is printed."
},
{
"code": null,
"e": 13028,
"s": 12778,
"text": "def square(n):\n result = n*n\n return result\nif __name__ == '__main__':\n inputs = list(range(5))\n p = multiprocessing.Pool(processes = 4)\n p_outputs = pool.map(function_square, inputs)\n p.close()\n p.join()\n print ('Pool :', p_outputs)"
},
{
"code": null,
"e": 13053,
"s": 13028,
"text": "Pool : [0, 1, 4, 9, 16]\n"
},
{
"code": null,
"e": 13086,
"s": 13053,
"text": "\n 57 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 13101,
"s": 13086,
"text": " Denis Tishkov"
},
{
"code": null,
"e": 13108,
"s": 13101,
"text": " Print"
},
{
"code": null,
"e": 13119,
"s": 13108,
"text": " Add Notes"
}
] |
RxJS - Latest Updates
|
We are using RxJS version 6 in this tutorial. RxJS is commonly used to deal with reactive programming and used more often with Angular, ReactJS. Angular 6 loads rxjs6 by default.
RxJS version 5 was handled differently in comparison to version 6. The code will break in case you update your RxJS 5 to 6. In this chapter, we are going to see the difference in ways of handling the version update.
In case you are updating RxJS to 6 and don't want to make the code changes, you can do that too, and will have to install the following package.
npm install --save-dev rxjs-compact
This package will take care of providing backward compatibility and old code will work fine with RxJS version 6. If you want to make the code changes that works fine with RxJS 6, here are the changes that needs to be done.
The packages for operators, observables, subject were restructured and hence, the major changes go in for imports and they are explained below.
As per version 5, for operators the following import statements should be included −
import 'rxjs/add/operator/mapTo'
import 'rxjs/add/operator/take'
import 'rxjs/add/operator/tap'
import 'rxjs/add/operator/map'
In RxJS version 6 the imports will be as follows −
import {mapTo, take, tap, map} from "rxjs/operators"
As per version 5, while working with Observables, the following import methods should be included −
import "rxjs/add/observable/from";
import "rxjs/add/observable/of";
import "rxjs/add/observable/fromEvent";
import "rxjs/add/observable/interval";
In RxJS version 6 the imports will be as follows −
import {from, of, fromEvent, interval} from 'rxjs';
In RxJS version 5, while working with Observables, the following import statements should be included −
import { Observable } from 'rxjs/Observable'
In RxJS version 6, the imports will be as follows −
import { Observable } from 'rxjs'
In RxJS version 5, subject should be included as follows −
import { Subject} from 'rxjs/Subject'
In RxJS version 6, the imports will be as follows −
import { Subject } from 'rxjs'
pipe() method is available on the observable created. It is added to RxJS from version 5.5. Using pipe() now you can work on multiple operators together in sequential order. This is how the operators were used in RxJS version 5.
import "rxjs/add/observable/from";
import 'rxjs/add/operator/max'
let list1 = [1, 6, 15, 10, 58, 2, 40];
from(list1).max((a,b)=>a-b).subscribe(x => console.log("The Max value is "+x));
From RxJS version 5.5 onwards, we have to use pipe() to execute the operator −
import { from } from 'rxjs';
import { max } from 'rxjs/operators';
from(list1).pipe(max((a,b)=>a-b)).subscribe(x => console.log(
"The Max value is "+x)
);
During restructuring of the packages some of the operators were renamed as they were conflicting or matching with javascript keywords. The list is as shown below −
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2003,
"s": 1824,
"text": "We are using RxJS version 6 in this tutorial. RxJS is commonly used to deal with reactive programming and used more often with Angular, ReactJS. Angular 6 loads rxjs6 by default."
},
{
"code": null,
"e": 2219,
"s": 2003,
"text": "RxJS version 5 was handled differently in comparison to version 6. The code will break in case you update your RxJS 5 to 6. In this chapter, we are going to see the difference in ways of handling the version update."
},
{
"code": null,
"e": 2364,
"s": 2219,
"text": "In case you are updating RxJS to 6 and don't want to make the code changes, you can do that too, and will have to install the following package."
},
{
"code": null,
"e": 2401,
"s": 2364,
"text": "npm install --save-dev rxjs-compact\n"
},
{
"code": null,
"e": 2624,
"s": 2401,
"text": "This package will take care of providing backward compatibility and old code will work fine with RxJS version 6. If you want to make the code changes that works fine with RxJS 6, here are the changes that needs to be done."
},
{
"code": null,
"e": 2768,
"s": 2624,
"text": "The packages for operators, observables, subject were restructured and hence, the major changes go in for imports and they are explained below."
},
{
"code": null,
"e": 2853,
"s": 2768,
"text": "As per version 5, for operators the following import statements should be included −"
},
{
"code": null,
"e": 2981,
"s": 2853,
"text": "import 'rxjs/add/operator/mapTo'\nimport 'rxjs/add/operator/take'\nimport 'rxjs/add/operator/tap'\nimport 'rxjs/add/operator/map'\n"
},
{
"code": null,
"e": 3032,
"s": 2981,
"text": "In RxJS version 6 the imports will be as follows −"
},
{
"code": null,
"e": 3086,
"s": 3032,
"text": "import {mapTo, take, tap, map} from \"rxjs/operators\"\n"
},
{
"code": null,
"e": 3186,
"s": 3086,
"text": "As per version 5, while working with Observables, the following import methods should be included −"
},
{
"code": null,
"e": 3334,
"s": 3186,
"text": "import \"rxjs/add/observable/from\";\nimport \"rxjs/add/observable/of\";\nimport \"rxjs/add/observable/fromEvent\";\nimport \"rxjs/add/observable/interval\";\n"
},
{
"code": null,
"e": 3385,
"s": 3334,
"text": "In RxJS version 6 the imports will be as follows −"
},
{
"code": null,
"e": 3438,
"s": 3385,
"text": "import {from, of, fromEvent, interval} from 'rxjs';\n"
},
{
"code": null,
"e": 3542,
"s": 3438,
"text": "In RxJS version 5, while working with Observables, the following import statements should be included −"
},
{
"code": null,
"e": 3588,
"s": 3542,
"text": "import { Observable } from 'rxjs/Observable'\n"
},
{
"code": null,
"e": 3640,
"s": 3588,
"text": "In RxJS version 6, the imports will be as follows −"
},
{
"code": null,
"e": 3675,
"s": 3640,
"text": "import { Observable } from 'rxjs'\n"
},
{
"code": null,
"e": 3734,
"s": 3675,
"text": "In RxJS version 5, subject should be included as follows −"
},
{
"code": null,
"e": 3773,
"s": 3734,
"text": "import { Subject} from 'rxjs/Subject'\n"
},
{
"code": null,
"e": 3825,
"s": 3773,
"text": "In RxJS version 6, the imports will be as follows −"
},
{
"code": null,
"e": 3857,
"s": 3825,
"text": "import { Subject } from 'rxjs'\n"
},
{
"code": null,
"e": 4086,
"s": 3857,
"text": "pipe() method is available on the observable created. It is added to RxJS from version 5.5. Using pipe() now you can work on multiple operators together in sequential order. This is how the operators were used in RxJS version 5."
},
{
"code": null,
"e": 4272,
"s": 4086,
"text": "import \"rxjs/add/observable/from\";\nimport 'rxjs/add/operator/max'\n\nlet list1 = [1, 6, 15, 10, 58, 2, 40];\nfrom(list1).max((a,b)=>a-b).subscribe(x => console.log(\"The Max value is \"+x));"
},
{
"code": null,
"e": 4351,
"s": 4272,
"text": "From RxJS version 5.5 onwards, we have to use pipe() to execute the operator −"
},
{
"code": null,
"e": 4510,
"s": 4351,
"text": "import { from } from 'rxjs';\nimport { max } from 'rxjs/operators';\n\nfrom(list1).pipe(max((a,b)=>a-b)).subscribe(x => console.log(\n \"The Max value is \"+x)\n);"
},
{
"code": null,
"e": 4674,
"s": 4510,
"text": "During restructuring of the packages some of the operators were renamed as they were conflicting or matching with javascript keywords. The list is as shown below −"
},
{
"code": null,
"e": 4707,
"s": 4674,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4721,
"s": 4707,
"text": " Daniel Stern"
},
{
"code": null,
"e": 4728,
"s": 4721,
"text": " Print"
},
{
"code": null,
"e": 4739,
"s": 4728,
"text": " Add Notes"
}
] |
Roll a six-sided die 6000 times in Java
|
In order to roll a six sided die 6000 times in Java, we need to the nextInt() statement with decision making statements.
The nextInt() method returns the next random integer value from this random number generator sequence.
Declaration − The java.util.Random.nextInt() method is declared as follows −
public int nextInt()
Let us see a program to roll a six sided die 6000 times −
Live Demo
import java.util.Random;
public class Example {
public static void main(String args[]) {
Random rd = new Random(); // random number generator
int freq[] = new int[6]; // creating an array to compute frequency of each face
int val;
int chance = 1;
// rolling the dice 6000 times
while(chance <= 6000){
val = 1 + rd.nextInt(6); // generates integers from 1 to 6
switch (val) {
case 1:
++freq[0];
break;
case 2:
++freq[1];
break;
case 3:
++freq[2];
break;
case 4:
++freq[3];
break;
case 5:
++freq[4];
break;
case 6:
++freq[5];
break;
}
chance++;
}
for(int i = 1; i <= 6; i++){
System.out.println("Side: " + i + "-> Frequency : " + freq[i - 1]);
}
}
}
Side: 1-> Frequency: 987
Side: 2-> Frequency : 971
Side: 3-> Frequency : 1057
Side: 4-> Frequency : 979
Side: 5-> Frequency : 982
Side: 6-> Frequency : 1024
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "In order to roll a six sided die 6000 times in Java, we need to the nextInt() statement with decision making statements."
},
{
"code": null,
"e": 1286,
"s": 1183,
"text": "The nextInt() method returns the next random integer value from this random number generator sequence."
},
{
"code": null,
"e": 1363,
"s": 1286,
"text": "Declaration − The java.util.Random.nextInt() method is declared as follows −"
},
{
"code": null,
"e": 1384,
"s": 1363,
"text": "public int nextInt()"
},
{
"code": null,
"e": 1442,
"s": 1384,
"text": "Let us see a program to roll a six sided die 6000 times −"
},
{
"code": null,
"e": 1453,
"s": 1442,
"text": " Live Demo"
},
{
"code": null,
"e": 2458,
"s": 1453,
"text": "import java.util.Random;\npublic class Example {\n public static void main(String args[]) {\n Random rd = new Random(); // random number generator\n int freq[] = new int[6]; // creating an array to compute frequency of each face\n int val;\n int chance = 1;\n // rolling the dice 6000 times\n while(chance <= 6000){\n val = 1 + rd.nextInt(6); // generates integers from 1 to 6\n switch (val) {\n case 1:\n ++freq[0];\n break;\n case 2:\n ++freq[1];\n break;\n case 3:\n ++freq[2];\n break;\n case 4:\n ++freq[3];\n break;\n case 5:\n ++freq[4];\n break;\n case 6:\n ++freq[5];\n break;\n }\n chance++;\n }\n for(int i = 1; i <= 6; i++){\n System.out.println(\"Side: \" + i + \"-> Frequency : \" + freq[i - 1]);\n }\n }\n}"
},
{
"code": null,
"e": 2615,
"s": 2458,
"text": "Side: 1-> Frequency: 987\nSide: 2-> Frequency : 971\nSide: 3-> Frequency : 1057\nSide: 4-> Frequency : 979\nSide: 5-> Frequency : 982\nSide: 6-> Frequency : 1024"
}
] |
Computing Node Embedding with a Graph Database: Neo4j & its Graph Data Science Library | by Estelle Scifo | Towards Data Science
|
Machine Learning these days is all about vectors. Performing a classification task requires that your data is well-arranged into rows (observations), each one containing the same amount of features (columns). While this is easy to obtain from data originally stored in an Excel sheet or in SQL or noSQL databases, the transformation is far from obvious when the problem involves complex objects such as texts, images or graphs.
For these objects to be represented as vectors, embedding techniques are used. Embedding algorithms assign a vector with given “small” size to each of these complex objects that would require thousands (at least) of features otherwise. The challenge of embedding is to preserve some characteristics of the object you are trying to model, while reducing the number of features. For instance, word embedding will try and capture the word meaning, such that words semantically close to each other have similar vector representations.
Graph embedding covers several techniques, depending on the objects to be represented. The most common ones are node embedding, where the entities to be represented as vectors are nodes, but we can also find edge embedding or whole-graph embedding. This post will focus on the former one, node embedding.
The primary purpose of graph databases is to make relationships easier to manage, whether we are talking about a web application with complex ManyToMany relationships, or graph data science. Interest for this kind of store is almost constantly increasing, especially since the Cypher query language has been introduced into Neo4j.
Cypher makes it so easy to write intuitive queries. For instance, I am sure you will get instantaneously what this query is doing:
MATCH (:User {name: "Emil"})-[:FOLLOWS]->(u:User)WHERE NOT u.name STARTS WITH "neo"RETURN u.name, u.dateJoined
A few things to note from the above query:
Nodes, delimited by parenthesis (), have a label, that can be identified thanks to the leading :
Relationships, delimited by square brackets [], must have a type. Conventionally, relationship types are capitalized.
Convinced to give a try to Neo4j? You have two ways to do it:
Using a sandbox that will run a Neo4j instance for you during a limited period (3 days, that can be extended for 7 more days): https://sandbox.neo4j.com/
Download Neo4j Desktop and run it locally and enjoy all the features: https://neo4j.com/download/
In both cases, this is totally free. I’ll be using the later in this blog, creating a new graph using Neo4j 4.1.
Let’s import some data into our graph. To do so, we are going to use the “Game Of Thrones” dataset using the got browser guide. Type:
:play got
in the browser, and follow the instructions.
Once you have imported the data, the graph schema looks like this:
It contains one node label, Character , and five relationship types depending on which book the characters were found to interact with each other, and a global INTERACTS relationship. We are going to use only the last one for the rest of this post. If you want to visualize some of the data, you can use:
MATCH (n)RETURN nLIMIT 200
Let’s go ahead and proceed to the graph analysis and node embedding.
The GDS is the successor of the Graph Algorithm plugin whose first release date back to 2018. It’s goal is to enable the use of graph algorithms, from path finding algorithms to graph neural networks, without having to extract data from Neo4j.
Follow the steps in https://neo4j.com/docs/graph-data-science/current/installation/#_neo4j_desktop for installation.
The Neo4j graph usually contains a lot of data: nodes with different labels, relationships with different types and properties attached to them. Most of the time, a data science algorithm requires only a small portion of these entities: only some node labels or some relationship type and only one property (relationship weight for shortest path algorithm for instance). That’s why the GDS does not run on the full Neo4j graph, but on a projected (lighter) version. So, let’s start and build our projected graph. In the Neo4j browser, execute:
CALL gds.graph.create( "MyGraph", "Character", "INTERACTS")
Here we create a projected graph named MyGraph, containing all nodes with label Character. Additionally, we add to this projected graph relationships with type INTERACTS.
Here we are, our projected graph is created, we can go ahead and execute algorithms on it.
The simplest way to run the node2vec algorithm on the MyGraph projected graph is to use this simple query:
CALL gds.alpha.node2vec.stream("MyGraph")
The result in the browser looks like the following image, where a list of numbers gets assigned to each node (identified by its internal Neo4j ID, nodeId):
If you know a bit about how node2vec works, you know there are many configuration parameters to configure how:
the training data is build (random walks parameters): number of steps, number of generated walks per node, in-out and return factors.
the skip-gram neural network is trained: embedding size, initial learning rate, etc.
The full list of parameters is reproduced below, from the GDS documentation page.
Let’s try for instance to reduce the embedding size:
CALL gds.alpha.node2vec.stream(“MyGraph”, {walksPerNode: 2, embeddingSize: 10})
Without surprise, the output now looks like:
Before dealing with the usage of these results, let’s see how to use another embedding algorithm, GraphSAGE.
While Node2vec only takes into account the graph structure, GraphSAGE is able to consider node properties, if any.
In our GoT graph, nodes only have a name property which is not that meaningful for embedding. We will then use only the node degree, or number of relationships attached to it, as property:
CALL gds.alpha.graphSage.stream("MyGraph", {degreeAsProperty: true})
The full list of parameters includes configuration of the properties (nodePropertyNames), the aggregator function (mean by default), the batch size... See image below for a full list.
Neo4j provides a python driver that can be easily installed through pip. However, in this post, I will talk about a small tool that I have developed allowing to call GDS procedures from Python without effort: pygds. It still needs to be heavily tested, so feel free to report issues if you find any.
Let’s start by installing the package in your favorite python environment:
pip install "pygds>=0.2.0"
Then, you can import the library and define the credentials to connect to your Neo4j graph:
from pygds import GDSURI = "bolt://localhost:7687"AUTH = ("neo4j", "<YOUR_PASSWORD>")
Usage of pygds is as follows:
with GDS(URI, auth=AUTH) as gds: # create the projected graph # NB: make sure a graph with the same does not already exists # otherwise run CALL gds.graph.drop("MyGraph") gds.graph.create( "MyGraph", "Character", "INTERACTS", ) # run any algorithm on it
For instance, to run the node2vec algorithm, we will write:
result = gds.alpha.node2vec.stream( "MyGraph", { "walksPerNode": 2, "embeddingSize": 10 })
The result can then be parsed into a DataFrame:
import pandas as pd_tmp = pd.DataFrame.from_records(result)df = pd.DataFrame(_tmp["embedding"].tolist())print(df.head())
Starting from there, you can perform any Machine Learning algorithm, from PCA for visualization to classification if nodes also have some target class...
As a last step, whether you are working with Cypher or pygds, you have to drop the projected graph which is stored in the live memory of your computer: gds.graph.drop("MyGraph")
That’s great! The GDS contains much more fantastic algorithms implementations (path finding, node importance, community detection, node similarity, link prediction) and features (e.g. writing the algorithms results as node properties to persist the result in the graph instead of streaming them).
Here are a few online resources you can check if you are interested in learning more about graph algorithms and Neo4j:
Free Book “Graph Algorithms: Practical Examples in Apache Spark and Neo4j” by Mark Needham: https://neo4j.com/graph-algorithms-book/ (caveat: this book was written using the Graph Algorithm library, predecessor of the GDS, but is still a must-read to understand graph algorithms use-cases (and a migration guide is available here together with updated examples using the GDS); caveat 2: it may not be free indefinitely and the end of its “free-period” is periodically announced by Neo4j and so far has always been extended but who knows)
Check the GraphAcademy created by Neo4j and its data science course:https://neo4j.com/graphacademy/online-training/data-science/part-0/
You can follow Tomaz Bratanic on medium and his blog to see many interesting use cases for all the algorithms of the GDS: https://tbgraph.wordpress.com/
And of course, read the doc: https://neo4j.com/docs/graph-data-science/current/
For more information about the algorithms discussed here, see for instance A Gentle Introduction to Graph Neural Networks (Basis, DeepWalk and GraphSage) by Kung-Hsiang, Huang (Steeve):
|
[
{
"code": null,
"e": 600,
"s": 172,
"text": "Machine Learning these days is all about vectors. Performing a classification task requires that your data is well-arranged into rows (observations), each one containing the same amount of features (columns). While this is easy to obtain from data originally stored in an Excel sheet or in SQL or noSQL databases, the transformation is far from obvious when the problem involves complex objects such as texts, images or graphs."
},
{
"code": null,
"e": 1131,
"s": 600,
"text": "For these objects to be represented as vectors, embedding techniques are used. Embedding algorithms assign a vector with given “small” size to each of these complex objects that would require thousands (at least) of features otherwise. The challenge of embedding is to preserve some characteristics of the object you are trying to model, while reducing the number of features. For instance, word embedding will try and capture the word meaning, such that words semantically close to each other have similar vector representations."
},
{
"code": null,
"e": 1436,
"s": 1131,
"text": "Graph embedding covers several techniques, depending on the objects to be represented. The most common ones are node embedding, where the entities to be represented as vectors are nodes, but we can also find edge embedding or whole-graph embedding. This post will focus on the former one, node embedding."
},
{
"code": null,
"e": 1767,
"s": 1436,
"text": "The primary purpose of graph databases is to make relationships easier to manage, whether we are talking about a web application with complex ManyToMany relationships, or graph data science. Interest for this kind of store is almost constantly increasing, especially since the Cypher query language has been introduced into Neo4j."
},
{
"code": null,
"e": 1898,
"s": 1767,
"text": "Cypher makes it so easy to write intuitive queries. For instance, I am sure you will get instantaneously what this query is doing:"
},
{
"code": null,
"e": 2009,
"s": 1898,
"text": "MATCH (:User {name: \"Emil\"})-[:FOLLOWS]->(u:User)WHERE NOT u.name STARTS WITH \"neo\"RETURN u.name, u.dateJoined"
},
{
"code": null,
"e": 2052,
"s": 2009,
"text": "A few things to note from the above query:"
},
{
"code": null,
"e": 2149,
"s": 2052,
"text": "Nodes, delimited by parenthesis (), have a label, that can be identified thanks to the leading :"
},
{
"code": null,
"e": 2267,
"s": 2149,
"text": "Relationships, delimited by square brackets [], must have a type. Conventionally, relationship types are capitalized."
},
{
"code": null,
"e": 2329,
"s": 2267,
"text": "Convinced to give a try to Neo4j? You have two ways to do it:"
},
{
"code": null,
"e": 2483,
"s": 2329,
"text": "Using a sandbox that will run a Neo4j instance for you during a limited period (3 days, that can be extended for 7 more days): https://sandbox.neo4j.com/"
},
{
"code": null,
"e": 2581,
"s": 2483,
"text": "Download Neo4j Desktop and run it locally and enjoy all the features: https://neo4j.com/download/"
},
{
"code": null,
"e": 2694,
"s": 2581,
"text": "In both cases, this is totally free. I’ll be using the later in this blog, creating a new graph using Neo4j 4.1."
},
{
"code": null,
"e": 2828,
"s": 2694,
"text": "Let’s import some data into our graph. To do so, we are going to use the “Game Of Thrones” dataset using the got browser guide. Type:"
},
{
"code": null,
"e": 2838,
"s": 2828,
"text": ":play got"
},
{
"code": null,
"e": 2883,
"s": 2838,
"text": "in the browser, and follow the instructions."
},
{
"code": null,
"e": 2950,
"s": 2883,
"text": "Once you have imported the data, the graph schema looks like this:"
},
{
"code": null,
"e": 3255,
"s": 2950,
"text": "It contains one node label, Character , and five relationship types depending on which book the characters were found to interact with each other, and a global INTERACTS relationship. We are going to use only the last one for the rest of this post. If you want to visualize some of the data, you can use:"
},
{
"code": null,
"e": 3282,
"s": 3255,
"text": "MATCH (n)RETURN nLIMIT 200"
},
{
"code": null,
"e": 3351,
"s": 3282,
"text": "Let’s go ahead and proceed to the graph analysis and node embedding."
},
{
"code": null,
"e": 3595,
"s": 3351,
"text": "The GDS is the successor of the Graph Algorithm plugin whose first release date back to 2018. It’s goal is to enable the use of graph algorithms, from path finding algorithms to graph neural networks, without having to extract data from Neo4j."
},
{
"code": null,
"e": 3712,
"s": 3595,
"text": "Follow the steps in https://neo4j.com/docs/graph-data-science/current/installation/#_neo4j_desktop for installation."
},
{
"code": null,
"e": 4256,
"s": 3712,
"text": "The Neo4j graph usually contains a lot of data: nodes with different labels, relationships with different types and properties attached to them. Most of the time, a data science algorithm requires only a small portion of these entities: only some node labels or some relationship type and only one property (relationship weight for shortest path algorithm for instance). That’s why the GDS does not run on the full Neo4j graph, but on a projected (lighter) version. So, let’s start and build our projected graph. In the Neo4j browser, execute:"
},
{
"code": null,
"e": 4327,
"s": 4256,
"text": "CALL gds.graph.create( \"MyGraph\", \"Character\", \"INTERACTS\")"
},
{
"code": null,
"e": 4498,
"s": 4327,
"text": "Here we create a projected graph named MyGraph, containing all nodes with label Character. Additionally, we add to this projected graph relationships with type INTERACTS."
},
{
"code": null,
"e": 4589,
"s": 4498,
"text": "Here we are, our projected graph is created, we can go ahead and execute algorithms on it."
},
{
"code": null,
"e": 4696,
"s": 4589,
"text": "The simplest way to run the node2vec algorithm on the MyGraph projected graph is to use this simple query:"
},
{
"code": null,
"e": 4738,
"s": 4696,
"text": "CALL gds.alpha.node2vec.stream(\"MyGraph\")"
},
{
"code": null,
"e": 4894,
"s": 4738,
"text": "The result in the browser looks like the following image, where a list of numbers gets assigned to each node (identified by its internal Neo4j ID, nodeId):"
},
{
"code": null,
"e": 5005,
"s": 4894,
"text": "If you know a bit about how node2vec works, you know there are many configuration parameters to configure how:"
},
{
"code": null,
"e": 5139,
"s": 5005,
"text": "the training data is build (random walks parameters): number of steps, number of generated walks per node, in-out and return factors."
},
{
"code": null,
"e": 5224,
"s": 5139,
"text": "the skip-gram neural network is trained: embedding size, initial learning rate, etc."
},
{
"code": null,
"e": 5306,
"s": 5224,
"text": "The full list of parameters is reproduced below, from the GDS documentation page."
},
{
"code": null,
"e": 5359,
"s": 5306,
"text": "Let’s try for instance to reduce the embedding size:"
},
{
"code": null,
"e": 5439,
"s": 5359,
"text": "CALL gds.alpha.node2vec.stream(“MyGraph”, {walksPerNode: 2, embeddingSize: 10})"
},
{
"code": null,
"e": 5484,
"s": 5439,
"text": "Without surprise, the output now looks like:"
},
{
"code": null,
"e": 5593,
"s": 5484,
"text": "Before dealing with the usage of these results, let’s see how to use another embedding algorithm, GraphSAGE."
},
{
"code": null,
"e": 5708,
"s": 5593,
"text": "While Node2vec only takes into account the graph structure, GraphSAGE is able to consider node properties, if any."
},
{
"code": null,
"e": 5897,
"s": 5708,
"text": "In our GoT graph, nodes only have a name property which is not that meaningful for embedding. We will then use only the node degree, or number of relationships attached to it, as property:"
},
{
"code": null,
"e": 5966,
"s": 5897,
"text": "CALL gds.alpha.graphSage.stream(\"MyGraph\", {degreeAsProperty: true})"
},
{
"code": null,
"e": 6150,
"s": 5966,
"text": "The full list of parameters includes configuration of the properties (nodePropertyNames), the aggregator function (mean by default), the batch size... See image below for a full list."
},
{
"code": null,
"e": 6450,
"s": 6150,
"text": "Neo4j provides a python driver that can be easily installed through pip. However, in this post, I will talk about a small tool that I have developed allowing to call GDS procedures from Python without effort: pygds. It still needs to be heavily tested, so feel free to report issues if you find any."
},
{
"code": null,
"e": 6525,
"s": 6450,
"text": "Let’s start by installing the package in your favorite python environment:"
},
{
"code": null,
"e": 6552,
"s": 6525,
"text": "pip install \"pygds>=0.2.0\""
},
{
"code": null,
"e": 6644,
"s": 6552,
"text": "Then, you can import the library and define the credentials to connect to your Neo4j graph:"
},
{
"code": null,
"e": 6730,
"s": 6644,
"text": "from pygds import GDSURI = \"bolt://localhost:7687\"AUTH = (\"neo4j\", \"<YOUR_PASSWORD>\")"
},
{
"code": null,
"e": 6760,
"s": 6730,
"text": "Usage of pygds is as follows:"
},
{
"code": null,
"e": 7060,
"s": 6760,
"text": "with GDS(URI, auth=AUTH) as gds: # create the projected graph # NB: make sure a graph with the same does not already exists # otherwise run CALL gds.graph.drop(\"MyGraph\") gds.graph.create( \"MyGraph\", \"Character\", \"INTERACTS\", ) # run any algorithm on it "
},
{
"code": null,
"e": 7120,
"s": 7060,
"text": "For instance, to run the node2vec algorithm, we will write:"
},
{
"code": null,
"e": 7236,
"s": 7120,
"text": "result = gds.alpha.node2vec.stream( \"MyGraph\", { \"walksPerNode\": 2, \"embeddingSize\": 10 })"
},
{
"code": null,
"e": 7284,
"s": 7236,
"text": "The result can then be parsed into a DataFrame:"
},
{
"code": null,
"e": 7405,
"s": 7284,
"text": "import pandas as pd_tmp = pd.DataFrame.from_records(result)df = pd.DataFrame(_tmp[\"embedding\"].tolist())print(df.head())"
},
{
"code": null,
"e": 7559,
"s": 7405,
"text": "Starting from there, you can perform any Machine Learning algorithm, from PCA for visualization to classification if nodes also have some target class..."
},
{
"code": null,
"e": 7737,
"s": 7559,
"text": "As a last step, whether you are working with Cypher or pygds, you have to drop the projected graph which is stored in the live memory of your computer: gds.graph.drop(\"MyGraph\")"
},
{
"code": null,
"e": 8034,
"s": 7737,
"text": "That’s great! The GDS contains much more fantastic algorithms implementations (path finding, node importance, community detection, node similarity, link prediction) and features (e.g. writing the algorithms results as node properties to persist the result in the graph instead of streaming them)."
},
{
"code": null,
"e": 8153,
"s": 8034,
"text": "Here are a few online resources you can check if you are interested in learning more about graph algorithms and Neo4j:"
},
{
"code": null,
"e": 8691,
"s": 8153,
"text": "Free Book “Graph Algorithms: Practical Examples in Apache Spark and Neo4j” by Mark Needham: https://neo4j.com/graph-algorithms-book/ (caveat: this book was written using the Graph Algorithm library, predecessor of the GDS, but is still a must-read to understand graph algorithms use-cases (and a migration guide is available here together with updated examples using the GDS); caveat 2: it may not be free indefinitely and the end of its “free-period” is periodically announced by Neo4j and so far has always been extended but who knows)"
},
{
"code": null,
"e": 8827,
"s": 8691,
"text": "Check the GraphAcademy created by Neo4j and its data science course:https://neo4j.com/graphacademy/online-training/data-science/part-0/"
},
{
"code": null,
"e": 8980,
"s": 8827,
"text": "You can follow Tomaz Bratanic on medium and his blog to see many interesting use cases for all the algorithms of the GDS: https://tbgraph.wordpress.com/"
},
{
"code": null,
"e": 9060,
"s": 8980,
"text": "And of course, read the doc: https://neo4j.com/docs/graph-data-science/current/"
}
] |
11 Pandas Built-in Functions You Should Know | by Roman Orac | Towards Data Science
|
I’ve been using pandas for a few years and each time I feel I am typing too much, I google the operation and I usually find a shorter way of doing it — a new pandas trick!
I learned about these functions recently and I deem them essential because of ease of use.
By reading this article, you’ll learn:
How to retrieve a column value from a DataframeHow to change a column value in a DataframeThe proper way of adding a new column to a DataFrameHow to retrieve a Series or a DataFrameHow to create a DataFrame from a pandas SeriesFilter with between functionFix the order of the rows with reindex functionAdvanced usages of Describe functionText search with regexBigger than memory datasets with pandasHow to save the disk space
How to retrieve a column value from a Dataframe
How to change a column value in a Dataframe
The proper way of adding a new column to a DataFrame
How to retrieve a Series or a DataFrame
How to create a DataFrame from a pandas Series
Filter with between function
Fix the order of the rows with reindex function
Advanced usages of Describe function
Text search with regex
Bigger than memory datasets with pandas
How to save the disk space
Let’s create a simple DataFrame to show these tips in action:
import pandas as pddf = pd.DataFrame({"col1": ["A0", "A1", "A0", "A2", "A0", "A1"]})
There are two ways of retrieving column values from a DataFrame:
based on integer-location indexing (iloc),
based on the label indexing (loc).
To retrieve the first column value for the col1 column (integer-location indexing):
df.iloc[0].col1# output: 'A0'
To retrieve the last column value:
df.iloc[-1].col1# output: ‘A1’
You can also retrieve a column value with the label. By default, pandas DataFrame has indices from 0 to n, where n is the number of rows in a DataFrame.
df.loc[1, “col1”]# output: ‘A1’
See pandas documentation to learn more about loc and iloc functions.
Similar to the example above, you can change the value of a column with loc and iloc functions. Which one you use depends if you have the integer position of the row (iloc) or label of the row (loc).
To change the first column value based on integer position:
df.iloc[0].col1 = “First”
To change the last column value based on integer position:
df.iloc[-1].col1 = “Last”
To change the column value by label:
df.loc[2, “col1”] = “Index”
By applying these changes, we get the following Dataframe:
Let’s say we would like to add a list of integers as a column to our DataFrame.
new_column = list(range(len(df))new_column# output: [0, 1, 2, 3, 4, 5]
How NOT to add a column (it doesn’t work):
df.new_column1 = new_column
Also NOT a proper way of adding a column, but it works. You might get a copy warning.
df["new_column2"] = new_column
A good way to add a new column:
df.loc[:, ‘new_column3’] = new_column
The proper way:
df = df.assign(new_column4=new_column)
assign function also takes an index as an argument with which we can define the order of rows in the column.
You might be tempted to add the inplace=True argument to the assign function to add a new column in place, but it won’t work. The assign function will also add the in-place column.
# This will add two columnsdf.assign(new_column4=new_column, inplace=True)
This is actually another benefit of the assign function. You can add multiple columns at the same time.
See pandas documentation, to learn more about assign function.
When using square brackets with pandas DataFrame, it returns:
a Series if you use single square brackets
a Dataframe if you use double square brackets.
Let’s look at an example.
How to retrieve a Series from a Dataframe?
df["col1"]
type(df["col1"])# pandas.core.series.Series
How to retrieve a DataFrame (with a subset of columns) from a Dataframe?
df[["col1"]]
type(df[["col1"]])# pandas.core.frame.DataFrame
When performing a grouping with aggregation, pandas returns a Series. What is the simplest way to convert a Series back to a Dataframe?
Let’s look at an example:
df = pd.DataFrame( { "col1": ["A0", "A1", "A0", "A2", "A0", "A1"], "col2": [1, 2, 3, 4, 5, 6], })df_group = df.groupby("col1").col2.sum()df_group
df_group is a Series.
Series has a to_frame function, which can covert a Series back to DataFrame:
df_group.to_frame()
See pandas documentation, to learn more about to_frame function.
I’ve been using “between” function in SQL for years, but I only discovered it recently in pandas.
Let’s say we have a DataFrame with prices and we would like to filter prices between 2 and 4.
df = pd.DataFrame({'price': [1.99, 3, 5, 0.5, 3.5, 5.5, 3.9]})
With between function, you can reduce this filter:
df[(df.price >= 2) & (df.price <= 4)]
To this:
df[df.price.between(2, 4)]
It might not seem much, but those parentheses are annoying when writing many filters. The filter with between function is also more readable.
between function sets interval left <= series <= right.
See pandas, documentation to learn more about between function.
The reindex function conforms a Series or a DataFrame to a new index. I resort to the reindex function when making reports with columns that have a predefined order.
Let’s add sizes of T-shirts to our Dataframe. The goal of the analysis is to calculate the mean price for each size:
df = pd.DataFrame({'price': [1.99, 3, 5], 'size': ['medium', 'large', 'small']})df_avg = df.groupby('size').price.mean()df_avg
Sizes have a random order in the table above. It should be ordered: small, medium, large. As sizes are strings we cannot use the sort_values function. Here comes reindex function to the rescue:
df_avg.reindex(['small', 'medium', 'large'])
By specifying the order of sizes in the reindex function makes a result table easier to interpret.
See pandas, documentation to learn more about reindex function.
Describe function is an essential tool when working on Exploratory Data Analysis. It shows basic summary statistics for all columns in a DataFrame.
df.price.describe()
What if we would like to calculate 10 quantiles instead of 3?
df.price.describe(percentiles=np.arange(0, 1, 0.1))
Describe function takes percentiles argument. We can specify the number of percentiles with NumPy’s arange function to avoid typing each percentile by hand.
This feature becomes really useful when combined with the group by function:
df.groupby('size').describe(percentiles=np.arange(0, 1, 0.1))
See pandas, documentation to learn more about describe function.
Our T-shirt dataset has 3 sizes. Let’s say we would like to filter small and medium sizes. A cumbersome way of filtering is:
df[(df['size'] == 'small') | (df['size'] == 'medium')]
This is bad because we usually combine it with other filters, which makes the expression unreadable. Is there a better way?
pandas string columns have an “str” accessor, which implements many functions that simplify manipulating string. One of them is “contains” function, which supports search with regular expressions.
df[df['size'].str.contains('small|medium')]
The filter with “contains” function is more readable, easier to extend and combine with other filters.
See pandas, documentation to learn more about contains function.
pandas cannot even read bigger than the main memory datasets. It throws a MemoryError or Jupyter Kernel crashes. But to process a big dataset you don’t need Dask or Vaex. You just need some ingenuity. Sounds too good to be true?
In case you’ve missed my article about Dask and Vaex with bigger than main memory datasets:
towardsdatascience.com
When doing an analysis you usually don’t need all rows or all columns in the dataset.
In a case, you don’t need all rows, you can read the dataset in chunks and filter unnecessary rows to reduce the memory usage:
iter_csv = pd.read_csv('dataset.csv', iterator=True, chunksize=1000)df = pd.concat([chunk[chunk['field'] > constant] for chunk in iter_csv])
Reading a dataset in chunks is slower than reading it all once. I would recommend using this approach only with bigger than memory datasets.
In a case, you don’t need all columns, you can specify required columns with “usecols” argument when reading a dataset:
df = pd.read_csv('file.csv', usecols=['col1', 'col2'])
The great thing about these two approaches is that you can combine them.
When working on multiple Data Science projects, you usually end up with many preprocessed datasets from different experiments. The small SSD on a laptop can get cluttered quickly.
Pandas enables us to compress the dataset when saving it and then reading back in compressed format.
Let’s create a big pandas DataFrame with random numbers.
import numpy as npdf = pd.DataFrame(np.random.randn(50000,300))
When we save this file as CSV, it takes almost 300 MB on the hard drive.
df.to_csv('random_data.csv', index=False)
We can reduce the file size to 136 MB by using gz extension instead of csv.
df.to_csv('random_data.gz', index=False)
We don’t lose any functionality with this as it is also easy to read the gzipped data to the DataFrame.
df = pd.read_csv('random_data.gz')
In this article, I’ve listed 11 pandas functions that I use daily to wrangle data and perform the analysis.
I’m sure you’re already met a few of them, but maybe you were using those functions in the wrong way. A good example is setting a new column into a DataFrame.
Pandas has multiple ways of achieving the same goal — some are more correct than others. Using the pandas-preferred approach will bring you fewer problems in the long run.
It’s always good to be on the safe side
- Correlation Analysis 101 in Python [Article]- 50% Off All AI Nanodegree Programs! [Course]- Data Science for Business Leaders [Course]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
|
[
{
"code": null,
"e": 344,
"s": 172,
"text": "I’ve been using pandas for a few years and each time I feel I am typing too much, I google the operation and I usually find a shorter way of doing it — a new pandas trick!"
},
{
"code": null,
"e": 435,
"s": 344,
"text": "I learned about these functions recently and I deem them essential because of ease of use."
},
{
"code": null,
"e": 474,
"s": 435,
"text": "By reading this article, you’ll learn:"
},
{
"code": null,
"e": 900,
"s": 474,
"text": "How to retrieve a column value from a DataframeHow to change a column value in a DataframeThe proper way of adding a new column to a DataFrameHow to retrieve a Series or a DataFrameHow to create a DataFrame from a pandas SeriesFilter with between functionFix the order of the rows with reindex functionAdvanced usages of Describe functionText search with regexBigger than memory datasets with pandasHow to save the disk space"
},
{
"code": null,
"e": 948,
"s": 900,
"text": "How to retrieve a column value from a Dataframe"
},
{
"code": null,
"e": 992,
"s": 948,
"text": "How to change a column value in a Dataframe"
},
{
"code": null,
"e": 1045,
"s": 992,
"text": "The proper way of adding a new column to a DataFrame"
},
{
"code": null,
"e": 1085,
"s": 1045,
"text": "How to retrieve a Series or a DataFrame"
},
{
"code": null,
"e": 1132,
"s": 1085,
"text": "How to create a DataFrame from a pandas Series"
},
{
"code": null,
"e": 1161,
"s": 1132,
"text": "Filter with between function"
},
{
"code": null,
"e": 1209,
"s": 1161,
"text": "Fix the order of the rows with reindex function"
},
{
"code": null,
"e": 1246,
"s": 1209,
"text": "Advanced usages of Describe function"
},
{
"code": null,
"e": 1269,
"s": 1246,
"text": "Text search with regex"
},
{
"code": null,
"e": 1309,
"s": 1269,
"text": "Bigger than memory datasets with pandas"
},
{
"code": null,
"e": 1336,
"s": 1309,
"text": "How to save the disk space"
},
{
"code": null,
"e": 1398,
"s": 1336,
"text": "Let’s create a simple DataFrame to show these tips in action:"
},
{
"code": null,
"e": 1483,
"s": 1398,
"text": "import pandas as pddf = pd.DataFrame({\"col1\": [\"A0\", \"A1\", \"A0\", \"A2\", \"A0\", \"A1\"]})"
},
{
"code": null,
"e": 1548,
"s": 1483,
"text": "There are two ways of retrieving column values from a DataFrame:"
},
{
"code": null,
"e": 1591,
"s": 1548,
"text": "based on integer-location indexing (iloc),"
},
{
"code": null,
"e": 1626,
"s": 1591,
"text": "based on the label indexing (loc)."
},
{
"code": null,
"e": 1710,
"s": 1626,
"text": "To retrieve the first column value for the col1 column (integer-location indexing):"
},
{
"code": null,
"e": 1740,
"s": 1710,
"text": "df.iloc[0].col1# output: 'A0'"
},
{
"code": null,
"e": 1775,
"s": 1740,
"text": "To retrieve the last column value:"
},
{
"code": null,
"e": 1806,
"s": 1775,
"text": "df.iloc[-1].col1# output: ‘A1’"
},
{
"code": null,
"e": 1959,
"s": 1806,
"text": "You can also retrieve a column value with the label. By default, pandas DataFrame has indices from 0 to n, where n is the number of rows in a DataFrame."
},
{
"code": null,
"e": 1991,
"s": 1959,
"text": "df.loc[1, “col1”]# output: ‘A1’"
},
{
"code": null,
"e": 2060,
"s": 1991,
"text": "See pandas documentation to learn more about loc and iloc functions."
},
{
"code": null,
"e": 2260,
"s": 2060,
"text": "Similar to the example above, you can change the value of a column with loc and iloc functions. Which one you use depends if you have the integer position of the row (iloc) or label of the row (loc)."
},
{
"code": null,
"e": 2320,
"s": 2260,
"text": "To change the first column value based on integer position:"
},
{
"code": null,
"e": 2346,
"s": 2320,
"text": "df.iloc[0].col1 = “First”"
},
{
"code": null,
"e": 2405,
"s": 2346,
"text": "To change the last column value based on integer position:"
},
{
"code": null,
"e": 2431,
"s": 2405,
"text": "df.iloc[-1].col1 = “Last”"
},
{
"code": null,
"e": 2468,
"s": 2431,
"text": "To change the column value by label:"
},
{
"code": null,
"e": 2496,
"s": 2468,
"text": "df.loc[2, “col1”] = “Index”"
},
{
"code": null,
"e": 2555,
"s": 2496,
"text": "By applying these changes, we get the following Dataframe:"
},
{
"code": null,
"e": 2635,
"s": 2555,
"text": "Let’s say we would like to add a list of integers as a column to our DataFrame."
},
{
"code": null,
"e": 2706,
"s": 2635,
"text": "new_column = list(range(len(df))new_column# output: [0, 1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 2749,
"s": 2706,
"text": "How NOT to add a column (it doesn’t work):"
},
{
"code": null,
"e": 2777,
"s": 2749,
"text": "df.new_column1 = new_column"
},
{
"code": null,
"e": 2863,
"s": 2777,
"text": "Also NOT a proper way of adding a column, but it works. You might get a copy warning."
},
{
"code": null,
"e": 2894,
"s": 2863,
"text": "df[\"new_column2\"] = new_column"
},
{
"code": null,
"e": 2926,
"s": 2894,
"text": "A good way to add a new column:"
},
{
"code": null,
"e": 2964,
"s": 2926,
"text": "df.loc[:, ‘new_column3’] = new_column"
},
{
"code": null,
"e": 2980,
"s": 2964,
"text": "The proper way:"
},
{
"code": null,
"e": 3019,
"s": 2980,
"text": "df = df.assign(new_column4=new_column)"
},
{
"code": null,
"e": 3128,
"s": 3019,
"text": "assign function also takes an index as an argument with which we can define the order of rows in the column."
},
{
"code": null,
"e": 3309,
"s": 3128,
"text": "You might be tempted to add the inplace=True argument to the assign function to add a new column in place, but it won’t work. The assign function will also add the in-place column."
},
{
"code": null,
"e": 3384,
"s": 3309,
"text": "# This will add two columnsdf.assign(new_column4=new_column, inplace=True)"
},
{
"code": null,
"e": 3488,
"s": 3384,
"text": "This is actually another benefit of the assign function. You can add multiple columns at the same time."
},
{
"code": null,
"e": 3551,
"s": 3488,
"text": "See pandas documentation, to learn more about assign function."
},
{
"code": null,
"e": 3613,
"s": 3551,
"text": "When using square brackets with pandas DataFrame, it returns:"
},
{
"code": null,
"e": 3656,
"s": 3613,
"text": "a Series if you use single square brackets"
},
{
"code": null,
"e": 3703,
"s": 3656,
"text": "a Dataframe if you use double square brackets."
},
{
"code": null,
"e": 3729,
"s": 3703,
"text": "Let’s look at an example."
},
{
"code": null,
"e": 3772,
"s": 3729,
"text": "How to retrieve a Series from a Dataframe?"
},
{
"code": null,
"e": 3783,
"s": 3772,
"text": "df[\"col1\"]"
},
{
"code": null,
"e": 3827,
"s": 3783,
"text": "type(df[\"col1\"])# pandas.core.series.Series"
},
{
"code": null,
"e": 3900,
"s": 3827,
"text": "How to retrieve a DataFrame (with a subset of columns) from a Dataframe?"
},
{
"code": null,
"e": 3913,
"s": 3900,
"text": "df[[\"col1\"]]"
},
{
"code": null,
"e": 3961,
"s": 3913,
"text": "type(df[[\"col1\"]])# pandas.core.frame.DataFrame"
},
{
"code": null,
"e": 4097,
"s": 3961,
"text": "When performing a grouping with aggregation, pandas returns a Series. What is the simplest way to convert a Series back to a Dataframe?"
},
{
"code": null,
"e": 4123,
"s": 4097,
"text": "Let’s look at an example:"
},
{
"code": null,
"e": 4289,
"s": 4123,
"text": "df = pd.DataFrame( { \"col1\": [\"A0\", \"A1\", \"A0\", \"A2\", \"A0\", \"A1\"], \"col2\": [1, 2, 3, 4, 5, 6], })df_group = df.groupby(\"col1\").col2.sum()df_group"
},
{
"code": null,
"e": 4311,
"s": 4289,
"text": "df_group is a Series."
},
{
"code": null,
"e": 4388,
"s": 4311,
"text": "Series has a to_frame function, which can covert a Series back to DataFrame:"
},
{
"code": null,
"e": 4408,
"s": 4388,
"text": "df_group.to_frame()"
},
{
"code": null,
"e": 4473,
"s": 4408,
"text": "See pandas documentation, to learn more about to_frame function."
},
{
"code": null,
"e": 4571,
"s": 4473,
"text": "I’ve been using “between” function in SQL for years, but I only discovered it recently in pandas."
},
{
"code": null,
"e": 4665,
"s": 4571,
"text": "Let’s say we have a DataFrame with prices and we would like to filter prices between 2 and 4."
},
{
"code": null,
"e": 4728,
"s": 4665,
"text": "df = pd.DataFrame({'price': [1.99, 3, 5, 0.5, 3.5, 5.5, 3.9]})"
},
{
"code": null,
"e": 4779,
"s": 4728,
"text": "With between function, you can reduce this filter:"
},
{
"code": null,
"e": 4817,
"s": 4779,
"text": "df[(df.price >= 2) & (df.price <= 4)]"
},
{
"code": null,
"e": 4826,
"s": 4817,
"text": "To this:"
},
{
"code": null,
"e": 4853,
"s": 4826,
"text": "df[df.price.between(2, 4)]"
},
{
"code": null,
"e": 4995,
"s": 4853,
"text": "It might not seem much, but those parentheses are annoying when writing many filters. The filter with between function is also more readable."
},
{
"code": null,
"e": 5051,
"s": 4995,
"text": "between function sets interval left <= series <= right."
},
{
"code": null,
"e": 5115,
"s": 5051,
"text": "See pandas, documentation to learn more about between function."
},
{
"code": null,
"e": 5281,
"s": 5115,
"text": "The reindex function conforms a Series or a DataFrame to a new index. I resort to the reindex function when making reports with columns that have a predefined order."
},
{
"code": null,
"e": 5398,
"s": 5281,
"text": "Let’s add sizes of T-shirts to our Dataframe. The goal of the analysis is to calculate the mean price for each size:"
},
{
"code": null,
"e": 5525,
"s": 5398,
"text": "df = pd.DataFrame({'price': [1.99, 3, 5], 'size': ['medium', 'large', 'small']})df_avg = df.groupby('size').price.mean()df_avg"
},
{
"code": null,
"e": 5719,
"s": 5525,
"text": "Sizes have a random order in the table above. It should be ordered: small, medium, large. As sizes are strings we cannot use the sort_values function. Here comes reindex function to the rescue:"
},
{
"code": null,
"e": 5764,
"s": 5719,
"text": "df_avg.reindex(['small', 'medium', 'large'])"
},
{
"code": null,
"e": 5863,
"s": 5764,
"text": "By specifying the order of sizes in the reindex function makes a result table easier to interpret."
},
{
"code": null,
"e": 5927,
"s": 5863,
"text": "See pandas, documentation to learn more about reindex function."
},
{
"code": null,
"e": 6075,
"s": 5927,
"text": "Describe function is an essential tool when working on Exploratory Data Analysis. It shows basic summary statistics for all columns in a DataFrame."
},
{
"code": null,
"e": 6095,
"s": 6075,
"text": "df.price.describe()"
},
{
"code": null,
"e": 6157,
"s": 6095,
"text": "What if we would like to calculate 10 quantiles instead of 3?"
},
{
"code": null,
"e": 6209,
"s": 6157,
"text": "df.price.describe(percentiles=np.arange(0, 1, 0.1))"
},
{
"code": null,
"e": 6366,
"s": 6209,
"text": "Describe function takes percentiles argument. We can specify the number of percentiles with NumPy’s arange function to avoid typing each percentile by hand."
},
{
"code": null,
"e": 6443,
"s": 6366,
"text": "This feature becomes really useful when combined with the group by function:"
},
{
"code": null,
"e": 6505,
"s": 6443,
"text": "df.groupby('size').describe(percentiles=np.arange(0, 1, 0.1))"
},
{
"code": null,
"e": 6570,
"s": 6505,
"text": "See pandas, documentation to learn more about describe function."
},
{
"code": null,
"e": 6695,
"s": 6570,
"text": "Our T-shirt dataset has 3 sizes. Let’s say we would like to filter small and medium sizes. A cumbersome way of filtering is:"
},
{
"code": null,
"e": 6750,
"s": 6695,
"text": "df[(df['size'] == 'small') | (df['size'] == 'medium')]"
},
{
"code": null,
"e": 6874,
"s": 6750,
"text": "This is bad because we usually combine it with other filters, which makes the expression unreadable. Is there a better way?"
},
{
"code": null,
"e": 7071,
"s": 6874,
"text": "pandas string columns have an “str” accessor, which implements many functions that simplify manipulating string. One of them is “contains” function, which supports search with regular expressions."
},
{
"code": null,
"e": 7115,
"s": 7071,
"text": "df[df['size'].str.contains('small|medium')]"
},
{
"code": null,
"e": 7218,
"s": 7115,
"text": "The filter with “contains” function is more readable, easier to extend and combine with other filters."
},
{
"code": null,
"e": 7283,
"s": 7218,
"text": "See pandas, documentation to learn more about contains function."
},
{
"code": null,
"e": 7512,
"s": 7283,
"text": "pandas cannot even read bigger than the main memory datasets. It throws a MemoryError or Jupyter Kernel crashes. But to process a big dataset you don’t need Dask or Vaex. You just need some ingenuity. Sounds too good to be true?"
},
{
"code": null,
"e": 7604,
"s": 7512,
"text": "In case you’ve missed my article about Dask and Vaex with bigger than main memory datasets:"
},
{
"code": null,
"e": 7627,
"s": 7604,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7713,
"s": 7627,
"text": "When doing an analysis you usually don’t need all rows or all columns in the dataset."
},
{
"code": null,
"e": 7840,
"s": 7713,
"text": "In a case, you don’t need all rows, you can read the dataset in chunks and filter unnecessary rows to reduce the memory usage:"
},
{
"code": null,
"e": 7981,
"s": 7840,
"text": "iter_csv = pd.read_csv('dataset.csv', iterator=True, chunksize=1000)df = pd.concat([chunk[chunk['field'] > constant] for chunk in iter_csv])"
},
{
"code": null,
"e": 8122,
"s": 7981,
"text": "Reading a dataset in chunks is slower than reading it all once. I would recommend using this approach only with bigger than memory datasets."
},
{
"code": null,
"e": 8242,
"s": 8122,
"text": "In a case, you don’t need all columns, you can specify required columns with “usecols” argument when reading a dataset:"
},
{
"code": null,
"e": 8297,
"s": 8242,
"text": "df = pd.read_csv('file.csv', usecols=['col1', 'col2'])"
},
{
"code": null,
"e": 8370,
"s": 8297,
"text": "The great thing about these two approaches is that you can combine them."
},
{
"code": null,
"e": 8550,
"s": 8370,
"text": "When working on multiple Data Science projects, you usually end up with many preprocessed datasets from different experiments. The small SSD on a laptop can get cluttered quickly."
},
{
"code": null,
"e": 8651,
"s": 8550,
"text": "Pandas enables us to compress the dataset when saving it and then reading back in compressed format."
},
{
"code": null,
"e": 8708,
"s": 8651,
"text": "Let’s create a big pandas DataFrame with random numbers."
},
{
"code": null,
"e": 8772,
"s": 8708,
"text": "import numpy as npdf = pd.DataFrame(np.random.randn(50000,300))"
},
{
"code": null,
"e": 8845,
"s": 8772,
"text": "When we save this file as CSV, it takes almost 300 MB on the hard drive."
},
{
"code": null,
"e": 8887,
"s": 8845,
"text": "df.to_csv('random_data.csv', index=False)"
},
{
"code": null,
"e": 8963,
"s": 8887,
"text": "We can reduce the file size to 136 MB by using gz extension instead of csv."
},
{
"code": null,
"e": 9004,
"s": 8963,
"text": "df.to_csv('random_data.gz', index=False)"
},
{
"code": null,
"e": 9108,
"s": 9004,
"text": "We don’t lose any functionality with this as it is also easy to read the gzipped data to the DataFrame."
},
{
"code": null,
"e": 9143,
"s": 9108,
"text": "df = pd.read_csv('random_data.gz')"
},
{
"code": null,
"e": 9251,
"s": 9143,
"text": "In this article, I’ve listed 11 pandas functions that I use daily to wrangle data and perform the analysis."
},
{
"code": null,
"e": 9410,
"s": 9251,
"text": "I’m sure you’re already met a few of them, but maybe you were using those functions in the wrong way. A good example is setting a new column into a DataFrame."
},
{
"code": null,
"e": 9582,
"s": 9410,
"text": "Pandas has multiple ways of achieving the same goal — some are more correct than others. Using the pandas-preferred approach will bring you fewer problems in the long run."
},
{
"code": null,
"e": 9622,
"s": 9582,
"text": "It’s always good to be on the safe side"
},
{
"code": null,
"e": 9826,
"s": 9622,
"text": "- Correlation Analysis 101 in Python [Article]- 50% Off All AI Nanodegree Programs! [Course]- Data Science for Business Leaders [Course]- Free skill tests for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 10063,
"s": 9826,
"text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases."
}
] |
Python | Check if two lists have at-least one element common
|
21 Nov, 2018
Given two lists a, b. Check if two lists have at least one element common in them.
Examples:
Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
Output : True
Input : a=[1, 2, 3, 4, 5]
b=[6, 7, 8, 9]
Output : False
Method 1 : Traversal of List
Using traversal in two lists, we can check if there exists one common element at least in them. While traversing two lists if we find one element to be common in them, then we return true. After complete traversal and checking, if no elements are same, then we return false.
# Python program to check # if two lists have at-least # one element common# using traversal of list def common_data(list1, list2): result = False # traverse in the 1st list for x in list1: # traverse in the 2nd list for y in list2: # if one common if x == y: result = True return result return result # driver codea = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_data(a, b)) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9]print(common_data(a, b))
Output:
True
False
Method 2 : Using Set and Property
Using set’s and property, if there exists at least one common element then set(a)&set(b) returns a positive integer, if it does not contains any positive integer, then it returns 0. So we insert a in set_a and b in set_b and then check if set_a & set_b for a positive integer or not.
# Python program to check # if two lists have at-least # one element common# using set and property def common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): return True else: return False a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b))
Output:
True
False
Method 3 : Using Set Intersection
Using set’s intersection inbuilt function. a_set.intersection(b_set) returns a positive integer if there is at least one element in common, else it returns 0. So we insert a in set_a and b in set_b and then check a_set.intersection(b_set), and returns depending on the value.
# Python program to check # if two lists have at-least # one element common# using set intersection def common_member(a, b): a_set = set(a) b_set = set(b) if len(a_set.intersection(b_set)) > 0: return(True) return(False) a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b))
Output:
True
False
Python list-programs
Python set-programs
python-list
python-set
Python
python-list
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "Given two lists a, b. Check if two lists have at least one element common in them."
},
{
"code": null,
"e": 121,
"s": 111,
"text": "Examples:"
},
{
"code": null,
"e": 257,
"s": 121,
"text": "Input : a = [1, 2, 3, 4, 5]\n b = [5, 6, 7, 8, 9]\nOutput : True\n\nInput : a=[1, 2, 3, 4, 5]\n b=[6, 7, 8, 9]\nOutput : False\n"
},
{
"code": null,
"e": 286,
"s": 257,
"text": "Method 1 : Traversal of List"
},
{
"code": null,
"e": 561,
"s": 286,
"text": "Using traversal in two lists, we can check if there exists one common element at least in them. While traversing two lists if we find one element to be common in them, then we return true. After complete traversal and checking, if no elements are same, then we return false."
},
{
"code": "# Python program to check # if two lists have at-least # one element common# using traversal of list def common_data(list1, list2): result = False # traverse in the 1st list for x in list1: # traverse in the 2nd list for y in list2: # if one common if x == y: result = True return result return result # driver codea = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_data(a, b)) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9]print(common_data(a, b))",
"e": 1111,
"s": 561,
"text": null
},
{
"code": null,
"e": 1119,
"s": 1111,
"text": "Output:"
},
{
"code": null,
"e": 1132,
"s": 1119,
"text": "True \nFalse\n"
},
{
"code": null,
"e": 1166,
"s": 1132,
"text": "Method 2 : Using Set and Property"
},
{
"code": null,
"e": 1450,
"s": 1166,
"text": "Using set’s and property, if there exists at least one common element then set(a)&set(b) returns a positive integer, if it does not contains any positive integer, then it returns 0. So we insert a in set_a and b in set_b and then check if set_a & set_b for a positive integer or not."
},
{
"code": "# Python program to check # if two lists have at-least # one element common# using set and property def common_member(a, b): a_set = set(a) b_set = set(b) if (a_set & b_set): return True else: return False a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b))",
"e": 1821,
"s": 1450,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1821,
"text": "Output:"
},
{
"code": null,
"e": 1842,
"s": 1829,
"text": "True \nFalse\n"
},
{
"code": null,
"e": 1876,
"s": 1842,
"text": "Method 3 : Using Set Intersection"
},
{
"code": null,
"e": 2152,
"s": 1876,
"text": "Using set’s intersection inbuilt function. a_set.intersection(b_set) returns a positive integer if there is at least one element in common, else it returns 0. So we insert a in set_a and b in set_b and then check a_set.intersection(b_set), and returns depending on the value."
},
{
"code": "# Python program to check # if two lists have at-least # one element common# using set intersection def common_member(a, b): a_set = set(a) b_set = set(b) if len(a_set.intersection(b_set)) > 0: return(True) return(False) a = [1, 2, 3, 4, 5]b = [5, 6, 7, 8, 9]print(common_member(a, b)) a =[1, 2, 3, 4, 5]b =[6, 7, 8, 9]print(common_member(a, b))",
"e": 2524,
"s": 2152,
"text": null
},
{
"code": null,
"e": 2532,
"s": 2524,
"text": "Output:"
},
{
"code": null,
"e": 2545,
"s": 2532,
"text": "True \nFalse\n"
},
{
"code": null,
"e": 2566,
"s": 2545,
"text": "Python list-programs"
},
{
"code": null,
"e": 2586,
"s": 2566,
"text": "Python set-programs"
},
{
"code": null,
"e": 2598,
"s": 2586,
"text": "python-list"
},
{
"code": null,
"e": 2609,
"s": 2598,
"text": "python-set"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "Python"
},
{
"code": null,
"e": 2628,
"s": 2616,
"text": "python-list"
},
{
"code": null,
"e": 2639,
"s": 2628,
"text": "python-set"
}
] |
R – Line Graphs
|
09 Dec, 2021
A line graph is a chart that is used to display information in the form of a series of data points. It utilizes points and lines to represent change over time. Line graphs are drawn by plotting different points on their X coordinates and Y coordinates, then by joining them together through a line from beginning to end. The graph represents different values as it can move up and down based on the suitable variable.
The plot() function in R is used to create the line graph.
Syntax: plot(v, type, col, xlab, ylab)
Parameters:
v: This parameter is a contains only the numeric values
type: This parameter has the following value: “p” : This value is used to draw only the points.“l” : This value is used to draw only the lines.“o”: This value is used to draw both points and lines
“p” : This value is used to draw only the points.“l” : This value is used to draw only the lines.“o”: This value is used to draw both points and lines
“p” : This value is used to draw only the points.
“l” : This value is used to draw only the lines.
“o”: This value is used to draw both points and lines
xlab: This parameter is the label for x axis in the chart.
ylab: This parameter is the label for y axis in the chart.
main: This parameter main is the title of the chart.
col: This parameter is used to give colors to both the points and lines.
Approach: In order to create a line graph:
It is created using the type parameter as “o” and input vector.Below code to describe the line graph.
It is created using the type parameter as “o” and input vector.
Below code to describe the line graph.
Example:
R
# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = "o")
Output:
Approach: To create a colored and labeled line chart.
Take all parameters which are required to make line chart by giving a title to the chart and add labels to the axes.We can add more features by adding more parameters with more colors to the points and lines.
Take all parameters which are required to make line chart by giving a title to the chart and add labels to the axes.
We can add more features by adding more parameters with more colors to the points and lines.
Example:
R
# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = "o", col = "green", xlab = "Month", ylab = "Article Written", main = "Article Written chart")
Output:
Approach: To create multiple line graphs.
In above example, we created line graphs by only one line in each graph.Now creating multiple lines to describe it more clearly.
In above example, we created line graphs by only one line in each graph.
Now creating multiple lines to describe it more clearly.
Example:
R
# Create the data for the chart.v <- c(17, 25, 38, 13, 41)t <- c(22, 19, 36, 19, 23)m <- c(25, 14, 16, 34, 29) # Plot the bar chart.plot(v, type = "o", col = "red", xlab = "Month", ylab = "Article Written ", main = "Article Written chart") lines(t, type = "o", col = "blue")lines(m, type = "o", col = "green")
Output: When we execute the above code, it shows the following result-
kumar_satyam
Picked
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "A line graph is a chart that is used to display information in the form of a series of data points. It utilizes points and lines to represent change over time. Line graphs are drawn by plotting different points on their X coordinates and Y coordinates, then by joining them together through a line from beginning to end. The graph represents different values as it can move up and down based on the suitable variable."
},
{
"code": null,
"e": 505,
"s": 446,
"text": "The plot() function in R is used to create the line graph."
},
{
"code": null,
"e": 544,
"s": 505,
"text": "Syntax: plot(v, type, col, xlab, ylab)"
},
{
"code": null,
"e": 557,
"s": 544,
"text": "Parameters: "
},
{
"code": null,
"e": 613,
"s": 557,
"text": "v: This parameter is a contains only the numeric values"
},
{
"code": null,
"e": 810,
"s": 613,
"text": "type: This parameter has the following value: “p” : This value is used to draw only the points.“l” : This value is used to draw only the lines.“o”: This value is used to draw both points and lines"
},
{
"code": null,
"e": 961,
"s": 810,
"text": "“p” : This value is used to draw only the points.“l” : This value is used to draw only the lines.“o”: This value is used to draw both points and lines"
},
{
"code": null,
"e": 1011,
"s": 961,
"text": "“p” : This value is used to draw only the points."
},
{
"code": null,
"e": 1060,
"s": 1011,
"text": "“l” : This value is used to draw only the lines."
},
{
"code": null,
"e": 1114,
"s": 1060,
"text": "“o”: This value is used to draw both points and lines"
},
{
"code": null,
"e": 1173,
"s": 1114,
"text": "xlab: This parameter is the label for x axis in the chart."
},
{
"code": null,
"e": 1232,
"s": 1173,
"text": "ylab: This parameter is the label for y axis in the chart."
},
{
"code": null,
"e": 1285,
"s": 1232,
"text": "main: This parameter main is the title of the chart."
},
{
"code": null,
"e": 1358,
"s": 1285,
"text": "col: This parameter is used to give colors to both the points and lines."
},
{
"code": null,
"e": 1402,
"s": 1358,
"text": "Approach: In order to create a line graph: "
},
{
"code": null,
"e": 1504,
"s": 1402,
"text": "It is created using the type parameter as “o” and input vector.Below code to describe the line graph."
},
{
"code": null,
"e": 1568,
"s": 1504,
"text": "It is created using the type parameter as “o” and input vector."
},
{
"code": null,
"e": 1607,
"s": 1568,
"text": "Below code to describe the line graph."
},
{
"code": null,
"e": 1617,
"s": 1607,
"text": "Example: "
},
{
"code": null,
"e": 1619,
"s": 1617,
"text": "R"
},
{
"code": "# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = \"o\")",
"e": 1719,
"s": 1619,
"text": null
},
{
"code": null,
"e": 1728,
"s": 1719,
"text": "Output: "
},
{
"code": null,
"e": 1783,
"s": 1728,
"text": "Approach: To create a colored and labeled line chart. "
},
{
"code": null,
"e": 1992,
"s": 1783,
"text": "Take all parameters which are required to make line chart by giving a title to the chart and add labels to the axes.We can add more features by adding more parameters with more colors to the points and lines."
},
{
"code": null,
"e": 2109,
"s": 1992,
"text": "Take all parameters which are required to make line chart by giving a title to the chart and add labels to the axes."
},
{
"code": null,
"e": 2202,
"s": 2109,
"text": "We can add more features by adding more parameters with more colors to the points and lines."
},
{
"code": null,
"e": 2212,
"s": 2202,
"text": "Example: "
},
{
"code": null,
"e": 2214,
"s": 2212,
"text": "R"
},
{
"code": "# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = \"o\", col = \"green\", xlab = \"Month\", ylab = \"Article Written\", main = \"Article Written chart\")",
"e": 2409,
"s": 2214,
"text": null
},
{
"code": null,
"e": 2418,
"s": 2409,
"text": "Output: "
},
{
"code": null,
"e": 2461,
"s": 2418,
"text": "Approach: To create multiple line graphs. "
},
{
"code": null,
"e": 2590,
"s": 2461,
"text": "In above example, we created line graphs by only one line in each graph.Now creating multiple lines to describe it more clearly."
},
{
"code": null,
"e": 2663,
"s": 2590,
"text": "In above example, we created line graphs by only one line in each graph."
},
{
"code": null,
"e": 2720,
"s": 2663,
"text": "Now creating multiple lines to describe it more clearly."
},
{
"code": null,
"e": 2730,
"s": 2720,
"text": "Example: "
},
{
"code": null,
"e": 2732,
"s": 2730,
"text": "R"
},
{
"code": "# Create the data for the chart.v <- c(17, 25, 38, 13, 41)t <- c(22, 19, 36, 19, 23)m <- c(25, 14, 16, 34, 29) # Plot the bar chart.plot(v, type = \"o\", col = \"red\", xlab = \"Month\", ylab = \"Article Written \", main = \"Article Written chart\") lines(t, type = \"o\", col = \"blue\")lines(m, type = \"o\", col = \"green\")",
"e": 3048,
"s": 2732,
"text": null
},
{
"code": null,
"e": 3120,
"s": 3048,
"text": "Output: When we execute the above code, it shows the following result- "
},
{
"code": null,
"e": 3133,
"s": 3120,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3140,
"s": 3133,
"text": "Picked"
},
{
"code": null,
"e": 3148,
"s": 3140,
"text": "R-plots"
},
{
"code": null,
"e": 3159,
"s": 3148,
"text": "R Language"
}
] |
C++ Program to swap two members using Friend Function
|
07 Jul, 2022
Pre-requisite: Friend FunctionCASE 1: Given two numbers a & b, swap these two numbers using the friend function of C++.
Examples:
Input : a = 5, b = 9
Output : a = 9, b = 5
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach: Create a class Swap, declare three variables in it, i.e., a, b, and temp and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation with Swap variables.
C++
// C++ Program to swap two numbers using friend function#include <iostream> using namespace std; class Swap { // Declare the variables of Swap Class int temp, a, b; public: // Define the parameterized constructor, for inputs Swap(int a, int b) { this->a = a; this->b = b; } // Declare the friend function to swap, take arguments // as call by reference friend void swap(Swap&);}; // Define the swap function outside class scopevoid swap(Swap& s1){ // Call by reference is used to passed object copy to // the function cout << "\nBefore Swapping: " << s1.a << " " << s1.b; // Swap operations with Swap Class variables s1.temp = s1.a; s1.a = s1.b; s1.b = s1.temp; cout << "\nAfter Swapping: " << s1.a << " " << s1.b;} // Driver Codeint main(){ // Declare and Initialize the Swap object Swap s(4, 6); swap(s); return 0;}
Before Swapping: 4 6
After Swapping: 6 4
CASE 2: Given two objects s1 & s2 of a class, swap the data members of these two objects using friend function of C++.
Examples:
Input : a = 6, b = 10
Output : a = 10, b = 6
Input : a = 4, b = 6
Output : a= 6, b = 4
Approach: Create a class Swap, declare one variable in it, i.e., num and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation.
C++
//C++ Program to swap data members of two objects of a class using friend function.#include <iostream> using namespace std; class Swap { // Declare the variable of Swap Class int num; public: // Define the parameterized constructor, for input. Swap(int num) { this->num = num; } // Declare the friend function to swap, take arguments // as call by reference friend void swap(Swap&, Swap&);}; // Define the swap function outside class scopevoid swap(Swap& s1, Swap& s2){ // declare a temporary variable. int temp; // Call by reference is used to passed object copy to // the function cout << "\nBefore Swapping: " << s1.num << " " << s2.num; // Swap operations with objects of class Swap temp = s1.num; s1.num = s2.num; s2.num = temp; cout << "\nAfter Swapping: " << s1.num << " " << s2.num;} // Driver Codeint main(){ // Declare and Initialize the objects of Swap class Swap s1(6), s2(10); swap(s1,s2); return 0;}
Before Swapping: 6 10
After Swapping: 10 6
Time Complexity: O(1)Auxiliary Space: O(1)
routpranab03
gabaa406
jayanth_mkv
cpp-friend
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 174,
"s": 53,
"text": "Pre-requisite: Friend FunctionCASE 1: Given two numbers a & b, swap these two numbers using the friend function of C++. "
},
{
"code": null,
"e": 185,
"s": 174,
"text": "Examples: "
},
{
"code": null,
"e": 271,
"s": 185,
"text": "Input : a = 5, b = 9\nOutput : a = 9, b = 5\n\nInput : a = 4, b = 6\nOutput : a= 6, b = 4"
},
{
"code": null,
"e": 597,
"s": 271,
"text": "Approach: Create a class Swap, declare three variables in it, i.e., a, b, and temp and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation with Swap variables."
},
{
"code": null,
"e": 601,
"s": 597,
"text": "C++"
},
{
"code": "// C++ Program to swap two numbers using friend function#include <iostream> using namespace std; class Swap { // Declare the variables of Swap Class int temp, a, b; public: // Define the parameterized constructor, for inputs Swap(int a, int b) { this->a = a; this->b = b; } // Declare the friend function to swap, take arguments // as call by reference friend void swap(Swap&);}; // Define the swap function outside class scopevoid swap(Swap& s1){ // Call by reference is used to passed object copy to // the function cout << \"\\nBefore Swapping: \" << s1.a << \" \" << s1.b; // Swap operations with Swap Class variables s1.temp = s1.a; s1.a = s1.b; s1.b = s1.temp; cout << \"\\nAfter Swapping: \" << s1.a << \" \" << s1.b;} // Driver Codeint main(){ // Declare and Initialize the Swap object Swap s(4, 6); swap(s); return 0;}",
"e": 1500,
"s": 601,
"text": null
},
{
"code": null,
"e": 1541,
"s": 1500,
"text": "Before Swapping: 4 6\nAfter Swapping: 6 4"
},
{
"code": null,
"e": 1663,
"s": 1543,
"text": "CASE 2: Given two objects s1 & s2 of a class, swap the data members of these two objects using friend function of C++. "
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": "Examples: "
},
{
"code": null,
"e": 1762,
"s": 1674,
"text": "Input : a = 6, b = 10\nOutput : a = 10, b = 6\n\nInput : a = 4, b = 6\nOutput : a= 6, b = 4"
},
{
"code": null,
"e": 2054,
"s": 1762,
"text": "Approach: Create a class Swap, declare one variable in it, i.e., num and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation."
},
{
"code": null,
"e": 2058,
"s": 2054,
"text": "C++"
},
{
"code": "//C++ Program to swap data members of two objects of a class using friend function.#include <iostream> using namespace std; class Swap { // Declare the variable of Swap Class int num; public: // Define the parameterized constructor, for input. Swap(int num) { this->num = num; } // Declare the friend function to swap, take arguments // as call by reference friend void swap(Swap&, Swap&);}; // Define the swap function outside class scopevoid swap(Swap& s1, Swap& s2){ // declare a temporary variable. int temp; // Call by reference is used to passed object copy to // the function cout << \"\\nBefore Swapping: \" << s1.num << \" \" << s2.num; // Swap operations with objects of class Swap temp = s1.num; s1.num = s2.num; s2.num = temp; cout << \"\\nAfter Swapping: \" << s1.num << \" \" << s2.num;} // Driver Codeint main(){ // Declare and Initialize the objects of Swap class Swap s1(6), s2(10); swap(s1,s2); return 0;}",
"e": 3071,
"s": 2058,
"text": null
},
{
"code": null,
"e": 3114,
"s": 3071,
"text": "Before Swapping: 6 10\nAfter Swapping: 10 6"
},
{
"code": null,
"e": 3159,
"s": 3116,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3172,
"s": 3159,
"text": "routpranab03"
},
{
"code": null,
"e": 3181,
"s": 3172,
"text": "gabaa406"
},
{
"code": null,
"e": 3193,
"s": 3181,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 3204,
"s": 3193,
"text": "cpp-friend"
},
{
"code": null,
"e": 3208,
"s": 3204,
"text": "C++"
},
{
"code": null,
"e": 3221,
"s": 3208,
"text": "C++ Programs"
},
{
"code": null,
"e": 3240,
"s": 3221,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3244,
"s": 3240,
"text": "CPP"
},
{
"code": null,
"e": 3342,
"s": 3244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3366,
"s": 3342,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3386,
"s": 3366,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3411,
"s": 3386,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3444,
"s": 3411,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3488,
"s": 3444,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3523,
"s": 3488,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 3557,
"s": 3523,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 3601,
"s": 3557,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 3660,
"s": 3601,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Python Dictionary clear()
|
13 Jan, 2018
The clear() method removes all items from the dictionary.
Syntax:
dict.clear()
Parameters:
The clear() method doesn't take any parameters.
Returns:
The clear() method doesn't return any value.
Examples:
Input : d = {1: "geeks", 2: "for"}
d.clear()
Output : d = {}
Error:
As we are not passing any parameters there
is no chance for any error.
# Python program to demonstrate working of# dictionary clear()text = {1: "geeks", 2: "for"} text.clear()print('text =', text)
Output:
text = {}
How is it different from assigning {} to a dictionary?Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty.
# Python code to demonstrate difference# clear and {}. text1 = {1: "geeks", 2: "for"}text2 = text1 # Using clear makes both text1 and text2# empty.text1.clear() print('After removing items using clear()')print('text1 =', text1)print('text2 =', text2) text1 = {1: "one", 2: "two"}text2 = text1 # This makes only text1 empty.text1 = {} print('After removing items by assigning {}')print('text1 =', text1)print('text2 =', text2)
Output:
After removing items using clear()
text1 = {}
text2 = {}
After removing items by assigning {}
text1 = {}
text2 = {1: 'one', 2: 'two'}
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jan, 2018"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "The clear() method removes all items from the dictionary."
},
{
"code": null,
"e": 118,
"s": 110,
"text": "Syntax:"
},
{
"code": null,
"e": 132,
"s": 118,
"text": "dict.clear()\n"
},
{
"code": null,
"e": 144,
"s": 132,
"text": "Parameters:"
},
{
"code": null,
"e": 193,
"s": 144,
"text": "The clear() method doesn't take any parameters.\n"
},
{
"code": null,
"e": 202,
"s": 193,
"text": "Returns:"
},
{
"code": null,
"e": 248,
"s": 202,
"text": "The clear() method doesn't return any value.\n"
},
{
"code": null,
"e": 258,
"s": 248,
"text": "Examples:"
},
{
"code": null,
"e": 328,
"s": 258,
"text": "Input : d = {1: \"geeks\", 2: \"for\"}\n d.clear()\nOutput : d = {}\n"
},
{
"code": null,
"e": 335,
"s": 328,
"text": "Error:"
},
{
"code": null,
"e": 407,
"s": 335,
"text": "As we are not passing any parameters there\nis no chance for any error.\n"
},
{
"code": "# Python program to demonstrate working of# dictionary clear()text = {1: \"geeks\", 2: \"for\"} text.clear()print('text =', text)",
"e": 534,
"s": 407,
"text": null
},
{
"code": null,
"e": 542,
"s": 534,
"text": "Output:"
},
{
"code": null,
"e": 553,
"s": 542,
"text": "text = {}\n"
},
{
"code": null,
"e": 908,
"s": 553,
"text": "How is it different from assigning {} to a dictionary?Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty."
},
{
"code": "# Python code to demonstrate difference# clear and {}. text1 = {1: \"geeks\", 2: \"for\"}text2 = text1 # Using clear makes both text1 and text2# empty.text1.clear() print('After removing items using clear()')print('text1 =', text1)print('text2 =', text2) text1 = {1: \"one\", 2: \"two\"}text2 = text1 # This makes only text1 empty.text1 = {} print('After removing items by assigning {}')print('text1 =', text1)print('text2 =', text2)",
"e": 1340,
"s": 908,
"text": null
},
{
"code": null,
"e": 1348,
"s": 1340,
"text": "Output:"
},
{
"code": null,
"e": 1483,
"s": 1348,
"text": "After removing items using clear()\ntext1 = {}\ntext2 = {}\nAfter removing items by assigning {}\ntext1 = {}\ntext2 = {1: 'one', 2: 'two'}\n"
},
{
"code": null,
"e": 1495,
"s": 1483,
"text": "python-dict"
},
{
"code": null,
"e": 1502,
"s": 1495,
"text": "Python"
},
{
"code": null,
"e": 1514,
"s": 1502,
"text": "python-dict"
}
] |
random.seed( ) in Python
|
16 May, 2020
random() function is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
random() function generates numbers for some values. This value is also called seed value.
How Seed Function Works ?Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator. For the first time when there is no previous value, it uses current system time.
Using random.seed() function
Here we will see how we can generate the same random number every time with the same seed value.
Example 1:
# random module is importedimport random for i in range(5): # Any number can be used in place of '0'. random.seed(0) # Generated random number will be between 1 to 1000. print(random.randint(1, 1000))
865
865
865
865
865
Example 2:
# importing random moduleimport random random.seed(3) # print a random number between 1 and 1000.print(random.randint(1, 1000)) # if you want to get the same random number again then,random.seed(3) print(random.randint(1, 1000)) # If seed function is not used # Gives totally unpredictable responses.print(random.randint(1, 1000))
244
244
607
On executing the above code, the above two print statements will generate a response 244 but the third print statement gives an unpredictable response.
Uses of random.seed()
This is used in the generation of a pseudo-random encryption key. Encryption keys are an important part of computer security. These are the kind of secret keys which used to protect data from unauthorized access over the internet.It makes optimization of codes easy where random numbers are used for testing. The output of the code sometime depends on input. So the use of random numbers for testing algorithms can be complex. Also seed function is used to generate same random numbers again and again and simplifies algorithm testing process.
This is used in the generation of a pseudo-random encryption key. Encryption keys are an important part of computer security. These are the kind of secret keys which used to protect data from unauthorized access over the internet.
It makes optimization of codes easy where random numbers are used for testing. The output of the code sometime depends on input. So the use of random numbers for testing algorithms can be complex. Also seed function is used to generate same random numbers again and again and simplifies algorithm testing process.
itsayushisaxena
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2020"
},
{
"code": null,
"e": 262,
"s": 52,
"text": "random() function is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined."
},
{
"code": null,
"e": 353,
"s": 262,
"text": "random() function generates numbers for some values. This value is also called seed value."
},
{
"code": null,
"e": 746,
"s": 353,
"text": "How Seed Function Works ?Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator. For the first time when there is no previous value, it uses current system time."
},
{
"code": null,
"e": 775,
"s": 746,
"text": "Using random.seed() function"
},
{
"code": null,
"e": 872,
"s": 775,
"text": "Here we will see how we can generate the same random number every time with the same seed value."
},
{
"code": null,
"e": 883,
"s": 872,
"text": "Example 1:"
},
{
"code": "# random module is importedimport random for i in range(5): # Any number can be used in place of '0'. random.seed(0) # Generated random number will be between 1 to 1000. print(random.randint(1, 1000)) ",
"e": 1107,
"s": 883,
"text": null
},
{
"code": null,
"e": 1128,
"s": 1107,
"text": "865\n865\n865\n865\n865\n"
},
{
"code": null,
"e": 1140,
"s": 1128,
"text": " Example 2:"
},
{
"code": "# importing random moduleimport random random.seed(3) # print a random number between 1 and 1000.print(random.randint(1, 1000)) # if you want to get the same random number again then,random.seed(3) print(random.randint(1, 1000)) # If seed function is not used # Gives totally unpredictable responses.print(random.randint(1, 1000))",
"e": 1476,
"s": 1140,
"text": null
},
{
"code": null,
"e": 1489,
"s": 1476,
"text": "244\n244\n607\n"
},
{
"code": null,
"e": 1641,
"s": 1489,
"text": "On executing the above code, the above two print statements will generate a response 244 but the third print statement gives an unpredictable response."
},
{
"code": null,
"e": 1663,
"s": 1641,
"text": "Uses of random.seed()"
},
{
"code": null,
"e": 2207,
"s": 1663,
"text": "This is used in the generation of a pseudo-random encryption key. Encryption keys are an important part of computer security. These are the kind of secret keys which used to protect data from unauthorized access over the internet.It makes optimization of codes easy where random numbers are used for testing. The output of the code sometime depends on input. So the use of random numbers for testing algorithms can be complex. Also seed function is used to generate same random numbers again and again and simplifies algorithm testing process."
},
{
"code": null,
"e": 2438,
"s": 2207,
"text": "This is used in the generation of a pseudo-random encryption key. Encryption keys are an important part of computer security. These are the kind of secret keys which used to protect data from unauthorized access over the internet."
},
{
"code": null,
"e": 2752,
"s": 2438,
"text": "It makes optimization of codes easy where random numbers are used for testing. The output of the code sometime depends on input. So the use of random numbers for testing algorithms can be complex. Also seed function is used to generate same random numbers again and again and simplifies algorithm testing process."
},
{
"code": null,
"e": 2768,
"s": 2752,
"text": "itsayushisaxena"
},
{
"code": null,
"e": 2785,
"s": 2768,
"text": "Python-Functions"
},
{
"code": null,
"e": 2792,
"s": 2785,
"text": "Python"
}
] |
Subtract String Lists in Python
|
04 Oct, 2021
Sometimes, while working with lists, we can have a problem in which we need to remove one list elements from other, i.e perform subtraction. This has application across many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + remove() The combination of above functionalities can be used to perform this task. In this, we perform the removal of elements using remove() and check for similar elements using loop.
Python3
# Python3 code to demonstrate working of# Subtract String Lists# using loop + remove() # initialize liststest_list1 = ["gfg", "is", "best", "for", "CS"]test_list2 = ["preferred", "is", "gfg"] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Subtract String Lists# using loop + remove()res = [ ele for ele in test_list1 ]for a in test_list2: if a in test_list1: res.remove(a) # printing resultprint("The Subtracted list is : " + str(res))
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
Method #2 : Using Counter() + elements() The combination of the above functions provides a shorthand to solve this problem. In this, we extract the count of elements in both list and then perform separation by their extraction using element().
Python3
# Python3 code to demonstrate working of# Subtract String Lists# using Counter() + elements()from collections import Counter # initialize liststest_list1 = ["gfg", "is", "best", "for", "CS"]test_list2 = ["preferred", "is", "gfg"] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Subtract String Lists# using Counter() + elements()res = list((Counter(test_list1)-Counter(test_list2)).elements()) # printing resultprint("The Subtracted list is : " + str(res))
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
nidhi_biet
akshaysingh98088
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "Sometimes, while working with lists, we can have a problem in which we need to remove one list elements from other, i.e perform subtraction. This has application across many domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 487,
"s": 275,
"text": "Method #1 : Using loop + remove() The combination of above functionalities can be used to perform this task. In this, we perform the removal of elements using remove() and check for similar elements using loop. "
},
{
"code": null,
"e": 495,
"s": 487,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Subtract String Lists# using loop + remove() # initialize liststest_list1 = [\"gfg\", \"is\", \"best\", \"for\", \"CS\"]test_list2 = [\"preferred\", \"is\", \"gfg\"] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Subtract String Lists# using loop + remove()res = [ ele for ele in test_list1 ]for a in test_list2: if a in test_list1: res.remove(a) # printing resultprint(\"The Subtracted list is : \" + str(res))",
"e": 1014,
"s": 495,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1014,
"text": "The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']\nThe original list 2 : ['preferred', 'is', 'gfg']\nThe Subtracted list is : ['best', 'for', 'CS']"
},
{
"code": null,
"e": 1412,
"s": 1167,
"text": " Method #2 : Using Counter() + elements() The combination of the above functions provides a shorthand to solve this problem. In this, we extract the count of elements in both list and then perform separation by their extraction using element()."
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Subtract String Lists# using Counter() + elements()from collections import Counter # initialize liststest_list1 = [\"gfg\", \"is\", \"best\", \"for\", \"CS\"]test_list2 = [\"preferred\", \"is\", \"gfg\"] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Subtract String Lists# using Counter() + elements()res = list((Counter(test_list1)-Counter(test_list2)).elements()) # printing resultprint(\"The Subtracted list is : \" + str(res))",
"e": 1955,
"s": 1420,
"text": null
},
{
"code": null,
"e": 2108,
"s": 1955,
"text": "The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']\nThe original list 2 : ['preferred', 'is', 'gfg']\nThe Subtracted list is : ['best', 'for', 'CS']"
},
{
"code": null,
"e": 2119,
"s": 2108,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2136,
"s": 2119,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2157,
"s": 2136,
"text": "Python list-programs"
},
{
"code": null,
"e": 2164,
"s": 2157,
"text": "Python"
},
{
"code": null,
"e": 2180,
"s": 2164,
"text": "Python Programs"
}
] |
How to Install Statsmodels in Python?
|
16 Dec, 2021
Statsmodels is a popular library in Python that enables us to estimate and analyze various statistical models. It is built on numeric and scientific libraries like NumPy and SciPy. It is a python module that provides classes & functions for the estimation of many different statistical models.
In this article, we will look into the process of Installing Satsmodels in Python.
Follow the below steps to install statsmodels in Python on Linux using pip:
Step 1: Open the terminal & execute the following commands:
$ python -m venv StatsM
$ source ./StatsM/bin/activate
$ pip install statsmodels
Hence installation is successful.
Follow the below steps to install statsmodels in Python on Linux using conda:
Step 1: Open terminal & execute the below commands:
$ conda create --name SM ,then press y to continue
Step 2: Again execute the two commands given below:
$ conda activate SM
$ conda install statsmodels
Step 3: Press y to continue.
Open terminal & write following commands
$ python
import statsmodels as sm
sm.__version__
It will give the version as shown below:
Hence, your installation is successful.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Statsmodels is a popular library in Python that enables us to estimate and analyze various statistical models. It is built on numeric and scientific libraries like NumPy and SciPy. It is a python module that provides classes & functions for the estimation of many different statistical models."
},
{
"code": null,
"e": 405,
"s": 322,
"text": "In this article, we will look into the process of Installing Satsmodels in Python."
},
{
"code": null,
"e": 481,
"s": 405,
"text": "Follow the below steps to install statsmodels in Python on Linux using pip:"
},
{
"code": null,
"e": 541,
"s": 481,
"text": "Step 1: Open the terminal & execute the following commands:"
},
{
"code": null,
"e": 622,
"s": 541,
"text": "$ python -m venv StatsM\n$ source ./StatsM/bin/activate\n$ pip install statsmodels"
},
{
"code": null,
"e": 656,
"s": 622,
"text": "Hence installation is successful."
},
{
"code": null,
"e": 734,
"s": 656,
"text": "Follow the below steps to install statsmodels in Python on Linux using conda:"
},
{
"code": null,
"e": 786,
"s": 734,
"text": "Step 1: Open terminal & execute the below commands:"
},
{
"code": null,
"e": 837,
"s": 786,
"text": "$ conda create --name SM ,then press y to continue"
},
{
"code": null,
"e": 889,
"s": 837,
"text": "Step 2: Again execute the two commands given below:"
},
{
"code": null,
"e": 937,
"s": 889,
"text": "$ conda activate SM\n$ conda install statsmodels"
},
{
"code": null,
"e": 966,
"s": 937,
"text": "Step 3: Press y to continue."
},
{
"code": null,
"e": 1007,
"s": 966,
"text": "Open terminal & write following commands"
},
{
"code": null,
"e": 1056,
"s": 1007,
"text": "$ python\nimport statsmodels as sm\nsm.__version__"
},
{
"code": null,
"e": 1097,
"s": 1056,
"text": "It will give the version as shown below:"
},
{
"code": null,
"e": 1137,
"s": 1097,
"text": "Hence, your installation is successful."
},
{
"code": null,
"e": 1152,
"s": 1137,
"text": "how-to-install"
},
{
"code": null,
"e": 1159,
"s": 1152,
"text": "Picked"
},
{
"code": null,
"e": 1166,
"s": 1159,
"text": "How To"
},
{
"code": null,
"e": 1185,
"s": 1166,
"text": "Installation Guide"
},
{
"code": null,
"e": 1283,
"s": 1185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1332,
"s": 1283,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 1374,
"s": 1332,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 1415,
"s": 1374,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 1457,
"s": 1415,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 1496,
"s": 1457,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 1529,
"s": 1496,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1564,
"s": 1529,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1603,
"s": 1564,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 1645,
"s": 1603,
"text": "How to Install Jupyter Notebook on MacOS?"
}
] |
Use image as a button in kivy
|
29 Jun, 2022
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. As we have discussed earlier that how to work with images and now in this we will gonna be learn how to use the images and create a button with them. In this article we will learn how can we use the image as button and how to add functionality and styling on that image.
To learn about it you must be aware about some properties, that are – background_down : 1) Background image of the button used for the default graphical representation when the button is pressed. 2) background_down is a StringProperty . background_normal : 1) Background image of the button used for the default graphical representation when the button is not pressed. 2) background_normal is also a StringProperty . background_disabled_normal : 1) Background image of the button used for the default graphical representation when the button is disabled and not pressed. 2) background_disabled_normal is also a StringProperty . Notes : 1) Now its only sufficient to understand that string property means they only take values in string that means like background_down: “normal.png” like this. 2) On click on the image it looks same like a simple button (as we uses it in a button).
Image used in this article are: normal.png: down.png:
Basic Approach :
-> import kivy
-> import kivy App
-> import button
-> set minimum version(optional)
-> Extend the class :
-> create an image a button
-> Do styling
-> Arrange call back if needed
-> Add and return a button
-> Run an instance of the class
Kivy Tutorial – Learn Kivy with Examples.
Simple Implementation that how to create a button using image
Python3
## Sample Python application demonstrating that ## how to create button using image in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the image buttonclass ButtonApp(App): def build(self): # create an image a button # Adding images normal.png image as button # decided its position and size btn = Button(text ="Push Me !", color =(1, 0, .65, 1), background_normal = 'normal.png', background_down ='down.png', size_hint = (.3, .3), pos_hint = {"x":0.35, "y":0.3} ) return btn # creating the object root for ButtonApp() class root = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run()
Output: Code to implement the styling and arranging a callback to the button –
Python3
## Sample Python application demonstrating that ## how to create button using image in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the imagebuttonclass ButtonApp(App): def build(self): # create a fully styled functional button # Adding images normal.png and down.png btn = Button(text ="Push Me !", background_normal = 'normal.png', background_down = 'down.png', size_hint = (.3, .3), pos_hint = {"x":0.35, "y":0.3} ) # bind() use to bind the button to function callback btn.bind(on_press = self.callback) return btn # callback function tells when button pressed def callback(self, event): print("button pressed") print('Yoooo !!!!!!!!!!!') # creating the object root for ButtonApp() class root = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run()
Output:
surinderdawra388
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 535,
"s": 28,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. As we have discussed earlier that how to work with images and now in this we will gonna be learn how to use the images and create a button with them. In this article we will learn how can we use the image as button and how to add functionality and styling on that image."
},
{
"code": null,
"e": 1417,
"s": 535,
"text": "To learn about it you must be aware about some properties, that are – background_down : 1) Background image of the button used for the default graphical representation when the button is pressed. 2) background_down is a StringProperty . background_normal : 1) Background image of the button used for the default graphical representation when the button is not pressed. 2) background_normal is also a StringProperty . background_disabled_normal : 1) Background image of the button used for the default graphical representation when the button is disabled and not pressed. 2) background_disabled_normal is also a StringProperty . Notes : 1) Now its only sufficient to understand that string property means they only take values in string that means like background_down: “normal.png” like this. 2) On click on the image it looks same like a simple button (as we uses it in a button)."
},
{
"code": null,
"e": 1473,
"s": 1417,
"text": "Image used in this article are: normal.png: down.png: "
},
{
"code": null,
"e": 1776,
"s": 1473,
"text": "Basic Approach :\n\n-> import kivy\n-> import kivy App\n-> import button\n-> set minimum version(optional)\n-> Extend the class : \n -> create an image a button\n -> Do styling\n -> Arrange call back if needed \n-> Add and return a button\n-> Run an instance of the class"
},
{
"code": null,
"e": 1818,
"s": 1776,
"text": "Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 1881,
"s": 1818,
"text": "Simple Implementation that how to create a button using image "
},
{
"code": null,
"e": 1889,
"s": 1881,
"text": "Python3"
},
{
"code": "## Sample Python application demonstrating that ## how to create button using image in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the image buttonclass ButtonApp(App): def build(self): # create an image a button # Adding images normal.png image as button # decided its position and size btn = Button(text =\"Push Me !\", color =(1, 0, .65, 1), background_normal = 'normal.png', background_down ='down.png', size_hint = (.3, .3), pos_hint = {\"x\":0.35, \"y\":0.3} ) return btn # creating the object root for ButtonApp() class root = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run()",
"e": 3544,
"s": 1889,
"text": null
},
{
"code": null,
"e": 3625,
"s": 3544,
"text": "Output: Code to implement the styling and arranging a callback to the button – "
},
{
"code": null,
"e": 3633,
"s": 3625,
"text": "Python3"
},
{
"code": "## Sample Python application demonstrating that ## how to create button using image in kivy ################################################## # import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to change the kivy default settings we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # class in which we are creating the imagebuttonclass ButtonApp(App): def build(self): # create a fully styled functional button # Adding images normal.png and down.png btn = Button(text =\"Push Me !\", background_normal = 'normal.png', background_down = 'down.png', size_hint = (.3, .3), pos_hint = {\"x\":0.35, \"y\":0.3} ) # bind() use to bind the button to function callback btn.bind(on_press = self.callback) return btn # callback function tells when button pressed def callback(self, event): print(\"button pressed\") print('Yoooo !!!!!!!!!!!') # creating the object root for ButtonApp() class root = ButtonApp() # run function runs the whole program# i.e run() method which calls the target# function passed to the constructor.root.run()",
"e": 5451,
"s": 3633,
"text": null
},
{
"code": null,
"e": 5461,
"s": 5451,
"text": "Output: "
},
{
"code": null,
"e": 5478,
"s": 5461,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5489,
"s": 5478,
"text": "Python-gui"
},
{
"code": null,
"e": 5501,
"s": 5489,
"text": "Python-kivy"
},
{
"code": null,
"e": 5508,
"s": 5501,
"text": "Python"
},
{
"code": null,
"e": 5606,
"s": 5508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5624,
"s": 5606,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5666,
"s": 5624,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5688,
"s": 5666,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5714,
"s": 5688,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5746,
"s": 5714,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5775,
"s": 5746,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5805,
"s": 5775,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5832,
"s": 5805,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5855,
"s": 5832,
"text": "Introduction To PYTHON"
}
] |
Matplotlib.figure.Figure() in Python
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
This class is the top level container for all the plot elements.The Figure instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance.Note: In the Figure, the Base is the matplotlib.artist.Artist.
Syntax: class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)
Parameters: This accept the following parameters that are described below:
figsize : This parameter is the Figure dimension (width, height) in inches.
dpi : This parameter is the dots per inch.
facecolor : This parameter is the figure patch facecolor.
edgecolor : This parameter is the figure patch edge color.
linewidth : This parameter is the linewidth of the frame.
frameon : This parameter is the suppress drawing the figure background patch.
subplotpars : This parameter is the Subplot parameters.
tight_layout : This parameter is used to adjust subplot parameters.
constrained_layout : This parameter is used to adjust positioning of plot elements.
Returns: This method return the figure instances.
Below examples illustrate the matplotlib.figure.Figure() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(5, 4)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.suptitle('matplotlib.figure.Figure() class Example\n\n', fontweight ="bold") plt.show()
Output:
Example-2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure(facecolor ="green") ax = Subplot(fig, 111) fig.add_subplot(ax) ax.axis["left"].set_visible(False) ax.axis["top"].set_visible(False) fig.suptitle('matplotlib.figure.Figure() class Example\n\n', fontweight ="bold") plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 572,
"s": 339,
"text": "This class is the top level container for all the plot elements.The Figure instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance.Note: In the Figure, the Base is the matplotlib.artist.Artist."
},
{
"code": null,
"e": 758,
"s": 572,
"text": "Syntax: class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)"
},
{
"code": null,
"e": 833,
"s": 758,
"text": "Parameters: This accept the following parameters that are described below:"
},
{
"code": null,
"e": 909,
"s": 833,
"text": "figsize : This parameter is the Figure dimension (width, height) in inches."
},
{
"code": null,
"e": 952,
"s": 909,
"text": "dpi : This parameter is the dots per inch."
},
{
"code": null,
"e": 1010,
"s": 952,
"text": "facecolor : This parameter is the figure patch facecolor."
},
{
"code": null,
"e": 1069,
"s": 1010,
"text": "edgecolor : This parameter is the figure patch edge color."
},
{
"code": null,
"e": 1127,
"s": 1069,
"text": "linewidth : This parameter is the linewidth of the frame."
},
{
"code": null,
"e": 1205,
"s": 1127,
"text": "frameon : This parameter is the suppress drawing the figure background patch."
},
{
"code": null,
"e": 1261,
"s": 1205,
"text": "subplotpars : This parameter is the Subplot parameters."
},
{
"code": null,
"e": 1329,
"s": 1261,
"text": "tight_layout : This parameter is used to adjust subplot parameters."
},
{
"code": null,
"e": 1413,
"s": 1329,
"text": "constrained_layout : This parameter is used to adjust positioning of plot elements."
},
{
"code": null,
"e": 1463,
"s": 1413,
"text": "Returns: This method return the figure instances."
},
{
"code": null,
"e": 1551,
"s": 1463,
"text": "Below examples illustrate the matplotlib.figure.Figure() function in matplotlib.figure:"
},
{
"code": null,
"e": 1562,
"s": 1551,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(5, 4)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.suptitle('matplotlib.figure.Figure() class Example\\n\\n', fontweight =\"bold\") plt.show() ",
"e": 1948,
"s": 1562,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1948,
"text": "Output:"
},
{
"code": null,
"e": 1967,
"s": 1956,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure(facecolor =\"green\") ax = Subplot(fig, 111) fig.add_subplot(ax) ax.axis[\"left\"].set_visible(False) ax.axis[\"top\"].set_visible(False) fig.suptitle('matplotlib.figure.Figure() class Example\\n\\n', fontweight =\"bold\") plt.show() ",
"e": 2422,
"s": 1967,
"text": null
},
{
"code": null,
"e": 2430,
"s": 2422,
"text": "Output:"
},
{
"code": null,
"e": 2448,
"s": 2430,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2455,
"s": 2448,
"text": "Python"
}
] |
Linux Error Redirection
|
02 Dec, 2020
Redirection is a feature in Linux which can be used to change the standard input device (keyboard) or standard output device (screen) during the execution of a command. The basic process of any Linux command is that it takes an input and gives output but the standard/input and output can be changed using the redirection technique.
Error Redirection
There are mainly two types of output streams in Linux- standard output and standard error. The redirection operator (command > file) only redirects standard output and hence, the standard error is still displayed on the terminal. The default standard error is the screen. The standard error can also be redirected so that error messages do not clutter up the output of the program. ‘2’ denotes the stderr of a program.
2> stderr
‘2>’ redirects the error of an output to a file. The error messages are redirected and clean output is displayed. The Syntax of this operator is as follows:
command 2> file
Consider an example:
eccho "gfg" 2>file.txt
echo "gfg" 2>file.txt
There is no command as echo and hence error message will be displayed. But if 2>file.txt is used, then the error will be redirected to file.txt and no error is displayed on the screen. The cat command can be used to display the content of the file named file.txt which is the error message for the previous command. While executing the second command, gfg is displayed as the echo is a command in Linux to display. Hence, 2> does not redirect standard output.
When 2>& is used both standard error and standard output get redirected to the same file.
Syntax:
command > file 2>&
Consider an example:
eccho "gfg" >error.txt 2>&1
echo "gfg" >error.txt 2>&1
There is no command as echo and hence the error message is redirected to the file error.txt and no error is displayed. The second command echo “gfg” is correct but still, no output is displayed, as the standard output is also redirected to the file error.txt. The content of the file can be displayed after each step using the cat command.
Note: >& can be used to redirect both standard output and standard error, but it is not supported in all shells. sh and ksh do not support >& while bash and zsh support it.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 361,
"s": 28,
"text": "Redirection is a feature in Linux which can be used to change the standard input device (keyboard) or standard output device (screen) during the execution of a command. The basic process of any Linux command is that it takes an input and gives output but the standard/input and output can be changed using the redirection technique."
},
{
"code": null,
"e": 379,
"s": 361,
"text": "Error Redirection"
},
{
"code": null,
"e": 798,
"s": 379,
"text": "There are mainly two types of output streams in Linux- standard output and standard error. The redirection operator (command > file) only redirects standard output and hence, the standard error is still displayed on the terminal. The default standard error is the screen. The standard error can also be redirected so that error messages do not clutter up the output of the program. ‘2’ denotes the stderr of a program."
},
{
"code": null,
"e": 808,
"s": 798,
"text": "2> stderr"
},
{
"code": null,
"e": 965,
"s": 808,
"text": "‘2>’ redirects the error of an output to a file. The error messages are redirected and clean output is displayed. The Syntax of this operator is as follows:"
},
{
"code": null,
"e": 981,
"s": 965,
"text": "command 2> file"
},
{
"code": null,
"e": 1002,
"s": 981,
"text": "Consider an example:"
},
{
"code": null,
"e": 1047,
"s": 1002,
"text": "eccho \"gfg\" 2>file.txt\necho \"gfg\" 2>file.txt"
},
{
"code": null,
"e": 1507,
"s": 1047,
"text": "There is no command as echo and hence error message will be displayed. But if 2>file.txt is used, then the error will be redirected to file.txt and no error is displayed on the screen. The cat command can be used to display the content of the file named file.txt which is the error message for the previous command. While executing the second command, gfg is displayed as the echo is a command in Linux to display. Hence, 2> does not redirect standard output."
},
{
"code": null,
"e": 1597,
"s": 1507,
"text": "When 2>& is used both standard error and standard output get redirected to the same file."
},
{
"code": null,
"e": 1624,
"s": 1597,
"text": "Syntax:\ncommand > file 2>&"
},
{
"code": null,
"e": 1645,
"s": 1624,
"text": "Consider an example:"
},
{
"code": null,
"e": 1700,
"s": 1645,
"text": "eccho \"gfg\" >error.txt 2>&1\necho \"gfg\" >error.txt 2>&1"
},
{
"code": null,
"e": 2040,
"s": 1700,
"text": "There is no command as echo and hence the error message is redirected to the file error.txt and no error is displayed. The second command echo “gfg” is correct but still, no output is displayed, as the standard output is also redirected to the file error.txt. The content of the file can be displayed after each step using the cat command."
},
{
"code": null,
"e": 2213,
"s": 2040,
"text": "Note: >& can be used to redirect both standard output and standard error, but it is not supported in all shells. sh and ksh do not support >& while bash and zsh support it."
},
{
"code": null,
"e": 2224,
"s": 2213,
"text": "Linux-Unix"
}
] |
Sum of first n odd numbers in O(1) Complexity
|
24 May, 2021
Given the sequence of odd numbers 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, .... Find the sum of first n odd numbersExamples:
Input : n = 2
Output : 4
Sum of first two odd numbers is 1 + 3 = 4.
Input : 5
Output : 25
Sum of first 5 odd numbers is 1 + 3 + 5 +
7 + 9 = 25
A simple solution is to iterate through all odd numbers.
C++
Java
Python3
C#
PHP
Javascript
// A naive CPP program to find sum of// first n odd numbers#include <iostream>using namespace std; // Returns the sum of first// n odd numbersint oddSum(int n){ int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum;} // Driver functionint main(){ int n = 20; cout << " Sum of first " << n << " Odd Numbers is: " << oddSum(n); return 0;}
// Java program to find sum of// first n odd numbersimport java.util.*; class Odd{ // Returns the sum of first // n odd numbers public static int oddSum(int n) { int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum; } // driver function public static void main(String[] args) { int n = 20; System.out.println(" Sum of first "+ n +" Odd Numbers is: "+oddSum(n)); }} // This code is contributed by rishabh_jain
# Python3 program to find sum# of first n odd numbers def oddSum(n) : sum = 0 curr = 1 i = 0 while i < n: sum = sum + curr curr = curr + 2 i = i + 1 return sum # Driver Coden = 20print (" Sum of first" , n, "Odd Numbers is: ", oddSum(n) ) # This code is contributed by rishabh_jain
// C# program to find sum of// first n odd numbersusing System; class GFG { // Returns the sum of first // n odd numbers public static int oddSum(int n) { int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum; } // driver function public static void Main() { int n = 20; Console.WriteLine(" Sum of first " + n + " Odd Numbers is: " + oddSum(n)); }} // This code is contributed by vt_m.
<?php// A naive PHP program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum($n){ $sum = 0; $curr = 1; for ($i = 0; $i < $n; $i++) { $sum += $curr; $curr += 2; } return $sum;} // Driver Code$n = 20;echo " Sum of first ", $n , " Odd Numbers is: ", oddSum($n); // This code is contributed by vt_m.?>
<script> // A naive Javascript program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum(n){ let sum = 0; curr = 1; for (let i = 0; i < n; i++) { sum += curr; curr += 2; } return sum;} // Driver Codelet n = 20;document.write(" Sum of first " + n + " Odd Numbers is: " + oddSum(n)); // This code is contributed by gfgking.</script>
Output:
Sum of first 20 odd numbers is 400
Time Complexity: O(n) Auxiliary Space : O(1) An efficient solution is to use direct formula. To find the sum of first n odd numbers we can apply odd number theorem, it states that the sum of first n odd numbers is equal to the square of n.
∑(2i – 1) = n2 where i varies from 1 to n
let n = 10, therefore sum of first 10 odd numbers is1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 = 100if we apply odd number theorem:sum of first 10 odd numbers = n * n = 10 * 10 = 100.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// Efficient program to find sum of// first n odd numbers#include <iostream>using namespace std; // Returns the sum of first// n odd numbersint oddSum(int n){ return (n * n);} // Driver functionint main(){ int n = 20; cout << " Sum of first " << n << " Odd Numbers is: " << oddSum(n); return 0;}
// Java program to find sum of// first n odd numbersimport java.util.*; class Odd{ // Returns the sum of first // n odd numbers public static int oddSum(int n) { return (n * n); } // driver function public static void main(String[] args) { int n = 20; System.out.println(" Sum of first "+ n +" Odd Numbers is: "+oddSum(n)); }} // This code is contributed by rishabh_jain
# Python3 program to find sum# of first n odd numbers def oddSum(n) : return (n * n); # Driver Coden = 20print (" Sum of first" , n, "Odd Numbers is: ", oddSum(n) ) # This code is contributed by rishabh_jain
// C# program to find sum of// first n odd numbersusing System; class GFG { // Returns the sum of first // n odd numbers public static int oddSum(int n) { return (n * n); } // driver function public static void Main() { int n = 20; Console.WriteLine(" Sum of first " + n + " Odd Numbers is: " + oddSum(n)); }} // This code is contributed by vt_m.
<?php// Efficient program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum($n){ return ($n * $n);} // Driver Code$n = 20;echo " Sum of first " , $n, " Odd Numbers is: ", oddSum($n); // This code is contributed by vt_m.?>
<script> // Javascript program to find sum of first n odd numbers // Returns the sum of first // n odd numbers function oddSum(n) { return (n * n); } let n = 20; document.write(" Sum of first " + n + " Odd Numbers is: " + oddSum(n)); // This code is contributed by divyesh072019.</script>
Output:
Sum of first 20 odd numbers is 400
Time Complexity: O(1) Auxiliary Space : O(1)How does it work? We can prove it using mathematical induction. We know it is true for n = 1 and n = 2 as sums are 1 and 4 (1 + 3) respectively.
Let it be true for n = k-1.
Sum of first k odd numbers =
Sum of first k-1 odd numbers + k'th odd number
= (k-1)*(k-1) + (2k - 1)
= k*k
vt_m
gfgking
divyesh072019
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 181,
"s": 52,
"text": "Given the sequence of odd numbers 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, .... Find the sum of first n odd numbersExamples: "
},
{
"code": null,
"e": 325,
"s": 181,
"text": "Input : n = 2\nOutput : 4\nSum of first two odd numbers is 1 + 3 = 4.\n\nInput : 5\nOutput : 25\nSum of first 5 odd numbers is 1 + 3 + 5 +\n7 + 9 = 25"
},
{
"code": null,
"e": 386,
"s": 327,
"text": "A simple solution is to iterate through all odd numbers. "
},
{
"code": null,
"e": 390,
"s": 386,
"text": "C++"
},
{
"code": null,
"e": 395,
"s": 390,
"text": "Java"
},
{
"code": null,
"e": 403,
"s": 395,
"text": "Python3"
},
{
"code": null,
"e": 406,
"s": 403,
"text": "C#"
},
{
"code": null,
"e": 410,
"s": 406,
"text": "PHP"
},
{
"code": null,
"e": 421,
"s": 410,
"text": "Javascript"
},
{
"code": "// A naive CPP program to find sum of// first n odd numbers#include <iostream>using namespace std; // Returns the sum of first// n odd numbersint oddSum(int n){ int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum;} // Driver functionint main(){ int n = 20; cout << \" Sum of first \" << n << \" Odd Numbers is: \" << oddSum(n); return 0;}",
"e": 837,
"s": 421,
"text": null
},
{
"code": "// Java program to find sum of// first n odd numbersimport java.util.*; class Odd{ // Returns the sum of first // n odd numbers public static int oddSum(int n) { int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum; } // driver function public static void main(String[] args) { int n = 20; System.out.println(\" Sum of first \"+ n +\" Odd Numbers is: \"+oddSum(n)); }} // This code is contributed by rishabh_jain",
"e": 1388,
"s": 837,
"text": null
},
{
"code": "# Python3 program to find sum# of first n odd numbers def oddSum(n) : sum = 0 curr = 1 i = 0 while i < n: sum = sum + curr curr = curr + 2 i = i + 1 return sum # Driver Coden = 20print (\" Sum of first\" , n, \"Odd Numbers is: \", oddSum(n) ) # This code is contributed by rishabh_jain",
"e": 1737,
"s": 1388,
"text": null
},
{
"code": "// C# program to find sum of// first n odd numbersusing System; class GFG { // Returns the sum of first // n odd numbers public static int oddSum(int n) { int sum = 0, curr = 1; for (int i = 0; i < n; i++) { sum += curr; curr += 2; } return sum; } // driver function public static void Main() { int n = 20; Console.WriteLine(\" Sum of first \" + n + \" Odd Numbers is: \" + oddSum(n)); }} // This code is contributed by vt_m.",
"e": 2276,
"s": 1737,
"text": null
},
{
"code": "<?php// A naive PHP program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum($n){ $sum = 0; $curr = 1; for ($i = 0; $i < $n; $i++) { $sum += $curr; $curr += 2; } return $sum;} // Driver Code$n = 20;echo \" Sum of first \", $n , \" Odd Numbers is: \", oddSum($n); // This code is contributed by vt_m.?>",
"e": 2659,
"s": 2276,
"text": null
},
{
"code": "<script> // A naive Javascript program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum(n){ let sum = 0; curr = 1; for (let i = 0; i < n; i++) { sum += curr; curr += 2; } return sum;} // Driver Codelet n = 20;document.write(\" Sum of first \" + n + \" Odd Numbers is: \" + oddSum(n)); // This code is contributed by gfgking.</script>",
"e": 3074,
"s": 2659,
"text": null
},
{
"code": null,
"e": 3083,
"s": 3074,
"text": "Output: "
},
{
"code": null,
"e": 3118,
"s": 3083,
"text": "Sum of first 20 odd numbers is 400"
},
{
"code": null,
"e": 3359,
"s": 3118,
"text": "Time Complexity: O(n) Auxiliary Space : O(1) An efficient solution is to use direct formula. To find the sum of first n odd numbers we can apply odd number theorem, it states that the sum of first n odd numbers is equal to the square of n. "
},
{
"code": null,
"e": 3401,
"s": 3359,
"text": "∑(2i – 1) = n2 where i varies from 1 to n"
},
{
"code": null,
"e": 3637,
"s": 3401,
"text": "let n = 10, therefore sum of first 10 odd numbers is1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 = 100if we apply odd number theorem:sum of first 10 odd numbers = n * n = 10 * 10 = 100.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3641,
"s": 3637,
"text": "C++"
},
{
"code": null,
"e": 3646,
"s": 3641,
"text": "Java"
},
{
"code": null,
"e": 3654,
"s": 3646,
"text": "Python3"
},
{
"code": null,
"e": 3657,
"s": 3654,
"text": "C#"
},
{
"code": null,
"e": 3661,
"s": 3657,
"text": "PHP"
},
{
"code": null,
"e": 3672,
"s": 3661,
"text": "Javascript"
},
{
"code": "// Efficient program to find sum of// first n odd numbers#include <iostream>using namespace std; // Returns the sum of first// n odd numbersint oddSum(int n){ return (n * n);} // Driver functionint main(){ int n = 20; cout << \" Sum of first \" << n << \" Odd Numbers is: \" << oddSum(n); return 0;}",
"e": 3988,
"s": 3672,
"text": null
},
{
"code": "// Java program to find sum of// first n odd numbersimport java.util.*; class Odd{ // Returns the sum of first // n odd numbers public static int oddSum(int n) { return (n * n); } // driver function public static void main(String[] args) { int n = 20; System.out.println(\" Sum of first \"+ n +\" Odd Numbers is: \"+oddSum(n)); }} // This code is contributed by rishabh_jain",
"e": 4421,
"s": 3988,
"text": null
},
{
"code": "# Python3 program to find sum# of first n odd numbers def oddSum(n) : return (n * n); # Driver Coden = 20print (\" Sum of first\" , n, \"Odd Numbers is: \", oddSum(n) ) # This code is contributed by rishabh_jain",
"e": 4662,
"s": 4421,
"text": null
},
{
"code": "// C# program to find sum of// first n odd numbersusing System; class GFG { // Returns the sum of first // n odd numbers public static int oddSum(int n) { return (n * n); } // driver function public static void Main() { int n = 20; Console.WriteLine(\" Sum of first \" + n + \" Odd Numbers is: \" + oddSum(n)); }} // This code is contributed by vt_m.",
"e": 5074,
"s": 4662,
"text": null
},
{
"code": "<?php// Efficient program to find sum of// first n odd numbers // Returns the sum of first// n odd numbersfunction oddSum($n){ return ($n * $n);} // Driver Code$n = 20;echo \" Sum of first \" , $n, \" Odd Numbers is: \", oddSum($n); // This code is contributed by vt_m.?>",
"e": 5349,
"s": 5074,
"text": null
},
{
"code": "<script> // Javascript program to find sum of first n odd numbers // Returns the sum of first // n odd numbers function oddSum(n) { return (n * n); } let n = 20; document.write(\" Sum of first \" + n + \" Odd Numbers is: \" + oddSum(n)); // This code is contributed by divyesh072019.</script>",
"e": 5708,
"s": 5349,
"text": null
},
{
"code": null,
"e": 5718,
"s": 5708,
"text": "Output: "
},
{
"code": null,
"e": 5753,
"s": 5718,
"text": "Sum of first 20 odd numbers is 400"
},
{
"code": null,
"e": 5943,
"s": 5753,
"text": "Time Complexity: O(1) Auxiliary Space : O(1)How does it work? We can prove it using mathematical induction. We know it is true for n = 1 and n = 2 as sums are 1 and 4 (1 + 3) respectively. "
},
{
"code": null,
"e": 6082,
"s": 5943,
"text": "Let it be true for n = k-1.\n\nSum of first k odd numbers = \n Sum of first k-1 odd numbers + k'th odd number\n= (k-1)*(k-1) + (2k - 1)\n= k*k"
},
{
"code": null,
"e": 6089,
"s": 6084,
"text": "vt_m"
},
{
"code": null,
"e": 6097,
"s": 6089,
"text": "gfgking"
},
{
"code": null,
"e": 6111,
"s": 6097,
"text": "divyesh072019"
},
{
"code": null,
"e": 6125,
"s": 6111,
"text": "number-theory"
},
{
"code": null,
"e": 6132,
"s": 6125,
"text": "series"
},
{
"code": null,
"e": 6145,
"s": 6132,
"text": "Mathematical"
},
{
"code": null,
"e": 6159,
"s": 6145,
"text": "number-theory"
},
{
"code": null,
"e": 6172,
"s": 6159,
"text": "Mathematical"
},
{
"code": null,
"e": 6179,
"s": 6172,
"text": "series"
}
] |
Isoformat() Method Of Datetime Class In Python
|
15 Oct, 2021
In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format.
The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date needs to be represented using a 4-digit year followed by a two-digit month and a two-digit date. i.e., YYYY-MM-DD. Example: 2020-01-01.
Syntax: isoformat(sep=’T’, timespec=’auto’)
Parameters: This function accepts two parameters which are illustrated below:
sep: It is the separator character that is to be printed between the date and time fields. It is an Optional Parameter having default value of “T”.
timespec: It is the format specifier for the timespec. It is also an Optional Parameter with a default value of “auto”. This parameter is also having some values that are illustrated below:auto: For the auto value, the time component will be printed in HH:MM:SS format. If microseconds component is available it will be printed. Otherwise, microseconds will be omitted instead of printing as zero.hours: For the hours value, the returned time component will have only Hours in HH format. Note that, time zone component is different from time component.minutes: For the specified value of minutes, the returned time component will have only the Hours and Minutes printed in HH:MM format.seconds: For the specified value of seconds, the returned time component will have HH:MM:SS format.milliseconds: For the specified value of milliseconds, the returned time component will have HH:MM:SS:mmm format, where mmm is milliseconds. Microseconds will be excluded.microseconds: For the specified microseconds, the returned time component will have HH:MM:mmmmmm format, where mmmmmm is microseconds.
auto: For the auto value, the time component will be printed in HH:MM:SS format. If microseconds component is available it will be printed. Otherwise, microseconds will be omitted instead of printing as zero.
hours: For the hours value, the returned time component will have only Hours in HH format. Note that, time zone component is different from time component.
minutes: For the specified value of minutes, the returned time component will have only the Hours and Minutes printed in HH:MM format.
seconds: For the specified value of seconds, the returned time component will have HH:MM:SS format.
milliseconds: For the specified value of milliseconds, the returned time component will have HH:MM:SS:mmm format, where mmm is milliseconds. Microseconds will be excluded.
microseconds: For the specified microseconds, the returned time component will have HH:MM:mmmmmm format, where mmmmmm is microseconds.
Return values: This function returns the date value of a Python DateTime.date object in ISO 8601 format.
Example 1: In the below example, the isoformat() function has been called on today’s date and it returns the same today’s date string in ISO 8601 format.
Python3
# Python3 code to demonstrate# Getting date values in ISO 8601 format # importing datetime and time moduleimport datetimeimport time # Getting today's datetodays_Date = datetime.date.fromtimestamp(time.time()) # Calling the isoformat() function over the# today's datedate_in_ISOFormat = todays_Date.isoformat() # Printing Today's date in ISO formatprint("Today's date in ISO Format: %s" % date_in_ISOFormat)
Output:
Today’s date in ISO Format: 2021-07-27
Example 2: In the below example, the isoformat() function has been called on today’s date and time and it returns the same today’s date and time string in ISO 8601 format.
Python3
# Python3 code to demonstrate# Getting date and time values# in ISO 8601 format # importing datetime and time moduleimport datetimeimport time # Getting today's date and timetodays_Date = datetime.datetime.now() # Calling the isoformat() function over the# today's date and timeDateTime_in_ISOFormat = todays_Date.isoformat() # Printing Today's date and time in ISO formatprint("Today's date and time in ISO Format: %s" % DateTime_in_ISOFormat)
Output:
Today’s date and time in ISO Format: 2021-07-27T16:02:08.070557
In the below example, the isoformat() function has taken two parameters one is separator character such as ‘#’ and another parameter is format specifier for the time-specific. But if different values for time specifiers are used the output can be formatted according to that.
Example 3: Here different values for the time-specific parameter are used that are already illustrated in the above parameter section.
Python3
# Python3 code to demonstrate# Getting date and time values# in ISO 8601 format # importing datetime moduleimport datetime # Getting today's date and timeDateTime_in_ISOFormat = datetime.datetime.now() # Printing Today's date and time in ISO format of# auto value for the format specifierprint(DateTime_in_ISOFormat.isoformat("#", "auto")) # Printing Today's date and time format specifier# as hoursprint(DateTime_in_ISOFormat.isoformat("#", "hours")) # Printing Today's date and time format specifier# as minutesprint(DateTime_in_ISOFormat.isoformat("#", "minutes")) # Printing Today's date and time format specifier# as secondsprint(DateTime_in_ISOFormat.isoformat("#", "seconds")) # Printing Today's date and time format specifier# as millisecondsprint(DateTime_in_ISOFormat.isoformat("#", "milliseconds")) # Printing Today's date and time format specifier# as microsecondsprint(DateTime_in_ISOFormat.isoformat("#", "microseconds"))
Output:
2021-07-27#16:01:12.090202
2021-07-27#16
2021-07-27#16:01
2021-07-27#16:01:12
2021-07-27#16:01:12.090
2021-07-27#16:01:12.090202
surindertarika1234
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format."
},
{
"code": null,
"e": 511,
"s": 248,
"text": "The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date needs to be represented using a 4-digit year followed by a two-digit month and a two-digit date. i.e., YYYY-MM-DD. Example: 2020-01-01."
},
{
"code": null,
"e": 555,
"s": 511,
"text": "Syntax: isoformat(sep=’T’, timespec=’auto’)"
},
{
"code": null,
"e": 633,
"s": 555,
"text": "Parameters: This function accepts two parameters which are illustrated below:"
},
{
"code": null,
"e": 781,
"s": 633,
"text": "sep: It is the separator character that is to be printed between the date and time fields. It is an Optional Parameter having default value of “T”."
},
{
"code": null,
"e": 1872,
"s": 781,
"text": "timespec: It is the format specifier for the timespec. It is also an Optional Parameter with a default value of “auto”. This parameter is also having some values that are illustrated below:auto: For the auto value, the time component will be printed in HH:MM:SS format. If microseconds component is available it will be printed. Otherwise, microseconds will be omitted instead of printing as zero.hours: For the hours value, the returned time component will have only Hours in HH format. Note that, time zone component is different from time component.minutes: For the specified value of minutes, the returned time component will have only the Hours and Minutes printed in HH:MM format.seconds: For the specified value of seconds, the returned time component will have HH:MM:SS format.milliseconds: For the specified value of milliseconds, the returned time component will have HH:MM:SS:mmm format, where mmm is milliseconds. Microseconds will be excluded.microseconds: For the specified microseconds, the returned time component will have HH:MM:mmmmmm format, where mmmmmm is microseconds."
},
{
"code": null,
"e": 2081,
"s": 1872,
"text": "auto: For the auto value, the time component will be printed in HH:MM:SS format. If microseconds component is available it will be printed. Otherwise, microseconds will be omitted instead of printing as zero."
},
{
"code": null,
"e": 2237,
"s": 2081,
"text": "hours: For the hours value, the returned time component will have only Hours in HH format. Note that, time zone component is different from time component."
},
{
"code": null,
"e": 2372,
"s": 2237,
"text": "minutes: For the specified value of minutes, the returned time component will have only the Hours and Minutes printed in HH:MM format."
},
{
"code": null,
"e": 2472,
"s": 2372,
"text": "seconds: For the specified value of seconds, the returned time component will have HH:MM:SS format."
},
{
"code": null,
"e": 2644,
"s": 2472,
"text": "milliseconds: For the specified value of milliseconds, the returned time component will have HH:MM:SS:mmm format, where mmm is milliseconds. Microseconds will be excluded."
},
{
"code": null,
"e": 2779,
"s": 2644,
"text": "microseconds: For the specified microseconds, the returned time component will have HH:MM:mmmmmm format, where mmmmmm is microseconds."
},
{
"code": null,
"e": 2884,
"s": 2779,
"text": "Return values: This function returns the date value of a Python DateTime.date object in ISO 8601 format."
},
{
"code": null,
"e": 3038,
"s": 2884,
"text": "Example 1: In the below example, the isoformat() function has been called on today’s date and it returns the same today’s date string in ISO 8601 format."
},
{
"code": null,
"e": 3046,
"s": 3038,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Getting date values in ISO 8601 format # importing datetime and time moduleimport datetimeimport time # Getting today's datetodays_Date = datetime.date.fromtimestamp(time.time()) # Calling the isoformat() function over the# today's datedate_in_ISOFormat = todays_Date.isoformat() # Printing Today's date in ISO formatprint(\"Today's date in ISO Format: %s\" % date_in_ISOFormat)",
"e": 3454,
"s": 3046,
"text": null
},
{
"code": null,
"e": 3462,
"s": 3454,
"text": "Output:"
},
{
"code": null,
"e": 3501,
"s": 3462,
"text": "Today’s date in ISO Format: 2021-07-27"
},
{
"code": null,
"e": 3673,
"s": 3501,
"text": "Example 2: In the below example, the isoformat() function has been called on today’s date and time and it returns the same today’s date and time string in ISO 8601 format."
},
{
"code": null,
"e": 3681,
"s": 3673,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Getting date and time values# in ISO 8601 format # importing datetime and time moduleimport datetimeimport time # Getting today's date and timetodays_Date = datetime.datetime.now() # Calling the isoformat() function over the# today's date and timeDateTime_in_ISOFormat = todays_Date.isoformat() # Printing Today's date and time in ISO formatprint(\"Today's date and time in ISO Format: %s\" % DateTime_in_ISOFormat)",
"e": 4126,
"s": 3681,
"text": null
},
{
"code": null,
"e": 4134,
"s": 4126,
"text": "Output:"
},
{
"code": null,
"e": 4198,
"s": 4134,
"text": "Today’s date and time in ISO Format: 2021-07-27T16:02:08.070557"
},
{
"code": null,
"e": 4475,
"s": 4198,
"text": "In the below example, the isoformat() function has taken two parameters one is separator character such as ‘#’ and another parameter is format specifier for the time-specific. But if different values for time specifiers are used the output can be formatted according to that. "
},
{
"code": null,
"e": 4610,
"s": 4475,
"text": "Example 3: Here different values for the time-specific parameter are used that are already illustrated in the above parameter section."
},
{
"code": null,
"e": 4618,
"s": 4610,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Getting date and time values# in ISO 8601 format # importing datetime moduleimport datetime # Getting today's date and timeDateTime_in_ISOFormat = datetime.datetime.now() # Printing Today's date and time in ISO format of# auto value for the format specifierprint(DateTime_in_ISOFormat.isoformat(\"#\", \"auto\")) # Printing Today's date and time format specifier# as hoursprint(DateTime_in_ISOFormat.isoformat(\"#\", \"hours\")) # Printing Today's date and time format specifier# as minutesprint(DateTime_in_ISOFormat.isoformat(\"#\", \"minutes\")) # Printing Today's date and time format specifier# as secondsprint(DateTime_in_ISOFormat.isoformat(\"#\", \"seconds\")) # Printing Today's date and time format specifier# as millisecondsprint(DateTime_in_ISOFormat.isoformat(\"#\", \"milliseconds\")) # Printing Today's date and time format specifier# as microsecondsprint(DateTime_in_ISOFormat.isoformat(\"#\", \"microseconds\"))",
"e": 5554,
"s": 4618,
"text": null
},
{
"code": null,
"e": 5562,
"s": 5554,
"text": "Output:"
},
{
"code": null,
"e": 5589,
"s": 5562,
"text": "2021-07-27#16:01:12.090202"
},
{
"code": null,
"e": 5603,
"s": 5589,
"text": "2021-07-27#16"
},
{
"code": null,
"e": 5620,
"s": 5603,
"text": "2021-07-27#16:01"
},
{
"code": null,
"e": 5640,
"s": 5620,
"text": "2021-07-27#16:01:12"
},
{
"code": null,
"e": 5664,
"s": 5640,
"text": "2021-07-27#16:01:12.090"
},
{
"code": null,
"e": 5691,
"s": 5664,
"text": "2021-07-27#16:01:12.090202"
},
{
"code": null,
"e": 5710,
"s": 5691,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5717,
"s": 5710,
"text": "Picked"
},
{
"code": null,
"e": 5733,
"s": 5717,
"text": "Python-datetime"
},
{
"code": null,
"e": 5740,
"s": 5733,
"text": "Python"
}
] |
How to remove options from select element using jQuery ?
|
21 Jun, 2019
The task is to remove the option elements from the select element using jQuery.
Approach:
Select the option from select which needs to remove.
Use JQuery remove() method to remove the option from the HTML document.
Example 1: This example removes the option of which val = ‘val_1’ using remove() method.
<!DOCTYPE HTML><html> <head> <title> JQuery | Remove options from select. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <select> <option value="val_1"> Val_1</option> <option value="val_2"> Val_2</option> <option value="val_3"> Val_3</option> <option value="val_4"> Val_4</option> </select> <br> <br> <button> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text( 'Click on the button to '+ 'remove a option from select'); $('button').on('click', function() { $("option[value='val_1']").remove(); $('#GFG_DOWN').text( 'option with val_1 is removed!'); }); </script></body> </html>
Output:
Before reaching the bottom:
After reaching the bottom:
Example 2: This example removes the options of which class = ‘val’ using remove() method.
<!DOCTYPE HTML><html> <head> <title> JQuery | Remove options from select. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <select> <option class="val" value="val_1"> Val_1 </option> <option class="val" value="val_2"> Val_2 </option> <option value="val_3"> Val_3 </option> <option value="val_4"> Val_4 </option> </select> <br> <br> <button> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text( 'Click on the button to remove a option from select'); $('button').on('click', function() { $("option[class='val']").remove(); $('#GFG_DOWN').text( 'option with class = "val" are removed!'); }); </script></body> </html>
Output:
Before reaching the bottom:
After reaching the bottom:
JavaScript-Misc
jQuery-Misc
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
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "The task is to remove the option elements from the select element using jQuery."
},
{
"code": null,
"e": 118,
"s": 108,
"text": "Approach:"
},
{
"code": null,
"e": 171,
"s": 118,
"text": "Select the option from select which needs to remove."
},
{
"code": null,
"e": 243,
"s": 171,
"text": "Use JQuery remove() method to remove the option from the HTML document."
},
{
"code": null,
"e": 332,
"s": 243,
"text": "Example 1: This example removes the option of which val = ‘val_1’ using remove() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Remove options from select. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <select> <option value=\"val_1\"> Val_1</option> <option value=\"val_2\"> Val_2</option> <option value=\"val_3\"> Val_3</option> <option value=\"val_4\"> Val_4</option> </select> <br> <br> <button> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text( 'Click on the button to '+ 'remove a option from select'); $('button').on('click', function() { $(\"option[value='val_1']\").remove(); $('#GFG_DOWN').text( 'option with val_1 is removed!'); }); </script></body> </html>",
"e": 1458,
"s": 332,
"text": null
},
{
"code": null,
"e": 1466,
"s": 1458,
"text": "Output:"
},
{
"code": null,
"e": 1494,
"s": 1466,
"text": "Before reaching the bottom:"
},
{
"code": null,
"e": 1521,
"s": 1494,
"text": "After reaching the bottom:"
},
{
"code": null,
"e": 1611,
"s": 1521,
"text": "Example 2: This example removes the options of which class = ‘val’ using remove() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Remove options from select. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <select> <option class=\"val\" value=\"val_1\"> Val_1 </option> <option class=\"val\" value=\"val_2\"> Val_2 </option> <option value=\"val_3\"> Val_3 </option> <option value=\"val_4\"> Val_4 </option> </select> <br> <br> <button> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> $('#GFG_UP').text( 'Click on the button to remove a option from select'); $('button').on('click', function() { $(\"option[class='val']\").remove(); $('#GFG_DOWN').text( 'option with class = \"val\" are removed!'); }); </script></body> </html>",
"e": 2814,
"s": 1611,
"text": null
},
{
"code": null,
"e": 2822,
"s": 2814,
"text": "Output:"
},
{
"code": null,
"e": 2850,
"s": 2822,
"text": "Before reaching the bottom:"
},
{
"code": null,
"e": 2877,
"s": 2850,
"text": "After reaching the bottom:"
},
{
"code": null,
"e": 2893,
"s": 2877,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2905,
"s": 2893,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 2916,
"s": 2905,
"text": "JavaScript"
},
{
"code": null,
"e": 2933,
"s": 2916,
"text": "Web Technologies"
},
{
"code": null,
"e": 3031,
"s": 2933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3092,
"s": 3031,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3132,
"s": 3092,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3204,
"s": 3132,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3246,
"s": 3204,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3287,
"s": 3246,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3320,
"s": 3287,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3382,
"s": 3320,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3443,
"s": 3382,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3493,
"s": 3443,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Create a Music Website Template using HTML, CSS & JavaScript
|
23 Aug, 2021
A music website is basically a webpage where one can play/pause music. It has other options like the home section, music section, about section, contact section, etc. In this project, we are going to make a website that will play/pause music using HTML, CSS, and JavaScript. We will use HTML to give a basic layout and with CSS, we will give beautify our design by giving aground and play pause button image. We will use basic JavaScript feature like if-else and document.getElementById to play and pause our music.
Approach:
We will create the basic layout i.e. two divs (left and right) inside one div tag. In the left div we will write some text and in the right div we will place play or pause image. We will also create a basic nav-bar and float in the right.
With the help of CSS, we will beautify our overall structure by giving background image, padding, margin etc.
We will use basic JavaScript functions like onclick(), play() , pause() and getElementById() to get the current status of music and make changes accordingly.
When user will play the music we will show play image or icon and when user presses pause pause image or icon will be displayed. This is done using simple if-else statement.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> /* Styling the body */ * { padding: 0; margin: 0; } /* Styling the background image by giving its url and position */ .container { height: 100vh; width: 100%; background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402235143/background.jpg'); /* Image used: */ background-size: cover; background-position: center; position: relative; } /* Styling the list tags to the right of the navigation bar */ .nav li { float: right; list-style: none; } /* Styling the anchor tags of the navigation bar */ .nav a { list-style: none; height: 50px; line-height: 50px; font-size: 1rem; font-weight: 550; display: block; padding: 5px 35px; color: black; text-decoration: none; } /* Giving position and margin to the content-div */ .content { width: 100%; position: absolute; top: 45%; } /* Styling the left-col by giving margin */ .left-col { margin-left: 11%; } /* Styling the my sound placed in the left-col */ .left-col h1 { font-size: 50px; color: crimson; } /* Styling the right-col */ .right-col { float: right; margin-right: 10%; margin-top: -5%; display: flex; align-items: center; } /* Styling the text in the right-col */ .right-col p { font-size: 21px; color: black; font-weight: 650; margin-right: 20px; } /* Styling the cursor type of the icon to pointer */ #icon { cursor: pointer; } </style></head> <body> <div class="container"> <ul class="nav"> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> <li><a href="#">ARTISTS</a></li> <li><a href="#">MUSIC</a></li> <li><a href="#">HOME</a></li> </ul> </div> <div class="content"> <div class="left-col"> <h1>MY <br> SOUNDS</h1> </div> <div class="right-col"> <p>Click Here To Listen</p> <img src="media/play.png" id="icon"> </div> </div> <audio id="mysound"> <source src="media/music.mp3" type="audio/mp3"> </audio> <script> var mysound = document.getElementById("mysound"); var icon = document.getElementById("icon"); // Creating a function that will change // pause to play and vice-versa icon.onclick = function() { if (mysound.paused) { // If paused then play the // music and change the image mysound.play(); icon.src ="https://media.geeksforgeeks.org/wp-content/uploads/20210402235545/Pause.png"; } else { // If playing then pause the // music and change the image mysound.pause(); icon.src ="https://media.geeksforgeeks.org/wp-content/uploads/20210402235520/play.png"; } } </script></body> </html>
Output:
adnanirshad158
akshaysingh98088
CSS-Properties
CSS-Questions
HTML-Attributes
HTML-Questions
HTML-Tags
HTML5
JavaScript-Methods
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 569,
"s": 53,
"text": "A music website is basically a webpage where one can play/pause music. It has other options like the home section, music section, about section, contact section, etc. In this project, we are going to make a website that will play/pause music using HTML, CSS, and JavaScript. We will use HTML to give a basic layout and with CSS, we will give beautify our design by giving aground and play pause button image. We will use basic JavaScript feature like if-else and document.getElementById to play and pause our music."
},
{
"code": null,
"e": 579,
"s": 569,
"text": "Approach:"
},
{
"code": null,
"e": 818,
"s": 579,
"text": "We will create the basic layout i.e. two divs (left and right) inside one div tag. In the left div we will write some text and in the right div we will place play or pause image. We will also create a basic nav-bar and float in the right."
},
{
"code": null,
"e": 928,
"s": 818,
"text": "With the help of CSS, we will beautify our overall structure by giving background image, padding, margin etc."
},
{
"code": null,
"e": 1086,
"s": 928,
"text": "We will use basic JavaScript functions like onclick(), play() , pause() and getElementById() to get the current status of music and make changes accordingly."
},
{
"code": null,
"e": 1261,
"s": 1086,
"text": "When user will play the music we will show play image or icon and when user presses pause pause image or icon will be displayed. This is done using simple if-else statement."
},
{
"code": null,
"e": 1270,
"s": 1261,
"text": "Example:"
},
{
"code": null,
"e": 1275,
"s": 1270,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the body */ * { padding: 0; margin: 0; } /* Styling the background image by giving its url and position */ .container { height: 100vh; width: 100%; background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210402235143/background.jpg'); /* Image used: */ background-size: cover; background-position: center; position: relative; } /* Styling the list tags to the right of the navigation bar */ .nav li { float: right; list-style: none; } /* Styling the anchor tags of the navigation bar */ .nav a { list-style: none; height: 50px; line-height: 50px; font-size: 1rem; font-weight: 550; display: block; padding: 5px 35px; color: black; text-decoration: none; } /* Giving position and margin to the content-div */ .content { width: 100%; position: absolute; top: 45%; } /* Styling the left-col by giving margin */ .left-col { margin-left: 11%; } /* Styling the my sound placed in the left-col */ .left-col h1 { font-size: 50px; color: crimson; } /* Styling the right-col */ .right-col { float: right; margin-right: 10%; margin-top: -5%; display: flex; align-items: center; } /* Styling the text in the right-col */ .right-col p { font-size: 21px; color: black; font-weight: 650; margin-right: 20px; } /* Styling the cursor type of the icon to pointer */ #icon { cursor: pointer; } </style></head> <body> <div class=\"container\"> <ul class=\"nav\"> <li><a href=\"#\">CONTACT</a></li> <li><a href=\"#\">ABOUT</a></li> <li><a href=\"#\">ARTISTS</a></li> <li><a href=\"#\">MUSIC</a></li> <li><a href=\"#\">HOME</a></li> </ul> </div> <div class=\"content\"> <div class=\"left-col\"> <h1>MY <br> SOUNDS</h1> </div> <div class=\"right-col\"> <p>Click Here To Listen</p> <img src=\"media/play.png\" id=\"icon\"> </div> </div> <audio id=\"mysound\"> <source src=\"media/music.mp3\" type=\"audio/mp3\"> </audio> <script> var mysound = document.getElementById(\"mysound\"); var icon = document.getElementById(\"icon\"); // Creating a function that will change // pause to play and vice-versa icon.onclick = function() { if (mysound.paused) { // If paused then play the // music and change the image mysound.play(); icon.src =\"https://media.geeksforgeeks.org/wp-content/uploads/20210402235545/Pause.png\"; } else { // If playing then pause the // music and change the image mysound.pause(); icon.src =\"https://media.geeksforgeeks.org/wp-content/uploads/20210402235520/play.png\"; } } </script></body> </html>",
"e": 4760,
"s": 1275,
"text": null
},
{
"code": null,
"e": 4768,
"s": 4760,
"text": "Output:"
},
{
"code": null,
"e": 4783,
"s": 4768,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4800,
"s": 4783,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4815,
"s": 4800,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4829,
"s": 4815,
"text": "CSS-Questions"
},
{
"code": null,
"e": 4845,
"s": 4829,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 4860,
"s": 4845,
"text": "HTML-Questions"
},
{
"code": null,
"e": 4870,
"s": 4860,
"text": "HTML-Tags"
},
{
"code": null,
"e": 4876,
"s": 4870,
"text": "HTML5"
},
{
"code": null,
"e": 4895,
"s": 4876,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 4899,
"s": 4895,
"text": "CSS"
},
{
"code": null,
"e": 4904,
"s": 4899,
"text": "HTML"
},
{
"code": null,
"e": 4915,
"s": 4904,
"text": "JavaScript"
},
{
"code": null,
"e": 4932,
"s": 4915,
"text": "Web Technologies"
},
{
"code": null,
"e": 4937,
"s": 4932,
"text": "HTML"
}
] |
Python | Message Encode-Decode using Tkinter
|
06 Jul, 2021
Prerequisite : Basics of TkinterPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let’s try to implement a message encryption-decryption application according to the Vigenère cipher, which can encrypt the message using the key and can decrypt the encrypted hash using same key.
Modules used in the project :
Tkinter -> GUI toolkittime datetime base64 -> Vigenère cipher
Below is the implementation of above idea :
Python3
# import tkinter modulefrom tkinter import * # import other necessary modulesimport randomimport timeimport datetime # creating root objectroot = Tk() # defining size of windowroot.geometry("1200x6000") # setting up the title of windowroot.title("Message Encryption and Decryption") Tops = Frame(root, width = 1600, relief = SUNKEN)Tops.pack(side = TOP) f1 = Frame(root, width = 800, height = 700, relief = SUNKEN)f1.pack(side = LEFT) # ==============================================# TIME# ==============================================localtime = time.asctime(time.localtime(time.time())) lblInfo = Label(Tops, font = ('helvetica', 50, 'bold'), text = "SECRET MESSAGING \n Vigenère cipher", fg = "Black", bd = 10, anchor='w') lblInfo.grid(row = 0, column = 0) lblInfo = Label(Tops, font=('arial', 20, 'bold'), text = localtime, fg = "Steel Blue", bd = 10, anchor = 'w') lblInfo.grid(row = 1, column = 0) rand = StringVar()Msg = StringVar()key = StringVar()mode = StringVar()Result = StringVar() # exit functiondef qExit(): root.destroy() # Function to reset the windowdef Reset(): rand.set("") Msg.set("") key.set("") mode.set("") Result.set("") # referencelblReference = Label(f1, font = ('arial', 16, 'bold'), text = "Name:", bd = 16, anchor = "w") lblReference.grid(row = 0, column = 0) txtReference = Entry(f1, font = ('arial', 16, 'bold'), textvariable = rand, bd = 10, insertwidth = 4, bg = "powder blue", justify = 'right') txtReference.grid(row = 0, column = 1) # labelslblMsg = Label(f1, font = ('arial', 16, 'bold'), text = "MESSAGE", bd = 16, anchor = "w") lblMsg.grid(row = 1, column = 0) txtMsg = Entry(f1, font = ('arial', 16, 'bold'), textvariable = Msg, bd = 10, insertwidth = 4, bg = "powder blue", justify = 'right') txtMsg.grid(row = 1, column = 1) lblkey = Label(f1, font = ('arial', 16, 'bold'), text = "KEY", bd = 16, anchor = "w") lblkey.grid(row = 2, column = 0) txtkey = Entry(f1, font = ('arial', 16, 'bold'), textvariable = key, bd = 10, insertwidth = 4, bg = "powder blue", justify = 'right') txtkey.grid(row = 2, column = 1) lblmode = Label(f1, font = ('arial', 16, 'bold'), text = "MODE(e for encrypt, d for decrypt)", bd = 16, anchor = "w") lblmode.grid(row = 3, column = 0) txtmode = Entry(f1, font = ('arial', 16, 'bold'), textvariable = mode, bd = 10, insertwidth = 4, bg = "powder blue", justify = 'right') txtmode.grid(row = 3, column = 1) lblService = Label(f1, font = ('arial', 16, 'bold'), text = "The Result-", bd = 16, anchor = "w") lblService.grid(row = 2, column = 2) txtService = Entry(f1, font = ('arial', 16, 'bold'), textvariable = Result, bd = 10, insertwidth = 4, bg = "powder blue", justify = 'right') txtService.grid(row = 2, column = 3) # Vigenère cipherimport base64 # Function to encodedef encode(key, clear): enc = [] for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) enc.append(enc_c) return base64.urlsafe_b64encode("".join(enc).encode()).decode() # Function to decodedef decode(key, enc): dec = [] enc = base64.urlsafe_b64decode(enc).decode() for i in range(len(enc)): key_c = key[i % len(key)] dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) dec.append(dec_c) return "".join(dec) def Ref(): print("Message= ", (Msg.get())) clear = Msg.get() k = key.get() m = mode.get() if (m == 'e'): Result.set(encode(k, clear)) else: Result.set(decode(k, clear)) # Show message buttonbtnTotal = Button(f1, padx = 16, pady = 8, bd = 16, fg = "black", font = ('arial', 16, 'bold'), width = 10, text = "Show Message", bg = "powder blue", command = Ref).grid(row = 7, column = 1) # Reset buttonbtnReset = Button(f1, padx = 16, pady = 8, bd = 16, fg = "black", font = ('arial', 16, 'bold'), width = 10, text = "Reset", bg = "green", command = Reset).grid(row = 7, column = 2) # Exit buttonbtnExit = Button(f1, padx = 16, pady = 8, bd = 16, fg = "black", font = ('arial', 16, 'bold'), width = 10, text = "Exit", bg = "red", command = qExit).grid(row = 7, column = 3) # keeps window aliveroot.mainloop()
Output : Encrypt Window –
Decrypt Window –
saurabh1990aror
encoding-decoding
Python-projects
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 762,
"s": 52,
"text": "Prerequisite : Basics of TkinterPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Python provides the Tkinter toolkit to develop GUI applications. Now, it’s upto the imagination or necessity of developer, what he/she want to develop using this toolkit. Let’s try to implement a message encryption-decryption application according to the Vigenère cipher, which can encrypt the message using the key and can decrypt the encrypted hash using same key. "
},
{
"code": null,
"e": 860,
"s": 762,
"text": "Modules used in the project :\n\nTkinter -> GUI toolkittime datetime base64 -> Vigenère cipher"
},
{
"code": null,
"e": 906,
"s": 860,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 914,
"s": 906,
"text": "Python3"
},
{
"code": "# import tkinter modulefrom tkinter import * # import other necessary modulesimport randomimport timeimport datetime # creating root objectroot = Tk() # defining size of windowroot.geometry(\"1200x6000\") # setting up the title of windowroot.title(\"Message Encryption and Decryption\") Tops = Frame(root, width = 1600, relief = SUNKEN)Tops.pack(side = TOP) f1 = Frame(root, width = 800, height = 700, relief = SUNKEN)f1.pack(side = LEFT) # ==============================================# TIME# ==============================================localtime = time.asctime(time.localtime(time.time())) lblInfo = Label(Tops, font = ('helvetica', 50, 'bold'), text = \"SECRET MESSAGING \\n Vigenère cipher\", fg = \"Black\", bd = 10, anchor='w') lblInfo.grid(row = 0, column = 0) lblInfo = Label(Tops, font=('arial', 20, 'bold'), text = localtime, fg = \"Steel Blue\", bd = 10, anchor = 'w') lblInfo.grid(row = 1, column = 0) rand = StringVar()Msg = StringVar()key = StringVar()mode = StringVar()Result = StringVar() # exit functiondef qExit(): root.destroy() # Function to reset the windowdef Reset(): rand.set(\"\") Msg.set(\"\") key.set(\"\") mode.set(\"\") Result.set(\"\") # referencelblReference = Label(f1, font = ('arial', 16, 'bold'), text = \"Name:\", bd = 16, anchor = \"w\") lblReference.grid(row = 0, column = 0) txtReference = Entry(f1, font = ('arial', 16, 'bold'), textvariable = rand, bd = 10, insertwidth = 4, bg = \"powder blue\", justify = 'right') txtReference.grid(row = 0, column = 1) # labelslblMsg = Label(f1, font = ('arial', 16, 'bold'), text = \"MESSAGE\", bd = 16, anchor = \"w\") lblMsg.grid(row = 1, column = 0) txtMsg = Entry(f1, font = ('arial', 16, 'bold'), textvariable = Msg, bd = 10, insertwidth = 4, bg = \"powder blue\", justify = 'right') txtMsg.grid(row = 1, column = 1) lblkey = Label(f1, font = ('arial', 16, 'bold'), text = \"KEY\", bd = 16, anchor = \"w\") lblkey.grid(row = 2, column = 0) txtkey = Entry(f1, font = ('arial', 16, 'bold'), textvariable = key, bd = 10, insertwidth = 4, bg = \"powder blue\", justify = 'right') txtkey.grid(row = 2, column = 1) lblmode = Label(f1, font = ('arial', 16, 'bold'), text = \"MODE(e for encrypt, d for decrypt)\", bd = 16, anchor = \"w\") lblmode.grid(row = 3, column = 0) txtmode = Entry(f1, font = ('arial', 16, 'bold'), textvariable = mode, bd = 10, insertwidth = 4, bg = \"powder blue\", justify = 'right') txtmode.grid(row = 3, column = 1) lblService = Label(f1, font = ('arial', 16, 'bold'), text = \"The Result-\", bd = 16, anchor = \"w\") lblService.grid(row = 2, column = 2) txtService = Entry(f1, font = ('arial', 16, 'bold'), textvariable = Result, bd = 10, insertwidth = 4, bg = \"powder blue\", justify = 'right') txtService.grid(row = 2, column = 3) # Vigenère cipherimport base64 # Function to encodedef encode(key, clear): enc = [] for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) enc.append(enc_c) return base64.urlsafe_b64encode(\"\".join(enc).encode()).decode() # Function to decodedef decode(key, enc): dec = [] enc = base64.urlsafe_b64decode(enc).decode() for i in range(len(enc)): key_c = key[i % len(key)] dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) dec.append(dec_c) return \"\".join(dec) def Ref(): print(\"Message= \", (Msg.get())) clear = Msg.get() k = key.get() m = mode.get() if (m == 'e'): Result.set(encode(k, clear)) else: Result.set(decode(k, clear)) # Show message buttonbtnTotal = Button(f1, padx = 16, pady = 8, bd = 16, fg = \"black\", font = ('arial', 16, 'bold'), width = 10, text = \"Show Message\", bg = \"powder blue\", command = Ref).grid(row = 7, column = 1) # Reset buttonbtnReset = Button(f1, padx = 16, pady = 8, bd = 16, fg = \"black\", font = ('arial', 16, 'bold'), width = 10, text = \"Reset\", bg = \"green\", command = Reset).grid(row = 7, column = 2) # Exit buttonbtnExit = Button(f1, padx = 16, pady = 8, bd = 16, fg = \"black\", font = ('arial', 16, 'bold'), width = 10, text = \"Exit\", bg = \"red\", command = qExit).grid(row = 7, column = 3) # keeps window aliveroot.mainloop()",
"e": 5889,
"s": 914,
"text": null
},
{
"code": null,
"e": 5917,
"s": 5889,
"text": "Output : Encrypt Window – "
},
{
"code": null,
"e": 5936,
"s": 5917,
"text": "Decrypt Window – "
},
{
"code": null,
"e": 5954,
"s": 5938,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5972,
"s": 5954,
"text": "encoding-decoding"
},
{
"code": null,
"e": 5988,
"s": 5972,
"text": "Python-projects"
},
{
"code": null,
"e": 5996,
"s": 5988,
"text": "Project"
},
{
"code": null,
"e": 6003,
"s": 5996,
"text": "Python"
}
] |
Difference between Actual and Formal Parameters in PL/SQL
|
23 Nov, 2020
A parameter is an optional list of parameters that you define both pass information into the procedure and send information out of procedure back to the calling program. Parameter is also known as argument. When you define a parameter, you also specify the way in which it can be used. There are three different modes of parameter or argument.
1. Actual Parameters :The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. These are the variables or expressions referenced in the parameter list of a subprogram call. There is no need to specify datatype in actual parameter.
Example :
// X and Y NUMBER ARE ACTUAL PARAMETERS
SQL> CREATE OR REPLACE FUNCTION FUNC1(X NUMBER,
Y NUMBER)
2 RETURN NUMBER IS
3 R NUMBER;
4 BEGIN
5 R:=X+Y;
6 RETURN(R);
7 END;
8 /
FUNCTION CREATED.
SQL>|
2. Formal Parameters :These are the variables or expressions referenced in the parameter list of a subprogram specification. The datatype of the receiving value must be defined. The scope of formal arguments is local to the function definition in which they are used.
Example :
SQL> DECLARE
2 N1 NUMBER:=10;
3 N2 NUMBER:=20;
4 S NUMBER;
5 BEGIN
6 S:=FUNC1(N1, N2);
7 DBMS_OUTOUT.PUT_LINE('RESULT IS: '||S);
8 END;
9 /
OUTPUT: RESULT IS: 30
PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.
SQL>|
Difference between Actual and Formal Parameters :
DBMS-SQL
Difference Between
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
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Difference between DELETE and TRUNCATE
Differences and Applications of List, Tuple, Set and Dictionary in Python
Difference between Abstraction and Encapsulation in Java with Examples
Difference between FDMA, TDMA and CDMA
Differences Between .NET Core and .NET Framework
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 398,
"s": 54,
"text": "A parameter is an optional list of parameters that you define both pass information into the procedure and send information out of procedure back to the calling program. Parameter is also known as argument. When you define a parameter, you also specify the way in which it can be used. There are three different modes of parameter or argument."
},
{
"code": null,
"e": 703,
"s": 398,
"text": "1. Actual Parameters :The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. These are the variables or expressions referenced in the parameter list of a subprogram call. There is no need to specify datatype in actual parameter."
},
{
"code": null,
"e": 713,
"s": 703,
"text": "Example :"
},
{
"code": null,
"e": 974,
"s": 713,
"text": "// X and Y NUMBER ARE ACTUAL PARAMETERS\nSQL> CREATE OR REPLACE FUNCTION FUNC1(X NUMBER, \n Y NUMBER) \n2 RETURN NUMBER IS\n3 R NUMBER;\n4 BEGIN\n5 R:=X+Y;\n6 RETURN(R);\n7 END;\n8 /\nFUNCTION CREATED.\n\nSQL>|\n"
},
{
"code": null,
"e": 1242,
"s": 974,
"text": "2. Formal Parameters :These are the variables or expressions referenced in the parameter list of a subprogram specification. The datatype of the receiving value must be defined. The scope of formal arguments is local to the function definition in which they are used."
},
{
"code": null,
"e": 1252,
"s": 1242,
"text": "Example :"
},
{
"code": null,
"e": 1487,
"s": 1252,
"text": "SQL> DECLARE\n2 N1 NUMBER:=10;\n3 N2 NUMBER:=20;\n4 S NUMBER;\n5 BEGIN\n6 S:=FUNC1(N1, N2);\n7 DBMS_OUTOUT.PUT_LINE('RESULT IS: '||S);\n8 END;\n9 /\n\nOUTPUT: RESULT IS: 30\nPL/SQL PROCEDURE SUCCESSFULLY COMPLETED.\nSQL>|\n"
},
{
"code": null,
"e": 1537,
"s": 1487,
"text": "Difference between Actual and Formal Parameters :"
},
{
"code": null,
"e": 1546,
"s": 1537,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1565,
"s": 1546,
"text": "Difference Between"
},
{
"code": null,
"e": 1663,
"s": 1565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1724,
"s": 1663,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1792,
"s": 1724,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 1841,
"s": 1792,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 1896,
"s": 1841,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 1962,
"s": 1896,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 2001,
"s": 1962,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 2075,
"s": 2001,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 2146,
"s": 2075,
"text": "Difference between Abstraction and Encapsulation in Java with Examples"
},
{
"code": null,
"e": 2185,
"s": 2146,
"text": "Difference between FDMA, TDMA and CDMA"
}
] |
Instant truncatedTo() method in Java with Examples
|
29 Nov, 2018
The truncatedTo() method of an Instant class is used to get the value of this Instant in the specified unit. This method takes a parameter Unit, which is the Unit in which this Instant is to be truncated to. It returns a truncated immutable Instant with the value in the specified unit.
Syntax:
public Instant truncatedTo(TemporalUnit unit)
Parameter: This method takes a parameter unit which is the unit in which this Instant is to be truncated to. It should not be null.
Returns: This method returns an immutable truncated Instant with the value in the specified unit.
Exception: This method throws following Exceptions:
DateTimeException: if the unit is invalid for truncation.
UnsupportedTemporalTypeException: if the unit is not supported.
Below programs illustrate the Instant.truncatedTo() method:
Program 1:
// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2018-12-30T09:24:54.63Z"); // print instance System.out.println("Instant before" + " truncate: " + instant); // truncate to ChronoUnit.HOURS // means unit smaller than Hour // will be Zero Instant returnvalue = instant.truncatedTo(ChronoUnit.HOURS); // print result System.out.println("Instant after " + " truncate: " + returnvalue); }}
Instant before truncate: 2018-12-30T09:24:54.630Z
Instant after truncate: 2018-12-30T09:00:00Z
Program 2:
// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2018-12-30T09:24:54.63Z"); // print instance System.out.println("Instant before" + " truncate: " + instant); // truncate to ChronoUnit.DAYS // means unit smaller than DAY // will be Zero Instant returnvalue = instant.truncatedTo(ChronoUnit.DAYS); // print result System.out.println("Instant after " + " truncate: " + returnvalue); }}
Instant before truncate: 2018-12-30T09:24:54.630Z
Instant after truncate: 2018-12-30T00:00:00Z
Program 3: To show Exception:
// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse("2018-12-30T09:24:54.63Z"); try { instant.truncatedTo(ChronoUnit.ERAS); } catch (Exception e) { // print result System.out.println("Exception: " + e); } }}
Exception:
java.time.temporal.UnsupportedTemporalTypeException:
Unit is too large to be used for truncation
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#truncatedTo(java.time.temporal.TemporalUnit)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "The truncatedTo() method of an Instant class is used to get the value of this Instant in the specified unit. This method takes a parameter Unit, which is the Unit in which this Instant is to be truncated to. It returns a truncated immutable Instant with the value in the specified unit."
},
{
"code": null,
"e": 323,
"s": 315,
"text": "Syntax:"
},
{
"code": null,
"e": 370,
"s": 323,
"text": "public Instant truncatedTo(TemporalUnit unit)\n"
},
{
"code": null,
"e": 502,
"s": 370,
"text": "Parameter: This method takes a parameter unit which is the unit in which this Instant is to be truncated to. It should not be null."
},
{
"code": null,
"e": 600,
"s": 502,
"text": "Returns: This method returns an immutable truncated Instant with the value in the specified unit."
},
{
"code": null,
"e": 652,
"s": 600,
"text": "Exception: This method throws following Exceptions:"
},
{
"code": null,
"e": 710,
"s": 652,
"text": "DateTimeException: if the unit is invalid for truncation."
},
{
"code": null,
"e": 774,
"s": 710,
"text": "UnsupportedTemporalTypeException: if the unit is not supported."
},
{
"code": null,
"e": 834,
"s": 774,
"text": "Below programs illustrate the Instant.truncatedTo() method:"
},
{
"code": null,
"e": 845,
"s": 834,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2018-12-30T09:24:54.63Z\"); // print instance System.out.println(\"Instant before\" + \" truncate: \" + instant); // truncate to ChronoUnit.HOURS // means unit smaller than Hour // will be Zero Instant returnvalue = instant.truncatedTo(ChronoUnit.HOURS); // print result System.out.println(\"Instant after \" + \" truncate: \" + returnvalue); }}",
"e": 1636,
"s": 845,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1636,
"text": "Instant before truncate: 2018-12-30T09:24:54.630Z\nInstant after truncate: 2018-12-30T09:00:00Z\n"
},
{
"code": null,
"e": 1744,
"s": 1733,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2018-12-30T09:24:54.63Z\"); // print instance System.out.println(\"Instant before\" + \" truncate: \" + instant); // truncate to ChronoUnit.DAYS // means unit smaller than DAY // will be Zero Instant returnvalue = instant.truncatedTo(ChronoUnit.DAYS); // print result System.out.println(\"Instant after \" + \" truncate: \" + returnvalue); }}",
"e": 2532,
"s": 1744,
"text": null
},
{
"code": null,
"e": 2629,
"s": 2532,
"text": "Instant before truncate: 2018-12-30T09:24:54.630Z\nInstant after truncate: 2018-12-30T00:00:00Z\n"
},
{
"code": null,
"e": 2659,
"s": 2629,
"text": "Program 3: To show Exception:"
},
{
"code": "// Java program to demonstrate// Instant.truncatedTo() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a Instant object Instant instant = Instant.parse(\"2018-12-30T09:24:54.63Z\"); try { instant.truncatedTo(ChronoUnit.ERAS); } catch (Exception e) { // print result System.out.println(\"Exception: \" + e); } }}",
"e": 3156,
"s": 2659,
"text": null
},
{
"code": null,
"e": 3267,
"s": 3156,
"text": "Exception:\n java.time.temporal.UnsupportedTemporalTypeException:\n Unit is too large to be used for truncation\n"
},
{
"code": null,
"e": 3389,
"s": 3267,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#truncatedTo(java.time.temporal.TemporalUnit)"
},
{
"code": null,
"e": 3404,
"s": 3389,
"text": "Java-Functions"
},
{
"code": null,
"e": 3417,
"s": 3404,
"text": "Java-Instant"
},
{
"code": null,
"e": 3435,
"s": 3417,
"text": "Java-time package"
},
{
"code": null,
"e": 3440,
"s": 3435,
"text": "Java"
},
{
"code": null,
"e": 3445,
"s": 3440,
"text": "Java"
}
] |
Number of Reflexive Relations on a Set
|
Difficulty Level :
Easy
Given a number n, find out number of Reflexive Relation on a set of first n natural numbers {1, 2, ..n}.Examples :
Input : n = 2
Output : 4
The given set A = {1, 2}. The following
are reflexive relations on A * A :
{{1, 1), (2, 2)}
{(1, 1), (2, 2), (1, 2)}
{(1, 1), (2, 2), (1, 2), (2, 1)}
{(1, 1), (2, 2), (2, 1)}
Input : n = 3
Output : 64
The given set is {1, 2, 3}. There are
64 reflexive relations on A * A :
Explanation :Reflexive Relation : A Relation R on A a set A is said to be Reflexive if xRx for every element of x ? A.
The number of reflexive relations on an n-element set is 2n2 – nHow does this formula work? A relation R is reflexive if the matrix diagonal elements are 1.
If we take a closer look the matrix, we can notice that the size of matrix is n2. The n diagonal entries are fixed. For remaining n2 – n entries, we have choice to either fill 0 or 1. So there are total 2n2 – n ways of filling the matrix.
CPP
Java
Python3
C#
PHP
Javascript
// C++ Program to count reflexive relations// on a set of first n natural numbers.#include <iostream>using namespace std; int countReflexive(int n){ // Return 2^(n*n - n) return (1 << (n*n - n));} int main(){ int n = 3; cout << countReflexive(n); return 0;}
// Java Program to count reflexive// relations on a set of first n// natural numbers. import java.io.*;import java.util.*; class GFG { static int countReflexive(int n){ // Return 2^(n*n - n)return (1 << (n*n - n)); } // Driver function public static void main (String[] args) { int n = 3; System.out.println(countReflexive(n)); }} // This code is contributed by Gitanjali.
# Python3 Program to count# reflexive relations# on a set of first n# natural numbers. def countReflexive(n): # Return 2^(n*n - n) return (1 << (n*n - n)); # driver functionn = 3ans = countReflexive(n);print (ans) # This code is contributed by saloni1297
// C# Program to count reflexive// relations on a set of first n// natural numbers.using System; class GFG { static int countReflexive(int n) { // Return 2^(n*n - n) return (1 << (n*n - n)); } // Driver function public static void Main () { int n = 3; Console.WriteLine(countReflexive(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to count// reflexive relations on a// set of first n natural numbers. function countReflexive($n){// Return 2^(n * n - n)return (1 << ($n * $n - $n));} //Driver code$n = 3;echo countReflexive($n); // This code is contributed by mits?>
<script> // Javascript Program to count reflexive // relations on a set of first n // natural numbers. function countReflexive(n) { // Return 2^(n*n - n) return (1 << (n*n - n)); } let n = 3; document.write(countReflexive(n)); // This code is contributed by divyesh072019.</script>
Output :
64
Time Complexity : O(1)
Space Complexity : O(1)
Mithun Kumar
divyesh072019
ranjanrohit840
Bit Magic
Combinatorial
Mathematical
Mathematical
Bit Magic
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find whether a given number is power of 2
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Binary representation of a given number
Divide two integers without using multiplication, division and mod operator
Write a program to print all permutations of a given string
Permutation and Combination in Python
Count of subsets with sum equal to X
Combinational Sum
itertools.combinations() module in Python to print all possible combinations
|
[
{
"code": null,
"e": 24,
"s": 0,
"text": "Difficulty Level :\nEasy"
},
{
"code": null,
"e": 141,
"s": 24,
"text": "Given a number n, find out number of Reflexive Relation on a set of first n natural numbers {1, 2, ..n}.Examples : "
},
{
"code": null,
"e": 442,
"s": 141,
"text": "Input : n = 2\nOutput : 4\nThe given set A = {1, 2}. The following\nare reflexive relations on A * A :\n{{1, 1), (2, 2)}\n{(1, 1), (2, 2), (1, 2)}\n{(1, 1), (2, 2), (1, 2), (2, 1)}\n{(1, 1), (2, 2), (2, 1)}\n\nInput : n = 3\nOutput : 64\nThe given set is {1, 2, 3}. There are\n64 reflexive relations on A * A :"
},
{
"code": null,
"e": 562,
"s": 442,
"text": "Explanation :Reflexive Relation : A Relation R on A a set A is said to be Reflexive if xRx for every element of x ? A. "
},
{
"code": null,
"e": 721,
"s": 562,
"text": "The number of reflexive relations on an n-element set is 2n2 – nHow does this formula work? A relation R is reflexive if the matrix diagonal elements are 1. "
},
{
"code": null,
"e": 960,
"s": 721,
"text": "If we take a closer look the matrix, we can notice that the size of matrix is n2. The n diagonal entries are fixed. For remaining n2 – n entries, we have choice to either fill 0 or 1. So there are total 2n2 – n ways of filling the matrix."
},
{
"code": null,
"e": 966,
"s": 962,
"text": "CPP"
},
{
"code": null,
"e": 971,
"s": 966,
"text": "Java"
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Python3"
},
{
"code": null,
"e": 982,
"s": 979,
"text": "C#"
},
{
"code": null,
"e": 986,
"s": 982,
"text": "PHP"
},
{
"code": null,
"e": 997,
"s": 986,
"text": "Javascript"
},
{
"code": "// C++ Program to count reflexive relations// on a set of first n natural numbers.#include <iostream>using namespace std; int countReflexive(int n){ // Return 2^(n*n - n) return (1 << (n*n - n));} int main(){ int n = 3; cout << countReflexive(n); return 0;}",
"e": 1269,
"s": 997,
"text": null
},
{
"code": "// Java Program to count reflexive// relations on a set of first n// natural numbers. import java.io.*;import java.util.*; class GFG { static int countReflexive(int n){ // Return 2^(n*n - n)return (1 << (n*n - n)); } // Driver function public static void main (String[] args) { int n = 3; System.out.println(countReflexive(n)); }} // This code is contributed by Gitanjali.",
"e": 1667,
"s": 1269,
"text": null
},
{
"code": "# Python3 Program to count# reflexive relations# on a set of first n# natural numbers. def countReflexive(n): # Return 2^(n*n - n) return (1 << (n*n - n)); # driver functionn = 3ans = countReflexive(n);print (ans) # This code is contributed by saloni1297",
"e": 1931,
"s": 1667,
"text": null
},
{
"code": "// C# Program to count reflexive// relations on a set of first n// natural numbers.using System; class GFG { static int countReflexive(int n) { // Return 2^(n*n - n) return (1 << (n*n - n)); } // Driver function public static void Main () { int n = 3; Console.WriteLine(countReflexive(n)); }} // This code is contributed by vt_m.",
"e": 2332,
"s": 1931,
"text": null
},
{
"code": "<?php// PHP Program to count// reflexive relations on a// set of first n natural numbers. function countReflexive($n){// Return 2^(n * n - n)return (1 << ($n * $n - $n));} //Driver code$n = 3;echo countReflexive($n); // This code is contributed by mits?>",
"e": 2587,
"s": 2332,
"text": null
},
{
"code": "<script> // Javascript Program to count reflexive // relations on a set of first n // natural numbers. function countReflexive(n) { // Return 2^(n*n - n) return (1 << (n*n - n)); } let n = 3; document.write(countReflexive(n)); // This code is contributed by divyesh072019.</script>",
"e": 2927,
"s": 2587,
"text": null
},
{
"code": null,
"e": 2938,
"s": 2927,
"text": "Output : "
},
{
"code": null,
"e": 2941,
"s": 2938,
"text": "64"
},
{
"code": null,
"e": 2965,
"s": 2941,
"text": " Time Complexity : O(1)"
},
{
"code": null,
"e": 2989,
"s": 2965,
"text": "Space Complexity : O(1)"
},
{
"code": null,
"e": 3002,
"s": 2989,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 3016,
"s": 3002,
"text": "divyesh072019"
},
{
"code": null,
"e": 3031,
"s": 3016,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 3041,
"s": 3031,
"text": "Bit Magic"
},
{
"code": null,
"e": 3055,
"s": 3041,
"text": "Combinatorial"
},
{
"code": null,
"e": 3068,
"s": 3055,
"text": "Mathematical"
},
{
"code": null,
"e": 3081,
"s": 3068,
"text": "Mathematical"
},
{
"code": null,
"e": 3091,
"s": 3081,
"text": "Bit Magic"
},
{
"code": null,
"e": 3105,
"s": 3091,
"text": "Combinatorial"
},
{
"code": null,
"e": 3203,
"s": 3105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3256,
"s": 3203,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 3286,
"s": 3256,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 3324,
"s": 3286,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 3364,
"s": 3324,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 3440,
"s": 3364,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 3500,
"s": 3440,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 3538,
"s": 3500,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 3575,
"s": 3538,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 3593,
"s": 3575,
"text": "Combinational Sum"
}
] |
SQL Query to Display the Length and First 3 Characters of Ename Column in Emp Table
|
10 Oct, 2021
To display the length and first three characters of a string, string functions come in handy to do these in SQL. In this article let us see how to display the length and first 3 characters of the Ename column in the Emp table using MSSQL as the server.
To find the length of a string we use the LEN( ) function.
Syntax:
LEN(Ename)
To find the first n characters of string we use the LEFT() function:
Syntax:
LEFT(Ename , N)
Step 1: Creating a Database
We use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks
Step 2: Using the Database
To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks;
Step 3: Creating a table
Creating a table Emp with 5 columns using the following SQL query as follows.
CREATE TABLE Emp
(
E_id varchar(20),
Ename varchar(20),
Edept varchar(20),
E_age INT,
E_sex varchar(8)
);
Output:
Step 4: Verifying the database
To view the description of the database using the following SQL query as follows.
Query:
EXEC sp_columns Emp
Output:
Step 5: Inserting data into the table
Inserting rows into the Emp table using the following SQL query as follows.
Query:
INSERT INTO Emp VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male'),
('E00002','DARSHI','MARKETING',27,'male'),
('E00003','JASMINE','FRONTEND DEVELOPER',37,'female'),
('E00004','LILLY','FULL STACK DEVELOPER',47,'female'),
('E00005','RONALD','UI DEVELOPER',26,'male')
Output:
Step 6: Verifying inserted data
Check the inserted data in the table using the select query as follows.
Query:
SELECT* FROM Emp
Output:
Query to Display the Length and First 3 Characters of Ename Column.
Query:
SELECT LEN(Ename) AS LengthofEname,
LEFT(Ename,3) AS FirstThree FROM Emp
Output:
Query to Display the Length and Last 3 Characters of Ename Column.
Query:
SELECT LEN(Ename) AS LengthofEname,
RIGHT(Ename,3) AS LastThree FROM Emp
Output:
Picked
SQL-Query
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": "\n10 Oct, 2021"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "To display the length and first three characters of a string, string functions come in handy to do these in SQL. In this article let us see how to display the length and first 3 characters of the Ename column in the Emp table using MSSQL as the server."
},
{
"code": null,
"e": 340,
"s": 281,
"text": "To find the length of a string we use the LEN( ) function."
},
{
"code": null,
"e": 348,
"s": 340,
"text": "Syntax:"
},
{
"code": null,
"e": 359,
"s": 348,
"text": "LEN(Ename)"
},
{
"code": null,
"e": 428,
"s": 359,
"text": "To find the first n characters of string we use the LEFT() function:"
},
{
"code": null,
"e": 436,
"s": 428,
"text": "Syntax:"
},
{
"code": null,
"e": 452,
"s": 436,
"text": "LEFT(Ename , N)"
},
{
"code": null,
"e": 480,
"s": 452,
"text": "Step 1: Creating a Database"
},
{
"code": null,
"e": 547,
"s": 480,
"text": "We use the below command to create a database named GeeksforGeeks."
},
{
"code": null,
"e": 554,
"s": 547,
"text": "Query:"
},
{
"code": null,
"e": 584,
"s": 554,
"text": "CREATE DATABASE GeeksforGeeks"
},
{
"code": null,
"e": 611,
"s": 584,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 668,
"s": 611,
"text": "To use the GeeksforGeeks database use the below command:"
},
{
"code": null,
"e": 675,
"s": 668,
"text": "Query:"
},
{
"code": null,
"e": 694,
"s": 675,
"text": "USE GeeksforGeeks;"
},
{
"code": null,
"e": 719,
"s": 694,
"text": "Step 3: Creating a table"
},
{
"code": null,
"e": 797,
"s": 719,
"text": "Creating a table Emp with 5 columns using the following SQL query as follows."
},
{
"code": null,
"e": 903,
"s": 797,
"text": "CREATE TABLE Emp\n(\nE_id varchar(20),\nEname varchar(20),\nEdept varchar(20),\nE_age INT,\nE_sex varchar(8)\n);"
},
{
"code": null,
"e": 911,
"s": 903,
"text": "Output:"
},
{
"code": null,
"e": 942,
"s": 911,
"text": "Step 4: Verifying the database"
},
{
"code": null,
"e": 1024,
"s": 942,
"text": "To view the description of the database using the following SQL query as follows."
},
{
"code": null,
"e": 1031,
"s": 1024,
"text": "Query:"
},
{
"code": null,
"e": 1051,
"s": 1031,
"text": "EXEC sp_columns Emp"
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "Output:"
},
{
"code": null,
"e": 1098,
"s": 1059,
"text": "Step 5: Inserting data into the table "
},
{
"code": null,
"e": 1174,
"s": 1098,
"text": "Inserting rows into the Emp table using the following SQL query as follows."
},
{
"code": null,
"e": 1181,
"s": 1174,
"text": "Query:"
},
{
"code": null,
"e": 1454,
"s": 1181,
"text": " INSERT INTO Emp VALUES('E00001','JHONNY','BACKEND DEVELOPER',26,'male'),\n ('E00002','DARSHI','MARKETING',27,'male'),\n('E00003','JASMINE','FRONTEND DEVELOPER',37,'female'),\n('E00004','LILLY','FULL STACK DEVELOPER',47,'female'),\n('E00005','RONALD','UI DEVELOPER',26,'male')"
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Output:"
},
{
"code": null,
"e": 1495,
"s": 1462,
"text": "Step 6: Verifying inserted data "
},
{
"code": null,
"e": 1567,
"s": 1495,
"text": "Check the inserted data in the table using the select query as follows."
},
{
"code": null,
"e": 1574,
"s": 1567,
"text": "Query:"
},
{
"code": null,
"e": 1591,
"s": 1574,
"text": "SELECT* FROM Emp"
},
{
"code": null,
"e": 1599,
"s": 1591,
"text": "Output:"
},
{
"code": null,
"e": 1667,
"s": 1599,
"text": "Query to Display the Length and First 3 Characters of Ename Column."
},
{
"code": null,
"e": 1674,
"s": 1667,
"text": "Query:"
},
{
"code": null,
"e": 1747,
"s": 1674,
"text": "SELECT LEN(Ename) AS LengthofEname,\nLEFT(Ename,3) AS FirstThree FROM Emp"
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Output:"
},
{
"code": null,
"e": 1822,
"s": 1755,
"text": "Query to Display the Length and Last 3 Characters of Ename Column."
},
{
"code": null,
"e": 1829,
"s": 1822,
"text": "Query:"
},
{
"code": null,
"e": 1902,
"s": 1829,
"text": "SELECT LEN(Ename) AS LengthofEname,\nRIGHT(Ename,3) AS LastThree FROM Emp"
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Output:"
},
{
"code": null,
"e": 1917,
"s": 1910,
"text": "Picked"
},
{
"code": null,
"e": 1927,
"s": 1917,
"text": "SQL-Query"
},
{
"code": null,
"e": 1938,
"s": 1927,
"text": "SQL-Server"
},
{
"code": null,
"e": 1942,
"s": 1938,
"text": "SQL"
},
{
"code": null,
"e": 1946,
"s": 1942,
"text": "SQL"
}
] |
Detecting Multicollinearity with VIF - Python - GeeksforGeeks
|
29 Aug, 2020
Multicollinearity occurs when there are two or more independent variables in a multiple regression model, which have a high correlation among themselves. When some features are highly correlated, we might have difficulty in distinguishing between their individual effects on the dependent variable. Multicollinearity can be detected using various techniques, one such technique being the Variance Inflation Factor(VIF).
In VIF method, we pick each feature and regress it against all of the other features. For each regression, the factor is calculated as :
Where, R-squared is the coefficient of determination in linear regression. Its value lies between 0 and 1.
As we see from the formula, greater the value of R-squared, greater is the VIF. Hence, greater VIF denotes greater correlation. This is in agreement with the fact that a higher R-squared value denotes a stronger collinearity. Generally, a VIF above 5 indicates a high multicollinearity.
Implementing VIF using statsmodels:
statsmodels provides a function named variance_inflation_factor() for calculating VIF.
Syntax : statsmodels.stats.outliers_influence.variance_inflation_factor(exog, exog_idx)
Parameters :
exog : an array containing features on which linear regression is performed.
exog_idx : index of the additional feature whose influence on the other features is to be measured.
Let us see an example to implement the method on this dataset.
The dataset :
The dataset used in the example below, contains the height, weight, gender and Body Mass Index for 500 persons. Here the dependent variable is Index.
Python3
import pandas as pd # the datasetdata = pd.read_csv('BMI.csv') # printing first few rowsprint(data.head())
Output :
Gender Height Weight Index
0 Male 174 96 4
1 Male 189 87 2
2 Female 185 110 4
3 Female 195 104 3
4 Male 149 61 3
Approach :
Each of the feature indices are passed to variance_inflation_factor() to find the corresponding VIF.
These values are stored in the form of a Pandas DataFrame.
Python3
from statsmodels.stats.outliers_influence import variance_inflation_factor # creating dummies for genderdata['Gender'] = data['Gender'].map({'Male':0, 'Female':1}) # the independent variables setX = data[['Gender', 'Height', 'Weight']] # VIF dataframevif_data = pd.DataFrame()vif_data["feature"] = X.columns # calculating VIF for each featurevif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(len(X.columns))] print(vif_data)
Output :
feature VIF
0 Gender 2.028864
1 Height 11.623103
2 Weight 10.688377
As we can see, height and weight have very high values of VIF, indicating that these two variables are highly correlated. This is expected as the height of a person does influence their weight. Hence, considering these two features together leads to a model with high multicollinearity.
data-science
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Decision Tree
Python | Decision tree implementation
Search Algorithms in AI
Difference between Informed and Uninformed Search in AI
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 23889,
"s": 23861,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24309,
"s": 23889,
"text": "Multicollinearity occurs when there are two or more independent variables in a multiple regression model, which have a high correlation among themselves. When some features are highly correlated, we might have difficulty in distinguishing between their individual effects on the dependent variable. Multicollinearity can be detected using various techniques, one such technique being the Variance Inflation Factor(VIF)."
},
{
"code": null,
"e": 24446,
"s": 24309,
"text": "In VIF method, we pick each feature and regress it against all of the other features. For each regression, the factor is calculated as :"
},
{
"code": null,
"e": 24553,
"s": 24446,
"text": "Where, R-squared is the coefficient of determination in linear regression. Its value lies between 0 and 1."
},
{
"code": null,
"e": 24841,
"s": 24553,
"text": "As we see from the formula, greater the value of R-squared, greater is the VIF. Hence, greater VIF denotes greater correlation. This is in agreement with the fact that a higher R-squared value denotes a stronger collinearity. Generally, a VIF above 5 indicates a high multicollinearity. "
},
{
"code": null,
"e": 24877,
"s": 24841,
"text": "Implementing VIF using statsmodels:"
},
{
"code": null,
"e": 24964,
"s": 24877,
"text": "statsmodels provides a function named variance_inflation_factor() for calculating VIF."
},
{
"code": null,
"e": 25052,
"s": 24964,
"text": "Syntax : statsmodels.stats.outliers_influence.variance_inflation_factor(exog, exog_idx)"
},
{
"code": null,
"e": 25065,
"s": 25052,
"text": "Parameters :"
},
{
"code": null,
"e": 25142,
"s": 25065,
"text": "exog : an array containing features on which linear regression is performed."
},
{
"code": null,
"e": 25242,
"s": 25142,
"text": "exog_idx : index of the additional feature whose influence on the other features is to be measured."
},
{
"code": null,
"e": 25305,
"s": 25242,
"text": "Let us see an example to implement the method on this dataset."
},
{
"code": null,
"e": 25319,
"s": 25305,
"text": "The dataset :"
},
{
"code": null,
"e": 25470,
"s": 25319,
"text": "The dataset used in the example below, contains the height, weight, gender and Body Mass Index for 500 persons. Here the dependent variable is Index. "
},
{
"code": null,
"e": 25478,
"s": 25470,
"text": "Python3"
},
{
"code": "import pandas as pd # the datasetdata = pd.read_csv('BMI.csv') # printing first few rowsprint(data.head())",
"e": 25588,
"s": 25478,
"text": null
},
{
"code": null,
"e": 25597,
"s": 25588,
"text": "Output :"
},
{
"code": null,
"e": 25795,
"s": 25597,
"text": " Gender Height Weight Index\n0 Male 174 96 4\n1 Male 189 87 2\n2 Female 185 110 4\n3 Female 195 104 3\n4 Male 149 61 3"
},
{
"code": null,
"e": 25806,
"s": 25795,
"text": "Approach :"
},
{
"code": null,
"e": 25907,
"s": 25806,
"text": "Each of the feature indices are passed to variance_inflation_factor() to find the corresponding VIF."
},
{
"code": null,
"e": 25966,
"s": 25907,
"text": "These values are stored in the form of a Pandas DataFrame."
},
{
"code": null,
"e": 25974,
"s": 25966,
"text": "Python3"
},
{
"code": "from statsmodels.stats.outliers_influence import variance_inflation_factor # creating dummies for genderdata['Gender'] = data['Gender'].map({'Male':0, 'Female':1}) # the independent variables setX = data[['Gender', 'Height', 'Weight']] # VIF dataframevif_data = pd.DataFrame()vif_data[\"feature\"] = X.columns # calculating VIF for each featurevif_data[\"VIF\"] = [variance_inflation_factor(X.values, i) for i in range(len(X.columns))] print(vif_data)",
"e": 26452,
"s": 25974,
"text": null
},
{
"code": null,
"e": 26461,
"s": 26452,
"text": "Output :"
},
{
"code": null,
"e": 26545,
"s": 26461,
"text": " feature VIF\n0 Gender 2.028864\n1 Height 11.623103\n2 Weight 10.688377"
},
{
"code": null,
"e": 26832,
"s": 26545,
"text": "As we can see, height and weight have very high values of VIF, indicating that these two variables are highly correlated. This is expected as the height of a person does influence their weight. Hence, considering these two features together leads to a model with high multicollinearity."
},
{
"code": null,
"e": 26845,
"s": 26832,
"text": "data-science"
},
{
"code": null,
"e": 26862,
"s": 26845,
"text": "Machine Learning"
},
{
"code": null,
"e": 26869,
"s": 26862,
"text": "Python"
},
{
"code": null,
"e": 26886,
"s": 26869,
"text": "Machine Learning"
},
{
"code": null,
"e": 26984,
"s": 26886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26993,
"s": 26984,
"text": "Comments"
},
{
"code": null,
"e": 27006,
"s": 26993,
"text": "Old Comments"
},
{
"code": null,
"e": 27029,
"s": 27006,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27043,
"s": 27029,
"text": "Decision Tree"
},
{
"code": null,
"e": 27081,
"s": 27043,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 27105,
"s": 27081,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 27161,
"s": 27105,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 27189,
"s": 27161,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27239,
"s": 27189,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27261,
"s": 27239,
"text": "Python map() function"
}
] |
Count of AP (Arithmetic Progression) Subsequences in an array in C++
|
Given an array arr[] containing integer elements. The goal is to count the number of Arithmetic Progression subsequences inside arr[]. The range of elements inside arr[] are [1,1000000].
Empty sequence or single element will also be counted.
For Example
Input - arr[] = {1,2,3}
Output - Count of AP (Arithmetic Progression) Subsequences in an array are: 8
Explanation - The following subsequences will form AP:-
{}, {1}, {2}, {3}, {1,2}, {2,3}, {1,3}, {1,2,3}
Input - arr[] = {2,4,5,8}
Output - Count of AP (Arithmetic Progression) Subsequences in an array are: 12
Explanation - The following subsequences will form AP:-
{}, {2}, {4}, {5}, {8}, {2,4}, {2,5}, {2,8}, {4,5}, {4,8}, {5,8}, {2,5,8}
An empty sequence is also an AP.
A single value is also an AP.
Find minimum and maximum values within the array as max_val and min_val. The common differences in all AP subsequences will be between [ min_val - max_val , max_val - min_val ]
Now for each common difference we will find subsequences using dynamic programming and store in arr_2[size].
No subsequences of length 2 or more than 2 will be the sum of arr_2[i]-1 where i is [0,2] and difference is D.
arr_2[i] = 1+ sum ( arr[j] ) where i<j and arr_2[j] + D= arr_2[i]
For faster approach add sums ( arr_2[j] with arr[j]+D = arr[i] and j<i ) in arr_3[max_size]
Take integer array arr[] as input.
Function AP_subsequence(int arr[], int size) takes an input array and returns the count of AP (Arithmetic Progression) Subsequences in an array.
Take the initial count as 0.
Take variables max_val, min_val, arr_2[size] for storing subsequences count and arr_3[max_size] for storing sums.
Traverse arr[] using for loop and find maximum and minimum element and store in max_val and min_val.
Take count = size +1 for single element APs and empty AP.
Calculate maximum difference diff_max = max_val - min_val and diff_min = min_val - max_val as common differences possible.
Traverse using for loop from j=0 to j<size.
Set arr_2[j] = 1;
For arr[j] - i >= 1 and arr[j] - i <= 1000000 set arr_2[j] += arr_3[arr[j] - i].
Add arr_2[j]-1 to count.
Update sum as arr_3[arr[j]] = arr_3[arr[j]] + arr_2[j].
At the end return count as result.
Live Demo
#include<bits/stdc++.h>
using namespace std;
#define max_size 10000
int AP_subsequence(int arr[], int size) {
int count = 0;
int max_val = INT_MAX;
int min_val = INT_MIN;
int arr_2[size];
int arr_3[max_size];
for (int i = 0; i < size; i++) {
max_val = min(max_val, arr[i]);
min_val = max(min_val, arr[i]);
}
count = size + 1;
int diff_max = max_val - min_val;
int diff_min = min_val - max_val;
for (int i = diff_max; i <= diff_min; i++) {
memset(arr_3, 0, sizeof arr_3);
for (int j = 0; j < size; j++) {
arr_2[j] = 1;
if (arr[j] - i >= 1) {
if (arr[j] - i <= 1000000) {
arr_2[j] += arr_3[arr[j] - i];
}
}
count += arr_2[j] - 1;
arr_3[arr[j]] = arr_3[arr[j]] + arr_2[j];
}
}
return count;
}
int main() {
int arr[] = {1,1,6,7,8};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Count of AP (Arithmetic Progression) Subsequences in an array are: " << AP_subsequence(arr, size);
return 0;
}
If we run the above code it will generate the following output −
Count of AP (Arithmetic Progression) Subsequences in an array are: 17
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "Given an array arr[] containing integer elements. The goal is to count the number of Arithmetic Progression subsequences inside arr[]. The range of elements inside arr[] are [1,1000000]."
},
{
"code": null,
"e": 1304,
"s": 1249,
"text": "Empty sequence or single element will also be counted."
},
{
"code": null,
"e": 1316,
"s": 1304,
"text": "For Example"
},
{
"code": null,
"e": 1340,
"s": 1316,
"text": "Input - arr[] = {1,2,3}"
},
{
"code": null,
"e": 1418,
"s": 1340,
"text": "Output - Count of AP (Arithmetic Progression) Subsequences in an array are: 8"
},
{
"code": null,
"e": 1474,
"s": 1418,
"text": "Explanation - The following subsequences will form AP:-"
},
{
"code": null,
"e": 1522,
"s": 1474,
"text": "{}, {1}, {2}, {3}, {1,2}, {2,3}, {1,3}, {1,2,3}"
},
{
"code": null,
"e": 1548,
"s": 1522,
"text": "Input - arr[] = {2,4,5,8}"
},
{
"code": null,
"e": 1627,
"s": 1548,
"text": "Output - Count of AP (Arithmetic Progression) Subsequences in an array are: 12"
},
{
"code": null,
"e": 1683,
"s": 1627,
"text": "Explanation - The following subsequences will form AP:-"
},
{
"code": null,
"e": 1757,
"s": 1683,
"text": "{}, {2}, {4}, {5}, {8}, {2,4}, {2,5}, {2,8}, {4,5}, {4,8}, {5,8}, {2,5,8}"
},
{
"code": null,
"e": 1790,
"s": 1757,
"text": "An empty sequence is also an AP."
},
{
"code": null,
"e": 1820,
"s": 1790,
"text": "A single value is also an AP."
},
{
"code": null,
"e": 1997,
"s": 1820,
"text": "Find minimum and maximum values within the array as max_val and min_val. The common differences in all AP subsequences will be between [ min_val - max_val , max_val - min_val ]"
},
{
"code": null,
"e": 2106,
"s": 1997,
"text": "Now for each common difference we will find subsequences using dynamic programming and store in arr_2[size]."
},
{
"code": null,
"e": 2217,
"s": 2106,
"text": "No subsequences of length 2 or more than 2 will be the sum of arr_2[i]-1 where i is [0,2] and difference is D."
},
{
"code": null,
"e": 2283,
"s": 2217,
"text": "arr_2[i] = 1+ sum ( arr[j] ) where i<j and arr_2[j] + D= arr_2[i]"
},
{
"code": null,
"e": 2376,
"s": 2283,
"text": "For faster approach add sums ( arr_2[j] with arr[j]+D = arr[i] and j<i ) in arr_3[max_size]"
},
{
"code": null,
"e": 2411,
"s": 2376,
"text": "Take integer array arr[] as input."
},
{
"code": null,
"e": 2556,
"s": 2411,
"text": "Function AP_subsequence(int arr[], int size) takes an input array and returns the count of AP (Arithmetic Progression) Subsequences in an array."
},
{
"code": null,
"e": 2585,
"s": 2556,
"text": "Take the initial count as 0."
},
{
"code": null,
"e": 2700,
"s": 2585,
"text": "Take variables max_val, min_val, arr_2[size] for storing subsequences count and arr_3[max_size] for storing sums."
},
{
"code": null,
"e": 2801,
"s": 2700,
"text": "Traverse arr[] using for loop and find maximum and minimum element and store in max_val and min_val."
},
{
"code": null,
"e": 2859,
"s": 2801,
"text": "Take count = size +1 for single element APs and empty AP."
},
{
"code": null,
"e": 2982,
"s": 2859,
"text": "Calculate maximum difference diff_max = max_val - min_val and diff_min = min_val - max_val as common differences possible."
},
{
"code": null,
"e": 3026,
"s": 2982,
"text": "Traverse using for loop from j=0 to j<size."
},
{
"code": null,
"e": 3044,
"s": 3026,
"text": "Set arr_2[j] = 1;"
},
{
"code": null,
"e": 3128,
"s": 3044,
"text": "For arr[j] - i >= 1 and arr[j] - i <= 1000000 set arr_2[j] += arr_3[arr[j] - i]."
},
{
"code": null,
"e": 3153,
"s": 3128,
"text": "Add arr_2[j]-1 to count."
},
{
"code": null,
"e": 3210,
"s": 3153,
"text": "Update sum as arr_3[arr[j]] = arr_3[arr[j]] + arr_2[j]."
},
{
"code": null,
"e": 3245,
"s": 3210,
"text": "At the end return count as result."
},
{
"code": null,
"e": 3255,
"s": 3245,
"text": "Live Demo"
},
{
"code": null,
"e": 4312,
"s": 3255,
"text": "#include<bits/stdc++.h>\n\nusing namespace std;\n#define max_size 10000\n\nint AP_subsequence(int arr[], int size) {\n int count = 0;\n int max_val = INT_MAX;\n int min_val = INT_MIN;\n int arr_2[size];\n int arr_3[max_size];\n\n for (int i = 0; i < size; i++) {\n max_val = min(max_val, arr[i]);\n min_val = max(min_val, arr[i]);\n }\n count = size + 1;\n int diff_max = max_val - min_val;\n int diff_min = min_val - max_val;\n for (int i = diff_max; i <= diff_min; i++) {\n memset(arr_3, 0, sizeof arr_3);\n for (int j = 0; j < size; j++) {\n arr_2[j] = 1;\n if (arr[j] - i >= 1) {\n if (arr[j] - i <= 1000000) {\n arr_2[j] += arr_3[arr[j] - i];\n }\n }\n count += arr_2[j] - 1;\n arr_3[arr[j]] = arr_3[arr[j]] + arr_2[j];\n }\n }\n return count;\n}\nint main() {\n int arr[] = {1,1,6,7,8};\n int size = sizeof(arr) / sizeof(arr[0]);\n cout << \"Count of AP (Arithmetic Progression) Subsequences in an array are: \" << AP_subsequence(arr, size);\n return 0;\n}"
},
{
"code": null,
"e": 4377,
"s": 4312,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4447,
"s": 4377,
"text": "Count of AP (Arithmetic Progression) Subsequences in an array are: 17"
}
] |
Configure XGBoost Models with YAML | by Cole Brendel | Towards Data Science
|
How to use YAML files to make your models rapidly sharable, wickedly flexible, and to prepare them for production
There is nothing more enjoyable than starting work on a new ML project. First, you get your hands dirty with some data cleaning, then you get to load that squeaky-clean data into a pandas df to start some exploratory data analysis (where you inevitably discover you need to go back and do more data cleaning...) Next, you are onto feature engineering and then finally, you are at the stage where you are ready to build some models and experiment!
Throughout this whole process, you’ve likely put all of your code together in your trusty jupyter notebook. Now you’d like to actually put your model to use, but how do you even begin? You certainly can’t put a notebook into production.
One could write a book on the productionization of machine learning models. It is not my intent to teach you all of the engineering steps required for production. Instead, think of this article as a productionization kaizen: one small change you can make to your code to prepare for production.
In the article, I will show you how to use YAML configuration files to make your code cleaner, more scalable, easier to maintain, and more efficient at running experiments.
YAML is a recursively named language for storing information in a human readable format [1].
A detailed discussion on the structure of yaml would take us too far afield, so being sufficient for our purposes, let’s consider the following yaml block for initializing an XGBoost Classifier. This block defines a dictionary “model_settings”, taking another dictionary as its value the parameters dictionary. The parameters dictionary holds the values for each of the parameters of the xgboost model that we would like to set.
# basic yaml configmodel_settings: random_state: 90210 objective: 'binary:logistic' eval_metric: ['error', 'map', 'auc', 'aucpr'] n_jobs: -1 learning_rate: 0.01 colsample_bytree: 0.8 subsample: 0.75 reg_alpha: 2.5 reg_lambda: 1.25 max_depth: 7 gamma: 0.2 n_estimators: 1251 max_delta_step: 8.5 scale_pos_weight: 2.0
By writing the parameters of your model in a yaml config, you derive 4 primary benefits:
The parameters are no longer hard-coded in the initialization of the model making code cleanerCollaborators can easily implement your model by passing a single file (preferably in a git repo)Making changes to your model no longer requires code refactoringFollowing (3), you can easily conduct “what-if” experiments on your model. E.g., What if I changed max-depth to go one level deeper?
The parameters are no longer hard-coded in the initialization of the model making code cleaner
Collaborators can easily implement your model by passing a single file (preferably in a git repo)
Making changes to your model no longer requires code refactoring
Following (3), you can easily conduct “what-if” experiments on your model. E.g., What if I changed max-depth to go one level deeper?
We want to be able to pass the information contained in the yaml file to other scripts in your project. To this end, we define a super-class for your project holding all sub-classes (think of them as modules) which will hold the values in your yaml. By doing this, we can enforce types so that a user can’t pass strings where ints are expected. Let’s define one such object.
class YamlDemo: class ModelSettings: def __init__(self, random_state: int, objective: str, eval_metric: list, n_jobs: int, learning_rate: float, colsample_bytree: float, subsample: float, reg_alpha: float, reg_lambda: float, max_depth: int, gamma: float, n_estimators: int, max_delta_step: float, scale_pos_weight: float): self.random_state = random_state self.objective = objective self.eval_metric = eval_metric self.n_jobs = n_jobs self.learning_rate = learning_rate self.colsample_bytree = colsample_bytree self.subsample = subsample self.reg_alpha = reg_alpha self.reg_lambda = reg_lambda self.max_depth = max_depth self.gamma = gamma self.n_estimators = n_estimators self.max_delta_step = max_delta_step self.scale_pos_weight = scale_pos_weight def __init__(self, model_settings: ModelSettings, config_path: str): self.model_settings = model_settings self.config_path = config_path
With your yaml config and config object in place, the last component is the authoring of a parser to read your yaml and populate your config object with the values. A simple config parser function like the following can do this for you.
import yamldef parse_config(config_path: str) -> YamlDemo: """ parses yaml config; returns populated YamlDemo object """ with open(config_path, 'r') as stream: try: config_settings = yaml.safe_load(stream) except yaml.YAMLError as e: print(e)model_settings = YamlDemo.ModelSettings( random_state = config_settings["model_settings"]["random_state"], objective = config_settings["model_settings"]["objective"], eval_metric = config_settings["model_settings"]["eval_metric"], n_jobs = config_settings["model_settings"]["n_jobs"], learning_rate = config_settings["model_settings"]["learning_rate"], colsample_bytree = config_settings["model_settings"]["colsample_bytree"], subsample = config_settings["model_settings"]["subsample"], reg_alpha = config_settings["model_settings"]["reg_alpha"], reg_lambda = config_settings["model_settings"]["reg_lambda"], max_depth = config_settings["model_settings"]["max_depth"], gamma = config_settings["model_settings"]["gamma"], n_estimators = config_settings["model_settings"]["n_estimators"], max_delta_step = config_settings["model_settings"]["max_delta_step"], scale_pos_weight = config_settings["model_settings"]["scale_pos_weight"] ) config = YamlDemo(model_settings=model_settings, config_path=config_path) assert isinstance(config, YamlDemo) return config
Now, the last step in the process is to pass the information in your config object to your model.
First, we must parse our config to obtain a populated object:
config_settings = parse_config('/Users/cole.brendel/Desktop/demo.yaml')
Next, let’s get an example data set to see the model “in action”:
from sklearn.datasets import load_irisX,y = load_iris(return_X_y=True)# notice how I set the value for `random_state` from the config!from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.33, random_state=config_settings.model_settings.random_state)
Lastly, we’ll pass this config to a function which trains the model.
# fits a model on the training set/evals on test setimport pandas as pdfrom pandas import DataFrameimport xgboostfrom xgboost import XGBClassifierfrom sklearn.metrics import classification_reportdef fit_xgb_model(config_settings: YamlDemo, X_train: DataFrame, y_train: DataFrame, X_test: DataFrame, y_test: DataFrame) -> xgboost.XGBClassifier: """ fits an XGB model and returns model obejct """ eval_set = [(X_test, y_test)] # used for early stopping# populate the model with settings from config xgb = XGBClassifier( random_state=config_settings.model_settings.random_state, objective=config_settings.model_settings.objective, eval_metric=config_settings.model_settings.eval_metric, eval_set=eval_set, n_jobs=config_settings.model_settings.n_jobs, learning_rate=config_settings.model_settings.learning_rate, colsample_bytree=config_settings.model_settings.colsample_bytree, subsample=config_settings.model_settings.subsample, reg_alpha=config_settings.model_settings.reg_alpha, reg_lambda=config_settings.model_settings.reg_lambda, max_depth=config_settings.model_settings.max_depth, gamma=config_settings.model_settings.gamma, n_estimators=config_settings.model_settings.n_estimators, max_delta_step=config_settings.model_settings.max_delta_step, scale_pos_weight=config_settings.model_settings.scale_pos_weight ) # fit the model xgb_fit = xgb.fit(X_train, y_train) # predict on test set y_pred = xgb.predict(X_test) # show results print(classification_report(y_test, y_pred, digits=4, target_names=['setosa', 'versicolor', 'virginica'])) return xgb_fitxgb = fit_xgb_model(config_settings, X_train, y_train, X_test, y_test)
And violá! The model has been trained and evaluated!
You may be asking yourself:
Why would I write all this code just to pass some parameters to my model? It seems like a ton of work and way more code than is necessary!
It is true that you could simply populate a model with all of the parameters, but you are now locking yourself into that configuration! To make changes, you will need to go in and alter the code. What if you want to show your teammate your latest configuration which yielded the best results? Will you copy/paste your models code? Why not just slack them the config file?
This config is just the tip of the iceberg. By using a process such as the one I am outlining here, you can easily specify much more additional information that is relevant to your model pipeline. For example, where are the training files located? Put that path in the config! Which ETLs to run and where to store the temporary files after the application of each ETL? Config that! How many iterations of RandomSearch should be run? Config again! To give you an idea on the scope of these configs, consider the following highly simplified example:
ec2_settings: ip_address: xxx.xxx.xxx pem_file: '/Users/{}/Desktop/demo/ssh/my.pem'data_settings: deploy_date: 'today' # or 'YYYY-MM-DD' target_names: ['no', 'yes'] raw_bucket: '/Users/{}/Desktop/demo/datasets/raw' etl_bucket_train: '/Users/{}/Desktop/demo/datasets/etl_train' etl_bucket_score: '/Users/{}/Desktop/demo/datasets/etl_score' tmp_bucket: '/Users/{}/Desktop/demo/datasets/tmp' df_name: 'df.csv'logger_settings: log_name: 'demo.log' logs_path: '/Users/{}/Desktop/demo/logs'etl_settings: pickles: '/Users/{}/Desktop/demo/src/etls/pickles' target_variable: 'xxx_yyy' idx_column: 'idx_col'model_settings: pickles: '/Users/{}/Desktop/demo/src/modeling/pickles' predictions: '/Users/{}/Desktop/demo/predictions' eval_metric: ['error', 'map', 'aucpr'] n_iters: 500 sampling_points: 1000 optimization_metric: 'f1_weighted' cv_folds: 5
With such a system in place, the sharing of results and experiments becomes as simple as slacking your fellow DS a yaml file.
You now have all the tools necessary to begin writing configs for you machine learning projects! This process takes some time to set up, but it pays off in the long run.
You enable rapid experimentation and you don’ t have to interact with the code to make changes to your model. You enable other scientists to simply change some settings and test away. By reading the YAML into a python class, you can easily enforce types and prevent erroneous values from being passed before spending money on expensive compute resources.
[1] https://yaml.org/
Data structures for statistical computing in python, McKinney, Proceedings of the 9th Python in Science Conference, Volume 445, 2010.
@software{reback2020pandas, author = {The pandas development team}, title = {pandas-dev/pandas: Pandas}, month = feb, year = 2020, publisher = {Zenodo}, version = {latest}, doi = {10.5281/zenodo.3509134}, url = {https://doi.org/10.5281/zenodo.3509134}}
Harris, C.R., Millman, K.J., van der Walt, S.J. et al. Array programming with NumPy. Nature 585, 357–362 (2020). DOI: 10.1038/s41586–020–2649–2.
Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.
Chen, T., & Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting System. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (pp. 785–794). New York, NY, USA: ACM. https://doi.org/10.1145/2939672.2939785
|
[
{
"code": null,
"e": 286,
"s": 172,
"text": "How to use YAML files to make your models rapidly sharable, wickedly flexible, and to prepare them for production"
},
{
"code": null,
"e": 733,
"s": 286,
"text": "There is nothing more enjoyable than starting work on a new ML project. First, you get your hands dirty with some data cleaning, then you get to load that squeaky-clean data into a pandas df to start some exploratory data analysis (where you inevitably discover you need to go back and do more data cleaning...) Next, you are onto feature engineering and then finally, you are at the stage where you are ready to build some models and experiment!"
},
{
"code": null,
"e": 970,
"s": 733,
"text": "Throughout this whole process, you’ve likely put all of your code together in your trusty jupyter notebook. Now you’d like to actually put your model to use, but how do you even begin? You certainly can’t put a notebook into production."
},
{
"code": null,
"e": 1265,
"s": 970,
"text": "One could write a book on the productionization of machine learning models. It is not my intent to teach you all of the engineering steps required for production. Instead, think of this article as a productionization kaizen: one small change you can make to your code to prepare for production."
},
{
"code": null,
"e": 1438,
"s": 1265,
"text": "In the article, I will show you how to use YAML configuration files to make your code cleaner, more scalable, easier to maintain, and more efficient at running experiments."
},
{
"code": null,
"e": 1531,
"s": 1438,
"text": "YAML is a recursively named language for storing information in a human readable format [1]."
},
{
"code": null,
"e": 1960,
"s": 1531,
"text": "A detailed discussion on the structure of yaml would take us too far afield, so being sufficient for our purposes, let’s consider the following yaml block for initializing an XGBoost Classifier. This block defines a dictionary “model_settings”, taking another dictionary as its value the parameters dictionary. The parameters dictionary holds the values for each of the parameters of the xgboost model that we would like to set."
},
{
"code": null,
"e": 2290,
"s": 1960,
"text": "# basic yaml configmodel_settings: random_state: 90210 objective: 'binary:logistic' eval_metric: ['error', 'map', 'auc', 'aucpr'] n_jobs: -1 learning_rate: 0.01 colsample_bytree: 0.8 subsample: 0.75 reg_alpha: 2.5 reg_lambda: 1.25 max_depth: 7 gamma: 0.2 n_estimators: 1251 max_delta_step: 8.5 scale_pos_weight: 2.0"
},
{
"code": null,
"e": 2379,
"s": 2290,
"text": "By writing the parameters of your model in a yaml config, you derive 4 primary benefits:"
},
{
"code": null,
"e": 2767,
"s": 2379,
"text": "The parameters are no longer hard-coded in the initialization of the model making code cleanerCollaborators can easily implement your model by passing a single file (preferably in a git repo)Making changes to your model no longer requires code refactoringFollowing (3), you can easily conduct “what-if” experiments on your model. E.g., What if I changed max-depth to go one level deeper?"
},
{
"code": null,
"e": 2862,
"s": 2767,
"text": "The parameters are no longer hard-coded in the initialization of the model making code cleaner"
},
{
"code": null,
"e": 2960,
"s": 2862,
"text": "Collaborators can easily implement your model by passing a single file (preferably in a git repo)"
},
{
"code": null,
"e": 3025,
"s": 2960,
"text": "Making changes to your model no longer requires code refactoring"
},
{
"code": null,
"e": 3158,
"s": 3025,
"text": "Following (3), you can easily conduct “what-if” experiments on your model. E.g., What if I changed max-depth to go one level deeper?"
},
{
"code": null,
"e": 3533,
"s": 3158,
"text": "We want to be able to pass the information contained in the yaml file to other scripts in your project. To this end, we define a super-class for your project holding all sub-classes (think of them as modules) which will hold the values in your yaml. By doing this, we can enforce types so that a user can’t pass strings where ints are expected. Let’s define one such object."
},
{
"code": null,
"e": 4677,
"s": 3533,
"text": "class YamlDemo: class ModelSettings: def __init__(self, random_state: int, objective: str, eval_metric: list, n_jobs: int, learning_rate: float, colsample_bytree: float, subsample: float, reg_alpha: float, reg_lambda: float, max_depth: int, gamma: float, n_estimators: int, max_delta_step: float, scale_pos_weight: float): self.random_state = random_state self.objective = objective self.eval_metric = eval_metric self.n_jobs = n_jobs self.learning_rate = learning_rate self.colsample_bytree = colsample_bytree self.subsample = subsample self.reg_alpha = reg_alpha self.reg_lambda = reg_lambda self.max_depth = max_depth self.gamma = gamma self.n_estimators = n_estimators self.max_delta_step = max_delta_step self.scale_pos_weight = scale_pos_weight def __init__(self, model_settings: ModelSettings, config_path: str): self.model_settings = model_settings self.config_path = config_path"
},
{
"code": null,
"e": 4914,
"s": 4677,
"text": "With your yaml config and config object in place, the last component is the authoring of a parser to read your yaml and populate your config object with the values. A simple config parser function like the following can do this for you."
},
{
"code": null,
"e": 6446,
"s": 4914,
"text": "import yamldef parse_config(config_path: str) -> YamlDemo: \"\"\" parses yaml config; returns populated YamlDemo object \"\"\" with open(config_path, 'r') as stream: try: config_settings = yaml.safe_load(stream) except yaml.YAMLError as e: print(e)model_settings = YamlDemo.ModelSettings( random_state = config_settings[\"model_settings\"][\"random_state\"], objective = config_settings[\"model_settings\"][\"objective\"], eval_metric = config_settings[\"model_settings\"][\"eval_metric\"], n_jobs = config_settings[\"model_settings\"][\"n_jobs\"], learning_rate = config_settings[\"model_settings\"][\"learning_rate\"], colsample_bytree = config_settings[\"model_settings\"][\"colsample_bytree\"], subsample = config_settings[\"model_settings\"][\"subsample\"], reg_alpha = config_settings[\"model_settings\"][\"reg_alpha\"], reg_lambda = config_settings[\"model_settings\"][\"reg_lambda\"], max_depth = config_settings[\"model_settings\"][\"max_depth\"], gamma = config_settings[\"model_settings\"][\"gamma\"], n_estimators = config_settings[\"model_settings\"][\"n_estimators\"], max_delta_step = config_settings[\"model_settings\"][\"max_delta_step\"], scale_pos_weight = config_settings[\"model_settings\"][\"scale_pos_weight\"] ) config = YamlDemo(model_settings=model_settings, config_path=config_path) assert isinstance(config, YamlDemo) return config"
},
{
"code": null,
"e": 6544,
"s": 6446,
"text": "Now, the last step in the process is to pass the information in your config object to your model."
},
{
"code": null,
"e": 6606,
"s": 6544,
"text": "First, we must parse our config to obtain a populated object:"
},
{
"code": null,
"e": 6678,
"s": 6606,
"text": "config_settings = parse_config('/Users/cole.brendel/Desktop/demo.yaml')"
},
{
"code": null,
"e": 6744,
"s": 6678,
"text": "Next, let’s get an example data set to see the model “in action”:"
},
{
"code": null,
"e": 7061,
"s": 6744,
"text": "from sklearn.datasets import load_irisX,y = load_iris(return_X_y=True)# notice how I set the value for `random_state` from the config!from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.33, random_state=config_settings.model_settings.random_state)"
},
{
"code": null,
"e": 7130,
"s": 7061,
"text": "Lastly, we’ll pass this config to a function which trains the model."
},
{
"code": null,
"e": 8918,
"s": 7130,
"text": "# fits a model on the training set/evals on test setimport pandas as pdfrom pandas import DataFrameimport xgboostfrom xgboost import XGBClassifierfrom sklearn.metrics import classification_reportdef fit_xgb_model(config_settings: YamlDemo, X_train: DataFrame, y_train: DataFrame, X_test: DataFrame, y_test: DataFrame) -> xgboost.XGBClassifier: \"\"\" fits an XGB model and returns model obejct \"\"\" eval_set = [(X_test, y_test)] # used for early stopping# populate the model with settings from config xgb = XGBClassifier( random_state=config_settings.model_settings.random_state, objective=config_settings.model_settings.objective, eval_metric=config_settings.model_settings.eval_metric, eval_set=eval_set, n_jobs=config_settings.model_settings.n_jobs, learning_rate=config_settings.model_settings.learning_rate, colsample_bytree=config_settings.model_settings.colsample_bytree, subsample=config_settings.model_settings.subsample, reg_alpha=config_settings.model_settings.reg_alpha, reg_lambda=config_settings.model_settings.reg_lambda, max_depth=config_settings.model_settings.max_depth, gamma=config_settings.model_settings.gamma, n_estimators=config_settings.model_settings.n_estimators, max_delta_step=config_settings.model_settings.max_delta_step, scale_pos_weight=config_settings.model_settings.scale_pos_weight ) # fit the model xgb_fit = xgb.fit(X_train, y_train) # predict on test set y_pred = xgb.predict(X_test) # show results print(classification_report(y_test, y_pred, digits=4, target_names=['setosa', 'versicolor', 'virginica'])) return xgb_fitxgb = fit_xgb_model(config_settings, X_train, y_train, X_test, y_test)"
},
{
"code": null,
"e": 8972,
"s": 8918,
"text": "And violá! The model has been trained and evaluated!"
},
{
"code": null,
"e": 9000,
"s": 8972,
"text": "You may be asking yourself:"
},
{
"code": null,
"e": 9139,
"s": 9000,
"text": "Why would I write all this code just to pass some parameters to my model? It seems like a ton of work and way more code than is necessary!"
},
{
"code": null,
"e": 9511,
"s": 9139,
"text": "It is true that you could simply populate a model with all of the parameters, but you are now locking yourself into that configuration! To make changes, you will need to go in and alter the code. What if you want to show your teammate your latest configuration which yielded the best results? Will you copy/paste your models code? Why not just slack them the config file?"
},
{
"code": null,
"e": 10059,
"s": 9511,
"text": "This config is just the tip of the iceberg. By using a process such as the one I am outlining here, you can easily specify much more additional information that is relevant to your model pipeline. For example, where are the training files located? Put that path in the config! Which ETLs to run and where to store the temporary files after the application of each ETL? Config that! How many iterations of RandomSearch should be run? Config again! To give you an idea on the scope of these configs, consider the following highly simplified example:"
},
{
"code": null,
"e": 10919,
"s": 10059,
"text": "ec2_settings: ip_address: xxx.xxx.xxx pem_file: '/Users/{}/Desktop/demo/ssh/my.pem'data_settings: deploy_date: 'today' # or 'YYYY-MM-DD' target_names: ['no', 'yes'] raw_bucket: '/Users/{}/Desktop/demo/datasets/raw' etl_bucket_train: '/Users/{}/Desktop/demo/datasets/etl_train' etl_bucket_score: '/Users/{}/Desktop/demo/datasets/etl_score' tmp_bucket: '/Users/{}/Desktop/demo/datasets/tmp' df_name: 'df.csv'logger_settings: log_name: 'demo.log' logs_path: '/Users/{}/Desktop/demo/logs'etl_settings: pickles: '/Users/{}/Desktop/demo/src/etls/pickles' target_variable: 'xxx_yyy' idx_column: 'idx_col'model_settings: pickles: '/Users/{}/Desktop/demo/src/modeling/pickles' predictions: '/Users/{}/Desktop/demo/predictions' eval_metric: ['error', 'map', 'aucpr'] n_iters: 500 sampling_points: 1000 optimization_metric: 'f1_weighted' cv_folds: 5"
},
{
"code": null,
"e": 11045,
"s": 10919,
"text": "With such a system in place, the sharing of results and experiments becomes as simple as slacking your fellow DS a yaml file."
},
{
"code": null,
"e": 11215,
"s": 11045,
"text": "You now have all the tools necessary to begin writing configs for you machine learning projects! This process takes some time to set up, but it pays off in the long run."
},
{
"code": null,
"e": 11570,
"s": 11215,
"text": "You enable rapid experimentation and you don’ t have to interact with the code to make changes to your model. You enable other scientists to simply change some settings and test away. By reading the YAML into a python class, you can easily enforce types and prevent erroneous values from being passed before spending money on expensive compute resources."
},
{
"code": null,
"e": 11592,
"s": 11570,
"text": "[1] https://yaml.org/"
},
{
"code": null,
"e": 11726,
"s": 11592,
"text": "Data structures for statistical computing in python, McKinney, Proceedings of the 9th Python in Science Conference, Volume 445, 2010."
},
{
"code": null,
"e": 12057,
"s": 11726,
"text": "@software{reback2020pandas, author = {The pandas development team}, title = {pandas-dev/pandas: Pandas}, month = feb, year = 2020, publisher = {Zenodo}, version = {latest}, doi = {10.5281/zenodo.3509134}, url = {https://doi.org/10.5281/zenodo.3509134}}"
},
{
"code": null,
"e": 12202,
"s": 12057,
"text": "Harris, C.R., Millman, K.J., van der Walt, S.J. et al. Array programming with NumPy. Nature 585, 357–362 (2020). DOI: 10.1038/s41586–020–2649–2."
},
{
"code": null,
"e": 12292,
"s": 12202,
"text": "Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011."
}
] |
Getting the name of the Enumeration Constant having Specified value in C# - GeeksforGeeks
|
23 Jul, 2019
Enum.GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value.
Syntax:
public static string GetName (Type enumType, object value);
Parameters:
enumType: It is an enumeration type.
value: It is the value of a particular enumerated constant in terms of its underlying type.
Returns: It is a string containing the name of the enumerated constant in enumType whose value is the value or null if no such constant is found.
Exceptions:
ArgumentNullException: If the enumType or value is null.
ArgumentException: If the enumType is not an Enum or value is neither of type enumType nor does it have the same underlying type as enumType.
Example:
// C# program to illustrate the// Enum.GetName(Type, Object) Methodusing System; enum Animals { Dog, Cat, Cow, Monkey }; class GFG { // Main Method public static void Main(String[] args) { // using the method Console.WriteLine("2nd value is {0}", Enum.GetName(typeof(Animals), 1)); Console.WriteLine("4th value is {0}", Enum.GetName(typeof(Animals), 3)); }}
2nd value is Cat
4th value is Monkey
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.enum.getname?view=netframework-4.8
CSharp-Enum-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
Partial Classes in C#
HashSet in C# with Examples
C# | Inheritance
C# | How to insert an element in an Array?
C# | List Class
Lambda Expressions in C#
C# | Generics - Introduction
What is Regular Expression in C#?
|
[
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 24355,
"s": 24222,
"text": "Enum.GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value."
},
{
"code": null,
"e": 24363,
"s": 24355,
"text": "Syntax:"
},
{
"code": null,
"e": 24423,
"s": 24363,
"text": "public static string GetName (Type enumType, object value);"
},
{
"code": null,
"e": 24435,
"s": 24423,
"text": "Parameters:"
},
{
"code": null,
"e": 24472,
"s": 24435,
"text": "enumType: It is an enumeration type."
},
{
"code": null,
"e": 24564,
"s": 24472,
"text": "value: It is the value of a particular enumerated constant in terms of its underlying type."
},
{
"code": null,
"e": 24710,
"s": 24564,
"text": "Returns: It is a string containing the name of the enumerated constant in enumType whose value is the value or null if no such constant is found."
},
{
"code": null,
"e": 24722,
"s": 24710,
"text": "Exceptions:"
},
{
"code": null,
"e": 24779,
"s": 24722,
"text": "ArgumentNullException: If the enumType or value is null."
},
{
"code": null,
"e": 24921,
"s": 24779,
"text": "ArgumentException: If the enumType is not an Enum or value is neither of type enumType nor does it have the same underlying type as enumType."
},
{
"code": null,
"e": 24930,
"s": 24921,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Enum.GetName(Type, Object) Methodusing System; enum Animals { Dog, Cat, Cow, Monkey }; class GFG { // Main Method public static void Main(String[] args) { // using the method Console.WriteLine(\"2nd value is {0}\", Enum.GetName(typeof(Animals), 1)); Console.WriteLine(\"4th value is {0}\", Enum.GetName(typeof(Animals), 3)); }}",
"e": 25369,
"s": 24930,
"text": null
},
{
"code": null,
"e": 25407,
"s": 25369,
"text": "2nd value is Cat\n4th value is Monkey\n"
},
{
"code": null,
"e": 25418,
"s": 25407,
"text": "Reference:"
},
{
"code": null,
"e": 25504,
"s": 25418,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.enum.getname?view=netframework-4.8"
},
{
"code": null,
"e": 25522,
"s": 25504,
"text": "CSharp-Enum-Class"
},
{
"code": null,
"e": 25536,
"s": 25522,
"text": "CSharp-method"
},
{
"code": null,
"e": 25539,
"s": 25536,
"text": "C#"
},
{
"code": null,
"e": 25637,
"s": 25539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25646,
"s": 25637,
"text": "Comments"
},
{
"code": null,
"e": 25659,
"s": 25646,
"text": "Old Comments"
},
{
"code": null,
"e": 25682,
"s": 25659,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25722,
"s": 25682,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25744,
"s": 25722,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25772,
"s": 25744,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25789,
"s": 25772,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25832,
"s": 25789,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25848,
"s": 25832,
"text": "C# | List Class"
},
{
"code": null,
"e": 25873,
"s": 25848,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 25902,
"s": 25873,
"text": "C# | Generics - Introduction"
}
] |
How to add title to regression model using stargazer in R?
|
To add title to regression model using stargazer, we can use title argument inside stargazer function.
For example, if we have a model called Reg_Model with Output as text then the title to this model using stargazer can be added by using the below mentioned command −
stargazer(Reg_Model,type="text",title="Regression Model between x and y")
Following snippet creates a sample data frame −
x<-rnorm(20)
y<-rnorm(20)
df<-data.frame(x,y)
df
The following dataframe is created −
x y
1 0.80296200 1.1413965
2 0.05853869 -1.1227868
3 1.79348142 -0.7212954
4 0.64830308 0.2956645
5 0.28551170 -1.0645189
6 0.50265553 0.9082304
7 0.25883301 0.6513258
8 -0.28277606 0.5892909
9 -1.96142707 0.8310168
10 1.29804865 -0.7780162
11 -0.53807406 0.7256280
12 -0.01142374 0.3550352
13 0.61684358 0.5681672
14 -0.03707776 0.7279025
15 0.14411337 0.7942300
16 0.95380409 0.2789388
17 0.32599974 1.2477048
18 -0.80785235 0.3246518
19 -0.77913184 -0.5227336
20 0.11869989 0.4344650
To create regression model between x and y, add the following code to the above snippet −
Model<-lm(y~x,data=df)
summary(Model)
If you execute all the above given snippets as a single program, it generates the following Output −
Call:
lm(formula = y ~ x, data = df)
Residuals:
Min 1Q Median 3Q Max
-1.4303 -0.2917 0.1538 0.3906 0.9988
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.3204 0.1645 1.947 0.0673 .
x -0.2191 0.2019 -1.085 0.2921
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.7196 on 18 degrees of freedom
Multiple R-squared: 0.06142, Adjusted R-squared: 0.009276
F-statistic: 1.178 on 1 and 18 DF, p-value: 0.2921
To get the model Output by using stargazer, add the following code to the above snippet −
library(stargazer)
stargazer(Model,type="text")
If you execute all the above given snippets as a single program, it generates the following Output −
===============================================
Dependent variable:
---------------------------
y
-----------------------------------------------
x -0.219
(0.202)
Constant 0.320*
(0.165)
-----------------------------------------------
Observations 20
R2 0.061
Adjusted R2 0.009
Residual Std. Error 0.720 (df = 18)
F Statistic 1.178 (df = 1; 18)
===============================================
Note: *p<0.1; **p<0.05; ***p<0.01
To get the model Output stargazer with title, add the following code to the above snippet −
stargazer(Model,type="text",title="Regression Model between x and y")
If you execute all the above given snippets as a single program, it generates the following Output −
Regression Model between x and y
===============================================
Dependent variable:
---------------------------
y
-----------------------------------------------
x -0.219
(0.202)
Constant 0.320*
(0.165)
-----------------------------------------------
Observations 20
R2 0.061
Adjusted R2 0.009
Residual Std. Error 0.720 (df = 18)
F Statistic 1.178 (df = 1; 18)
===============================================
Note: *p<0.1; **p<0.05; ***p<0.01
Following snippet creates a sample data frame −
Height<-sample(135:180,20)
Weight<-sample(38:80,20)
dat<-data.frame(Height,Weight)
dat
The following dataframe is created −
Height Weight
1 172 56
2 149 49
3 163 76
4 135 73
5 138 75
6 168 54
7 169 45
8 165 63
9 178 79
10 159 55
11 150 47
12 171 65
13 147 53
14 173 39
15 162 57
16 144 46
17 136 40
18 156 43
19 142 42
20 151 78
Add the following code to the above snippet −
Mod<-lm(Height~Weight,data=dat)
summary(Mod)
If you execute all the above given snippets as a single program, it generates the following Output −
Call:
lm(formula = Height ~ Weight, data = dat)
Residuals:
Min 1Q Median 3Q Max
-23.007 -9.606 1.867 12.345 19.399
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 150.78696 13.61725 11.073 1.82e-09 ***
Weight 0.09891 0.23376 0.423 0.677
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 13.75 on 18 degrees of freedom
Multiple R-squared: 0.009848, Adjusted R-squared: -0.04516
F-statistic: 0.179 on 1 and 18 DF, p-value: 0.6772
Add the following code to the above snippet −
stargazer(Mod,type="text",title="Regression Model between Height and Weight")
If you execute all the above given snippets as a single program, it generates the following Output −
Regression Model between Height and Weight
===============================================
Dependent variable:
---------------------------
Height
-----------------------------------------------
Weight 0.099
(0.234)
Constant 150.787***
(13.617)
-----------------------------------------------
Observations 20
R2 0.010
Adjusted R2 -0.045
Residual Std. Error 13.746 (df = 18)
F Statistic 0.179 (df = 1; 18)
===============================================
Note: *p<0.1; **p<0.05; ***p<0.01
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To add title to regression model using stargazer, we can use title argument inside stargazer function."
},
{
"code": null,
"e": 1331,
"s": 1165,
"text": "For example, if we have a model called Reg_Model with Output as text then the title to this model using stargazer can be added by using the below mentioned command −"
},
{
"code": null,
"e": 1405,
"s": 1331,
"text": "stargazer(Reg_Model,type=\"text\",title=\"Regression Model between x and y\")"
},
{
"code": null,
"e": 1453,
"s": 1405,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1502,
"s": 1453,
"text": "x<-rnorm(20)\ny<-rnorm(20)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1539,
"s": 1502,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 2120,
"s": 1539,
"text": " x y\n1 0.80296200 1.1413965\n2 0.05853869 -1.1227868\n3 1.79348142 -0.7212954\n4 0.64830308 0.2956645\n5 0.28551170 -1.0645189\n6 0.50265553 0.9082304\n7 0.25883301 0.6513258\n8 -0.28277606 0.5892909\n9 -1.96142707 0.8310168\n10 1.29804865 -0.7780162\n11 -0.53807406 0.7256280\n12 -0.01142374 0.3550352\n13 0.61684358 0.5681672\n14 -0.03707776 0.7279025\n15 0.14411337 0.7942300\n16 0.95380409 0.2789388\n17 0.32599974 1.2477048\n18 -0.80785235 0.3246518\n19 -0.77913184 -0.5227336\n20 0.11869989 0.4344650"
},
{
"code": null,
"e": 2210,
"s": 2120,
"text": "To create regression model between x and y, add the following code to the above snippet −"
},
{
"code": null,
"e": 2248,
"s": 2210,
"text": "Model<-lm(y~x,data=df)\nsummary(Model)"
},
{
"code": null,
"e": 2349,
"s": 2248,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 2848,
"s": 2349,
"text": "Call:\nlm(formula = y ~ x, data = df)\n\nResiduals:\n Min 1Q Median 3Q Max\n-1.4303 -0.2917 0.1538 0.3906 0.9988\n\nCoefficients:\n Estimate Std. Error t value Pr(>|t|)\n(Intercept) 0.3204 0.1645 1.947 0.0673 .\n x -0.2191 0.2019 -1.085 0.2921\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 0.7196 on 18 degrees of freedom\nMultiple R-squared: 0.06142, Adjusted R-squared: 0.009276\nF-statistic: 1.178 on 1 and 18 DF, p-value: 0.2921"
},
{
"code": null,
"e": 2938,
"s": 2848,
"text": "To get the model Output by using stargazer, add the following code to the above snippet −"
},
{
"code": null,
"e": 2986,
"s": 2938,
"text": "library(stargazer)\nstargazer(Model,type=\"text\")"
},
{
"code": null,
"e": 3087,
"s": 2986,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 3606,
"s": 3087,
"text": "===============================================\n Dependent variable:\n ---------------------------\n y\n-----------------------------------------------\n x -0.219\n (0.202)\n\nConstant 0.320*\n (0.165)\n\n-----------------------------------------------\nObservations 20\nR2 0.061\nAdjusted R2 0.009\nResidual Std. Error 0.720 (df = 18)\nF Statistic 1.178 (df = 1; 18)\n===============================================\nNote: *p<0.1; **p<0.05; ***p<0.01"
},
{
"code": null,
"e": 3698,
"s": 3606,
"text": "To get the model Output stargazer with title, add the following code to the above snippet −"
},
{
"code": null,
"e": 3768,
"s": 3698,
"text": "stargazer(Model,type=\"text\",title=\"Regression Model between x and y\")"
},
{
"code": null,
"e": 3869,
"s": 3768,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 4424,
"s": 3869,
"text": "Regression Model between x and y\n===============================================\n Dependent variable:\n ---------------------------\n y\n-----------------------------------------------\n x -0.219\n (0.202)\n\nConstant 0.320*\n (0.165)\n\n-----------------------------------------------\nObservations 20\nR2 0.061\nAdjusted R2 0.009\nResidual Std. Error 0.720 (df = 18)\nF Statistic 1.178 (df = 1; 18)\n===============================================\nNote: *p<0.1; **p<0.05; ***p<0.01"
},
{
"code": null,
"e": 4472,
"s": 4424,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 4559,
"s": 4472,
"text": "Height<-sample(135:180,20)\nWeight<-sample(38:80,20)\ndat<-data.frame(Height,Weight)\ndat"
},
{
"code": null,
"e": 4596,
"s": 4559,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 4872,
"s": 4596,
"text": " Height Weight\n1 172 56\n2 149 49\n3 163 76\n4 135 73\n5 138 75\n6 168 54\n7 169 45\n8 165 63\n9 178 79\n10 159 55\n11 150 47\n12 171 65\n13 147 53\n14 173 39\n15 162 57\n16 144 46\n17 136 40\n18 156 43\n19 142 42\n20 151 78"
},
{
"code": null,
"e": 4918,
"s": 4872,
"text": "Add the following code to the above snippet −"
},
{
"code": null,
"e": 4963,
"s": 4918,
"text": "Mod<-lm(Height~Weight,data=dat)\nsummary(Mod)"
},
{
"code": null,
"e": 5064,
"s": 4963,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 5599,
"s": 5064,
"text": "Call:\nlm(formula = Height ~ Weight, data = dat)\n\nResiduals:\n Min 1Q Median 3Q Max\n-23.007 -9.606 1.867 12.345 19.399\n\nCoefficients:\n Estimate Std. Error t value Pr(>|t|)\n(Intercept) 150.78696 13.61725 11.073 1.82e-09 ***\nWeight 0.09891 0.23376 0.423 0.677\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 13.75 on 18 degrees of freedom\nMultiple R-squared: 0.009848, Adjusted R-squared: -0.04516\nF-statistic: 0.179 on 1 and 18 DF, p-value: 0.6772"
},
{
"code": null,
"e": 5645,
"s": 5599,
"text": "Add the following code to the above snippet −"
},
{
"code": null,
"e": 5723,
"s": 5645,
"text": "stargazer(Mod,type=\"text\",title=\"Regression Model between Height and Weight\")"
},
{
"code": null,
"e": 5824,
"s": 5723,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 6399,
"s": 5824,
"text": "Regression Model between Height and Weight\n===============================================\n Dependent variable:\n---------------------------\n Height\n-----------------------------------------------\nWeight 0.099\n (0.234)\n\nConstant 150.787***\n (13.617)\n\n-----------------------------------------------\nObservations 20\nR2 0.010\nAdjusted R2 -0.045\nResidual Std. Error 13.746 (df = 18)\nF Statistic 0.179 (df = 1; 18)\n===============================================\nNote: *p<0.1; **p<0.05; ***p<0.01"
}
] |
Python Program to Read a Number n And Print the Series "1+2+.....+n= "
|
When it is required to display the sum all the natural numbers within a given range, a method can be defined that uses a loop to iterate over the elements, and returns the sum of these numbers as output.
Below is a demonstration of the same −
Live Demo
def sum_natural_nums(val):
my_sum = 0
for i in range(1, val + 1):
my_sum += i * (i + 1) / 2
return my_sum
val = 9
print("The value is ")
print(val)
print("The sum of natural numbers upto 9 is : ")
print(sum_natural_nums(val))
The value is
9
The sum of natural numbers upto 9 is :
165.0
A method named ‘sum_natural_nums’ is defined that takes a number as parameter.
A method named ‘sum_natural_nums’ is defined that takes a number as parameter.
A sum value is defined as 0.
A sum value is defined as 0.
A loop is iterated over the number passed as a parameter.
A loop is iterated over the number passed as a parameter.
The sum is incremented every time a number is encountered.
The sum is incremented every time a number is encountered.
This is returned as output.
This is returned as output.
The value for number of natural numbers whose sum needs to be found is defined.
The value for number of natural numbers whose sum needs to be found is defined.
The method is called by passing this number as a parameter.
The method is called by passing this number as a parameter.
The relevant output is displayed on the console.
The relevant output is displayed on the console.
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "When it is required to display the sum all the natural numbers within a given range, a method can be defined that uses a loop to iterate over the elements, and returns the sum of these numbers as output."
},
{
"code": null,
"e": 1305,
"s": 1266,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1316,
"s": 1305,
"text": " Live Demo"
},
{
"code": null,
"e": 1558,
"s": 1316,
"text": "def sum_natural_nums(val):\n my_sum = 0\n for i in range(1, val + 1):\n my_sum += i * (i + 1) / 2\n return my_sum\n\nval = 9\nprint(\"The value is \")\nprint(val)\nprint(\"The sum of natural numbers upto 9 is : \")\nprint(sum_natural_nums(val))"
},
{
"code": null,
"e": 1618,
"s": 1558,
"text": "The value is\n9\nThe sum of natural numbers upto 9 is :\n165.0"
},
{
"code": null,
"e": 1697,
"s": 1618,
"text": "A method named ‘sum_natural_nums’ is defined that takes a number as parameter."
},
{
"code": null,
"e": 1776,
"s": 1697,
"text": "A method named ‘sum_natural_nums’ is defined that takes a number as parameter."
},
{
"code": null,
"e": 1805,
"s": 1776,
"text": "A sum value is defined as 0."
},
{
"code": null,
"e": 1834,
"s": 1805,
"text": "A sum value is defined as 0."
},
{
"code": null,
"e": 1892,
"s": 1834,
"text": "A loop is iterated over the number passed as a parameter."
},
{
"code": null,
"e": 1950,
"s": 1892,
"text": "A loop is iterated over the number passed as a parameter."
},
{
"code": null,
"e": 2009,
"s": 1950,
"text": "The sum is incremented every time a number is encountered."
},
{
"code": null,
"e": 2068,
"s": 2009,
"text": "The sum is incremented every time a number is encountered."
},
{
"code": null,
"e": 2096,
"s": 2068,
"text": "This is returned as output."
},
{
"code": null,
"e": 2124,
"s": 2096,
"text": "This is returned as output."
},
{
"code": null,
"e": 2204,
"s": 2124,
"text": "The value for number of natural numbers whose sum needs to be found is defined."
},
{
"code": null,
"e": 2284,
"s": 2204,
"text": "The value for number of natural numbers whose sum needs to be found is defined."
},
{
"code": null,
"e": 2344,
"s": 2284,
"text": "The method is called by passing this number as a parameter."
},
{
"code": null,
"e": 2404,
"s": 2344,
"text": "The method is called by passing this number as a parameter."
},
{
"code": null,
"e": 2453,
"s": 2404,
"text": "The relevant output is displayed on the console."
},
{
"code": null,
"e": 2502,
"s": 2453,
"text": "The relevant output is displayed on the console."
}
] |
How does $('iframe').ready() method work in jQuery?
|
Here’s an example wherein the iframe size is larger than the page. We will scroll to the top of the page whenever the iframe loads using jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('iframe').ready(function(){
$(window).scrollTop(0);
});
});
});
</script>
</head>
<body>
<iframe frameborder="2" height="900" id="iframe" align="top" src="https://www.qries.com" width="900" ></iframe><br>
<button>Loop through each image</button>
</body>
</html>
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "Here’s an example wherein the iframe size is larger than the page. We will scroll to the top of the page whenever the iframe loads using jQuery −"
},
{
"code": null,
"e": 1218,
"s": 1208,
"text": "Live Demo"
},
{
"code": null,
"e": 1734,
"s": 1218,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $('iframe').ready(function(){\n $(window).scrollTop(0);\n });\n });\n });\n </script>\n </head>\n<body>\n <iframe frameborder=\"2\" height=\"900\" id=\"iframe\" align=\"top\" src=\"https://www.qries.com\" width=\"900\" ></iframe><br>\n <button>Loop through each image</button>\n</body>\n</html>"
}
] |
Using Genetic Algorithms to Build Trading Strategies | by Victor Sim | Towards Data Science
|
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Genetic algorithms are often ignored, as another unsupervised learning algorithm that fails to converge effectively. This is partly true, as genetic algorithms do not use partial derivatives and therefore the training algorithm is less direct. However, genetic algorithms allow for the formulation of solutions that would have been impossible, using traditional gradient-based optimization.
Why is this so? If the gradient descent based model started at local minimum, it would be permanently stuck, as the gradient of the points on each side would be higher. However, due to the more stochastic nature for genetic algorithms it would eventually find the solution.
Additionally, neural networks require labelled data with well-defined loss functions. Genetic algorithms only require data, and a custom loss function (often called a fitness function for genetic algorithms) can be cleverly crafted to optimize certain features. This flexibility makes genetic algorithm stand out from the rest of the unsupervised algorithms.
Genetic algorithms are a form of a brute-force type attack to the problem. The only differences being using the concept of evolution to speed up the process. Here is how the genetic algorithm works:
An agent is generated. It contains a set of weights that are compatible with the neural network.The agent’s fitness value is calculatedRepeat this many times until you have a “population” of agentsSort the population by their fitness, with the agents with the best fitness at the top of the list.“Breed” the top agents together.Repeat until a satisfactory loss value has been reached.
An agent is generated. It contains a set of weights that are compatible with the neural network.
The agent’s fitness value is calculated
Repeat this many times until you have a “population” of agents
Sort the population by their fitness, with the agents with the best fitness at the top of the list.
“Breed” the top agents together.
Repeat until a satisfactory loss value has been reached.
By changing the fitness function and the input data, the genetic algorithm can be applied to literally every problem!
For elementary tasks such as regression and classification, a deep neural network, trained using a gradient-based optimizer will always converge faster than a genetic algorithm.
Genetic algorithm are not good for finding patterns, but rather having a wide scope of view, to find solutions that have not been considered.
Stock trading is complex, as the noise from different sources dilute the true pattern behind the data. Using a genetic algorithm is like taking a shortcut through all of this; disregarding the pattern recognition and the complex analysis. It simply tests different strategies, and finds the best strategy to trade a security. If a genetic algorithm fails to find a good solution this can only be one (or both!) of these two reasons:
The genetic algorithm has not be trained for a long enough period of time
The genetic algorithm has not be trained for a long enough period of time
Genetic algorithm, being a brute-force algorithm, requires a long period of time to narrow down the results. This is a large hurdle to overcome, as the computing power must be very high to overcome this problem
2. The loss function is faulty
This is much more common. The loss function that evaluates the network simply does not encapsulate the goal of the loss function.
Disclaimer: This code has been adapted from the code here to make it compatible to optimize neural networks that create trading strategies.
import randomimport numpy as npdef sigmoid(x): return 1/(1+np.exp(-x))
These are the most basic dependencies for the project. To make the learning process better, you can add more activation functions for your suitable datasets.
class Agent: def __init__(self,network): class neural_network: def __init__(self,network): self.weights = [] self.activations = [] for layer in network: if layer[0] != None: input_size = layer[0] else: input_size = network[network.index(layer)-1][1] output_size = layer[1] activation = layer[2] self.weights.append(np.random.randn(input_size,output_size)) self.activations.append(activation) def propagate(self,data): input_data = data for i in range(len(self.weights)): z = np.dot(input_data,self.weights[i]) a = self.activations[i](z) input_data = a yhat = a return yhat self.neural_network = neural_network(network) self.fitness = 0 def __str__(self): return 'Loss: ' + str(self.fitness[0])
Each agent has its own set of weights, generated randomly with the architecture of the neural network setup. The argument network is a list that looks like so:
network = [[5,10,sigmoid],[None,1,sigmoid]]
Each term in the list is describing a layer in the Neural Network. The first term in each nested list is the number of input neurons for the layer, the second term is the output and the third the activation function to be applied for the layer.
def generate_agents(population, network): return [Agent(network) for _ in range(population)]
This is used to generate the agents, as detailed in step 1 of the methodology to run a genetic algorithm.
def fitness(agents,X): neutral_range = 0 for agent in agents: profit = 0 qty = 10 yhat = agent.neural_network.propagate(X[1:]) for i in range(len(yhat)): if 0.5 + neutral_range > yhat[i] and yhat[i] > 0.5 -neutral_range: yhat[i] = None elif 1-yhat[i] > yhat[i]-0: yhat[i] = 0 elif 1-yhat[i] < yhat[i]-0: yhat[i] = 1 correct_trades = [] for i in range(1,len(X)): if X[i][3] > X[i-1][3]: correct_trades.append(1) elif X[i][3] < X[i-1][3]: correct_trades.append(0) for i in range(len(yhat)): if yhat[i]: if correct_trades[i] == yhat[i]: profit += abs(X[i+1][3] - X[i][3])*qty elif correct_trades[i] != yhat[i]: profit -= abs(X[i+1][3] - X[i][3])*qty agent.fitness = profit return agents
This fitness function is a trading simulation, that uses past data to calculate the profits of the model. Each agent generates a list of trades, by outputting a sigmoid value. These values are then rounded to the nearest value. If this value is 0, the simulation will sell the stock. If this value is 1, the simulation will buy the stock.
It then calculates the profits, by comparing the best possible trade to the actual trade.
def selection(agents): agents = sorted(agents, key=lambda agent: agent.fitness, reverse=False) print('\n'.join(map(str, agents))) agents = agents[:int(0.2 * len(agents))] return agents
This code essentially sorts the agents by their fitness value, from the lowest value to the highest. Keep in mind that the lower the fitness value, the better. It then shortens the list of agents to only the top 20% of the agents.
Step 6| Agent Crossover:
def unflatten(flattened,shapes): newarray = [] index = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[index : index + size].reshape(shape)) index += size return newarray def crossover(agents,network,pop_size): offspring = [] for _ in range((pop_size - len(agents)) // 2): parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(network) child2 = Agent(network) shapes = [a.shape for a in parent1.neural_network.weights] genes1 = np.concatenate([a.flatten() for a in parent1.neural_network.weights]) genes2 = np.concatenate([a.flatten() for a in parent2.neural_network.weights]) split = random.randint(0,len(genes1)-1)child1_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child2_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child1.neural_network.weights = unflatten(child1_genes,shapes) child2.neural_network.weights = unflatten(child2_genes,shapes) offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents
This is the most complex part of the program. In the crossover process two random parents are chosen from within the selected agents. The nested list of weights are reduced to one long list. A splitting point is randomly picked. This determines how much of each parent’s weights the child will be composed of. This child’s weights is then reformatted and the child is added to the list of agents.
def mutation(agents): for agent in agents: if random.uniform(0.0, 1.0) <= 0.1: weights = agent.neural_network.weights shapes = [a.shape for a in weights]flattened = np.concatenate([a.flatten() for a in weights]) randint = random.randint(0,len(flattened)-1) flattened[randint] = np.random.randn()newarray = [] indeweights = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[indeweights : indeweights + size].reshape(shape)) indeweights += size agent.neural_network.weights = newarray return agents
Genetic Algorithms are technically “blind” as they have no insight to how the surface plotted by the loss function looks like. This means it is very easy for the genetic algorithm to get stuck at a certain point. Mutation allows for slight, random, infrequent changes to stir the pot and get the system out of local minimas.
def split_sequences(sequences, n_steps): X, y = list(), list() for i in range(len(sequences)): end_ix = i + n_steps if end_ix > len(sequences)-1: break seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y)np.random.seed(0) X,y = split_sequences(np.random.randn(1000,1),5)X = np.reshape(X,(X.shape[0],X.shape[1]))network = [[5,10,sigmoid],[None,1,sigmoid]]ga = genetic_algorithmagent = ga.execute(100,100,10000,X,network)
To execute the program we need data. For some reason, the SSL certificate would not let me get financial data from yfinance or alphavantage. I have not been able to run this program, so I just used random numpy arrays as data.
If you want to use your own financial data, the concept would be to have an array of closing price data split it into chunks of size-n.
For reproducibility, this program will set its own seed, making the randomness fixed. This is to decrease the randomness, to allow for the tweaking of parameters like population size, epochs and the neural network architecture. The more interesting parameter here is the length of each chunk of data to be fed into the network. Tweaking this parameter will find the optimum period of time in which the program will work.
As I have said in many other articles of my own, this is merely the framework for what can be done with the concept. There are countless things that you can do to improve my program. Here are a few of them:
Record generation of past agents
Record generation of past agents
By recording the generation of past agents, it prevents the program from regenerating agents that have been generated before.
2. Link the program to a paper trading account
Alpaca is the obvious choice to use a paper trading portfolio. It can make trades quickly, allowing for easy analysis of the program’s performance.
3. Create more trade types
This is the hardest of the three. Add different trades such as stop-loss and put and buy trades, allowing for much more nuanced and layered trading strategies, layering different trade types onto each other, to maximize profits.
If you want to see more of my content, click this link.
|
[
{
"code": null,
"e": 471,
"s": 171,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 862,
"s": 471,
"text": "Genetic algorithms are often ignored, as another unsupervised learning algorithm that fails to converge effectively. This is partly true, as genetic algorithms do not use partial derivatives and therefore the training algorithm is less direct. However, genetic algorithms allow for the formulation of solutions that would have been impossible, using traditional gradient-based optimization."
},
{
"code": null,
"e": 1136,
"s": 862,
"text": "Why is this so? If the gradient descent based model started at local minimum, it would be permanently stuck, as the gradient of the points on each side would be higher. However, due to the more stochastic nature for genetic algorithms it would eventually find the solution."
},
{
"code": null,
"e": 1495,
"s": 1136,
"text": "Additionally, neural networks require labelled data with well-defined loss functions. Genetic algorithms only require data, and a custom loss function (often called a fitness function for genetic algorithms) can be cleverly crafted to optimize certain features. This flexibility makes genetic algorithm stand out from the rest of the unsupervised algorithms."
},
{
"code": null,
"e": 1694,
"s": 1495,
"text": "Genetic algorithms are a form of a brute-force type attack to the problem. The only differences being using the concept of evolution to speed up the process. Here is how the genetic algorithm works:"
},
{
"code": null,
"e": 2079,
"s": 1694,
"text": "An agent is generated. It contains a set of weights that are compatible with the neural network.The agent’s fitness value is calculatedRepeat this many times until you have a “population” of agentsSort the population by their fitness, with the agents with the best fitness at the top of the list.“Breed” the top agents together.Repeat until a satisfactory loss value has been reached."
},
{
"code": null,
"e": 2176,
"s": 2079,
"text": "An agent is generated. It contains a set of weights that are compatible with the neural network."
},
{
"code": null,
"e": 2216,
"s": 2176,
"text": "The agent’s fitness value is calculated"
},
{
"code": null,
"e": 2279,
"s": 2216,
"text": "Repeat this many times until you have a “population” of agents"
},
{
"code": null,
"e": 2379,
"s": 2279,
"text": "Sort the population by their fitness, with the agents with the best fitness at the top of the list."
},
{
"code": null,
"e": 2412,
"s": 2379,
"text": "“Breed” the top agents together."
},
{
"code": null,
"e": 2469,
"s": 2412,
"text": "Repeat until a satisfactory loss value has been reached."
},
{
"code": null,
"e": 2587,
"s": 2469,
"text": "By changing the fitness function and the input data, the genetic algorithm can be applied to literally every problem!"
},
{
"code": null,
"e": 2765,
"s": 2587,
"text": "For elementary tasks such as regression and classification, a deep neural network, trained using a gradient-based optimizer will always converge faster than a genetic algorithm."
},
{
"code": null,
"e": 2907,
"s": 2765,
"text": "Genetic algorithm are not good for finding patterns, but rather having a wide scope of view, to find solutions that have not been considered."
},
{
"code": null,
"e": 3340,
"s": 2907,
"text": "Stock trading is complex, as the noise from different sources dilute the true pattern behind the data. Using a genetic algorithm is like taking a shortcut through all of this; disregarding the pattern recognition and the complex analysis. It simply tests different strategies, and finds the best strategy to trade a security. If a genetic algorithm fails to find a good solution this can only be one (or both!) of these two reasons:"
},
{
"code": null,
"e": 3414,
"s": 3340,
"text": "The genetic algorithm has not be trained for a long enough period of time"
},
{
"code": null,
"e": 3488,
"s": 3414,
"text": "The genetic algorithm has not be trained for a long enough period of time"
},
{
"code": null,
"e": 3699,
"s": 3488,
"text": "Genetic algorithm, being a brute-force algorithm, requires a long period of time to narrow down the results. This is a large hurdle to overcome, as the computing power must be very high to overcome this problem"
},
{
"code": null,
"e": 3730,
"s": 3699,
"text": "2. The loss function is faulty"
},
{
"code": null,
"e": 3860,
"s": 3730,
"text": "This is much more common. The loss function that evaluates the network simply does not encapsulate the goal of the loss function."
},
{
"code": null,
"e": 4000,
"s": 3860,
"text": "Disclaimer: This code has been adapted from the code here to make it compatible to optimize neural networks that create trading strategies."
},
{
"code": null,
"e": 4074,
"s": 4000,
"text": "import randomimport numpy as npdef sigmoid(x): return 1/(1+np.exp(-x))"
},
{
"code": null,
"e": 4232,
"s": 4074,
"text": "These are the most basic dependencies for the project. To make the learning process better, you can add more activation functions for your suitable datasets."
},
{
"code": null,
"e": 5516,
"s": 4232,
"text": "class Agent: def __init__(self,network): class neural_network: def __init__(self,network): self.weights = [] self.activations = [] for layer in network: if layer[0] != None: input_size = layer[0] else: input_size = network[network.index(layer)-1][1] output_size = layer[1] activation = layer[2] self.weights.append(np.random.randn(input_size,output_size)) self.activations.append(activation) def propagate(self,data): input_data = data for i in range(len(self.weights)): z = np.dot(input_data,self.weights[i]) a = self.activations[i](z) input_data = a yhat = a return yhat self.neural_network = neural_network(network) self.fitness = 0 def __str__(self): return 'Loss: ' + str(self.fitness[0])"
},
{
"code": null,
"e": 5676,
"s": 5516,
"text": "Each agent has its own set of weights, generated randomly with the architecture of the neural network setup. The argument network is a list that looks like so:"
},
{
"code": null,
"e": 5720,
"s": 5676,
"text": "network = [[5,10,sigmoid],[None,1,sigmoid]]"
},
{
"code": null,
"e": 5965,
"s": 5720,
"text": "Each term in the list is describing a layer in the Neural Network. The first term in each nested list is the number of input neurons for the layer, the second term is the output and the third the activation function to be applied for the layer."
},
{
"code": null,
"e": 6069,
"s": 5965,
"text": "def generate_agents(population, network): return [Agent(network) for _ in range(population)]"
},
{
"code": null,
"e": 6175,
"s": 6069,
"text": "This is used to generate the agents, as detailed in step 1 of the methodology to run a genetic algorithm."
},
{
"code": null,
"e": 7365,
"s": 6175,
"text": "def fitness(agents,X): neutral_range = 0 for agent in agents: profit = 0 qty = 10 yhat = agent.neural_network.propagate(X[1:]) for i in range(len(yhat)): if 0.5 + neutral_range > yhat[i] and yhat[i] > 0.5 -neutral_range: yhat[i] = None elif 1-yhat[i] > yhat[i]-0: yhat[i] = 0 elif 1-yhat[i] < yhat[i]-0: yhat[i] = 1 correct_trades = [] for i in range(1,len(X)): if X[i][3] > X[i-1][3]: correct_trades.append(1) elif X[i][3] < X[i-1][3]: correct_trades.append(0) for i in range(len(yhat)): if yhat[i]: if correct_trades[i] == yhat[i]: profit += abs(X[i+1][3] - X[i][3])*qty elif correct_trades[i] != yhat[i]: profit -= abs(X[i+1][3] - X[i][3])*qty agent.fitness = profit return agents"
},
{
"code": null,
"e": 7704,
"s": 7365,
"text": "This fitness function is a trading simulation, that uses past data to calculate the profits of the model. Each agent generates a list of trades, by outputting a sigmoid value. These values are then rounded to the nearest value. If this value is 0, the simulation will sell the stock. If this value is 1, the simulation will buy the stock."
},
{
"code": null,
"e": 7794,
"s": 7704,
"text": "It then calculates the profits, by comparing the best possible trade to the actual trade."
},
{
"code": null,
"e": 8023,
"s": 7794,
"text": "def selection(agents): agents = sorted(agents, key=lambda agent: agent.fitness, reverse=False) print('\\n'.join(map(str, agents))) agents = agents[:int(0.2 * len(agents))] return agents"
},
{
"code": null,
"e": 8254,
"s": 8023,
"text": "This code essentially sorts the agents by their fitness value, from the lowest value to the highest. Keep in mind that the lower the fitness value, the better. It then shortens the list of agents to only the top 20% of the agents."
},
{
"code": null,
"e": 8279,
"s": 8254,
"text": "Step 6| Agent Crossover:"
},
{
"code": null,
"e": 9736,
"s": 8279,
"text": "def unflatten(flattened,shapes): newarray = [] index = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[index : index + size].reshape(shape)) index += size return newarray def crossover(agents,network,pop_size): offspring = [] for _ in range((pop_size - len(agents)) // 2): parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(network) child2 = Agent(network) shapes = [a.shape for a in parent1.neural_network.weights] genes1 = np.concatenate([a.flatten() for a in parent1.neural_network.weights]) genes2 = np.concatenate([a.flatten() for a in parent2.neural_network.weights]) split = random.randint(0,len(genes1)-1)child1_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child2_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child1.neural_network.weights = unflatten(child1_genes,shapes) child2.neural_network.weights = unflatten(child2_genes,shapes) offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents"
},
{
"code": null,
"e": 10133,
"s": 9736,
"text": "This is the most complex part of the program. In the crossover process two random parents are chosen from within the selected agents. The nested list of weights are reduced to one long list. A splitting point is randomly picked. This determines how much of each parent’s weights the child will be composed of. This child’s weights is then reformatted and the child is added to the list of agents."
},
{
"code": null,
"e": 10893,
"s": 10133,
"text": "def mutation(agents): for agent in agents: if random.uniform(0.0, 1.0) <= 0.1: weights = agent.neural_network.weights shapes = [a.shape for a in weights]flattened = np.concatenate([a.flatten() for a in weights]) randint = random.randint(0,len(flattened)-1) flattened[randint] = np.random.randn()newarray = [] indeweights = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[indeweights : indeweights + size].reshape(shape)) indeweights += size agent.neural_network.weights = newarray return agents"
},
{
"code": null,
"e": 11218,
"s": 10893,
"text": "Genetic Algorithms are technically “blind” as they have no insight to how the surface plotted by the loss function looks like. This means it is very easy for the genetic algorithm to get stuck at a certain point. Mutation allows for slight, random, infrequent changes to stir the pot and get the system out of local minimas."
},
{
"code": null,
"e": 11775,
"s": 11218,
"text": "def split_sequences(sequences, n_steps): X, y = list(), list() for i in range(len(sequences)): end_ix = i + n_steps if end_ix > len(sequences)-1: break seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :] X.append(seq_x) y.append(seq_y) return np.array(X), np.array(y)np.random.seed(0) X,y = split_sequences(np.random.randn(1000,1),5)X = np.reshape(X,(X.shape[0],X.shape[1]))network = [[5,10,sigmoid],[None,1,sigmoid]]ga = genetic_algorithmagent = ga.execute(100,100,10000,X,network)"
},
{
"code": null,
"e": 12002,
"s": 11775,
"text": "To execute the program we need data. For some reason, the SSL certificate would not let me get financial data from yfinance or alphavantage. I have not been able to run this program, so I just used random numpy arrays as data."
},
{
"code": null,
"e": 12138,
"s": 12002,
"text": "If you want to use your own financial data, the concept would be to have an array of closing price data split it into chunks of size-n."
},
{
"code": null,
"e": 12559,
"s": 12138,
"text": "For reproducibility, this program will set its own seed, making the randomness fixed. This is to decrease the randomness, to allow for the tweaking of parameters like population size, epochs and the neural network architecture. The more interesting parameter here is the length of each chunk of data to be fed into the network. Tweaking this parameter will find the optimum period of time in which the program will work."
},
{
"code": null,
"e": 12766,
"s": 12559,
"text": "As I have said in many other articles of my own, this is merely the framework for what can be done with the concept. There are countless things that you can do to improve my program. Here are a few of them:"
},
{
"code": null,
"e": 12799,
"s": 12766,
"text": "Record generation of past agents"
},
{
"code": null,
"e": 12832,
"s": 12799,
"text": "Record generation of past agents"
},
{
"code": null,
"e": 12958,
"s": 12832,
"text": "By recording the generation of past agents, it prevents the program from regenerating agents that have been generated before."
},
{
"code": null,
"e": 13005,
"s": 12958,
"text": "2. Link the program to a paper trading account"
},
{
"code": null,
"e": 13153,
"s": 13005,
"text": "Alpaca is the obvious choice to use a paper trading portfolio. It can make trades quickly, allowing for easy analysis of the program’s performance."
},
{
"code": null,
"e": 13180,
"s": 13153,
"text": "3. Create more trade types"
},
{
"code": null,
"e": 13409,
"s": 13180,
"text": "This is the hardest of the three. Add different trades such as stop-loss and put and buy trades, allowing for much more nuanced and layered trading strategies, layering different trade types onto each other, to maximize profits."
}
] |
Reconstruct the array by replacing arr[i] with (arr[i-1]+1) % M - GeeksforGeeks
|
25 Aug, 2021
Given an array of N elements and an integer M. Now, the array is modified by replacing some of the array elements with -1. The task is to print the original array.The elements in the original array are related as, for every index i, a[i] = (a[i-1]+1)% M.It is guaranteed that there is one non-zero value in the array.
Examples:
Input: arr[] = {5, -1, -1, 1, 2, 3}, M = 7
Output: 5 6 0 1 2 3
M = 7, so value at index 2 should be (5+1) % 7 = 6
value at index 3 should be (6+1) % 7 = 0
Input: arr[] = {5, -1, 7, -1, 9, 0}, M = 10
Output: 5 6 7 8 9 0
Approach: First find the index of the non-negative value index i. Then simply go in two directions i.e. From i-1 to 0 and i+1 to n.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; void construct(int n, int m, int a[]){ int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { cout<< a[i] << " "; } } // Driver codeint main(){ int n = 6, m = 7; int a[] = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); return 0;} // This code is contributed by 29AjayKumar
// Java implementation of the above approachclass GFG{ static void construct(int n, int m, int[] a) { int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } } // Driver code public static void main(String[] args) { int n = 6, m = 7; int[] a = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); }} // This code is contributed by 29AjayKumar
# Python implementation of the above approachdef construct(n, m, a): ind = 0 # Finding the index which is not -1 for i in range(n): if (a[i]!=-1): ind = i break # Calculating the values of the indexes ind-1 to 0 for i in range(ind-1, -1, -1): if (a[i]==-1): a[i]=(a[i + 1]-1 + m)% m # Calculating the values of the indexes ind + 1 to n for i in range(ind + 1, n): if(a[i]==-1): a[i]=(a[i-1]+1)% m print(*a) # Driver coden, m = 6, 7a =[5, -1, -1, 1, 2, 3]construct(n, m, a)
// C# implementation of the above approachusing System; class GFG{ static void construct(int n, int m, int[] a) { int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { Console.Write(a[i] + " "); } } // Driver code public static void Main(String[] args) { int n = 6, m = 7; int[] a = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of above approach function construct(n, m, a){ var ind = 0; // Finding the index which is not -1 for (var i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (var i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (var i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (var i = 0; i < n; i++) { document.write( a[i] + " "); } } // Driver codevar n = 6, m = 7;var a = [5, -1, -1, 1, 2, 3];construct(n, m, a); </script>
5 6 0 1 2 3
29AjayKumar
importantly
akshaysingh98088
math
Arrays
Python Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24862,
"s": 24834,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 25180,
"s": 24862,
"text": "Given an array of N elements and an integer M. Now, the array is modified by replacing some of the array elements with -1. The task is to print the original array.The elements in the original array are related as, for every index i, a[i] = (a[i-1]+1)% M.It is guaranteed that there is one non-zero value in the array."
},
{
"code": null,
"e": 25192,
"s": 25180,
"text": "Examples: "
},
{
"code": null,
"e": 25413,
"s": 25192,
"text": "Input: arr[] = {5, -1, -1, 1, 2, 3}, M = 7\nOutput: 5 6 0 1 2 3\nM = 7, so value at index 2 should be (5+1) % 7 = 6\nvalue at index 3 should be (6+1) % 7 = 0\n\nInput: arr[] = {5, -1, 7, -1, 9, 0}, M = 10\nOutput: 5 6 7 8 9 0 "
},
{
"code": null,
"e": 25546,
"s": 25413,
"text": "Approach: First find the index of the non-negative value index i. Then simply go in two directions i.e. From i-1 to 0 and i+1 to n. "
},
{
"code": null,
"e": 25598,
"s": 25546,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25602,
"s": 25598,
"text": "C++"
},
{
"code": null,
"e": 25607,
"s": 25602,
"text": "Java"
},
{
"code": null,
"e": 25615,
"s": 25607,
"text": "Python3"
},
{
"code": null,
"e": 25618,
"s": 25615,
"text": "C#"
},
{
"code": null,
"e": 25629,
"s": 25618,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; void construct(int n, int m, int a[]){ int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { cout<< a[i] << \" \"; } } // Driver codeint main(){ int n = 6, m = 7; int a[] = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); return 0;} // This code is contributed by 29AjayKumar",
"e": 26519,
"s": 25629,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ static void construct(int n, int m, int[] a) { int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { System.out.print(a[i] + \" \"); } } // Driver code public static void main(String[] args) { int n = 6, m = 7; int[] a = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); }} // This code is contributed by 29AjayKumar",
"e": 27571,
"s": 26519,
"text": null
},
{
"code": "# Python implementation of the above approachdef construct(n, m, a): ind = 0 # Finding the index which is not -1 for i in range(n): if (a[i]!=-1): ind = i break # Calculating the values of the indexes ind-1 to 0 for i in range(ind-1, -1, -1): if (a[i]==-1): a[i]=(a[i + 1]-1 + m)% m # Calculating the values of the indexes ind + 1 to n for i in range(ind + 1, n): if(a[i]==-1): a[i]=(a[i-1]+1)% m print(*a) # Driver coden, m = 6, 7a =[5, -1, -1, 1, 2, 3]construct(n, m, a)",
"e": 28136,
"s": 27571,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static void construct(int n, int m, int[] a) { int ind = 0; // Finding the index which is not -1 for (int i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (int i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (int i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (int i = 0; i < n; i++) { Console.Write(a[i] + \" \"); } } // Driver code public static void Main(String[] args) { int n = 6, m = 7; int[] a = { 5, -1, -1, 1, 2, 3 }; construct(n, m, a); }} // This code is contributed by 29AjayKumar",
"e": 29197,
"s": 28136,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach function construct(n, m, a){ var ind = 0; // Finding the index which is not -1 for (var i = 0; i < n; i++) { if (a[i] != -1) { ind = i; break; } } // Calculating the values of // the indexes ind-1 to 0 for (var i = ind - 1; i > -1; i--) { if (a[i] == -1) a[i] = (a[i + 1] - 1 + m) % m; } // Calculating the values of // the indexes ind + 1 to n for (var i = ind + 1; i < n; i++) { if (a[i] == -1) a[i] = (a[i - 1] + 1) % m; } for (var i = 0; i < n; i++) { document.write( a[i] + \" \"); } } // Driver codevar n = 6, m = 7;var a = [5, -1, -1, 1, 2, 3];construct(n, m, a); </script>",
"e": 29983,
"s": 29197,
"text": null
},
{
"code": null,
"e": 29995,
"s": 29983,
"text": "5 6 0 1 2 3"
},
{
"code": null,
"e": 30009,
"s": 29997,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30021,
"s": 30009,
"text": "importantly"
},
{
"code": null,
"e": 30038,
"s": 30021,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 30043,
"s": 30038,
"text": "math"
},
{
"code": null,
"e": 30050,
"s": 30043,
"text": "Arrays"
},
{
"code": null,
"e": 30066,
"s": 30050,
"text": "Python Programs"
},
{
"code": null,
"e": 30073,
"s": 30066,
"text": "Arrays"
},
{
"code": null,
"e": 30171,
"s": 30073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30180,
"s": 30171,
"text": "Comments"
},
{
"code": null,
"e": 30193,
"s": 30180,
"text": "Old Comments"
},
{
"code": null,
"e": 30216,
"s": 30193,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 30248,
"s": 30216,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30269,
"s": 30248,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 30314,
"s": 30269,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 30368,
"s": 30314,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 30411,
"s": 30368,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 30433,
"s": 30411,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30472,
"s": 30433,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 30518,
"s": 30472,
"text": "Python | Split string into list of characters"
}
] |
10 Netstat Command Examples on Linux
|
Netstat is a command line utility that can be utilized to list out all the network (socket) connections on a method comparable to network connections, routing tables, interface records, masquerade connections, multicast memberships etc. This article explains about – Top 10 Netstat Command Examples on Linux.
To show about listening and non-listening sockets, use the following command –
$ netstat -all
The sample output should be like this –
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 localhost:mysql *:* LISTEN
tcp 0 0 linux-Inspiron-3:domain *:* LISTEN
tcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:59820 maa03s22-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED
tcp 0 0 linux-Inspiron-35:41914 bom05s08-in-f4.1e:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:59760 maa03s22-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:33172 ec2-54-221-62-191:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:43480 a104-81-21-73.depl:http TIME_WAIT
tcp 0 0 linux-Inspiron-35:36270 maa03s20-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:53360 maa03s20-in-f3.1e1:http ESTABLISHED
........................................................................................
To show the PID and name of the program to which each socket belongs, use the following command –
$ netstat --program
The sample output should be like this –
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED 23074/chrome
tcp 0 0 linux-Inspiron-35:59820 maa03s22-in-f14.1:https ESTABLISHED 23235/chromium-brow
tcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED 23074/chrome
tcp 0 0 linux-Inspiron-35:41914 bom05s08-in-f4.1e:https ESTABLISHED 23074/chrome
tcp 1 0 linux-Inspiron-35:60770 117.18.237.42:http CLOSE_WAIT 23074/chrome
tcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED 23074/chrome
............................................................................................
To get the TCP ports information, use the following command –
$ netstat --tcp
The sample output should be like this –
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q L ocal Address Foreign Address State
tcp 0 0 linux-Inspiron-35:36310 maa03s20-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED
tcp 0 0 linux-Inspiron-35:36320 maa03s20-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:33216 ec2-54-221-62-191:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:46478 arn02s05-in-f3.1e:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:60794 117.18.237.42:http ESTABLISHED
tcp 0 0 linux-Inspiron-35:48080 104.244.42.136:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:58048 ip-166-62-112-150.:http ESTABLISHED
tcp 0 0 linux-Inspiron-35:33272 bom05s08-in-f163.:https ESTABLISHED
To get the UDP ports information, use the following command –
$ netstat --udp
The sample output should be like this –
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
udp 0 0 linux-Inspiron-35:46539 maa03s20-in-f5.1e:https ESTABLISHED
udp 768 0 localhost:46996 linux-Inspiron-3:domain ESTABLISHED
To get the list of linux ports, use the following command –
$ netstat -lx
The sample output should be like this –
Active UNIX domain sockets (only servers)
Proto RefCnt Flags Type State I-Node Path
unix 2 [ ACC ] STREAM LISTENING 27810 @/tmp/.ICE-unix/2345
unix 2 [ ACC ] STREAM LISTENING 26776 @/tmp/ibus/dbus-RkYlcXlm
unix 2 [ ACC ] STREAM LISTENING 20175 /var/run/mysqld/mysqld.sock
unix 2 [ ACC ] STREAM LISTENING 25423 /run/user/1000/systemd/private
unix 2 [ ACC ] STREAM LISTENING 24848 /run/user/126/systemd/private
unix 2 [ ACC ] SEQPACKET LISTENING 1784 /run/udev/control
unix 2 [ ACC ] STREAM LISTENING 25933 /run/user/1000/keyring/control
unix 2 [ ACC ] STREAM LISTENING 22555 /var/run/NetworkManager/private-dhcp
unix 2 [ ACC ] STREAM LISTENING 24475 /run/user/1000/keyring/pkcs11
unix 2 [ ACC ] STREAM LISTENING 24477 /run/user/1000/keyring/ssh
unix 2 [ ACC ] STREAM LISTENING 112357 /tmp/.com.google.Chrome.3r7jSQ/SingletonSocket
To display routing table, use the following command –
$ netstat -r
The sample output should be like this –
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
default TutorialsPoint1 0.0.0.0 UG 0 0 0 enp7s0
default 192.168.1.254 0.0.0.0 UG 0 0 0 wlp6s0
link-local * 255.255.0.0 U 0 0 0 enp7s0
192.168.1.0 * 255.255.255.0 U 0 0 0 enp7s0
192.168.1.0 * 255.255.255.0 U 0 0 0 wlp6s0
To display networking statistics, use the following command –
$ netstat -s
The sample output should be like this –
Ip:
226777 total packets received
99 with invalid addresses
0 forwarded
0 incoming packets discarded
213036 incoming packets delivered
126141 requests sent out
48 outgoing packets dropped
Icmp:
420 ICMP messages received
120 input ICMP message failed.
ICMP input histogram:
destination unreachable: 414
echo requests: 6
576 ICMP messages sent
0 ICMP messages failed
ICMP output histogram:
destination unreachable: 570
echo replies: 6
IcmpMsg:
InType3: 414
InType8: 6
OutType0: 6
OutType3: 570
....................................................................................
To find the nonsupportive Address families, use the following command –
$ netstat -v
The sample output should be like this –
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:39418 arn09s10-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:36398 maa03s20-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:59950 maa03s22-in-f14.1:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:60888 117.18.237.42:http ESTABLISHED
tcp 0 0 linux-Inspiron-35:55716 maa03s20-in-f3.1e:https TIME_WAIT
tcp 0 0 linux-Inspiron-35:42044 bom05s08-in-f4.1e:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:49654 ec2-54-221-3-35.c:https ESTABLISHED
tcp 0 0 linux-Inspiron-35:47238 sc-in-f188.1e100.n:5228 ESTABLISHED
tcp 0 0 linux-Inspiron-35:42046 bom05s08-in-f4.1e:https ESTABLISHED
...........................................................................................
To display other/more information about network, use the following command –
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode
tcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED linux 123811
tcp 0 0 linux-Inspiron-35:55458 52.222.136.134:https ESTABLISHED linux 148067
tcp 0 0 linux-Inspiron-35:43780 sb-in-f188.1e100.n:5228 ESTABLISHED linux 147150
tcp 0 0 linux-Inspiron-35:60924 117.18.237.42:http ESTAB LISHED linux 148291
tcp 0 0 linux-Inspiron-35:36446 maa03s20-in-f14.1:https ESTABLISHED linux 148068
tcp 0 0 linux-Inspiron-35:51126 edge-star-mini-sh:https ESTABLISHED linux 149411
tcp 0 0 linux-Inspiron-35:33338 ec2-54-221-62-191:https CLOSE_WAIT linux 146371
udp 0 0 linux-Inspiron-35:46539 maa03s20-in-f5.1e:https ESTABLISHED linux 117623
udp 768 0 localhost:46996 linux-Inspiron-3:domain ESTABLISHED linux 123551
..................................................................................
To get the help of netstat, use the following command –
$ netstat -h
The sample output should be like this –
usage: netstat [-vWeenNcCF] [] -r netstat {-V|--version|-h|--help}
netstat [-vWnNcaeol] [ ...]
netstat { [-vWeenNac] -i | [-cWnNe] -M | -s }
-r, --route display routing table
-i, --interfaces display interface table
-g, --groups display multicast group memberships
-s, --statistics display networking statistics (like SNMP)
-M, --masquerade display masqueraded connections
-v, --verbose be verbose
-W, --wide don't truncate IP addresses
-n, --numeric don't resolve names
--numeric-hosts don't resolve host names
--numeric-ports don't resolve port names
--numeric-users don't resolve user names
-N, --symbolic resolve hardware names
-e, --extend display other/more information
-p, --programs display PID/Program name for sockets
-c, --continuous c ontinuous listing
-l, --listening display listening server sockets
-a, --all, --listening display all sockets (default: connected)
-o, --timers display timers
-F, --fib display Forwarding Information Base (default)
-C, --cache display routing cache instead of FIB
={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom
=Use '-6|-4' or '-A ' or '--'; default: inet
List of possible address families (which support routing):
inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25)
netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP)
x25 (CCITT X.25)
In the above article, we have learnt about – Top 10 Netstat command examples on Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
|
[
{
"code": null,
"e": 1371,
"s": 1062,
"text": "Netstat is a command line utility that can be utilized to list out all the network (socket) connections on a method comparable to network connections, routing tables, interface records, masquerade connections, multicast memberships etc. This article explains about – Top 10 Netstat Command Examples on Linux."
},
{
"code": null,
"e": 1450,
"s": 1371,
"text": "To show about listening and non-listening sockets, use the following command –"
},
{
"code": null,
"e": 1465,
"s": 1450,
"text": "$ netstat -all"
},
{
"code": null,
"e": 1505,
"s": 1465,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 2460,
"s": 1505,
"text": "Active Internet connections (servers and established)\nProto Recv-Q Send-Q Local Address Foreign Address State\ntcp 0 0 localhost:mysql *:* LISTEN\ntcp 0 0 linux-Inspiron-3:domain *:* LISTEN\ntcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:59820 maa03s22-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED\ntcp 0 0 linux-Inspiron-35:41914 bom05s08-in-f4.1e:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:59760 maa03s22-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:33172 ec2-54-221-62-191:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:43480 a104-81-21-73.depl:http TIME_WAIT\ntcp 0 0 linux-Inspiron-35:36270 maa03s20-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:53360 maa03s20-in-f3.1e1:http ESTABLISHED\n........................................................................................"
},
{
"code": null,
"e": 2558,
"s": 2460,
"text": "To show the PID and name of the program to which each socket belongs, use the following command –"
},
{
"code": null,
"e": 2578,
"s": 2558,
"text": "$ netstat --program"
},
{
"code": null,
"e": 2618,
"s": 2578,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3418,
"s": 2618,
"text": "Active Internet connections (w/o servers)\nProto Recv-Q Send-Q Local Address Foreign Address State PID/Program name\ntcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED 23074/chrome\ntcp 0 0 linux-Inspiron-35:59820 maa03s22-in-f14.1:https ESTABLISHED 23235/chromium-brow\ntcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED 23074/chrome\ntcp 0 0 linux-Inspiron-35:41914 bom05s08-in-f4.1e:https ESTABLISHED 23074/chrome\ntcp 1 0 linux-Inspiron-35:60770 117.18.237.42:http CLOSE_WAIT 23074/chrome\ntcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED 23074/chrome\n............................................................................................"
},
{
"code": null,
"e": 3480,
"s": 3418,
"text": "To get the TCP ports information, use the following command –"
},
{
"code": null,
"e": 3496,
"s": 3480,
"text": "$ netstat --tcp"
},
{
"code": null,
"e": 3536,
"s": 3496,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4551,
"s": 3536,
"text": "Active Internet connections (w/o servers)\nProto Recv-Q Send-Q L ocal Address Foreign Address State\ntcp 0 0 linux-Inspiron-35:36310 maa03s20-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:46662 sc-in-f188.1e100.n:5228 ESTABLISHED\ntcp 0 0 linux-Inspiron-35:36320 maa03s20-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:33216 ec2-54-221-62-191:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:46478 arn02s05-in-f3.1e:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:43466 ec2-34-192-133-18:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:60794 117.18.237.42:http ESTABLISHED\ntcp 0 0 linux-Inspiron-35:48080 104.244.42.136:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:58048 ip-166-62-112-150.:http ESTABLISHED\ntcp 0 0 linux-Inspiron-35:33272 bom05s08-in-f163.:https ESTABLISHED"
},
{
"code": null,
"e": 4613,
"s": 4551,
"text": "To get the UDP ports information, use the following command –"
},
{
"code": null,
"e": 4629,
"s": 4613,
"text": "$ netstat --udp"
},
{
"code": null,
"e": 4669,
"s": 4629,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4957,
"s": 4669,
"text": "Active Internet connections (w/o servers)\nProto Recv-Q Send-Q Local Address Foreign Address State\nudp 0 0 linux-Inspiron-35:46539 maa03s20-in-f5.1e:https ESTABLISHED\nudp 768 0 localhost:46996 linux-Inspiron-3:domain ESTABLISHED"
},
{
"code": null,
"e": 5017,
"s": 4957,
"text": "To get the list of linux ports, use the following command –"
},
{
"code": null,
"e": 5031,
"s": 5017,
"text": "$ netstat -lx"
},
{
"code": null,
"e": 5071,
"s": 5031,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6151,
"s": 5071,
"text": "Active UNIX domain sockets (only servers)\nProto RefCnt Flags Type State I-Node Path\nunix 2 [ ACC ] STREAM LISTENING 27810 @/tmp/.ICE-unix/2345\nunix 2 [ ACC ] STREAM LISTENING 26776 @/tmp/ibus/dbus-RkYlcXlm\nunix 2 [ ACC ] STREAM LISTENING 20175 /var/run/mysqld/mysqld.sock\nunix 2 [ ACC ] STREAM LISTENING 25423 /run/user/1000/systemd/private\nunix 2 [ ACC ] STREAM LISTENING 24848 /run/user/126/systemd/private\nunix 2 [ ACC ] SEQPACKET LISTENING 1784 /run/udev/control\nunix 2 [ ACC ] STREAM LISTENING 25933 /run/user/1000/keyring/control\nunix 2 [ ACC ] STREAM LISTENING 22555 /var/run/NetworkManager/private-dhcp\nunix 2 [ ACC ] STREAM LISTENING 24475 /run/user/1000/keyring/pkcs11\nunix 2 [ ACC ] STREAM LISTENING 24477 /run/user/1000/keyring/ssh\nunix 2 [ ACC ] STREAM LISTENING 112357 /tmp/.com.google.Chrome.3r7jSQ/SingletonSocket"
},
{
"code": null,
"e": 6205,
"s": 6151,
"text": "To display routing table, use the following command –"
},
{
"code": null,
"e": 6218,
"s": 6205,
"text": "$ netstat -r"
},
{
"code": null,
"e": 6258,
"s": 6218,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6803,
"s": 6258,
"text": "Kernel IP routing table\nDestination Gateway Genmask Flags MSS Window irtt Iface\ndefault TutorialsPoint1 0.0.0.0 UG 0 0 0 enp7s0\ndefault 192.168.1.254 0.0.0.0 UG 0 0 0 wlp6s0\nlink-local * 255.255.0.0 U 0 0 0 enp7s0\n192.168.1.0 * 255.255.255.0 U 0 0 0 enp7s0\n192.168.1.0 * 255.255.255.0 U 0 0 0 wlp6s0"
},
{
"code": null,
"e": 6865,
"s": 6803,
"text": "To display networking statistics, use the following command –"
},
{
"code": null,
"e": 6878,
"s": 6865,
"text": "$ netstat -s"
},
{
"code": null,
"e": 6918,
"s": 6878,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 7571,
"s": 6918,
"text": "Ip:\n 226777 total packets received\n 99 with invalid addresses\n 0 forwarded\n 0 incoming packets discarded\n 213036 incoming packets delivered\n 126141 requests sent out\n 48 outgoing packets dropped\nIcmp:\n 420 ICMP messages received\n 120 input ICMP message failed.\n ICMP input histogram:\n destination unreachable: 414\n echo requests: 6\n 576 ICMP messages sent\n 0 ICMP messages failed\n ICMP output histogram:\n destination unreachable: 570\n echo replies: 6\nIcmpMsg:\n InType3: 414\n InType8: 6\n OutType0: 6\n OutType3: 570\n...................................................................................."
},
{
"code": null,
"e": 7643,
"s": 7571,
"text": "To find the nonsupportive Address families, use the following command –"
},
{
"code": null,
"e": 7656,
"s": 7643,
"text": "$ netstat -v"
},
{
"code": null,
"e": 7696,
"s": 7656,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 8837,
"s": 7696,
"text": "Active Internet connections (w/o servers)\nProto Recv-Q Send-Q Local Address Foreign Address State\ntcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:39418 arn09s10-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:36398 maa03s20-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:59950 maa03s22-in-f14.1:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:60888 117.18.237.42:http ESTABLISHED\ntcp 0 0 linux-Inspiron-35:55716 maa03s20-in-f3.1e:https TIME_WAIT\ntcp 0 0 linux-Inspiron-35:42044 bom05s08-in-f4.1e:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:49654 ec2-54-221-3-35.c:https ESTABLISHED\ntcp 0 0 linux-Inspiron-35:47238 sc-in-f188.1e100.n:5228 ESTABLISHED\ntcp 0 0 linux-Inspiron-35:42046 bom05s08-in-f4.1e:https ESTABLISHED\n..........................................................................................."
},
{
"code": null,
"e": 8914,
"s": 8837,
"text": "To display other/more information about network, use the following command –"
},
{
"code": null,
"e": 10118,
"s": 8914,
"text": "Active Internet connections (w/o servers)\nProto Recv-Q Send-Q Local Address Foreign Address State User Inode\ntcp 0 0 linux-Inspiron-35:46930 ec2-54-236-207-15:https ESTABLISHED linux 123811\ntcp 0 0 linux-Inspiron-35:55458 52.222.136.134:https ESTABLISHED linux 148067\ntcp 0 0 linux-Inspiron-35:43780 sb-in-f188.1e100.n:5228 ESTABLISHED linux 147150\ntcp 0 0 linux-Inspiron-35:60924 117.18.237.42:http ESTAB LISHED linux 148291\ntcp 0 0 linux-Inspiron-35:36446 maa03s20-in-f14.1:https ESTABLISHED linux 148068\ntcp 0 0 linux-Inspiron-35:51126 edge-star-mini-sh:https ESTABLISHED linux 149411\ntcp 0 0 linux-Inspiron-35:33338 ec2-54-221-62-191:https CLOSE_WAIT linux 146371\nudp 0 0 linux-Inspiron-35:46539 maa03s20-in-f5.1e:https ESTABLISHED linux 117623\nudp 768 0 localhost:46996 linux-Inspiron-3:domain ESTABLISHED linux 123551\n.................................................................................."
},
{
"code": null,
"e": 10174,
"s": 10118,
"text": "To get the help of netstat, use the following command –"
},
{
"code": null,
"e": 10187,
"s": 10174,
"text": "$ netstat -h"
},
{
"code": null,
"e": 10227,
"s": 10187,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 11731,
"s": 10227,
"text": "usage: netstat [-vWeenNcCF] [] -r netstat {-V|--version|-h|--help}\n netstat [-vWnNcaeol] [ ...]\n netstat { [-vWeenNac] -i | [-cWnNe] -M | -s }\n\n-r, --route display routing table\n-i, --interfaces display interface table\n-g, --groups display multicast group memberships\n-s, --statistics display networking statistics (like SNMP)\n-M, --masquerade display masqueraded connections\n\n-v, --verbose be verbose\n-W, --wide don't truncate IP addresses\n-n, --numeric don't resolve names\n--numeric-hosts don't resolve host names\n--numeric-ports don't resolve port names\n--numeric-users don't resolve user names\n-N, --symbolic resolve hardware names\n-e, --extend display other/more information\n-p, --programs display PID/Program name for sockets\n-c, --continuous c ontinuous listing\n\n-l, --listening display listening server sockets\n-a, --all, --listening display all sockets (default: connected)\n-o, --timers display timers\n-F, --fib display Forwarding Information Base (default)\n-C, --cache display routing cache instead of FIB\n\n={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom\n=Use '-6|-4' or '-A ' or '--'; default: inet\nList of possible address families (which support routing):\ninet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25)\nnetrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP)\nx25 (CCITT X.25)\n\n"
},
{
"code": null,
"e": 11909,
"s": 11731,
"text": "In the above article, we have learnt about – Top 10 Netstat command examples on Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!"
}
] |
React JSX
|
JSX stands for JavaScript XML.
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.
JSX allows us to write HTML elements in JavaScript and place them in the DOM
without any createElement() and/or
appendChild() methods.
JSX converts HTML tags into react elements.
You are not required to use JSX, but JSX makes it easier to write React applications.
Here are two examples. The first uses JSX and the second does
not:
JSX:
const myElement = <h1>I Love JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
Run
Example »
Without JSX:
const myElement = React.createElement('h1', {}, 'I do not use JSX!');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
Run
Example »
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime.
With JSX you can write expressions inside curly braces { }.
The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:
Execute the expression 5 + 5:
const myElement = <h1>React is {5 + 5} times better with JSX</h1>;
Run
Example »
To write HTML on multiple lines, put the HTML inside parentheses:
Create a list with three list items:
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
Run
Example »
The HTML code must be wrapped in ONE top level element.
So if you like to write two paragraphs, you must put them inside a
parent element, like a div element.
Wrap two paragraphs inside one DIV element:
const myElement = (
<div>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>
);
Run
Example »
JSX will throw an error if the HTML is not correct, or if the HTML misses a
parent element.
Alternatively, you can use a "fragment" to wrap multiple lines.
This will prevent unnecessarily adding extra nodes to the DOM.
A fragment looks like an empty HTML tag: <></>.
Wrap two paragraphs inside a fragment:
const myElement = (
<>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</>
);
Run
Example »
JSX follows XML rules, and therefore HTML elements must be properly closed.
Close empty elements with />
const myElement = <input type="text" />;
Run
Example »
JSX will throw an error if the HTML is not properly closed.
The class attribute is a much used attribute
in HTML, but since JSX is rendered as JavaScript, and the
class keyword is a reserved word in JavaScript,
you are not allowed to use it in JSX.
Use attribute className instead.
JSX solved this by using className instead.
When JSX is rendered, it translates className
attributes into class attributes.
Use attribute className instead of
class in JSX:
const myElement = <h1 className="myclass">Hello World</h1>;
Run
Example »
React supports if statements, but not inside JSX.
To be able to use conditional statements in JSX, you should put the if
statements outside of the JSX, or you could use a ternary expression instead:
Write if statements outside of the JSX code:
Write "Hello" if x is less than 10, otherwise "Goodbye":
const x = 5;
let text = "Goodbye";
if (x < 10) {
text = "Hello";
}
const myElement = <h1>{text}</h1>;
Run
Example »
Use ternary expressions instead:
Write "Hello" if x is less than 10, otherwise "Goodbye":
const x = 5;
const myElement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;
Run
Example »
Note that in order to embed a JavaScript expression inside JSX,
the JavaScript must be wrapped with curly braces, {}.
Render a <p> element without using JSX.
const paragraph = React.createElement(, {}, 'This is a paragraph without using JSX!');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(paragraph);
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 31,
"s": 0,
"text": "JSX stands for JavaScript XML."
},
{
"code": null,
"e": 69,
"s": 31,
"text": "JSX allows us to write HTML in React."
},
{
"code": null,
"e": 121,
"s": 69,
"text": "JSX makes it easier to write and add HTML in React."
},
{
"code": null,
"e": 258,
"s": 121,
"text": "JSX allows us to write HTML elements in JavaScript and place them in the DOM \nwithout any createElement() and/or\nappendChild() methods."
},
{
"code": null,
"e": 302,
"s": 258,
"text": "JSX converts HTML tags into react elements."
},
{
"code": null,
"e": 388,
"s": 302,
"text": "You are not required to use JSX, but JSX makes it easier to write React applications."
},
{
"code": null,
"e": 456,
"s": 388,
"text": "Here are two examples. The first uses JSX and the second does \nnot:"
},
{
"code": null,
"e": 461,
"s": 456,
"text": "JSX:"
},
{
"code": null,
"e": 594,
"s": 461,
"text": "const myElement = <h1>I Love JSX!</h1>;\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(myElement);\n"
},
{
"code": null,
"e": 611,
"s": 594,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 624,
"s": 611,
"text": "Without JSX:"
},
{
"code": null,
"e": 787,
"s": 624,
"text": "const myElement = React.createElement('h1', {}, 'I do not use JSX!');\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(myElement);\n"
},
{
"code": null,
"e": 804,
"s": 787,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 906,
"s": 804,
"text": "As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code."
},
{
"code": null,
"e": 1021,
"s": 906,
"text": "JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime."
},
{
"code": null,
"e": 1081,
"s": 1021,
"text": "With JSX you can write expressions inside curly braces { }."
},
{
"code": null,
"e": 1231,
"s": 1081,
"text": "The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:"
},
{
"code": null,
"e": 1261,
"s": 1231,
"text": "Execute the expression 5 + 5:"
},
{
"code": null,
"e": 1329,
"s": 1261,
"text": "const myElement = <h1>React is {5 + 5} times better with JSX</h1>;\n"
},
{
"code": null,
"e": 1346,
"s": 1329,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1412,
"s": 1346,
"text": "To write HTML on multiple lines, put the HTML inside parentheses:"
},
{
"code": null,
"e": 1449,
"s": 1412,
"text": "Create a list with three list items:"
},
{
"code": null,
"e": 1551,
"s": 1449,
"text": "const myElement = (\n <ul>\n <li>Apples</li>\n <li>Bananas</li>\n <li>Cherries</li>\n </ul>\n);\n"
},
{
"code": null,
"e": 1568,
"s": 1551,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1624,
"s": 1568,
"text": "The HTML code must be wrapped in ONE top level element."
},
{
"code": null,
"e": 1728,
"s": 1624,
"text": "So if you like to write two paragraphs, you must put them inside a \nparent element, like a div element."
},
{
"code": null,
"e": 1772,
"s": 1728,
"text": "Wrap two paragraphs inside one DIV element:"
},
{
"code": null,
"e": 1875,
"s": 1772,
"text": "const myElement = (\n <div>\n <p>I am a paragraph.</p>\n <p>I am a paragraph too.</p>\n </div>\n);\n"
},
{
"code": null,
"e": 1892,
"s": 1875,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1985,
"s": 1892,
"text": "JSX will throw an error if the HTML is not correct, or if the HTML misses a \nparent element."
},
{
"code": null,
"e": 2112,
"s": 1985,
"text": "Alternatively, you can use a \"fragment\" to wrap multiple lines.\nThis will prevent unnecessarily adding extra nodes to the DOM."
},
{
"code": null,
"e": 2160,
"s": 2112,
"text": "A fragment looks like an empty HTML tag: <></>."
},
{
"code": null,
"e": 2199,
"s": 2160,
"text": "Wrap two paragraphs inside a fragment:"
},
{
"code": null,
"e": 2296,
"s": 2199,
"text": "const myElement = (\n <>\n <p>I am a paragraph.</p>\n <p>I am a paragraph too.</p>\n </>\n);\n"
},
{
"code": null,
"e": 2313,
"s": 2296,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2389,
"s": 2313,
"text": "JSX follows XML rules, and therefore HTML elements must be properly closed."
},
{
"code": null,
"e": 2418,
"s": 2389,
"text": "Close empty elements with />"
},
{
"code": null,
"e": 2460,
"s": 2418,
"text": "const myElement = <input type=\"text\" />;\n"
},
{
"code": null,
"e": 2477,
"s": 2460,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2537,
"s": 2477,
"text": "JSX will throw an error if the HTML is not properly closed."
},
{
"code": null,
"e": 2728,
"s": 2537,
"text": "The class attribute is a much used attribute \nin HTML, but since JSX is rendered as JavaScript, and the\nclass keyword is a reserved word in JavaScript, \nyou are not allowed to use it in JSX."
},
{
"code": null,
"e": 2761,
"s": 2728,
"text": "Use attribute className instead."
},
{
"code": null,
"e": 2887,
"s": 2761,
"text": "JSX solved this by using className instead. \nWhen JSX is rendered, it translates className \nattributes into class attributes."
},
{
"code": null,
"e": 2937,
"s": 2887,
"text": "Use attribute className instead of \nclass in JSX:"
},
{
"code": null,
"e": 2998,
"s": 2937,
"text": "const myElement = <h1 className=\"myclass\">Hello World</h1>;\n"
},
{
"code": null,
"e": 3015,
"s": 2998,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3065,
"s": 3015,
"text": "React supports if statements, but not inside JSX."
},
{
"code": null,
"e": 3215,
"s": 3065,
"text": "To be able to use conditional statements in JSX, you should put the if \nstatements outside of the JSX, or you could use a ternary expression instead:"
},
{
"code": null,
"e": 3260,
"s": 3215,
"text": "Write if statements outside of the JSX code:"
},
{
"code": null,
"e": 3317,
"s": 3260,
"text": "Write \"Hello\" if x is less than 10, otherwise \"Goodbye\":"
},
{
"code": null,
"e": 3423,
"s": 3317,
"text": "const x = 5;\nlet text = \"Goodbye\";\nif (x < 10) {\n text = \"Hello\";\n}\n\nconst myElement = <h1>{text}</h1>;\n"
},
{
"code": null,
"e": 3440,
"s": 3423,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3473,
"s": 3440,
"text": "Use ternary expressions instead:"
},
{
"code": null,
"e": 3530,
"s": 3473,
"text": "Write \"Hello\" if x is less than 10, otherwise \"Goodbye\":"
},
{
"code": null,
"e": 3606,
"s": 3530,
"text": "const x = 5;\n\nconst myElement = <h1>{(x) < 10 ? \"Hello\" : \"Goodbye\"}</h1>;\n"
},
{
"code": null,
"e": 3623,
"s": 3606,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3741,
"s": 3623,
"text": "Note that in order to embed a JavaScript expression inside JSX,\nthe JavaScript must be wrapped with curly braces, {}."
},
{
"code": null,
"e": 3781,
"s": 3741,
"text": "Render a <p> element without using JSX."
},
{
"code": null,
"e": 3961,
"s": 3781,
"text": "const paragraph = React.createElement(, {}, 'This is a paragraph without using JSX!');\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(paragraph);\n"
},
{
"code": null,
"e": 3980,
"s": 3961,
"text": "Start the Exercise"
},
{
"code": null,
"e": 4013,
"s": 3980,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4055,
"s": 4013,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4162,
"s": 4055,
"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": 4181,
"s": 4162,
"text": "help@w3schools.com"
}
] |
Encrypt and Decrypt Files using Python — Python Programming | by Misha Sv | Towards Data Science
|
Table of Contents
Introduction
Creating a key
Loading a key
Encrypting a file
Decrypting a file
Complete Object-Oriented Programming Example
Conclusion
Today we observe data from all different sources, and ultimately the challenge becomes its security and privacy. That involves not only major datasets held by businesses, but also the AI/ML models and algorithms, and ultimately the data with forecasts.
The amount of data is growing as the number of industries adapting data science practices in their decision making grows. There have been several companies found in the field of encryption and security for AI/ML and cloud computing, which are now even allowing computations on encrypted data.
In the evolving world of data and information transfer, security of the file contents remain to be one of the greatest concerns for companies. Some information can be password protected (emails, logins) while other information being transferred via emails or FTP lacks efficiency if protected by some keyword. This is where file encryption plays a big role and provides security and convenience sought by parties engaged in file transfers.
So what is encryption? It is a process of converting information into some form of a code to hide its true content. The only way to access the file information then is to decrypt it. The process of encryption/decryption is called cryptography.
Let’s see how we can encrypt and decrypt some of our files using Python. We will follow symmetric encryption which means using the same key to encrypt and decrypt the files.
To continue following this tutorial we will need the following Python library: cryptography.
If you don’t have them installed, please open “Command Prompt” (on Windows) and install them using the following code:
pip install cryptography
And we will also need a sample file we will be working with. Below is the sample .csv file with some data on students’ grades:
https://pyshark.com/wp-content/uploads/2020/08/grades.csv
In our example we will be using symmetric equation:
Fernet is authenticated cryptography which doesn’t allow to read and/or modify the file without a “key”.
Now, let’s create the key and save it in the same folder as our data file:
If you check the directory where you Python code is located, you should see the mykey.key file. You can open it with any text editor (in my case it shows up in the local directory because I use VS Code). The file should contain one line which is a string of some order of characters. For me it is “VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk=”.
After we generated the encryption key, we would need to load it into our environment in order to encrypt/decrypt the files.
The following step is very simple, and requires to just open the mykey.key file and store it in local memory:
And just to verify, we will see the following output:
VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk=
The encryption key is now stored locally as the key variable.
Now that we have the file to encrypt and the encryption key, we will now write a function to utilize these and return the encrypted file:
Let’s discuss what we did here:
We initialize the Fernet object as store is as a local variable f
Next, we read our original data (grades.csv file) into original
Then we encrypt the data using the Fernet object and store it as encrypted
And finally, we write it into a new .csv file called “enc_grades.csv”
You can take a look at the encrypted file here:
https://pyshark.com/wp-content/uploads/2020/09/enc_grades.csv
After you encrypted the file and, for example, successfully transferred the file to another location, you will want to access it. Now, that data is in the encrypted format. The next step is to decrypt it back to the original content.
The process we will follow now is the reverse of the encryption in the previous part. Exactly the same process, but now we will go from encrypted file to decrypted file:
Let’s discuss what we did here:
We initialize the Fernet object as store is as a local variable f
Next, we read our encrypted data (enc_grades.csv file) into encrypted
Then we decrypt the data using the Fernet object and store it as decrypted
And finally, we write it into a new .csv file called “dec_grades.csv”
You can take a look at the decrypted file here:
https://pyshark.com/wp-content/uploads/2020/09/dec_grades.csv
Comparing “dec_grades.csv” with the original “grades.csv”, you will see that in fact these two have identical contents. Our encryption/decryption process was successful.
This is a bonus part where I organized everything in a more structured format:
And this is an example of encryption/decryption using the above class:
This article introduces basic symmetric file encryption and decryption using Python. We have discussed some parts of cryptography library as well as created a full process example.
Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Programming articles.
Originally published at https://pyshark.com on September 1, 2020.
|
[
{
"code": null,
"e": 189,
"s": 171,
"text": "Table of Contents"
},
{
"code": null,
"e": 202,
"s": 189,
"text": "Introduction"
},
{
"code": null,
"e": 217,
"s": 202,
"text": "Creating a key"
},
{
"code": null,
"e": 231,
"s": 217,
"text": "Loading a key"
},
{
"code": null,
"e": 249,
"s": 231,
"text": "Encrypting a file"
},
{
"code": null,
"e": 267,
"s": 249,
"text": "Decrypting a file"
},
{
"code": null,
"e": 312,
"s": 267,
"text": "Complete Object-Oriented Programming Example"
},
{
"code": null,
"e": 323,
"s": 312,
"text": "Conclusion"
},
{
"code": null,
"e": 576,
"s": 323,
"text": "Today we observe data from all different sources, and ultimately the challenge becomes its security and privacy. That involves not only major datasets held by businesses, but also the AI/ML models and algorithms, and ultimately the data with forecasts."
},
{
"code": null,
"e": 869,
"s": 576,
"text": "The amount of data is growing as the number of industries adapting data science practices in their decision making grows. There have been several companies found in the field of encryption and security for AI/ML and cloud computing, which are now even allowing computations on encrypted data."
},
{
"code": null,
"e": 1309,
"s": 869,
"text": "In the evolving world of data and information transfer, security of the file contents remain to be one of the greatest concerns for companies. Some information can be password protected (emails, logins) while other information being transferred via emails or FTP lacks efficiency if protected by some keyword. This is where file encryption plays a big role and provides security and convenience sought by parties engaged in file transfers."
},
{
"code": null,
"e": 1553,
"s": 1309,
"text": "So what is encryption? It is a process of converting information into some form of a code to hide its true content. The only way to access the file information then is to decrypt it. The process of encryption/decryption is called cryptography."
},
{
"code": null,
"e": 1727,
"s": 1553,
"text": "Let’s see how we can encrypt and decrypt some of our files using Python. We will follow symmetric encryption which means using the same key to encrypt and decrypt the files."
},
{
"code": null,
"e": 1820,
"s": 1727,
"text": "To continue following this tutorial we will need the following Python library: cryptography."
},
{
"code": null,
"e": 1939,
"s": 1820,
"text": "If you don’t have them installed, please open “Command Prompt” (on Windows) and install them using the following code:"
},
{
"code": null,
"e": 1964,
"s": 1939,
"text": "pip install cryptography"
},
{
"code": null,
"e": 2091,
"s": 1964,
"text": "And we will also need a sample file we will be working with. Below is the sample .csv file with some data on students’ grades:"
},
{
"code": null,
"e": 2149,
"s": 2091,
"text": "https://pyshark.com/wp-content/uploads/2020/08/grades.csv"
},
{
"code": null,
"e": 2201,
"s": 2149,
"text": "In our example we will be using symmetric equation:"
},
{
"code": null,
"e": 2306,
"s": 2201,
"text": "Fernet is authenticated cryptography which doesn’t allow to read and/or modify the file without a “key”."
},
{
"code": null,
"e": 2381,
"s": 2306,
"text": "Now, let’s create the key and save it in the same folder as our data file:"
},
{
"code": null,
"e": 2726,
"s": 2381,
"text": "If you check the directory where you Python code is located, you should see the mykey.key file. You can open it with any text editor (in my case it shows up in the local directory because I use VS Code). The file should contain one line which is a string of some order of characters. For me it is “VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk=”."
},
{
"code": null,
"e": 2850,
"s": 2726,
"text": "After we generated the encryption key, we would need to load it into our environment in order to encrypt/decrypt the files."
},
{
"code": null,
"e": 2960,
"s": 2850,
"text": "The following step is very simple, and requires to just open the mykey.key file and store it in local memory:"
},
{
"code": null,
"e": 3014,
"s": 2960,
"text": "And just to verify, we will see the following output:"
},
{
"code": null,
"e": 3059,
"s": 3014,
"text": "VlD8h2tEiJkQpKKnDNKnu8ya2fpIBMOo5oc7JKNasvk="
},
{
"code": null,
"e": 3121,
"s": 3059,
"text": "The encryption key is now stored locally as the key variable."
},
{
"code": null,
"e": 3259,
"s": 3121,
"text": "Now that we have the file to encrypt and the encryption key, we will now write a function to utilize these and return the encrypted file:"
},
{
"code": null,
"e": 3291,
"s": 3259,
"text": "Let’s discuss what we did here:"
},
{
"code": null,
"e": 3357,
"s": 3291,
"text": "We initialize the Fernet object as store is as a local variable f"
},
{
"code": null,
"e": 3421,
"s": 3357,
"text": "Next, we read our original data (grades.csv file) into original"
},
{
"code": null,
"e": 3496,
"s": 3421,
"text": "Then we encrypt the data using the Fernet object and store it as encrypted"
},
{
"code": null,
"e": 3566,
"s": 3496,
"text": "And finally, we write it into a new .csv file called “enc_grades.csv”"
},
{
"code": null,
"e": 3614,
"s": 3566,
"text": "You can take a look at the encrypted file here:"
},
{
"code": null,
"e": 3676,
"s": 3614,
"text": "https://pyshark.com/wp-content/uploads/2020/09/enc_grades.csv"
},
{
"code": null,
"e": 3910,
"s": 3676,
"text": "After you encrypted the file and, for example, successfully transferred the file to another location, you will want to access it. Now, that data is in the encrypted format. The next step is to decrypt it back to the original content."
},
{
"code": null,
"e": 4080,
"s": 3910,
"text": "The process we will follow now is the reverse of the encryption in the previous part. Exactly the same process, but now we will go from encrypted file to decrypted file:"
},
{
"code": null,
"e": 4112,
"s": 4080,
"text": "Let’s discuss what we did here:"
},
{
"code": null,
"e": 4178,
"s": 4112,
"text": "We initialize the Fernet object as store is as a local variable f"
},
{
"code": null,
"e": 4248,
"s": 4178,
"text": "Next, we read our encrypted data (enc_grades.csv file) into encrypted"
},
{
"code": null,
"e": 4323,
"s": 4248,
"text": "Then we decrypt the data using the Fernet object and store it as decrypted"
},
{
"code": null,
"e": 4393,
"s": 4323,
"text": "And finally, we write it into a new .csv file called “dec_grades.csv”"
},
{
"code": null,
"e": 4441,
"s": 4393,
"text": "You can take a look at the decrypted file here:"
},
{
"code": null,
"e": 4503,
"s": 4441,
"text": "https://pyshark.com/wp-content/uploads/2020/09/dec_grades.csv"
},
{
"code": null,
"e": 4673,
"s": 4503,
"text": "Comparing “dec_grades.csv” with the original “grades.csv”, you will see that in fact these two have identical contents. Our encryption/decryption process was successful."
},
{
"code": null,
"e": 4752,
"s": 4673,
"text": "This is a bonus part where I organized everything in a more structured format:"
},
{
"code": null,
"e": 4823,
"s": 4752,
"text": "And this is an example of encryption/decryption using the above class:"
},
{
"code": null,
"e": 5004,
"s": 4823,
"text": "This article introduces basic symmetric file encryption and decryption using Python. We have discussed some parts of cryptography library as well as created a full process example."
},
{
"code": null,
"e": 5153,
"s": 5004,
"text": "Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Programming articles."
}
] |
A Boolean Matrix Question - GeeksforGeeks
|
25 Feb, 2022
Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1.
Example 1
The matrix
1 0
0 0
should be changed to following
1 1
1 0
Example 2
The matrix
0 0 0
0 0 1
should be changed to following
0 0 1
1 1 1
Example 3
The matrix
1 0 0 1
0 0 1 0
0 0 0 0
should be changed to following
1 1 1 1
1 1 1 1
1 0 1 1
Method 1 (Use two temporary arrays) 1) Create two temporary arrays row[M] and col[N]. Initialize all values of row[] and col[] as 0. 2) Traverse the input matrix mat[M][N]. If you see an entry mat[i][j] as true, then mark row[i] and col[j] as true. 3) Traverse the input matrix mat[M][N] again. For each entry mat[i][j], check the values of row[i] and col[j]. If any of the two values (row[i] or col[j]) is true, then mark mat[i][j] as true.Thanks to Dixit Sethi for suggesting this method.
C++
Java
Python3
C#
PHP
Javascript
// C++ Code For A Boolean Matrix Question#include <bits/stdc++.h> using namespace std;#define R 3#define C 4 void modifyMatrix(bool mat[R][C]){ bool row[R]; bool col[C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } // Store the rows and columns to be marked as // 1 in row[] and col[] arrays respectively for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } // Modify the input matrix mat[] using the // above constructed row[] and col[] arrays for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } }} /* A utility function to print a 2D matrix */void printMatrix(bool mat[R][C]){ int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { cout << mat[i][j]; } cout << endl; }} // Driver Codeint main(){ bool mat[R][C] = { {1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; cout << "Input Matrix \n"; printMatrix(mat); modifyMatrix(mat); printf("Matrix after modification \n"); printMatrix(mat); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// Java Code For A Boolean Matrix Questionclass GFG{ public static void modifyMatrix(int mat[ ][ ], int R, int C) { int row[ ]= new int [R]; int col[ ]= new int [C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int mat[ ][ ], int R, int C) { int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { System.out.print(mat[i][j]+ " "); } System.out.println(); } } /* Driver program to test above functions */ public static void main(String[] args) { int mat[ ][ ] = { {1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0},}; System.out.println("Matrix Initially"); printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); System.out.println("Matrix after modification n"); printMatrix(mat, 3, 4); } } // This code is contributed by Kamal Rawal
# Python3 Code For A Boolean Matrix QuestionR = 3C = 4 def modifyMatrix(mat): row = [0] * R col = [0] * C # Initialize all values of row[] as 0 for i in range(0, R): row[i] = 0 # Initialize all values of col[] as 0 for i in range(0, C) : col[i] = 0 # Store the rows and columns to be marked # as 1 in row[] and col[] arrays respectively for i in range(0, R) : for j in range(0, C) : if (mat[i][j] == 1) : row[i] = 1 col[j] = 1 # Modify the input matrix mat[] using the # above constructed row[] and col[] arrays for i in range(0, R) : for j in range(0, C): if ( row[i] == 1 or col[j] == 1 ) : mat[i][j] = 1 # A utility function to print a 2D matrixdef printMatrix(mat) : for i in range(0, R): for j in range(0, C) : print(mat[i][j], end = " ") print() # Driver Codemat = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ] print("Input Matrix n")printMatrix(mat) modifyMatrix(mat) print("Matrix after modification n")printMatrix(mat) # This code is contributed by Nikita Tiwari.
// C# Code For A Boolean// Matrix Questionusing System; class GFG{ public static void modifyMatrix(int [,]mat, int R, int C) { int []row = new int [R]; int []col = new int [C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i, j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (row[i] == 1 || col[j] == 1) { mat[i, j] = 1; } } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int [,]mat, int R, int C) { int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { Console.Write(mat[i, j] + " "); } Console.WriteLine(); } } // Driver code static public void Main () { int [,]mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; Console.WriteLine("Matrix Initially"); printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); Console.WriteLine("Matrix after "+ "modification n"); printMatrix(mat, 3, 4); }} // This code is contributed by ajit
<?php// PHP Code For A Boolean// Matrix Question$R = 3;$C = 4; function modifyMatrix(&$mat){ global $R,$C; $row = array(); $col = array(); /* Initialize all values of row[] as 0 */ for ($i = 0; $i < $R; $i++) { $row[$i] = 0; } /* Initialize all values of col[] as 0 */ for ($i = 0; $i < $C; $i++) { $col[$i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($mat[$i][$j] == 1) { $row[$i] = 1; $col[$j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($row[$i] == 1 || $col[$j] == 1 ) { $mat[$i][$j] = 1; } } }} /* A utility function to print a 2D matrix */function printMatrix(&$mat){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $mat[$i][$j] . " "; } echo "\n"; }} // Driver code$mat = array(array(1, 0, 0, 1), array(0, 0, 1, 0), array(0, 0, 0, 0)); echo "Input Matrix \n";printMatrix($mat); modifyMatrix($mat); echo "Matrix after modification \n";printMatrix($mat); // This code is contributed// by ChitraNayal?>
<script> // Javascript Code For A Boolean Matrix Question function modifyMatrix(mat,R,C) { let row=new Array(R); let col = new Array(C); /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } } } /* A utility function to print a 2D matrix */ function printMatrix(mat,R,C) { let i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { document.write(mat[i][j]+ " "); } document.write("<br>"); } } /* Driver program to test above functions */ let mat = [[1, 0, 0, 1],[0, 0, 1, 0],[0, 0, 0, 0]]; document.write("Matrix Initially <br>") printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); document.write("Matrix after modification n <br>"); printMatrix(mat, 3, 4); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Input Matrix
1 0 0 1
0 0 1 0
0 0 0 0
Matrix after modification
1 1 1 1
1 1 1 1
1 0 1 1
Time Complexity: O(M*N) Auxiliary Space: O(M + N)Method 2 (A Space Optimized Version of Method 1) This method is a space optimized version of above method 1. This method uses the first row and first column of the input matrix in place of the auxiliary arrays row[] and col[] of method 1. So what we do is: first take care of first row and column and store the info about these two in two flag variables rowFlag and colFlag. Once we have this info, we can use first row and first column as auxiliary arrays and apply method 1 for submatrix (matrix excluding first row and first column) of size (M-1)*(N-1).1) Scan the first row and set a variable rowFlag to indicate whether we need to set all 1s in first row or not. 2) Scan the first column and set a variable colFlag to indicate whether we need to set all 1s in first column or not. 3) Use first row and first column as the auxiliary arrays row[] and col[] respectively, consider the matrix as submatrix starting from second row and second column and apply method 1. 4) Finally, using rowFlag and colFlag, update first row and first column if needed.Time Complexity: O(M*N) Auxiliary Space: O(1)Thanks to Sidh for suggesting this method.
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;#define R 3#define C 4 void modifyMatrix(int mat[R][C]){ // variables to check if there are any 1 // in first row and column bool row_flag = false; bool col_flag = false; // updating the first row and col if 1 // is encountered for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1) { mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { if (mat[0][j] == 1 || mat[i][0] == 1) { mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true) { for (int i = 0; i < C; i++) { mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true) { for (int i = 0; i < R; i++) { mat[i][0] = 1; } }} /* A utility function to print a 2D matrix */void printMatrix(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { cout << mat[i][j]; } cout << "\n"; }} // Driver function to test the above functionint main(){ int mat[R][C] = { { 1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }; cout << "Input Matrix :\n"; printMatrix(mat); modifyMatrix(mat); cout << "Matrix After Modification :\n"; printMatrix(mat); return 0;} // This code is contributed by Nikita Tiwari
class GFG{ public static void modifyMatrix(int mat[][]){ // variables to check if there are any 1 // in first row and column boolean row_flag = false; boolean col_flag = false; // updating the first row and col if 1 // is encountered for (int i = 0; i < mat.length; i++ ){ for (int j = 0; j < mat[0].length; j++){ if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1){ mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (int i = 1; i < mat.length; i ++){ for (int j = 1; j < mat[0].length; j ++){ if (mat[0][j] == 1 || mat[i][0] == 1){ mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true){ for (int i = 0; i < mat[0].length; i++){ mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true){ for (int i = 0; i < mat.length; i ++){ mat[i][0] = 1; } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int mat[][]){ for (int i = 0; i < mat.length; i ++){ for (int j = 0; j < mat[0].length; j ++){ System.out.print( mat[i][j] ); } System.out.println(""); } } // Driver function to test the above function public static void main(String args[] ){ int mat[][] = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; System.out.println("Input Matrix :"); printMatrix(mat); modifyMatrix(mat); System.out.println("Matrix After Modification :"); printMatrix(mat); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 Code For A Boolean Matrix Questiondef modifyMatrix(mat) : # variables to check if there are any 1 # in first row and column row_flag = False col_flag = False # updating the first row and col # if 1 is encountered for i in range(0, len(mat)) : for j in range(0, len(mat)) : if (i == 0 and mat[i][j] == 1) : row_flag = True if (j == 0 and mat[i][j] == 1) : col_flag = True if (mat[i][j] == 1) : mat[0][j] = 1 mat[i][0] = 1 # Modify the input matrix mat[] using the # first row and first column of Matrix mat for i in range(1, len(mat)) : for j in range(1, len(mat) + 1) : if (mat[0][j] == 1 or mat[i][0] == 1) : mat[i][j] = 1 # modify first row if there was any 1 if (row_flag == True) : for i in range(0, len(mat)) : mat[0][i] = 1 # modify first col if there was any 1 if (col_flag == True) : for i in range(0, len(mat)) : mat[i][0] = 1 # A utility function to print a 2D matrixdef printMatrix(mat) : for i in range(0, len(mat)) : for j in range(0, len(mat) + 1) : print( mat[i][j], end = "" ) print() # Driver Codemat = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ] print("Input Matrix :")printMatrix(mat) modifyMatrix(mat) print("Matrix After Modification :")printMatrix(mat) # This code is contributed by Nikita tiwari.
// C# Code For A Boolean// Matrix Questionusing System; class GFG{ public static void modifyMatrix(int[,] mat) { // variables to check // if there are any 1 // in first row and column bool row_flag = false; bool col_flag = false; // updating the first // row and col if 1 // is encountered for (int i = 0; i < mat.GetLength(0); i++ ) { for (int j = 0; j < mat.GetLength(1); j++) { if (i == 0 && mat[i, j] == 1) row_flag = true; if (j == 0 && mat[i, j] == 1) col_flag = true; if (mat[i, j] == 1) { mat[0, j] = 1; mat[i,0] = 1; } } } // Modify the input matrix mat[] // using the first row and first // column of Matrix mat for (int i = 1; i < mat.GetLength(0); i ++) { for (int j = 1; j < mat.GetLength(1); j ++) { if (mat[0, j] == 1 || mat[i, 0] == 1) { mat[i, j] = 1; } } } // modify first row // if there was any 1 if (row_flag == true) { for (int i = 0; i < mat.GetLength(1); i++) { mat[0, i] = 1; } } // modify first col if // there was any 1 if (col_flag == true) { for (int i = 0; i < mat.GetLength(0); i ++) { mat[i, 0] = 1; } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int[,] mat) { for (int i = 0; i < mat.GetLength(0); i ++) { for (int j = 0; j < mat.GetLength(1); j ++) { Console.Write(mat[i, j] + " " ); } Console.Write("\n"); } } // Driver Code public static void Main() { int[,] mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; Console.Write("Input Matrix :\n"); printMatrix(mat); modifyMatrix(mat); Console.Write("Matrix After " + "Modification :\n"); printMatrix(mat); }} // This code is contributed// by ChitraNayal
<?php// PHP Code For A Boolean// Matrix Question$R = 3;$C = 4; function modifyMatrix(&$mat){ global $R, $C; // variables to check if // there are any 1 in // first row and column $row_flag = false; $col_flag = false; // updating the first // row and col if 1 // is encountered for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($i == 0 && $mat[$i][$j] == 1) $row_flag = true; if ($j == 0 && $mat[$i][$j] == 1) $col_flag = true; if ($mat[$i][$j] == 1) { $mat[0][$j] = 1; $mat[$i][0] = 1; } } } // Modify the input matrix // mat[] using the first // row and first column of // Matrix mat for ($i = 1; $i < $R; $i++) { for ($j = 1; $j < $C; $j++) { if ($mat[0][$j] == 1 || $mat[$i][0] == 1) { $mat[$i][$j] = 1; } } } // modify first row // if there was any 1 if ($row_flag == true) { for ($i = 0; $i < $C; $i++) { $mat[0][$i] = 1; } } // modify first col // if there was any 1 if ($col_flag == true) { for ($i = 0; $i < $R; $i++) { $mat[$i][0] = 1; } }} /* A utility functionto print a 2D matrix */function printMatrix(&$mat){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $mat[$i][$j]." "; } echo "\n"; }} // Driver Code$mat = array(array(1, 0, 0, 1 ), array(0, 0, 1, 0 ), array(0, 0, 0, 0 )); echo "Input Matrix :\n";printMatrix($mat); modifyMatrix($mat); echo "Matrix After Modification :\n";printMatrix($mat); // This code is contributed// by ChitraNayal?>
<script> function modifyMatrix(mat){ // variables to check if there are any 1 // in first row and column let row_flag = false; let col_flag = false; // updating the first row and col if 1 // is encountered for (let i = 0; i < mat.length; i++ ){ for (let j = 0; j < mat[0].length; j++){ if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1){ mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (let i = 1; i < mat.length; i ++){ for (let j = 1; j < mat[0].length; j ++){ if (mat[0][j] == 1 || mat[i][0] == 1){ mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true){ for (let i = 0; i < mat[0].length; i++){ mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true){ for (let i = 0; i < mat.length; i ++){ mat[i][0] = 1; } }} /* A utility function to print a 2D matrix */function printMatrix(mat){ for (let i = 0; i < mat.length; i ++){ for (let j = 0; j < mat[0].length; j ++){ document.write( mat[i][j] ); } document.write("<br>"); }} // Driver function to test the above functionlet mat=[[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]];document.write("Input Matrix :<br>");printMatrix(mat); modifyMatrix(mat); document.write("Matrix After Modification :<br>");printMatrix(mat); // This code is contributed by ab2127 </script>
Output:
Input Matrix :
1001
0010
0000
Matrix After Modification :
1111
1111
1011
YouTubeGeeksforGeeks500K subscribersBoolean Matrix | 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 / 13:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UDWrv63bOXw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
ukasp
Akanksha_Rai
avanitrachhadiya2155
simmytarika5
ab2127
surinderdawra388
Amazon
Boomerang Commerce
FactSet
Morgan Stanley
Ola Cabs
SAP Labs
VMWare
Arrays
Matrix
VMWare
Morgan Stanley
Amazon
FactSet
Ola Cabs
SAP Labs
Boomerang Commerce
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
|
[
{
"code": null,
"e": 24589,
"s": 24561,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 24757,
"s": 24589,
"text": "Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1. "
},
{
"code": null,
"e": 25003,
"s": 24757,
"text": "Example 1\nThe matrix\n1 0\n0 0\nshould be changed to following\n1 1\n1 0\n\nExample 2\nThe matrix\n0 0 0\n0 0 1\nshould be changed to following\n0 0 1\n1 1 1\n\nExample 3\nThe matrix\n1 0 0 1\n0 0 1 0\n0 0 0 0\nshould be changed to following\n1 1 1 1\n1 1 1 1\n1 0 1 1"
},
{
"code": null,
"e": 25498,
"s": 25005,
"text": "Method 1 (Use two temporary arrays) 1) Create two temporary arrays row[M] and col[N]. Initialize all values of row[] and col[] as 0. 2) Traverse the input matrix mat[M][N]. If you see an entry mat[i][j] as true, then mark row[i] and col[j] as true. 3) Traverse the input matrix mat[M][N] again. For each entry mat[i][j], check the values of row[i] and col[j]. If any of the two values (row[i] or col[j]) is true, then mark mat[i][j] as true.Thanks to Dixit Sethi for suggesting this method. "
},
{
"code": null,
"e": 25502,
"s": 25498,
"text": "C++"
},
{
"code": null,
"e": 25507,
"s": 25502,
"text": "Java"
},
{
"code": null,
"e": 25515,
"s": 25507,
"text": "Python3"
},
{
"code": null,
"e": 25518,
"s": 25515,
"text": "C#"
},
{
"code": null,
"e": 25522,
"s": 25518,
"text": "PHP"
},
{
"code": null,
"e": 25533,
"s": 25522,
"text": "Javascript"
},
{
"code": "// C++ Code For A Boolean Matrix Question#include <bits/stdc++.h> using namespace std;#define R 3#define C 4 void modifyMatrix(bool mat[R][C]){ bool row[R]; bool col[C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } // Store the rows and columns to be marked as // 1 in row[] and col[] arrays respectively for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } // Modify the input matrix mat[] using the // above constructed row[] and col[] arrays for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } }} /* A utility function to print a 2D matrix */void printMatrix(bool mat[R][C]){ int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { cout << mat[i][j]; } cout << endl; }} // Driver Codeint main(){ bool mat[R][C] = { {1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; cout << \"Input Matrix \\n\"; printMatrix(mat); modifyMatrix(mat); printf(\"Matrix after modification \\n\"); printMatrix(mat); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 27076,
"s": 25533,
"text": null
},
{
"code": "// Java Code For A Boolean Matrix Questionclass GFG{ public static void modifyMatrix(int mat[ ][ ], int R, int C) { int row[ ]= new int [R]; int col[ ]= new int [C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int mat[ ][ ], int R, int C) { int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { System.out.print(mat[i][j]+ \" \"); } System.out.println(); } } /* Driver program to test above functions */ public static void main(String[] args) { int mat[ ][ ] = { {1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0},}; System.out.println(\"Matrix Initially\"); printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); System.out.println(\"Matrix after modification n\"); printMatrix(mat, 3, 4); } } // This code is contributed by Kamal Rawal",
"e": 29129,
"s": 27076,
"text": null
},
{
"code": "# Python3 Code For A Boolean Matrix QuestionR = 3C = 4 def modifyMatrix(mat): row = [0] * R col = [0] * C # Initialize all values of row[] as 0 for i in range(0, R): row[i] = 0 # Initialize all values of col[] as 0 for i in range(0, C) : col[i] = 0 # Store the rows and columns to be marked # as 1 in row[] and col[] arrays respectively for i in range(0, R) : for j in range(0, C) : if (mat[i][j] == 1) : row[i] = 1 col[j] = 1 # Modify the input matrix mat[] using the # above constructed row[] and col[] arrays for i in range(0, R) : for j in range(0, C): if ( row[i] == 1 or col[j] == 1 ) : mat[i][j] = 1 # A utility function to print a 2D matrixdef printMatrix(mat) : for i in range(0, R): for j in range(0, C) : print(mat[i][j], end = \" \") print() # Driver Codemat = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ] print(\"Input Matrix n\")printMatrix(mat) modifyMatrix(mat) print(\"Matrix after modification n\")printMatrix(mat) # This code is contributed by Nikita Tiwari.",
"e": 30354,
"s": 29129,
"text": null
},
{
"code": "// C# Code For A Boolean// Matrix Questionusing System; class GFG{ public static void modifyMatrix(int [,]mat, int R, int C) { int []row = new int [R]; int []col = new int [C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i, j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (row[i] == 1 || col[j] == 1) { mat[i, j] = 1; } } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int [,]mat, int R, int C) { int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { Console.Write(mat[i, j] + \" \"); } Console.WriteLine(); } } // Driver code static public void Main () { int [,]mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; Console.WriteLine(\"Matrix Initially\"); printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); Console.WriteLine(\"Matrix after \"+ \"modification n\"); printMatrix(mat, 3, 4); }} // This code is contributed by ajit",
"e": 32411,
"s": 30354,
"text": null
},
{
"code": "<?php// PHP Code For A Boolean// Matrix Question$R = 3;$C = 4; function modifyMatrix(&$mat){ global $R,$C; $row = array(); $col = array(); /* Initialize all values of row[] as 0 */ for ($i = 0; $i < $R; $i++) { $row[$i] = 0; } /* Initialize all values of col[] as 0 */ for ($i = 0; $i < $C; $i++) { $col[$i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($mat[$i][$j] == 1) { $row[$i] = 1; $col[$j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($row[$i] == 1 || $col[$j] == 1 ) { $mat[$i][$j] = 1; } } }} /* A utility function to print a 2D matrix */function printMatrix(&$mat){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $mat[$i][$j] . \" \"; } echo \"\\n\"; }} // Driver code$mat = array(array(1, 0, 0, 1), array(0, 0, 1, 0), array(0, 0, 0, 0)); echo \"Input Matrix \\n\";printMatrix($mat); modifyMatrix($mat); echo \"Matrix after modification \\n\";printMatrix($mat); // This code is contributed// by ChitraNayal?>",
"e": 33943,
"s": 32411,
"text": null
},
{
"code": "<script> // Javascript Code For A Boolean Matrix Question function modifyMatrix(mat,R,C) { let row=new Array(R); let col = new Array(C); /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) { row[i] = 0; } /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) { col[i] = 0; } /* Store the rows and columns to be marked as 1 in row[] and col[] arrays respectively */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } /* Modify the input matrix mat[] using the above constructed row[] and col[] arrays */ for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if ( row[i] == 1 || col[j] == 1 ) { mat[i][j] = 1; } } } } /* A utility function to print a 2D matrix */ function printMatrix(mat,R,C) { let i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { document.write(mat[i][j]+ \" \"); } document.write(\"<br>\"); } } /* Driver program to test above functions */ let mat = [[1, 0, 0, 1],[0, 0, 1, 0],[0, 0, 0, 0]]; document.write(\"Matrix Initially <br>\") printMatrix(mat, 3, 4); modifyMatrix(mat, 3, 4); document.write(\"Matrix after modification n <br>\"); printMatrix(mat, 3, 4); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 35747,
"s": 33943,
"text": null
},
{
"code": null,
"e": 35757,
"s": 35747,
"text": "Output: "
},
{
"code": null,
"e": 35844,
"s": 35757,
"text": "Input Matrix\n1 0 0 1\n0 0 1 0\n0 0 0 0\nMatrix after modification\n1 1 1 1\n1 1 1 1\n1 0 1 1"
},
{
"code": null,
"e": 37036,
"s": 35844,
"text": "Time Complexity: O(M*N) Auxiliary Space: O(M + N)Method 2 (A Space Optimized Version of Method 1) This method is a space optimized version of above method 1. This method uses the first row and first column of the input matrix in place of the auxiliary arrays row[] and col[] of method 1. So what we do is: first take care of first row and column and store the info about these two in two flag variables rowFlag and colFlag. Once we have this info, we can use first row and first column as auxiliary arrays and apply method 1 for submatrix (matrix excluding first row and first column) of size (M-1)*(N-1).1) Scan the first row and set a variable rowFlag to indicate whether we need to set all 1s in first row or not. 2) Scan the first column and set a variable colFlag to indicate whether we need to set all 1s in first column or not. 3) Use first row and first column as the auxiliary arrays row[] and col[] respectively, consider the matrix as submatrix starting from second row and second column and apply method 1. 4) Finally, using rowFlag and colFlag, update first row and first column if needed.Time Complexity: O(M*N) Auxiliary Space: O(1)Thanks to Sidh for suggesting this method. "
},
{
"code": null,
"e": 37040,
"s": 37036,
"text": "C++"
},
{
"code": null,
"e": 37045,
"s": 37040,
"text": "Java"
},
{
"code": null,
"e": 37053,
"s": 37045,
"text": "Python3"
},
{
"code": null,
"e": 37056,
"s": 37053,
"text": "C#"
},
{
"code": null,
"e": 37060,
"s": 37056,
"text": "PHP"
},
{
"code": null,
"e": 37071,
"s": 37060,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define R 3#define C 4 void modifyMatrix(int mat[R][C]){ // variables to check if there are any 1 // in first row and column bool row_flag = false; bool col_flag = false; // updating the first row and col if 1 // is encountered for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1) { mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (int i = 1; i < R; i++) { for (int j = 1; j < C; j++) { if (mat[0][j] == 1 || mat[i][0] == 1) { mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true) { for (int i = 0; i < C; i++) { mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true) { for (int i = 0; i < R; i++) { mat[i][0] = 1; } }} /* A utility function to print a 2D matrix */void printMatrix(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { cout << mat[i][j]; } cout << \"\\n\"; }} // Driver function to test the above functionint main(){ int mat[R][C] = { { 1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }; cout << \"Input Matrix :\\n\"; printMatrix(mat); modifyMatrix(mat); cout << \"Matrix After Modification :\\n\"; printMatrix(mat); return 0;} // This code is contributed by Nikita Tiwari",
"e": 38855,
"s": 37071,
"text": null
},
{
"code": "class GFG{ public static void modifyMatrix(int mat[][]){ // variables to check if there are any 1 // in first row and column boolean row_flag = false; boolean col_flag = false; // updating the first row and col if 1 // is encountered for (int i = 0; i < mat.length; i++ ){ for (int j = 0; j < mat[0].length; j++){ if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1){ mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (int i = 1; i < mat.length; i ++){ for (int j = 1; j < mat[0].length; j ++){ if (mat[0][j] == 1 || mat[i][0] == 1){ mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true){ for (int i = 0; i < mat[0].length; i++){ mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true){ for (int i = 0; i < mat.length; i ++){ mat[i][0] = 1; } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int mat[][]){ for (int i = 0; i < mat.length; i ++){ for (int j = 0; j < mat[0].length; j ++){ System.out.print( mat[i][j] ); } System.out.println(\"\"); } } // Driver function to test the above function public static void main(String args[] ){ int mat[][] = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; System.out.println(\"Input Matrix :\"); printMatrix(mat); modifyMatrix(mat); System.out.println(\"Matrix After Modification :\"); printMatrix(mat); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 41426,
"s": 38855,
"text": null
},
{
"code": "# Python3 Code For A Boolean Matrix Questiondef modifyMatrix(mat) : # variables to check if there are any 1 # in first row and column row_flag = False col_flag = False # updating the first row and col # if 1 is encountered for i in range(0, len(mat)) : for j in range(0, len(mat)) : if (i == 0 and mat[i][j] == 1) : row_flag = True if (j == 0 and mat[i][j] == 1) : col_flag = True if (mat[i][j] == 1) : mat[0][j] = 1 mat[i][0] = 1 # Modify the input matrix mat[] using the # first row and first column of Matrix mat for i in range(1, len(mat)) : for j in range(1, len(mat) + 1) : if (mat[0][j] == 1 or mat[i][0] == 1) : mat[i][j] = 1 # modify first row if there was any 1 if (row_flag == True) : for i in range(0, len(mat)) : mat[0][i] = 1 # modify first col if there was any 1 if (col_flag == True) : for i in range(0, len(mat)) : mat[i][0] = 1 # A utility function to print a 2D matrixdef printMatrix(mat) : for i in range(0, len(mat)) : for j in range(0, len(mat) + 1) : print( mat[i][j], end = \"\" ) print() # Driver Codemat = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ] print(\"Input Matrix :\")printMatrix(mat) modifyMatrix(mat) print(\"Matrix After Modification :\")printMatrix(mat) # This code is contributed by Nikita tiwari.",
"e": 43077,
"s": 41426,
"text": null
},
{
"code": "// C# Code For A Boolean// Matrix Questionusing System; class GFG{ public static void modifyMatrix(int[,] mat) { // variables to check // if there are any 1 // in first row and column bool row_flag = false; bool col_flag = false; // updating the first // row and col if 1 // is encountered for (int i = 0; i < mat.GetLength(0); i++ ) { for (int j = 0; j < mat.GetLength(1); j++) { if (i == 0 && mat[i, j] == 1) row_flag = true; if (j == 0 && mat[i, j] == 1) col_flag = true; if (mat[i, j] == 1) { mat[0, j] = 1; mat[i,0] = 1; } } } // Modify the input matrix mat[] // using the first row and first // column of Matrix mat for (int i = 1; i < mat.GetLength(0); i ++) { for (int j = 1; j < mat.GetLength(1); j ++) { if (mat[0, j] == 1 || mat[i, 0] == 1) { mat[i, j] = 1; } } } // modify first row // if there was any 1 if (row_flag == true) { for (int i = 0; i < mat.GetLength(1); i++) { mat[0, i] = 1; } } // modify first col if // there was any 1 if (col_flag == true) { for (int i = 0; i < mat.GetLength(0); i ++) { mat[i, 0] = 1; } } } /* A utility function to print a 2D matrix */ public static void printMatrix(int[,] mat) { for (int i = 0; i < mat.GetLength(0); i ++) { for (int j = 0; j < mat.GetLength(1); j ++) { Console.Write(mat[i, j] + \" \" ); } Console.Write(\"\\n\"); } } // Driver Code public static void Main() { int[,] mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; Console.Write(\"Input Matrix :\\n\"); printMatrix(mat); modifyMatrix(mat); Console.Write(\"Matrix After \" + \"Modification :\\n\"); printMatrix(mat); }} // This code is contributed// by ChitraNayal",
"e": 46033,
"s": 43077,
"text": null
},
{
"code": "<?php// PHP Code For A Boolean// Matrix Question$R = 3;$C = 4; function modifyMatrix(&$mat){ global $R, $C; // variables to check if // there are any 1 in // first row and column $row_flag = false; $col_flag = false; // updating the first // row and col if 1 // is encountered for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { if ($i == 0 && $mat[$i][$j] == 1) $row_flag = true; if ($j == 0 && $mat[$i][$j] == 1) $col_flag = true; if ($mat[$i][$j] == 1) { $mat[0][$j] = 1; $mat[$i][0] = 1; } } } // Modify the input matrix // mat[] using the first // row and first column of // Matrix mat for ($i = 1; $i < $R; $i++) { for ($j = 1; $j < $C; $j++) { if ($mat[0][$j] == 1 || $mat[$i][0] == 1) { $mat[$i][$j] = 1; } } } // modify first row // if there was any 1 if ($row_flag == true) { for ($i = 0; $i < $C; $i++) { $mat[0][$i] = 1; } } // modify first col // if there was any 1 if ($col_flag == true) { for ($i = 0; $i < $R; $i++) { $mat[$i][0] = 1; } }} /* A utility functionto print a 2D matrix */function printMatrix(&$mat){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) { echo $mat[$i][$j].\" \"; } echo \"\\n\"; }} // Driver Code$mat = array(array(1, 0, 0, 1 ), array(0, 0, 1, 0 ), array(0, 0, 0, 0 )); echo \"Input Matrix :\\n\";printMatrix($mat); modifyMatrix($mat); echo \"Matrix After Modification :\\n\";printMatrix($mat); // This code is contributed// by ChitraNayal?>",
"e": 47895,
"s": 46033,
"text": null
},
{
"code": "<script> function modifyMatrix(mat){ // variables to check if there are any 1 // in first row and column let row_flag = false; let col_flag = false; // updating the first row and col if 1 // is encountered for (let i = 0; i < mat.length; i++ ){ for (let j = 0; j < mat[0].length; j++){ if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1){ mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (let i = 1; i < mat.length; i ++){ for (let j = 1; j < mat[0].length; j ++){ if (mat[0][j] == 1 || mat[i][0] == 1){ mat[i][j] = 1; } } } // modify first row if there was any 1 if (row_flag == true){ for (let i = 0; i < mat[0].length; i++){ mat[0][i] = 1; } } // modify first col if there was any 1 if (col_flag == true){ for (let i = 0; i < mat.length; i ++){ mat[i][0] = 1; } }} /* A utility function to print a 2D matrix */function printMatrix(mat){ for (let i = 0; i < mat.length; i ++){ for (let j = 0; j < mat[0].length; j ++){ document.write( mat[i][j] ); } document.write(\"<br>\"); }} // Driver function to test the above functionlet mat=[[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]];document.write(\"Input Matrix :<br>\");printMatrix(mat); modifyMatrix(mat); document.write(\"Matrix After Modification :<br>\");printMatrix(mat); // This code is contributed by ab2127 </script>",
"e": 50179,
"s": 47895,
"text": null
},
{
"code": null,
"e": 50189,
"s": 50179,
"text": "Output: "
},
{
"code": null,
"e": 50262,
"s": 50189,
"text": "Input Matrix :\n1001\n0010\n0000\nMatrix After Modification :\n1111\n1111\n1011"
},
{
"code": null,
"e": 51078,
"s": 50264,
"text": "YouTubeGeeksforGeeks500K subscribersBoolean Matrix | 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 / 13:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=UDWrv63bOXw\" 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": 51086,
"s": 51080,
"text": "jit_t"
},
{
"code": null,
"e": 51092,
"s": 51086,
"text": "ukasp"
},
{
"code": null,
"e": 51105,
"s": 51092,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 51126,
"s": 51105,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 51139,
"s": 51126,
"text": "simmytarika5"
},
{
"code": null,
"e": 51146,
"s": 51139,
"text": "ab2127"
},
{
"code": null,
"e": 51163,
"s": 51146,
"text": "surinderdawra388"
},
{
"code": null,
"e": 51170,
"s": 51163,
"text": "Amazon"
},
{
"code": null,
"e": 51189,
"s": 51170,
"text": "Boomerang Commerce"
},
{
"code": null,
"e": 51197,
"s": 51189,
"text": "FactSet"
},
{
"code": null,
"e": 51212,
"s": 51197,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 51221,
"s": 51212,
"text": "Ola Cabs"
},
{
"code": null,
"e": 51230,
"s": 51221,
"text": "SAP Labs"
},
{
"code": null,
"e": 51237,
"s": 51230,
"text": "VMWare"
},
{
"code": null,
"e": 51244,
"s": 51237,
"text": "Arrays"
},
{
"code": null,
"e": 51251,
"s": 51244,
"text": "Matrix"
},
{
"code": null,
"e": 51258,
"s": 51251,
"text": "VMWare"
},
{
"code": null,
"e": 51273,
"s": 51258,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 51280,
"s": 51273,
"text": "Amazon"
},
{
"code": null,
"e": 51288,
"s": 51280,
"text": "FactSet"
},
{
"code": null,
"e": 51297,
"s": 51288,
"text": "Ola Cabs"
},
{
"code": null,
"e": 51306,
"s": 51297,
"text": "SAP Labs"
},
{
"code": null,
"e": 51325,
"s": 51306,
"text": "Boomerang Commerce"
},
{
"code": null,
"e": 51332,
"s": 51325,
"text": "Arrays"
},
{
"code": null,
"e": 51339,
"s": 51332,
"text": "Matrix"
},
{
"code": null,
"e": 51437,
"s": 51339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51446,
"s": 51437,
"text": "Comments"
},
{
"code": null,
"e": 51459,
"s": 51446,
"text": "Old Comments"
},
{
"code": null,
"e": 51482,
"s": 51459,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 51514,
"s": 51482,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 51535,
"s": 51514,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 51580,
"s": 51535,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 51665,
"s": 51580,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 51700,
"s": 51665,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 51744,
"s": 51700,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 51768,
"s": 51744,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 51799,
"s": 51768,
"text": "Rat in a Maze | Backtracking-2"
}
] |
Working With Browsers Using Selenium Library
|
In this chapter, we will learn how to work with browsers using Robot Framework and Selenium Library in ride.
Project setup in Ride
Import Selenium Library
Test case using Chrome Browser
Test case using Firefox Browser
We will first create a project in Ride to work with browsers. Open ride using ride.py from the command line.
Click on New Project and give name to your project.
The name given is BrowserTestCases. Click OK to save the project. Right-click on the name of the project created and click on New Test Case −
Give name to the test case and click OK.
We are done with the project setup. Now, we will write test cases for the browser.
To work with browsers, we need selenium library to be imported in robot. We can do that as follows −
Go to https://robotframework.org/
On the left side, select the LIBRARIES option.
Select External option from above and it will list you all the libraries available to be used.
Click SeleniumLibrary.
You will be redirected to the github repo as shown below −
For Installation of seleniumlibrary, we can use the command from the github and install it using pip.
pip install --upgrade robotframework-seleniumlibrary
Selenium library gets installed inside the lib folder in python as follows −
Once the installation is done, we have to import the library in Ride as shown in the below steps.
Click on your project on the left side and use Library from Add Import −
Upon clicking Library, a screen will appear wherein you need to enter the library name −
Click OK and the library will get displayed in the settings.
The name given has to match with the name of the folder installed in site-packages. In case the names do not match, the library name will be in red as shown below −
Library import in red is as good as the library does not exist inside python. Now, we have completed selenium library import.
To work with Chrome browser in Robot, we need to first install the drivers for chrome to work with Selenium. The drives are available on Selenium site − https://www.seleniumhq.org/.
Click Download Selenium as in the above screenshot.
In download section, go to Third Party Browser Drivers NOT DEVELOPED by seleniumhq and select Google Chrome driver as shown in highlighted section below
Here we have a list of the various drivers available for browsers. For Chrome, click Google Chrome Driver and download the latest driver as per you operating system.
Click on the latest release. It will display the downloads as per the operating system – windows, linux and mac.
Download the version as per your operating system from the above list. It downloads the zip file. Once the file downloads, unzip it and copy the .exe driver file to python folder.
We are copying the file to C:\Python27\Scripts.
Now we are done installing the driver for chrome. We can get started with writing test case that will open browser and close browser.
Go back to ride and enter the keywords for opening the browser.
Ride helps you with keywords to be used with its built-in tool. Enter the command and press ctrl+spacebar. You will get all the details of the command as shown below
It gives the details of the command and also examples on how to use it. In the test case, we will open the site https://www.tutorialspoint.com/ in chrome and the test case details will be as follows −
Let us now run this test case to see the output −
The test case has passed; we can see the site is opened in chrome browser.
We will add more test cases as follows −
Open Browser − URL − https://www.tutorialspoint.com/ in Chrome browser
Open Browser − URL − https://www.tutorialspoint.com/ in Chrome browser
Capture Page Screenshot − name of the image is page.png
Capture Page Screenshot − name of the image is page.png
Close browser
Close browser
Here are the details of the report and log for above test cases executed.
Install the driver for Firefox and save it in python scripts folder.
We have seen how to install Selenium library and the browser drivers to work with browsers in Robot framework. Using the selenium library keywords, we can open any given link in the browsers and interact with it. The details of the test-case execution are available in the form of reports and logs, which give the time taken for execution.
17 Lectures
1 hours
Musab Zayadneh
11 Lectures
31 mins
Musab Zayadneh
20 Lectures
1.5 hours
Maksym Rudnyi
25 Lectures
3 hours
Kamal Kishor Girdher
16 Lectures
3.5 hours
Onur
10 Lectures
34 mins
Ashraf Said
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2278,
"s": 2169,
"text": "In this chapter, we will learn how to work with browsers using Robot Framework and Selenium Library in ride."
},
{
"code": null,
"e": 2300,
"s": 2278,
"text": "Project setup in Ride"
},
{
"code": null,
"e": 2324,
"s": 2300,
"text": "Import Selenium Library"
},
{
"code": null,
"e": 2355,
"s": 2324,
"text": "Test case using Chrome Browser"
},
{
"code": null,
"e": 2387,
"s": 2355,
"text": "Test case using Firefox Browser"
},
{
"code": null,
"e": 2496,
"s": 2387,
"text": "We will first create a project in Ride to work with browsers. Open ride using ride.py from the command line."
},
{
"code": null,
"e": 2548,
"s": 2496,
"text": "Click on New Project and give name to your project."
},
{
"code": null,
"e": 2690,
"s": 2548,
"text": "The name given is BrowserTestCases. Click OK to save the project. Right-click on the name of the project created and click on New Test Case −"
},
{
"code": null,
"e": 2731,
"s": 2690,
"text": "Give name to the test case and click OK."
},
{
"code": null,
"e": 2814,
"s": 2731,
"text": "We are done with the project setup. Now, we will write test cases for the browser."
},
{
"code": null,
"e": 2915,
"s": 2814,
"text": "To work with browsers, we need selenium library to be imported in robot. We can do that as follows −"
},
{
"code": null,
"e": 2949,
"s": 2915,
"text": "Go to https://robotframework.org/"
},
{
"code": null,
"e": 2996,
"s": 2949,
"text": "On the left side, select the LIBRARIES option."
},
{
"code": null,
"e": 3091,
"s": 2996,
"text": "Select External option from above and it will list you all the libraries available to be used."
},
{
"code": null,
"e": 3114,
"s": 3091,
"text": "Click SeleniumLibrary."
},
{
"code": null,
"e": 3173,
"s": 3114,
"text": "You will be redirected to the github repo as shown below −"
},
{
"code": null,
"e": 3275,
"s": 3173,
"text": "For Installation of seleniumlibrary, we can use the command from the github and install it using pip."
},
{
"code": null,
"e": 3329,
"s": 3275,
"text": "pip install --upgrade robotframework-seleniumlibrary\n"
},
{
"code": null,
"e": 3406,
"s": 3329,
"text": "Selenium library gets installed inside the lib folder in python as follows −"
},
{
"code": null,
"e": 3504,
"s": 3406,
"text": "Once the installation is done, we have to import the library in Ride as shown in the below steps."
},
{
"code": null,
"e": 3577,
"s": 3504,
"text": "Click on your project on the left side and use Library from Add Import −"
},
{
"code": null,
"e": 3666,
"s": 3577,
"text": "Upon clicking Library, a screen will appear wherein you need to enter the library name −"
},
{
"code": null,
"e": 3727,
"s": 3666,
"text": "Click OK and the library will get displayed in the settings."
},
{
"code": null,
"e": 3892,
"s": 3727,
"text": "The name given has to match with the name of the folder installed in site-packages. In case the names do not match, the library name will be in red as shown below −"
},
{
"code": null,
"e": 4018,
"s": 3892,
"text": "Library import in red is as good as the library does not exist inside python. Now, we have completed selenium library import."
},
{
"code": null,
"e": 4200,
"s": 4018,
"text": "To work with Chrome browser in Robot, we need to first install the drivers for chrome to work with Selenium. The drives are available on Selenium site − https://www.seleniumhq.org/."
},
{
"code": null,
"e": 4252,
"s": 4200,
"text": "Click Download Selenium as in the above screenshot."
},
{
"code": null,
"e": 4405,
"s": 4252,
"text": "In download section, go to Third Party Browser Drivers NOT DEVELOPED by seleniumhq and select Google Chrome driver as shown in highlighted section below"
},
{
"code": null,
"e": 4571,
"s": 4405,
"text": "Here we have a list of the various drivers available for browsers. For Chrome, click Google Chrome Driver and download the latest driver as per you operating system."
},
{
"code": null,
"e": 4684,
"s": 4571,
"text": "Click on the latest release. It will display the downloads as per the operating system – windows, linux and mac."
},
{
"code": null,
"e": 4864,
"s": 4684,
"text": "Download the version as per your operating system from the above list. It downloads the zip file. Once the file downloads, unzip it and copy the .exe driver file to python folder."
},
{
"code": null,
"e": 4912,
"s": 4864,
"text": "We are copying the file to C:\\Python27\\Scripts."
},
{
"code": null,
"e": 5046,
"s": 4912,
"text": "Now we are done installing the driver for chrome. We can get started with writing test case that will open browser and close browser."
},
{
"code": null,
"e": 5110,
"s": 5046,
"text": "Go back to ride and enter the keywords for opening the browser."
},
{
"code": null,
"e": 5276,
"s": 5110,
"text": "Ride helps you with keywords to be used with its built-in tool. Enter the command and press ctrl+spacebar. You will get all the details of the command as shown below"
},
{
"code": null,
"e": 5477,
"s": 5276,
"text": "It gives the details of the command and also examples on how to use it. In the test case, we will open the site https://www.tutorialspoint.com/ in chrome and the test case details will be as follows −"
},
{
"code": null,
"e": 5527,
"s": 5477,
"text": "Let us now run this test case to see the output −"
},
{
"code": null,
"e": 5602,
"s": 5527,
"text": "The test case has passed; we can see the site is opened in chrome browser."
},
{
"code": null,
"e": 5643,
"s": 5602,
"text": "We will add more test cases as follows −"
},
{
"code": null,
"e": 5714,
"s": 5643,
"text": "Open Browser − URL − https://www.tutorialspoint.com/ in Chrome browser"
},
{
"code": null,
"e": 5785,
"s": 5714,
"text": "Open Browser − URL − https://www.tutorialspoint.com/ in Chrome browser"
},
{
"code": null,
"e": 5841,
"s": 5785,
"text": "Capture Page Screenshot − name of the image is page.png"
},
{
"code": null,
"e": 5897,
"s": 5841,
"text": "Capture Page Screenshot − name of the image is page.png"
},
{
"code": null,
"e": 5911,
"s": 5897,
"text": "Close browser"
},
{
"code": null,
"e": 5925,
"s": 5911,
"text": "Close browser"
},
{
"code": null,
"e": 5999,
"s": 5925,
"text": "Here are the details of the report and log for above test cases executed."
},
{
"code": null,
"e": 6068,
"s": 5999,
"text": "Install the driver for Firefox and save it in python scripts folder."
},
{
"code": null,
"e": 6408,
"s": 6068,
"text": "We have seen how to install Selenium library and the browser drivers to work with browsers in Robot framework. Using the selenium library keywords, we can open any given link in the browsers and interact with it. The details of the test-case execution are available in the form of reports and logs, which give the time taken for execution."
},
{
"code": null,
"e": 6441,
"s": 6408,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6457,
"s": 6441,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6489,
"s": 6457,
"text": "\n 11 Lectures \n 31 mins\n"
},
{
"code": null,
"e": 6505,
"s": 6489,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6540,
"s": 6505,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6555,
"s": 6540,
"text": " Maksym Rudnyi"
},
{
"code": null,
"e": 6588,
"s": 6555,
"text": "\n 25 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6610,
"s": 6588,
"text": " Kamal Kishor Girdher"
},
{
"code": null,
"e": 6645,
"s": 6610,
"text": "\n 16 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6651,
"s": 6645,
"text": " Onur"
},
{
"code": null,
"e": 6683,
"s": 6651,
"text": "\n 10 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 6696,
"s": 6683,
"text": " Ashraf Said"
},
{
"code": null,
"e": 6703,
"s": 6696,
"text": " Print"
},
{
"code": null,
"e": 6714,
"s": 6703,
"text": " Add Notes"
}
] |
Real-Time Object detection API using Tensorflow and OpenCV | by Daniel Ajisafe | Towards Data Science
|
The amount of visual data in the world today has grown exponentially in the last couple of years and this is largely due to lots of sensors everywhere. Building machine learning models that are capable of localizing and identifying obejcts in a single image remains a core challenge in computer vision. Working to solve this problem has ignited my interest into the field.
As a path to my quest, I discovered Google just released an object detection API. The API has been trained on Microsoft COCO dataset { A dataset of about 300,000 images of 90 commonly found objects} with different trainable detection models .
The higher the mAp (minimum average precision), the better the model
I started by cloning the Tensorflow object detection repository on github. The API is an open source framework built on tensorflow making it easy to construct, train and deploy object detection models.
For this project [am on windows 10, Anaconda 3, Python 3.6], I was concerned with only the installation part and following the example which included
Installing required libraries e.g pillow, lxml etc that comes with installing the latest version of tensorflow using pip(latest version)
Downloading the latest version of protobuf compatible with my system for compilation on google protobuf releases
Cloning the tensorflow/models folder as a zip file
On my Anaconda prompt, ran this command for protobuf compilation without which the example wont work.
# From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=.
I preferred using Spyder as my editor so i made a copy of the notebook in the example and converted it to a python file
Using the pre-trained ssd_mobilenet_v1_coco model (which was fast, though had the least accuracy), I decided to test it out on my own images and the results were amazing !
Trick: test images were taken with my mobile phone and a digital camera. Resizing their dimensions helped the model’s detection.
Now i wanted real-time detection, so i connected OpenCV with my webcam. OpenCV is an open source computer vision library for image processing, machine learning and real-time detection.
And this was the result :
Please dont mind the quality of my webcam 😊, its an old one. I wish i could just pip install upgrade
Using the pre-trained model was really cool but I would love to train the API on my own dataset for super applications. That might not be easy but as it stands, I AM BATTLE READY !!!
You can get the full code on my repository so you can run the files directly and test it out. If you find my post interesting 😍, hit the clap button as much as you can.
Follow me on Twitter: @danielajisafe, @lautechdatasci
|
[
{
"code": null,
"e": 545,
"s": 172,
"text": "The amount of visual data in the world today has grown exponentially in the last couple of years and this is largely due to lots of sensors everywhere. Building machine learning models that are capable of localizing and identifying obejcts in a single image remains a core challenge in computer vision. Working to solve this problem has ignited my interest into the field."
},
{
"code": null,
"e": 788,
"s": 545,
"text": "As a path to my quest, I discovered Google just released an object detection API. The API has been trained on Microsoft COCO dataset { A dataset of about 300,000 images of 90 commonly found objects} with different trainable detection models ."
},
{
"code": null,
"e": 857,
"s": 788,
"text": "The higher the mAp (minimum average precision), the better the model"
},
{
"code": null,
"e": 1059,
"s": 857,
"text": "I started by cloning the Tensorflow object detection repository on github. The API is an open source framework built on tensorflow making it easy to construct, train and deploy object detection models."
},
{
"code": null,
"e": 1209,
"s": 1059,
"text": "For this project [am on windows 10, Anaconda 3, Python 3.6], I was concerned with only the installation part and following the example which included"
},
{
"code": null,
"e": 1346,
"s": 1209,
"text": "Installing required libraries e.g pillow, lxml etc that comes with installing the latest version of tensorflow using pip(latest version)"
},
{
"code": null,
"e": 1459,
"s": 1346,
"text": "Downloading the latest version of protobuf compatible with my system for compilation on google protobuf releases"
},
{
"code": null,
"e": 1510,
"s": 1459,
"text": "Cloning the tensorflow/models folder as a zip file"
},
{
"code": null,
"e": 1612,
"s": 1510,
"text": "On my Anaconda prompt, ran this command for protobuf compilation without which the example wont work."
},
{
"code": null,
"e": 1700,
"s": 1612,
"text": "# From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=."
},
{
"code": null,
"e": 1820,
"s": 1700,
"text": "I preferred using Spyder as my editor so i made a copy of the notebook in the example and converted it to a python file"
},
{
"code": null,
"e": 1992,
"s": 1820,
"text": "Using the pre-trained ssd_mobilenet_v1_coco model (which was fast, though had the least accuracy), I decided to test it out on my own images and the results were amazing !"
},
{
"code": null,
"e": 2121,
"s": 1992,
"text": "Trick: test images were taken with my mobile phone and a digital camera. Resizing their dimensions helped the model’s detection."
},
{
"code": null,
"e": 2306,
"s": 2121,
"text": "Now i wanted real-time detection, so i connected OpenCV with my webcam. OpenCV is an open source computer vision library for image processing, machine learning and real-time detection."
},
{
"code": null,
"e": 2332,
"s": 2306,
"text": "And this was the result :"
},
{
"code": null,
"e": 2433,
"s": 2332,
"text": "Please dont mind the quality of my webcam 😊, its an old one. I wish i could just pip install upgrade"
},
{
"code": null,
"e": 2616,
"s": 2433,
"text": "Using the pre-trained model was really cool but I would love to train the API on my own dataset for super applications. That might not be easy but as it stands, I AM BATTLE READY !!!"
},
{
"code": null,
"e": 2785,
"s": 2616,
"text": "You can get the full code on my repository so you can run the files directly and test it out. If you find my post interesting 😍, hit the clap button as much as you can."
}
] |
Different Ways For Integer to String Conversions in Java - GeeksforGeeks
|
24 Apr, 2022
To convert integer to string in Java, we have some inbuilt methods and classes.
Using toString() method of Integer classUsing valueOf() method of String classUsing Integer(int).toString() method of Integer classUsing DecimalFormat ClassUsing StringBuffer classusing StringBuilder class Using special radix and custom radixUsing concatenation with an empty string
Using toString() method of Integer class
Using valueOf() method of String class
Using Integer(int).toString() method of Integer class
Using DecimalFormat Class
Using StringBuffer class
using StringBuilder class
Using special radix and custom radix
Using concatenation with an empty string
The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved.
Example:
Java
// Java Program to Illustrate// Integer to String Conversions// Using toString() Method of// Integer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integers int a = 1234; int b = -1234; // Converting integer to string // using toString() method String str1 = Integer.toString(a); String str2 = Integer.toString(b); // Printing the above strings that // holds integer System.out.println("String str1 = " + str1); System.out.println("String str2 = " + str2); }}
String str1 = 1234
String str2 = -1234
Example A:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using valueOf() Method of// String class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer input int c = 1234; // Coverting above integer to string // using valueOf() Method String str3 = String.valueOf(c); // Printing the integer stored in above string System.out.println("String str3 = " + str3); }}
String str3 = 1234
Example B:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using valueOf() Method of// String class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Passing input integer as in argument and // storing it in a string String str3 = String.valueOf(1234); // Printing the integer stored in above string System.out.println("String str3 = " + str3); }}
String str3 = 1234
It is different from method 1 as proposed above, as in this method we use an instance of the Integer class to invoke its toString() method.
Example A:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG{ // Main driver method public static void main(String args[]) { // Custom input integer int d = 1234; // Creating an object of Integer class // inside main() method Integer obj = new Integer(d); String str4 = obj.toString(); // Printing the above string // holding integer value System.out.println("String str4 = " + str4); }}
Output:
Example B:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int d = 1234; // Converting integer to string // using toStirng() method of Integer class String str4 = new Integer(d).toString(); // Printing the integer value stored in above string System.out.println("String str4 = " + str4); }}
Output:
Example C:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Passing integer inside object as soon it is // created via parametrised constructor and // converting integer to string using toString() // method and storing it into a String String str4 = new Integer(1234).toString(); // Printing the above string holding integer value System.out.println("String str4 = " + str4); }}
Output:
Output explanation: If the variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int). But if the variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above.
Note: This method is not efficient as an instance of the Integer class is created before conversion is performed.
DecimalFormat is a class that formats a number to a String.
Example A:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using DecimalFormat Class // Importing requried classesimport java.text.DecimalFormat; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer input int e = 12345; // Creating an object of DecimalFormat class // inside main() method DecimalFormat df = new DecimalFormat("#"); // Formatting the integer to string // and storing it in a string String str5 = df.format(e); // Printing the above stored value // inside a string System.out.println(str5); }}
12345
Example B:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using DecimalFormat Class // Importing requried classesimport java.text.DecimalFormat; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer value int e = 12345; // Creating an object of DecimalFormat class // inside main() method DecimalFormat df = new DecimalFormat("#,###"); // Converting above integral value to string String Str5 = df.format(e); // Printing the value stored in above string System.out.println(Str5); }}
Output:
Tip: Using this method, you can specify the number of decimal places and comma separator for readability.
StringBuffer is a class that is used to concatenate multiple values into a String.
Example A:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using StringBuffer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Integer input value int f = 1234; // Creating an object of StringBuffer class StringBuffer sb = new StringBuffer(); sb.append(f); String str6 = sb.toString(); System.out.println("String str6 = " + str6); }}
String str6 = 1234
Example B:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using StringBuffer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { String str6 = new StringBuffer().append(1234).toString(); System.out.println("String str6 = " + str6); }}
Output:
String str6 = 1234
StringBuilder works similarly but is not thread-safe like StringBuffer.
Example A:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using StringBuilder Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer int g = 1234; // Creating an object of StringBuilder class inside // main() StringBuilder sb = new StringBuilder(); sb.append(g); String str7 = sb.toString(); // Printing the value stored in above string System.out.println("String str7 = " + str7); }}
String str7 = 1234
Example B:
Java
// Java Program to Illustrate Different Ways for// Integer to String Conversions// Using StringBuilder Class // Main classclass GFG { // Main driver method public static void main(String args[]) { String str7 = new StringBuilder().append(1234).toString(); // Printing the value stored in above string System.out.println("String str7 = " + str7); }}
String str7 = 1234
Note: All the examples above use the base (radix) 10. Following are convenient methods to convert to binary, octal, and hexadecimal systems. The arbitrary custom number system is also supported.
Example: Binary
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Binary Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer int h = 255; String binaryString = Integer.toBinaryString(h); // Printing the binary number stored in above string System.out.println(binaryString); }}
11111111
Output Explanation: 11111111 is the binary representation of the number 255.
Example: Octal
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Octal Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int i = 255; String octalString = Integer.toOctalString(i); // Printing the octal number stored in above string System.out.println(octalString); }}
377
377 is the octal representation of the number 255.
Example 3: Hexadecimal
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Hexadecimal Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int j = 255; String hexString = Integer.toHexString(j); // Printing the hexadecimal number // stored in above string System.out.println(hexString); }}
ff
The ff is the hexadecimal representation of the number 255.
Way 7-B: Custom Base/Radix
Approach: We are using the toString() method of the Integer class to get it converted into a string where additionally we will be passing a value as an argument known as radix. One can use any other custom base/radix when converting an int to string. In the below example, for illustration purposes, we are considering the base 7 number system.
Example:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Custom Radix // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer value int k = 255; // Setting base as 7, converting integer to string // using toString() method and // storing it into a string String customString = Integer.toString(k, 7); // Printing value stored in above string System.out.println(customString); }}
Output:
513 is the representation of the number 255 when written in the base 7 system.
Approach: Here we will declare an empty string and using the ‘+’ operator, we will simply store the resultant as a string. Now by virtue of this, we are successfully able to append and concatenate these strings.
Example:
Java
// Java Program to Illustrate the// Integer to String Conversions// Using Concatenation with Empty String // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer values int a = 1234; int b = -1234; // Concatenating with empty strings String str1 = "" + a; String str2 = "" + b; // Printing the concatinated strings System.out.println("String str1 = " + str1); System.out.println("String str2 = " + str2); }}
String str1 = 1234
String str2 = -1234
This article is contributed by Amit Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
itsharsh008
sanzzzay
rajatagrawal5
base-conversion
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Interfaces in Java
Operator Overloading in C++
|
[
{
"code": null,
"e": 24334,
"s": 24306,
"text": "\n24 Apr, 2022"
},
{
"code": null,
"e": 24415,
"s": 24334,
"text": "To convert integer to string in Java, we have some inbuilt methods and classes. "
},
{
"code": null,
"e": 24700,
"s": 24415,
"text": "Using toString() method of Integer classUsing valueOf() method of String classUsing Integer(int).toString() method of Integer classUsing DecimalFormat ClassUsing StringBuffer classusing StringBuilder class Using special radix and custom radixUsing concatenation with an empty string "
},
{
"code": null,
"e": 24741,
"s": 24700,
"text": "Using toString() method of Integer class"
},
{
"code": null,
"e": 24780,
"s": 24741,
"text": "Using valueOf() method of String class"
},
{
"code": null,
"e": 24834,
"s": 24780,
"text": "Using Integer(int).toString() method of Integer class"
},
{
"code": null,
"e": 24860,
"s": 24834,
"text": "Using DecimalFormat Class"
},
{
"code": null,
"e": 24885,
"s": 24860,
"text": "Using StringBuffer class"
},
{
"code": null,
"e": 24912,
"s": 24885,
"text": "using StringBuilder class "
},
{
"code": null,
"e": 24949,
"s": 24912,
"text": "Using special radix and custom radix"
},
{
"code": null,
"e": 24992,
"s": 24949,
"text": "Using concatenation with an empty string "
},
{
"code": null,
"e": 25218,
"s": 24992,
"text": "The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved. "
},
{
"code": null,
"e": 25227,
"s": 25218,
"text": "Example:"
},
{
"code": null,
"e": 25232,
"s": 25227,
"text": "Java"
},
{
"code": "// Java Program to Illustrate// Integer to String Conversions// Using toString() Method of// Integer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integers int a = 1234; int b = -1234; // Converting integer to string // using toString() method String str1 = Integer.toString(a); String str2 = Integer.toString(b); // Printing the above strings that // holds integer System.out.println(\"String str1 = \" + str1); System.out.println(\"String str2 = \" + str2); }}",
"e": 25848,
"s": 25232,
"text": null
},
{
"code": null,
"e": 25887,
"s": 25848,
"text": "String str1 = 1234\nString str2 = -1234"
},
{
"code": null,
"e": 25898,
"s": 25887,
"text": "Example A:"
},
{
"code": null,
"e": 25903,
"s": 25898,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using valueOf() Method of// String class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer input int c = 1234; // Coverting above integer to string // using valueOf() Method String str3 = String.valueOf(c); // Printing the integer stored in above string System.out.println(\"String str3 = \" + str3); }}",
"e": 26368,
"s": 25903,
"text": null
},
{
"code": null,
"e": 26387,
"s": 26368,
"text": "String str3 = 1234"
},
{
"code": null,
"e": 26398,
"s": 26387,
"text": "Example B:"
},
{
"code": null,
"e": 26403,
"s": 26398,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using valueOf() Method of// String class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Passing input integer as in argument and // storing it in a string String str3 = String.valueOf(1234); // Printing the integer stored in above string System.out.println(\"String str3 = \" + str3); }}",
"e": 26852,
"s": 26403,
"text": null
},
{
"code": null,
"e": 26871,
"s": 26852,
"text": "String str3 = 1234"
},
{
"code": null,
"e": 27012,
"s": 26871,
"text": "It is different from method 1 as proposed above, as in this method we use an instance of the Integer class to invoke its toString() method. "
},
{
"code": null,
"e": 27023,
"s": 27012,
"text": "Example A:"
},
{
"code": null,
"e": 27028,
"s": 27023,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG{ // Main driver method public static void main(String args[]) { // Custom input integer int d = 1234; // Creating an object of Integer class // inside main() method Integer obj = new Integer(d); String str4 = obj.toString(); // Printing the above string // holding integer value System.out.println(\"String str4 = \" + str4); }}",
"e": 27573,
"s": 27028,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27573,
"text": "Output:"
},
{
"code": null,
"e": 27592,
"s": 27581,
"text": "Example B:"
},
{
"code": null,
"e": 27597,
"s": 27592,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int d = 1234; // Converting integer to string // using toStirng() method of Integer class String str4 = new Integer(d).toString(); // Printing the integer value stored in above string System.out.println(\"String str4 = \" + str4); }}",
"e": 28159,
"s": 27597,
"text": null
},
{
"code": null,
"e": 28167,
"s": 28159,
"text": "Output:"
},
{
"code": null,
"e": 28178,
"s": 28167,
"text": "Example C:"
},
{
"code": null,
"e": 28183,
"s": 28178,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Integer(int).toString() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Passing integer inside object as soon it is // created via parametrised constructor and // converting integer to string using toString() // method and storing it into a String String str4 = new Integer(1234).toString(); // Printing the above string holding integer value System.out.println(\"String str4 = \" + str4); }}",
"e": 28810,
"s": 28183,
"text": null
},
{
"code": null,
"e": 28818,
"s": 28810,
"text": "Output:"
},
{
"code": null,
"e": 29112,
"s": 28818,
"text": "Output explanation: If the variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int). But if the variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above. "
},
{
"code": null,
"e": 29226,
"s": 29112,
"text": "Note: This method is not efficient as an instance of the Integer class is created before conversion is performed."
},
{
"code": null,
"e": 29287,
"s": 29226,
"text": "DecimalFormat is a class that formats a number to a String. "
},
{
"code": null,
"e": 29298,
"s": 29287,
"text": "Example A:"
},
{
"code": null,
"e": 29303,
"s": 29298,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using DecimalFormat Class // Importing requried classesimport java.text.DecimalFormat; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer input int e = 12345; // Creating an object of DecimalFormat class // inside main() method DecimalFormat df = new DecimalFormat(\"#\"); // Formatting the integer to string // and storing it in a string String str5 = df.format(e); // Printing the above stored value // inside a string System.out.println(str5); }}",
"e": 29967,
"s": 29303,
"text": null
},
{
"code": null,
"e": 29973,
"s": 29967,
"text": "12345"
},
{
"code": null,
"e": 29984,
"s": 29973,
"text": "Example B:"
},
{
"code": null,
"e": 29989,
"s": 29984,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using DecimalFormat Class // Importing requried classesimport java.text.DecimalFormat; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer value int e = 12345; // Creating an object of DecimalFormat class // inside main() method DecimalFormat df = new DecimalFormat(\"#,###\"); // Converting above integral value to string String Str5 = df.format(e); // Printing the value stored in above string System.out.println(Str5); }}",
"e": 30612,
"s": 29989,
"text": null
},
{
"code": null,
"e": 30621,
"s": 30612,
"text": "Output: "
},
{
"code": null,
"e": 30727,
"s": 30621,
"text": "Tip: Using this method, you can specify the number of decimal places and comma separator for readability."
},
{
"code": null,
"e": 30811,
"s": 30727,
"text": "StringBuffer is a class that is used to concatenate multiple values into a String. "
},
{
"code": null,
"e": 30822,
"s": 30811,
"text": "Example A:"
},
{
"code": null,
"e": 30827,
"s": 30822,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using StringBuffer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Integer input value int f = 1234; // Creating an object of StringBuffer class StringBuffer sb = new StringBuffer(); sb.append(f); String str6 = sb.toString(); System.out.println(\"String str6 = \" + str6); }}",
"e": 31282,
"s": 30827,
"text": null
},
{
"code": null,
"e": 31301,
"s": 31282,
"text": "String str6 = 1234"
},
{
"code": null,
"e": 31312,
"s": 31301,
"text": "Example B:"
},
{
"code": null,
"e": 31317,
"s": 31312,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using StringBuffer Class // Main classclass GFG { // Main driver method public static void main(String args[]) { String str6 = new StringBuffer().append(1234).toString(); System.out.println(\"String str6 = \" + str6); }}",
"e": 31642,
"s": 31317,
"text": null
},
{
"code": null,
"e": 31651,
"s": 31642,
"text": "Output: "
},
{
"code": null,
"e": 31670,
"s": 31651,
"text": "String str6 = 1234"
},
{
"code": null,
"e": 31743,
"s": 31670,
"text": "StringBuilder works similarly but is not thread-safe like StringBuffer. "
},
{
"code": null,
"e": 31754,
"s": 31743,
"text": "Example A:"
},
{
"code": null,
"e": 31759,
"s": 31754,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using StringBuilder Class // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer int g = 1234; // Creating an object of StringBuilder class inside // main() StringBuilder sb = new StringBuilder(); sb.append(g); String str7 = sb.toString(); // Printing the value stored in above string System.out.println(\"String str7 = \" + str7); }}",
"e": 32291,
"s": 31759,
"text": null
},
{
"code": null,
"e": 32310,
"s": 32291,
"text": "String str7 = 1234"
},
{
"code": null,
"e": 32321,
"s": 32310,
"text": "Example B:"
},
{
"code": null,
"e": 32326,
"s": 32321,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Different Ways for// Integer to String Conversions// Using StringBuilder Class // Main classclass GFG { // Main driver method public static void main(String args[]) { String str7 = new StringBuilder().append(1234).toString(); // Printing the value stored in above string System.out.println(\"String str7 = \" + str7); }}",
"e": 32721,
"s": 32326,
"text": null
},
{
"code": null,
"e": 32740,
"s": 32721,
"text": "String str7 = 1234"
},
{
"code": null,
"e": 32936,
"s": 32740,
"text": "Note: All the examples above use the base (radix) 10. Following are convenient methods to convert to binary, octal, and hexadecimal systems. The arbitrary custom number system is also supported. "
},
{
"code": null,
"e": 32952,
"s": 32936,
"text": "Example: Binary"
},
{
"code": null,
"e": 32957,
"s": 32952,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Binary Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer int h = 255; String binaryString = Integer.toBinaryString(h); // Printing the binary number stored in above string System.out.println(binaryString); }}",
"e": 33369,
"s": 32957,
"text": null
},
{
"code": null,
"e": 33378,
"s": 33369,
"text": "11111111"
},
{
"code": null,
"e": 33455,
"s": 33378,
"text": "Output Explanation: 11111111 is the binary representation of the number 255."
},
{
"code": null,
"e": 33471,
"s": 33455,
"text": "Example: Octal "
},
{
"code": null,
"e": 33476,
"s": 33471,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Octal Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int i = 255; String octalString = Integer.toOctalString(i); // Printing the octal number stored in above string System.out.println(octalString); }}",
"e": 33870,
"s": 33476,
"text": null
},
{
"code": null,
"e": 33874,
"s": 33870,
"text": "377"
},
{
"code": null,
"e": 33926,
"s": 33874,
"text": "377 is the octal representation of the number 255. "
},
{
"code": null,
"e": 33950,
"s": 33926,
"text": "Example 3: Hexadecimal "
},
{
"code": null,
"e": 33955,
"s": 33950,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Special Radix In Hexadecimal Numbers // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input integer int j = 255; String hexString = Integer.toHexString(j); // Printing the hexadecimal number // stored in above string System.out.println(hexString); }}",
"e": 34385,
"s": 33955,
"text": null
},
{
"code": null,
"e": 34388,
"s": 34385,
"text": "ff"
},
{
"code": null,
"e": 34448,
"s": 34388,
"text": "The ff is the hexadecimal representation of the number 255."
},
{
"code": null,
"e": 34476,
"s": 34448,
"text": "Way 7-B: Custom Base/Radix "
},
{
"code": null,
"e": 34822,
"s": 34476,
"text": "Approach: We are using the toString() method of the Integer class to get it converted into a string where additionally we will be passing a value as an argument known as radix. One can use any other custom base/radix when converting an int to string. In the below example, for illustration purposes, we are considering the base 7 number system. "
},
{
"code": null,
"e": 34831,
"s": 34822,
"text": "Example:"
},
{
"code": null,
"e": 34836,
"s": 34831,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Custom Radix // Main classclass GFG { // Main driver method public static void main(String args[]) { // Input integer value int k = 255; // Setting base as 7, converting integer to string // using toString() method and // storing it into a string String customString = Integer.toString(k, 7); // Printing value stored in above string System.out.println(customString); }}",
"e": 35352,
"s": 34836,
"text": null
},
{
"code": null,
"e": 35360,
"s": 35352,
"text": "Output:"
},
{
"code": null,
"e": 35439,
"s": 35360,
"text": "513 is the representation of the number 255 when written in the base 7 system."
},
{
"code": null,
"e": 35652,
"s": 35439,
"text": "Approach: Here we will declare an empty string and using the ‘+’ operator, we will simply store the resultant as a string. Now by virtue of this, we are successfully able to append and concatenate these strings. "
},
{
"code": null,
"e": 35661,
"s": 35652,
"text": "Example:"
},
{
"code": null,
"e": 35666,
"s": 35661,
"text": "Java"
},
{
"code": "// Java Program to Illustrate the// Integer to String Conversions// Using Concatenation with Empty String // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom integer values int a = 1234; int b = -1234; // Concatenating with empty strings String str1 = \"\" + a; String str2 = \"\" + b; // Printing the concatinated strings System.out.println(\"String str1 = \" + str1); System.out.println(\"String str2 = \" + str2); }}",
"e": 36202,
"s": 35666,
"text": null
},
{
"code": null,
"e": 36241,
"s": 36202,
"text": "String str1 = 1234\nString str2 = -1234"
},
{
"code": null,
"e": 36665,
"s": 36241,
"text": "This article is contributed by Amit Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36678,
"s": 36665,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 36690,
"s": 36678,
"text": "itsharsh008"
},
{
"code": null,
"e": 36699,
"s": 36690,
"text": "sanzzzay"
},
{
"code": null,
"e": 36713,
"s": 36699,
"text": "rajatagrawal5"
},
{
"code": null,
"e": 36729,
"s": 36713,
"text": "base-conversion"
},
{
"code": null,
"e": 36734,
"s": 36729,
"text": "Java"
},
{
"code": null,
"e": 36753,
"s": 36734,
"text": "School Programming"
},
{
"code": null,
"e": 36758,
"s": 36753,
"text": "Java"
},
{
"code": null,
"e": 36856,
"s": 36758,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36865,
"s": 36856,
"text": "Comments"
},
{
"code": null,
"e": 36878,
"s": 36865,
"text": "Old Comments"
},
{
"code": null,
"e": 36908,
"s": 36878,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 36927,
"s": 36908,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 36978,
"s": 36927,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 36996,
"s": 36978,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 37027,
"s": 36996,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 37045,
"s": 37027,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37061,
"s": 37045,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37080,
"s": 37061,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 37099,
"s": 37080,
"text": "Interfaces in Java"
}
] |
Modulus of a Complex Number - GeeksforGeeks
|
15 Apr, 2020
Given a complex number z, the task is to determine the modulus of this complex number.
Note: Given a complex number z = a + ib the modulus is denoted by |z| and is defined as
Examples:
Input: z = 3 + 4iOutput: 5|z| = (32 + 42)1/2 = (9 + 16)1/2 = 5
Input: z = 6 – 8iOutput: 10Explanation:|z| = (62 + (-8)2)1/2 = (36 + 64)1/2 = 10
Approach: For the given complex number z = x + iy:
Find the real and imaginary parts, x and y respectively.If z = x +iy
Real part = x
Imaginary part = y
Find the square of x and y separately.Square of Real part = x2
Square of Imaginary part = y2
Find the sum of the computed squares.Sum = Square of Real part
+ Square of Imaginary part
= x2 + y2
Find the square root of the computed sum. This will be the modulus of the given complex number
Find the real and imaginary parts, x and y respectively.If z = x +iy
Real part = x
Imaginary part = y
If z = x +iy
Real part = x
Imaginary part = y
Find the square of x and y separately.Square of Real part = x2
Square of Imaginary part = y2
Square of Real part = x2
Square of Imaginary part = y2
Find the sum of the computed squares.Sum = Square of Real part
+ Square of Imaginary part
= x2 + y2
Sum = Square of Real part
+ Square of Imaginary part
= x2 + y2
Find the square root of the computed sum. This will be the modulus of the given complex number
Below is the implementation of the above approach:
C++
Java
Python 3
C#
// C++ program to find the// Modulus of a Complex Number #include <bits/stdc++.h>using namespace std; // Function to find modulus// of a complex numbervoid findModulo(string s){ int l = s.length(); int i, modulus = 0; // Storing the index of '+' if (s.find('+') < l) { i = s.find('+'); } // Storing the index of '-' else { i = s.find('-'); } // Finding the real part // of the complex number string real = s.substr(0, i); // Finding the imaginary part // of the complex number string imaginary = s.substr(i + 1, l - 1); int x = stoi(real); int y = stoi(imaginary); cout << sqrt(x * x + y * y) << "\n";} // Driver codeint main(){ string s = "3+4i"; findModulo(s); return 0;}
// Java program to find the// Modulus of a Complex Numberimport java.util.*; class GFG{ // Function to find modulus// of a complex numberstatic void findModulo(String s){ int l = s.length(); int i, modulus = 0; // Storing the index of '+' if (s.contains("+")) { i = s.indexOf("+"); } // Storing the index of '-' else { i = s.indexOf("-"); } // Finding the real part // of the complex number String real = s.substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.substring(i + 1, l-1); int x = Integer.parseInt(real); int y = Integer.parseInt(imaginary); System.out.print(Math.sqrt(x * x + y * y)+ "\n");} // Driver codepublic static void main(String[] args){ String s = "3+4i"; findModulo(s);}} // This code is contributed by Rajput-Ji
# Python 3 program to find the# Modulus of a Complex Numberfrom math import sqrt # Function to find modulus# of a complex numberdef findModulo(s): l = len(s) modulus = 0 # Storing the index of '+' if ( '+' in s ): i = s.index('+') # Storing the index of '-' else: i = s.index('-') # Finding the real part # of the complex number real = s[0:i] # Finding the imaginary part # of the complex number imaginary = s[i + 1:l - 1] x = int(real) y = int(imaginary) print(int(sqrt(x * x + y * y))) # Driver codeif __name__ == '__main__': s = "3+4i" findModulo(s) # This code is contributed by Surendra_Gangwar
// C# program to find the// Modulus of a Complex Numberusing System; public class GFG{ // Function to find modulus// of a complex numberstatic void findModulo(String s){ int l = s.Length; int i; // Storing the index of '+' if (s.Contains("+")) { i = s.IndexOf("+"); } // Storing the index of '-' else { i = s.IndexOf("-"); } // Finding the real part // of the complex number String real = s.Substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.Substring(i + 1, l-i - 2); int x = Int32.Parse(real); int y = Int32.Parse(imaginary); Console.Write(Math.Sqrt(x * x + y * y)+ "\n");} // Driver codepublic static void Main(String[] args){ String s = "3+4i"; findModulo(s);}}// This code contributed by sapnasingh4991
5
SURENDRA_GANGWAR
Rajput-Ji
sapnasingh4991
Numbers
Geometric
Mathematical
School Programming
Mathematical
Numbers
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
Equation of circle when three points on the circle are given
Program to find slope of a line
Program to find line passing through 2 Points
Maximum Manhattan distance between a distinct pair from N coordinates
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": 26671,
"s": 26643,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 26758,
"s": 26671,
"text": "Given a complex number z, the task is to determine the modulus of this complex number."
},
{
"code": null,
"e": 26847,
"s": 26758,
"text": "Note: Given a complex number z = a + ib the modulus is denoted by |z| and is defined as "
},
{
"code": null,
"e": 26857,
"s": 26847,
"text": "Examples:"
},
{
"code": null,
"e": 26920,
"s": 26857,
"text": "Input: z = 3 + 4iOutput: 5|z| = (32 + 42)1/2 = (9 + 16)1/2 = 5"
},
{
"code": null,
"e": 27001,
"s": 26920,
"text": "Input: z = 6 – 8iOutput: 10Explanation:|z| = (62 + (-8)2)1/2 = (36 + 64)1/2 = 10"
},
{
"code": null,
"e": 27052,
"s": 27001,
"text": "Approach: For the given complex number z = x + iy:"
},
{
"code": null,
"e": 27454,
"s": 27052,
"text": "Find the real and imaginary parts, x and y respectively.If z = x +iy\n\nReal part = x\nImaginary part = y\nFind the square of x and y separately.Square of Real part = x2\nSquare of Imaginary part = y2\nFind the sum of the computed squares.Sum = Square of Real part \n + Square of Imaginary part\n = x2 + y2\nFind the square root of the computed sum. This will be the modulus of the given complex number"
},
{
"code": null,
"e": 27558,
"s": 27454,
"text": "Find the real and imaginary parts, x and y respectively.If z = x +iy\n\nReal part = x\nImaginary part = y\n"
},
{
"code": null,
"e": 27606,
"s": 27558,
"text": "If z = x +iy\n\nReal part = x\nImaginary part = y\n"
},
{
"code": null,
"e": 27700,
"s": 27606,
"text": "Find the square of x and y separately.Square of Real part = x2\nSquare of Imaginary part = y2\n"
},
{
"code": null,
"e": 27756,
"s": 27700,
"text": "Square of Real part = x2\nSquare of Imaginary part = y2\n"
},
{
"code": null,
"e": 27868,
"s": 27756,
"text": "Find the sum of the computed squares.Sum = Square of Real part \n + Square of Imaginary part\n = x2 + y2\n"
},
{
"code": null,
"e": 27943,
"s": 27868,
"text": "Sum = Square of Real part \n + Square of Imaginary part\n = x2 + y2\n"
},
{
"code": null,
"e": 28038,
"s": 27943,
"text": "Find the square root of the computed sum. This will be the modulus of the given complex number"
},
{
"code": null,
"e": 28089,
"s": 28038,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28093,
"s": 28089,
"text": "C++"
},
{
"code": null,
"e": 28098,
"s": 28093,
"text": "Java"
},
{
"code": null,
"e": 28107,
"s": 28098,
"text": "Python 3"
},
{
"code": null,
"e": 28110,
"s": 28107,
"text": "C#"
},
{
"code": "// C++ program to find the// Modulus of a Complex Number #include <bits/stdc++.h>using namespace std; // Function to find modulus// of a complex numbervoid findModulo(string s){ int l = s.length(); int i, modulus = 0; // Storing the index of '+' if (s.find('+') < l) { i = s.find('+'); } // Storing the index of '-' else { i = s.find('-'); } // Finding the real part // of the complex number string real = s.substr(0, i); // Finding the imaginary part // of the complex number string imaginary = s.substr(i + 1, l - 1); int x = stoi(real); int y = stoi(imaginary); cout << sqrt(x * x + y * y) << \"\\n\";} // Driver codeint main(){ string s = \"3+4i\"; findModulo(s); return 0;}",
"e": 28875,
"s": 28110,
"text": null
},
{
"code": "// Java program to find the// Modulus of a Complex Numberimport java.util.*; class GFG{ // Function to find modulus// of a complex numberstatic void findModulo(String s){ int l = s.length(); int i, modulus = 0; // Storing the index of '+' if (s.contains(\"+\")) { i = s.indexOf(\"+\"); } // Storing the index of '-' else { i = s.indexOf(\"-\"); } // Finding the real part // of the complex number String real = s.substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.substring(i + 1, l-1); int x = Integer.parseInt(real); int y = Integer.parseInt(imaginary); System.out.print(Math.sqrt(x * x + y * y)+ \"\\n\");} // Driver codepublic static void main(String[] args){ String s = \"3+4i\"; findModulo(s);}} // This code is contributed by Rajput-Ji",
"e": 29746,
"s": 28875,
"text": null
},
{
"code": "# Python 3 program to find the# Modulus of a Complex Numberfrom math import sqrt # Function to find modulus# of a complex numberdef findModulo(s): l = len(s) modulus = 0 # Storing the index of '+' if ( '+' in s ): i = s.index('+') # Storing the index of '-' else: i = s.index('-') # Finding the real part # of the complex number real = s[0:i] # Finding the imaginary part # of the complex number imaginary = s[i + 1:l - 1] x = int(real) y = int(imaginary) print(int(sqrt(x * x + y * y))) # Driver codeif __name__ == '__main__': s = \"3+4i\" findModulo(s) # This code is contributed by Surendra_Gangwar",
"e": 30428,
"s": 29746,
"text": null
},
{
"code": "// C# program to find the// Modulus of a Complex Numberusing System; public class GFG{ // Function to find modulus// of a complex numberstatic void findModulo(String s){ int l = s.Length; int i; // Storing the index of '+' if (s.Contains(\"+\")) { i = s.IndexOf(\"+\"); } // Storing the index of '-' else { i = s.IndexOf(\"-\"); } // Finding the real part // of the complex number String real = s.Substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.Substring(i + 1, l-i - 2); int x = Int32.Parse(real); int y = Int32.Parse(imaginary); Console.Write(Math.Sqrt(x * x + y * y)+ \"\\n\");} // Driver codepublic static void Main(String[] args){ String s = \"3+4i\"; findModulo(s);}}// This code contributed by sapnasingh4991",
"e": 31283,
"s": 30428,
"text": null
},
{
"code": null,
"e": 31286,
"s": 31283,
"text": "5\n"
},
{
"code": null,
"e": 31303,
"s": 31286,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31313,
"s": 31303,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31328,
"s": 31313,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 31336,
"s": 31328,
"text": "Numbers"
},
{
"code": null,
"e": 31346,
"s": 31336,
"text": "Geometric"
},
{
"code": null,
"e": 31359,
"s": 31346,
"text": "Mathematical"
},
{
"code": null,
"e": 31378,
"s": 31359,
"text": "School Programming"
},
{
"code": null,
"e": 31391,
"s": 31378,
"text": "Mathematical"
},
{
"code": null,
"e": 31399,
"s": 31391,
"text": "Numbers"
},
{
"code": null,
"e": 31409,
"s": 31399,
"text": "Geometric"
},
{
"code": null,
"e": 31507,
"s": 31409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31573,
"s": 31507,
"text": "Haversine formula to find distance between two points on a sphere"
},
{
"code": null,
"e": 31634,
"s": 31573,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 31666,
"s": 31634,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 31712,
"s": 31666,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 31782,
"s": 31712,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 31812,
"s": 31782,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31872,
"s": 31812,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31887,
"s": 31872,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31930,
"s": 31887,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to find Gradient of a Function using Python? - GeeksforGeeks
|
28 Jul, 2020
The gradient of a function simply means the rate of change of a function. We will use numdifftools to find Gradient of a function.
Examples:
Input : x^4+x+1
Output :Gradient of x^4+x+1 at x=1 is 4.99
Input :(1-x)^2+(y-x^2)^2
Output :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.]
Approach:
For Single variable function: For single variable function we can define directly using “lambda” as stated below:-g=lambda x:(x**4)+x+1
g=lambda x:(x**4)+x+1
For Multi-Variable Function: We will define a function using “def” and pass an array “x” and it will return multivariate function as described below:-def rosen(x):
return (1-x[0])**2 +(x[1]-x[0]**2)**2where ‘rosen’ is name of function and ‘x’ is passed as array. x[0] and x[1] are array elements in the same order as defined in array.i.e Function defined above is (1-x^2)+(y-x^2)^2.
def rosen(x):
return (1-x[0])**2 +(x[1]-x[0]**2)**2
where ‘rosen’ is name of function and ‘x’ is passed as array. x[0] and x[1] are array elements in the same order as defined in array.i.e Function defined above is (1-x^2)+(y-x^2)^2.
Similarly, We can define function of more than 2-variables also in same manner as stated above.
Method used: Gradient()Syntax:
nd.Gradient(func_name)
Example:
import numdifftools as nd g = lambda x:(x**4)+x + 1grad1 = nd.Gradient(g)([1])print("Gradient of x ^ 4 + x+1 at x = 1 is ", grad1) def rosen(x): return (1-x[0])**2 +(x[1]-x[0]**2)**2 grad2 = nd.Gradient(rosen)([1, 2])print("Gradient of (1-x ^ 2)+(y-x ^ 2)^2 at (1, 2) is ", grad2)
Output:
Gradient of x^4+x+1 at x=1 is 4.999999999999998
Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.]
python-utility
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": 25915,
"s": 25887,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 26046,
"s": 25915,
"text": "The gradient of a function simply means the rate of change of a function. We will use numdifftools to find Gradient of a function."
},
{
"code": null,
"e": 26056,
"s": 26046,
"text": "Examples:"
},
{
"code": null,
"e": 26206,
"s": 26056,
"text": "Input : x^4+x+1\nOutput :Gradient of x^4+x+1 at x=1 is 4.99\n\nInput :(1-x)^2+(y-x^2)^2\nOutput :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.] \n"
},
{
"code": null,
"e": 26216,
"s": 26206,
"text": "Approach:"
},
{
"code": null,
"e": 26352,
"s": 26216,
"text": "For Single variable function: For single variable function we can define directly using “lambda” as stated below:-g=lambda x:(x**4)+x+1"
},
{
"code": null,
"e": 26374,
"s": 26352,
"text": "g=lambda x:(x**4)+x+1"
},
{
"code": null,
"e": 26762,
"s": 26374,
"text": "For Multi-Variable Function: We will define a function using “def” and pass an array “x” and it will return multivariate function as described below:-def rosen(x): \n return (1-x[0])**2 +(x[1]-x[0]**2)**2where ‘rosen’ is name of function and ‘x’ is passed as array. x[0] and x[1] are array elements in the same order as defined in array.i.e Function defined above is (1-x^2)+(y-x^2)^2."
},
{
"code": null,
"e": 26819,
"s": 26762,
"text": "def rosen(x): \n return (1-x[0])**2 +(x[1]-x[0]**2)**2"
},
{
"code": null,
"e": 27001,
"s": 26819,
"text": "where ‘rosen’ is name of function and ‘x’ is passed as array. x[0] and x[1] are array elements in the same order as defined in array.i.e Function defined above is (1-x^2)+(y-x^2)^2."
},
{
"code": null,
"e": 27097,
"s": 27001,
"text": "Similarly, We can define function of more than 2-variables also in same manner as stated above."
},
{
"code": null,
"e": 27128,
"s": 27097,
"text": "Method used: Gradient()Syntax:"
},
{
"code": null,
"e": 27151,
"s": 27128,
"text": "nd.Gradient(func_name)"
},
{
"code": null,
"e": 27160,
"s": 27151,
"text": "Example:"
},
{
"code": "import numdifftools as nd g = lambda x:(x**4)+x + 1grad1 = nd.Gradient(g)([1])print(\"Gradient of x ^ 4 + x+1 at x = 1 is \", grad1) def rosen(x): return (1-x[0])**2 +(x[1]-x[0]**2)**2 grad2 = nd.Gradient(rosen)([1, 2])print(\"Gradient of (1-x ^ 2)+(y-x ^ 2)^2 at (1, 2) is \", grad2)",
"e": 27450,
"s": 27160,
"text": null
},
{
"code": null,
"e": 27458,
"s": 27450,
"text": "Output:"
},
{
"code": null,
"e": 27561,
"s": 27458,
"text": "Gradient of x^4+x+1 at x=1 is 4.999999999999998\nGradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4. 2.]"
},
{
"code": null,
"e": 27576,
"s": 27561,
"text": "python-utility"
},
{
"code": null,
"e": 27583,
"s": 27576,
"text": "Python"
},
{
"code": null,
"e": 27681,
"s": 27583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27699,
"s": 27681,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27734,
"s": 27699,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27766,
"s": 27734,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27788,
"s": 27766,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27830,
"s": 27788,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27860,
"s": 27830,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27886,
"s": 27860,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27915,
"s": 27886,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27959,
"s": 27915,
"text": "Reading and Writing to text files in Python"
}
] |
How to play videos in Android from assets folder or raw folder?
|
This example demonstrates how do I play videos in Android from the assets folder or raw folder in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="8dp"
tools:context=".MainActivity">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</VideoView>
</LinearLayout>
Step 3 − Create a new android resource folder(raw) and copy-paste your video file in that folder.
Step 4 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.videoView);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.videoplayback));
videoView.start();
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "This example demonstrates how do I play videos in Android from the assets folder or raw folder in android."
},
{
"code": null,
"e": 1298,
"s": 1169,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1363,
"s": 1298,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1876,
"s": 1363,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n<VideoView\n android:id=\"@+id/videoView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n</VideoView>\n</LinearLayout>"
},
{
"code": null,
"e": 1974,
"s": 1876,
"text": "Step 3 − Create a new android resource folder(raw) and copy-paste your video file in that folder."
},
{
"code": null,
"e": 2031,
"s": 1974,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2787,
"s": 2031,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.widget.MediaController;\nimport android.widget.VideoView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n VideoView videoView = findViewById(R.id.videoView);\n MediaController mediaController = new MediaController(this);\n mediaController.setAnchorView(videoView);\n videoView.setMediaController(mediaController);\n videoView.setVideoURI(Uri.parse(\"android.resource://\" + getPackageName() + \"/\" +\n R.raw.videoplayback));\n videoView.start();\n }\n}"
},
{
"code": null,
"e": 2842,
"s": 2787,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3515,
"s": 2842,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3870,
"s": 3515,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Largest number with given sum | Practice | GeeksforGeeks
|
Geek lost the password of his super locker. He remembers the number of digits N as well as the sum S of all the digits of his password. He know that his password is the largest number of N digits that can be made with given sum S. As he is busy doing his homework, help him retrieving his password.
Example 1:
Input:
N = 5, S = 12
Output:
93000
Explanation:
Sum of elements is 12. Largest possible
5 digit number is 93000 with sum 12.
Example 2:
Input:
N = 3, S = 29
Output:
-1
Explanation:
There is no such three digit number
whose sum is 29.
Your Task :
You don't need to read input or print anything. Your task is to complete the function largestNumber() which takes 2 integers N and S as input parameters and returns the password in the form of string, else return "-1" in the form of string.
Constraints:
1 ≤ N ≤ 104
0 ≤ S ≤ 9*104
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
0
shaank181816 hours ago
Java Code
class Solution
{
//Function to return the largest possible number of n digits
//with sum equal to given sum.
static String largestNumber(int n, int sum)
{
String ans = "";
if(sum>9*n){
return "-1";
}
for(int i = 0;i < n ;i++){
if(sum>=9){
sum -= 9;
ans = ans + 9;
}
else if(sum<9){
ans = ans + sum;
sum = sum - sum;
}
}
return ans;
}
}
0
princejee20191 month ago
C++ || EASY TO UNDERSTAND
string largestNumber(int n, int sum){ string res =""; int ans =0; if(sum>(n*9))return "-1"; int d = sum/9; for(int i =0;i<d;i++){ res+='9'; } if(sum%9!=0){ res+='0'+sum%9; } while(res.size()!=n){ res+='0'; } return res; }
0
praveenkumar1391521 month ago
def largestNum(self,n,s): k='' if s>n*9: return -1 else: while s>9: k=k+str(9) s=s-9 else: k=k+str(s) while len(k)!=n: k=k+"0" return k
+1
naveenapatnaik1 month ago
Java SOLUTION!!
static String largestNumber(int n, int sum) { // add your code here if(sum > n*9){ return "-1"; } String str=""; for(int i=0; i<n; i++){ if(sum>=9){ str+="9"; sum-=9; } else{ str+=sum; sum=0; } } return str; }
0
ayushnautiyal11101 month ago
string largestNumber(int n, int sum) { if(sum>n*9){ return "-1"; } else{ string ans=""; while(sum){ if(sum>=9){ sum-=9; ans+="9"; } else if(sum>=8){ sum-=8; ans+="8"; } else if(sum>=7){ sum-=7; ans+="7"; } else if(sum>=6){ sum-=6; ans+="6"; } else if(sum>=5){ sum-=5; ans+="5"; } else if(sum>=4){ sum-=4; ans+="4"; } else if(sum>=3){ sum-=3; ans+="3"; } else if(sum>=2){ sum-=2; ans+="2"; } else if(sum>=1){ sum-=1; ans+="1"; } } if(ans.length()!=n){ int diff=n-ans.length(); while(diff--){ ans+="0"; } } return ans; } }
0
abhinavmaurya2022 months ago
class Solution: def largestNum(self,n,s): if(9*n < s): return "-1" sumnum = 9*n i = n - 1 strnum = [9]*n while(sumnum != s): sumnum -= 1 strnum[i] = strnum[i] - 1 if (strnum[i] == 0): i -= 1 strres = "" for i in strnum: strres += str(i) return strres
0
sachinupreti1902 months ago
class Solution{ public: //Function to return the largest possible number of n digits //with sum equal to given sum.
// Easy explanation Please Upvote if it helps.... string largestNumber(int n, int sum) { // Your code here int i; string str=""; while(n!=0) { if(sum<9) { str+=to_string(sum); sum-=sum; } else if(sum >=9) { str+=to_string(9); sum-=9; } else if (sum==0) str+="0"; n--; } if(sum == 0) return str; else return "-1 }};
+2
siddhant072 months ago
string largestNumber(int n, int sum)
{
string ans = "";
if(9*n < sum){
return "-1";
}
while(ans.size() < n){
int dig = std::min(sum , 9);
sum -= dig;
ans += to_string(dig);
}
return ans;
}
-1
vibhors352Premium2 months ago
C++
string largestNumber(int n, int sum) { // Your code here if(sum>9*n) return "-1"; string ans=""; for(int i=0;i<n;i++){ if(sum>9){ ans+="9"; sum-=9; } else{ ans+=to_string(sum); sum=0; } } return ans; }
+1
kushwahasuraj3792 months ago
string largestNumber(int n, int sum) { int j=9; string s = ""; bool flage = true; for(int i=0;i<n;i++) { if(j <= sum) { sum -=j; string str= to_string(j); s +=str; } else if(flage) { string str= to_string(sum); s +=str; sum =0; flage = false; } else s +="0"; } if(sum >0) return "-1"; return s; }
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": 537,
"s": 238,
"text": "Geek lost the password of his super locker. He remembers the number of digits N as well as the sum S of all the digits of his password. He know that his password is the largest number of N digits that can be made with given sum S. As he is busy doing his homework, help him retrieving his password."
},
{
"code": null,
"e": 548,
"s": 537,
"text": "Example 1:"
},
{
"code": null,
"e": 675,
"s": 548,
"text": "Input:\nN = 5, S = 12\nOutput:\n93000\nExplanation:\nSum of elements is 12. Largest possible \n5 digit number is 93000 with sum 12.\n"
},
{
"code": null,
"e": 686,
"s": 675,
"text": "Example 2:"
},
{
"code": null,
"e": 785,
"s": 686,
"text": "Input:\nN = 3, S = 29\nOutput:\n-1\nExplanation:\nThere is no such three digit number \nwhose sum is 29."
},
{
"code": null,
"e": 1039,
"s": 785,
"text": "Your Task : \nYou don't need to read input or print anything. Your task is to complete the function largestNumber() which takes 2 integers N and S as input parameters and returns the password in the form of string, else return \"-1\" in the form of string."
},
{
"code": null,
"e": 1078,
"s": 1039,
"text": "Constraints:\n1 ≤ N ≤ 104\n0 ≤ S ≤ 9*104"
},
{
"code": null,
"e": 1143,
"s": 1078,
"text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(1)"
},
{
"code": null,
"e": 1145,
"s": 1143,
"text": "0"
},
{
"code": null,
"e": 1168,
"s": 1145,
"text": "shaank181816 hours ago"
},
{
"code": null,
"e": 1178,
"s": 1168,
"text": "Java Code"
},
{
"code": null,
"e": 1744,
"s": 1178,
"text": "class Solution\n{\n //Function to return the largest possible number of n digits\n //with sum equal to given sum.\n static String largestNumber(int n, int sum)\n {\n String ans = \"\";\n \n if(sum>9*n){\n return \"-1\";\n }\n \n \n for(int i = 0;i < n ;i++){\n if(sum>=9){\n sum -= 9;\n ans = ans + 9;\n }\n else if(sum<9){\n ans = ans + sum;\n sum = sum - sum;\n }\n }\n \n return ans;\n }\n}\n"
},
{
"code": null,
"e": 1746,
"s": 1744,
"text": "0"
},
{
"code": null,
"e": 1771,
"s": 1746,
"text": "princejee20191 month ago"
},
{
"code": null,
"e": 1798,
"s": 1771,
"text": "C++ || EASY TO UNDERSTAND "
},
{
"code": null,
"e": 2119,
"s": 1798,
"text": " string largestNumber(int n, int sum){ string res =\"\"; int ans =0; if(sum>(n*9))return \"-1\"; int d = sum/9; for(int i =0;i<d;i++){ res+='9'; } if(sum%9!=0){ res+='0'+sum%9; } while(res.size()!=n){ res+='0'; } return res; }"
},
{
"code": null,
"e": 2121,
"s": 2119,
"text": "0"
},
{
"code": null,
"e": 2151,
"s": 2121,
"text": "praveenkumar1391521 month ago"
},
{
"code": null,
"e": 2403,
"s": 2151,
"text": " def largestNum(self,n,s): k='' if s>n*9: return -1 else: while s>9: k=k+str(9) s=s-9 else: k=k+str(s) while len(k)!=n: k=k+\"0\" return k"
},
{
"code": null,
"e": 2406,
"s": 2403,
"text": "+1"
},
{
"code": null,
"e": 2432,
"s": 2406,
"text": "naveenapatnaik1 month ago"
},
{
"code": null,
"e": 2448,
"s": 2432,
"text": "Java SOLUTION!!"
},
{
"code": null,
"e": 2815,
"s": 2450,
"text": "static String largestNumber(int n, int sum) { // add your code here if(sum > n*9){ return \"-1\"; } String str=\"\"; for(int i=0; i<n; i++){ if(sum>=9){ str+=\"9\"; sum-=9; } else{ str+=sum; sum=0; } } return str; }"
},
{
"code": null,
"e": 2817,
"s": 2815,
"text": "0"
},
{
"code": null,
"e": 2846,
"s": 2817,
"text": "ayushnautiyal11101 month ago"
},
{
"code": null,
"e": 4101,
"s": 2846,
"text": "string largestNumber(int n, int sum) { if(sum>n*9){ return \"-1\"; } else{ string ans=\"\"; while(sum){ if(sum>=9){ sum-=9; ans+=\"9\"; } else if(sum>=8){ sum-=8; ans+=\"8\"; } else if(sum>=7){ sum-=7; ans+=\"7\"; } else if(sum>=6){ sum-=6; ans+=\"6\"; } else if(sum>=5){ sum-=5; ans+=\"5\"; } else if(sum>=4){ sum-=4; ans+=\"4\"; } else if(sum>=3){ sum-=3; ans+=\"3\"; } else if(sum>=2){ sum-=2; ans+=\"2\"; } else if(sum>=1){ sum-=1; ans+=\"1\"; } } if(ans.length()!=n){ int diff=n-ans.length(); while(diff--){ ans+=\"0\"; } } return ans; } }"
},
{
"code": null,
"e": 4103,
"s": 4101,
"text": "0"
},
{
"code": null,
"e": 4132,
"s": 4103,
"text": "abhinavmaurya2022 months ago"
},
{
"code": null,
"e": 4497,
"s": 4132,
"text": "class Solution: def largestNum(self,n,s): if(9*n < s): return \"-1\" sumnum = 9*n i = n - 1 strnum = [9]*n while(sumnum != s): sumnum -= 1 strnum[i] = strnum[i] - 1 if (strnum[i] == 0): i -= 1 strres = \"\" for i in strnum: strres += str(i) return strres"
},
{
"code": null,
"e": 4499,
"s": 4497,
"text": "0"
},
{
"code": null,
"e": 4527,
"s": 4499,
"text": "sachinupreti1902 months ago"
},
{
"code": null,
"e": 4649,
"s": 4527,
"text": "class Solution{ public: //Function to return the largest possible number of n digits //with sum equal to given sum."
},
{
"code": null,
"e": 5199,
"s": 4649,
"text": "// Easy explanation Please Upvote if it helps.... string largestNumber(int n, int sum) { // Your code here int i; string str=\"\"; while(n!=0) { if(sum<9) { str+=to_string(sum); sum-=sum; } else if(sum >=9) { str+=to_string(9); sum-=9; } else if (sum==0) str+=\"0\"; n--; } if(sum == 0) return str; else return \"-1 }}; "
},
{
"code": null,
"e": 5202,
"s": 5199,
"text": "+2"
},
{
"code": null,
"e": 5225,
"s": 5202,
"text": "siddhant072 months ago"
},
{
"code": null,
"e": 5522,
"s": 5225,
"text": " string largestNumber(int n, int sum)\n {\n string ans = \"\";\n if(9*n < sum){\n return \"-1\";\n }\n while(ans.size() < n){\n int dig = std::min(sum , 9);\n sum -= dig;\n ans += to_string(dig);\n }\n return ans;\n }"
},
{
"code": null,
"e": 5525,
"s": 5522,
"text": "-1"
},
{
"code": null,
"e": 5555,
"s": 5525,
"text": "vibhors352Premium2 months ago"
},
{
"code": null,
"e": 5559,
"s": 5555,
"text": "C++"
},
{
"code": null,
"e": 5898,
"s": 5559,
"text": " string largestNumber(int n, int sum) { // Your code here if(sum>9*n) return \"-1\"; string ans=\"\"; for(int i=0;i<n;i++){ if(sum>9){ ans+=\"9\"; sum-=9; } else{ ans+=to_string(sum); sum=0; } } return ans; }"
},
{
"code": null,
"e": 5901,
"s": 5898,
"text": "+1"
},
{
"code": null,
"e": 5930,
"s": 5901,
"text": "kushwahasuraj3792 months ago"
},
{
"code": null,
"e": 6465,
"s": 5930,
"text": " string largestNumber(int n, int sum) { int j=9; string s = \"\"; bool flage = true; for(int i=0;i<n;i++) { if(j <= sum) { sum -=j; string str= to_string(j); s +=str; } else if(flage) { string str= to_string(sum); s +=str; sum =0; flage = false; } else s +=\"0\"; } if(sum >0) return \"-1\"; return s; }"
},
{
"code": null,
"e": 6611,
"s": 6465,
"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": 6647,
"s": 6611,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6657,
"s": 6647,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6667,
"s": 6657,
"text": "\nContest\n"
},
{
"code": null,
"e": 6730,
"s": 6667,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6878,
"s": 6730,
"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": 7086,
"s": 6878,
"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": 7192,
"s": 7086,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Integer Promotions in C - GeeksforGeeks
|
28 May, 2017
Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and enum. They are first converted to int or unsigned int, and then arithmetic is done on them. If an int can represent all values of the original type, the value is converted to an int . Otherwise, it is converted to an unsigned int.
For example see the following program.
#include <stdio.h> int main(){ char a = 30, b = 40, c = 10; char d = (a * b) / c; printf ("%d ", d); return 0;}
Output:
120
At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200 which is greater than 128. But integer promotion happens here in arithmetic done on char types and we get the appropriate result without any overflow.
Consider the following program as another example.
#include <stdio.h> int main(){ char a = 0xfb; unsigned char b = 0xfb; printf("a = %c", a); printf("\nb = %c", b); if (a == b) printf("\nSame"); else printf("\nNot Same"); return 0;}
Output:
a = ?
b = ?
Not Same
When we print ‘a’ and ‘b’, same character is printed, but when we compare them, we get the output as “Not Same”.‘a’ and ‘b’ have same binary representation as char. But when comparison operation is performed on ‘a’ and ‘b’, they are first converted to int. ‘a’ is a signed char, when it is converted to int, its value becomes -5 (signed value of 0xfb). ‘b’ is unsigned char, when it is converted to int, its value becomes 251. The values -5 and 251 have different representations as int, so we get the output as “Not Same”.
We will soon be discussing integer conversion rules between signed and unsigned, int and long int, etc.
References:http://www.tru64unix.compaq.com/docs/base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_067.HTM
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Data Types
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
|
[
{
"code": null,
"e": 24155,
"s": 24127,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 24685,
"s": 24155,
"text": "Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and enum. They are first converted to int or unsigned int, and then arithmetic is done on them. If an int can represent all values of the original type, the value is converted to an int . Otherwise, it is converted to an unsigned int."
},
{
"code": null,
"e": 24724,
"s": 24685,
"text": "For example see the following program."
},
{
"code": "#include <stdio.h> int main(){ char a = 30, b = 40, c = 10; char d = (a * b) / c; printf (\"%d \", d); return 0;}",
"e": 24849,
"s": 24724,
"text": null
},
{
"code": null,
"e": 24857,
"s": 24849,
"text": "Output:"
},
{
"code": null,
"e": 24861,
"s": 24857,
"text": "120"
},
{
"code": null,
"e": 25226,
"s": 24861,
"text": "At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200 which is greater than 128. But integer promotion happens here in arithmetic done on char types and we get the appropriate result without any overflow."
},
{
"code": null,
"e": 25277,
"s": 25226,
"text": "Consider the following program as another example."
},
{
"code": "#include <stdio.h> int main(){ char a = 0xfb; unsigned char b = 0xfb; printf(\"a = %c\", a); printf(\"\\nb = %c\", b); if (a == b) printf(\"\\nSame\"); else printf(\"\\nNot Same\"); return 0;}",
"e": 25495,
"s": 25277,
"text": null
},
{
"code": null,
"e": 25503,
"s": 25495,
"text": "Output:"
},
{
"code": null,
"e": 25525,
"s": 25503,
"text": "a = ?\nb = ?\nNot Same "
},
{
"code": null,
"e": 26049,
"s": 25525,
"text": "When we print ‘a’ and ‘b’, same character is printed, but when we compare them, we get the output as “Not Same”.‘a’ and ‘b’ have same binary representation as char. But when comparison operation is performed on ‘a’ and ‘b’, they are first converted to int. ‘a’ is a signed char, when it is converted to int, its value becomes -5 (signed value of 0xfb). ‘b’ is unsigned char, when it is converted to int, its value becomes 251. The values -5 and 251 have different representations as int, so we get the output as “Not Same”."
},
{
"code": null,
"e": 26153,
"s": 26049,
"text": "We will soon be discussing integer conversion rules between signed and unsigned, int and long int, etc."
},
{
"code": null,
"e": 26256,
"s": 26153,
"text": "References:http://www.tru64unix.compaq.com/docs/base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_067.HTM"
},
{
"code": null,
"e": 26424,
"s": 26256,
"text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 26437,
"s": 26424,
"text": "C-Data Types"
},
{
"code": null,
"e": 26452,
"s": 26437,
"text": "cpp-data-types"
},
{
"code": null,
"e": 26463,
"s": 26452,
"text": "C Language"
},
{
"code": null,
"e": 26561,
"s": 26463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26570,
"s": 26561,
"text": "Comments"
},
{
"code": null,
"e": 26583,
"s": 26570,
"text": "Old Comments"
},
{
"code": null,
"e": 26611,
"s": 26583,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26657,
"s": 26611,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26669,
"s": 26657,
"text": "fork() in C"
},
{
"code": null,
"e": 26709,
"s": 26669,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26741,
"s": 26709,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26758,
"s": 26741,
"text": "Substring in C++"
},
{
"code": null,
"e": 26780,
"s": 26758,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26827,
"s": 26780,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 26865,
"s": 26827,
"text": "TCP Server-Client implementation in C"
}
] |
Get global variable dynamically by name string in JavaScript?
|
Display in alert by using alert(window()). Following is the syntax −
alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<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>
<script>
var globalVariablelocal_print100=100;
print100=1;
alert(window['globalVariable' + 'local_' + print100]);
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Display in alert by using alert(window()). Following is the syntax −"
},
{
"code": null,
"e": 1207,
"s": 1131,
"text": "alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);"
},
{
"code": null,
"e": 1218,
"s": 1207,
"text": " Live Demo"
},
{
"code": null,
"e": 1761,
"s": 1218,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<script>\n var globalVariablelocal_print100=100;\n print100=1;\n alert(window['globalVariable' + 'local_' + print100]);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1922,
"s": 1761,
"text": "To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor."
}
] |
C++ Program to Check Prime Number By Creating a Function
|
A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself.
Some of the first prime numbers are −
2, 3, 5, 7, 11, 13 ,17
A program to check if a number is prime or not using a function is as follows.
Live Demo
#include <iostream>
using namespace std;
void isPrime(int n) {
int i, flag = 0;
for(i=2; i<=n/2; ++i) {
if(n%i==0) {
flag=1;
break;
}
}
if (flag==0)
cout<<n<<" is a prime number"<<endl;
else
cout<<n<<" is not a prime number"<<endl;
}
int main() {
isPrime(17);
isPrime(20);
return 0;
}
17 is a prime number
20 is not a prime number
The function isPrime() is used to find out if a number is prime or not. There is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop as shown below −
for(i=2; i<=n/2; ++i) {
if(n%i==0) {
flag=1;
break;
}
}
If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.
if (flag==0)
cout<<n<<" is a prime number";
else
cout<<n<<" is not a prime number";
The function isPrime() is called from the main() function for the values 17 and 20. This is shown as follows.
isPrime(17);
isPrime(20);
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself."
},
{
"code": null,
"e": 1223,
"s": 1185,
"text": "Some of the first prime numbers are −"
},
{
"code": null,
"e": 1246,
"s": 1223,
"text": "2, 3, 5, 7, 11, 13 ,17"
},
{
"code": null,
"e": 1325,
"s": 1246,
"text": "A program to check if a number is prime or not using a function is as follows."
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": " Live Demo"
},
{
"code": null,
"e": 1681,
"s": 1336,
"text": "#include <iostream>\nusing namespace std;\nvoid isPrime(int n) {\n int i, flag = 0;\n for(i=2; i<=n/2; ++i) {\n if(n%i==0) {\n flag=1;\n break;\n }\n }\n if (flag==0)\n cout<<n<<\" is a prime number\"<<endl;\n else\n cout<<n<<\" is not a prime number\"<<endl;\n}\nint main() {\n isPrime(17);\n isPrime(20);\n return 0;\n}"
},
{
"code": null,
"e": 1727,
"s": 1681,
"text": "17 is a prime number\n20 is not a prime number"
},
{
"code": null,
"e": 2143,
"s": 1727,
"text": "The function isPrime() is used to find out if a number is prime or not. There is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop as shown below −"
},
{
"code": null,
"e": 2217,
"s": 2143,
"text": "for(i=2; i<=n/2; ++i) {\n if(n%i==0) {\n flag=1;\n break;\n }\n}"
},
{
"code": null,
"e": 2412,
"s": 2217,
"text": "If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed."
},
{
"code": null,
"e": 2496,
"s": 2412,
"text": "if (flag==0)\ncout<<n<<\" is a prime number\";\nelse\ncout<<n<<\" is not a prime number\";"
},
{
"code": null,
"e": 2606,
"s": 2496,
"text": "The function isPrime() is called from the main() function for the values 17 and 20. This is shown as follows."
},
{
"code": null,
"e": 2632,
"s": 2606,
"text": "isPrime(17);\nisPrime(20);"
}
] |
PyQt - Hello World
|
Creating a simple GUI application using PyQt involves the following steps −
Import QtGui module.
Import QtGui module.
Create an application object.
Create an application object.
A QWidget object creates top level window. Add QLabel object in it.
A QWidget object creates top level window. Add QLabel object in it.
Set the caption of label as “hello world”.
Set the caption of label as “hello world”.
Define the size and position of window by setGeometry() method.
Define the size and position of window by setGeometry() method.
Enter the mainloop of application by app.exec_() method.
Enter the mainloop of application by app.exec_() method.
import sys
from PyQt4 import QtGui
def window():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
b = QtGui.QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle(“PyQt”)
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2002,
"s": 1926,
"text": "Creating a simple GUI application using PyQt involves the following steps −"
},
{
"code": null,
"e": 2023,
"s": 2002,
"text": "Import QtGui module."
},
{
"code": null,
"e": 2044,
"s": 2023,
"text": "Import QtGui module."
},
{
"code": null,
"e": 2074,
"s": 2044,
"text": "Create an application object."
},
{
"code": null,
"e": 2104,
"s": 2074,
"text": "Create an application object."
},
{
"code": null,
"e": 2172,
"s": 2104,
"text": "A QWidget object creates top level window. Add QLabel object in it."
},
{
"code": null,
"e": 2240,
"s": 2172,
"text": "A QWidget object creates top level window. Add QLabel object in it."
},
{
"code": null,
"e": 2283,
"s": 2240,
"text": "Set the caption of label as “hello world”."
},
{
"code": null,
"e": 2326,
"s": 2283,
"text": "Set the caption of label as “hello world”."
},
{
"code": null,
"e": 2390,
"s": 2326,
"text": "Define the size and position of window by setGeometry() method."
},
{
"code": null,
"e": 2454,
"s": 2390,
"text": "Define the size and position of window by setGeometry() method."
},
{
"code": null,
"e": 2511,
"s": 2454,
"text": "Enter the mainloop of application by app.exec_() method."
},
{
"code": null,
"e": 2568,
"s": 2511,
"text": "Enter the mainloop of application by app.exec_() method."
},
{
"code": null,
"e": 2887,
"s": 2568,
"text": "import sys\nfrom PyQt4 import QtGui\n\ndef window():\n app = QtGui.QApplication(sys.argv)\n w = QtGui.QWidget()\n b = QtGui.QLabel(w)\n b.setText(\"Hello World!\")\n w.setGeometry(100,100,200,50)\n b.move(50,20)\n w.setWindowTitle(“PyQt”)\n w.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n window()"
},
{
"code": null,
"e": 2934,
"s": 2887,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 2971,
"s": 2934,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 2981,
"s": 2971,
"text": " ALAA EID"
},
{
"code": null,
"e": 2988,
"s": 2981,
"text": " Print"
},
{
"code": null,
"e": 2999,
"s": 2988,
"text": " Add Notes"
}
] |
How to convert 3-digit color code to 6-digit color code using JavaScript ? - GeeksforGeeks
|
12 Mar, 2021
In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first we copy of the individual digits and paster at consecutive position. For example – #34E will be converted into #3344EE and #E90 will be converted into #EE9900.
Steps to convert 3-digit color code to 6-digit color code:
Step 1: The color code is in string format. So, apply the split method on the string. After applying the split method we got an array of elements.
Javascript
<script> var digit = "39E" digit = digit.split("") console.log(digit) // ["#", "3", "9", "E"]</script>
Output:
["#", "3", "9", "E"]
Step 2: Now apply the map method and iterate over the array and return every item with concatenating to itself and check if the item is “#” then do not return the concatenated result, just return the item.
Javascript
<script> var digit = "#39E"; digit = digit.split("").map((item)=>{ if(item == "#"){return item} return item + item;}) console.log(digit) // ["#", "33", "99", "EE"]</script>
Output:
["#", "33", "99", "EE"]
Step 3: Now use the join method to convert all the array items into a single string.
Javascript
<script> var digit = "#39E" digit = digit.split("").map((item)=>{ if(item == "#"){return item} return item + item;}).join("") console.log(digit)<script>
Output:
"#3399EE"
Step 4: In the above step, we are converting “#39E” but we can see the first element of this code is “#”, but if the user does not provide the “#” then you have to check if the first element is “#” then concatenate it with the resulting code. And this is our complete code.
Javascript
<script> var digit = "#39E" digit = digit.split("").map((item)=>{ if(item == "#"){return item} return item + item;}).join("") if(digit[0] != "#"){ digit = "#" + digit;} console.log(digit)</script>
Output:
#3399EE
javascript-functions
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 25523,
"s": 25220,
"text": "In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first we copy of the individual digits and paster at consecutive position. For example – #34E will be converted into #3344EE and #E90 will be converted into #EE9900."
},
{
"code": null,
"e": 25582,
"s": 25523,
"text": "Steps to convert 3-digit color code to 6-digit color code:"
},
{
"code": null,
"e": 25729,
"s": 25582,
"text": "Step 1: The color code is in string format. So, apply the split method on the string. After applying the split method we got an array of elements."
},
{
"code": null,
"e": 25740,
"s": 25729,
"text": "Javascript"
},
{
"code": "<script> var digit = \"39E\" digit = digit.split(\"\") console.log(digit) // [\"#\", \"3\", \"9\", \"E\"]</script>",
"e": 25847,
"s": 25740,
"text": null
},
{
"code": null,
"e": 25855,
"s": 25847,
"text": "Output:"
},
{
"code": null,
"e": 25876,
"s": 25855,
"text": "[\"#\", \"3\", \"9\", \"E\"]"
},
{
"code": null,
"e": 26082,
"s": 25876,
"text": "Step 2: Now apply the map method and iterate over the array and return every item with concatenating to itself and check if the item is “#” then do not return the concatenated result, just return the item."
},
{
"code": null,
"e": 26093,
"s": 26082,
"text": "Javascript"
},
{
"code": "<script> var digit = \"#39E\"; digit = digit.split(\"\").map((item)=>{ if(item == \"#\"){return item} return item + item;}) console.log(digit) // [\"#\", \"33\", \"99\", \"EE\"]</script>",
"e": 26280,
"s": 26093,
"text": null
},
{
"code": null,
"e": 26288,
"s": 26280,
"text": "Output:"
},
{
"code": null,
"e": 26312,
"s": 26288,
"text": "[\"#\", \"33\", \"99\", \"EE\"]"
},
{
"code": null,
"e": 26397,
"s": 26312,
"text": "Step 3: Now use the join method to convert all the array items into a single string."
},
{
"code": null,
"e": 26408,
"s": 26397,
"text": "Javascript"
},
{
"code": "<script> var digit = \"#39E\" digit = digit.split(\"\").map((item)=>{ if(item == \"#\"){return item} return item + item;}).join(\"\") console.log(digit)<script>",
"e": 26574,
"s": 26408,
"text": null
},
{
"code": null,
"e": 26582,
"s": 26574,
"text": "Output:"
},
{
"code": null,
"e": 26592,
"s": 26582,
"text": "\"#3399EE\""
},
{
"code": null,
"e": 26866,
"s": 26592,
"text": "Step 4: In the above step, we are converting “#39E” but we can see the first element of this code is “#”, but if the user does not provide the “#” then you have to check if the first element is “#” then concatenate it with the resulting code. And this is our complete code."
},
{
"code": null,
"e": 26877,
"s": 26866,
"text": "Javascript"
},
{
"code": "<script> var digit = \"#39E\" digit = digit.split(\"\").map((item)=>{ if(item == \"#\"){return item} return item + item;}).join(\"\") if(digit[0] != \"#\"){ digit = \"#\" + digit;} console.log(digit)</script>",
"e": 27091,
"s": 26877,
"text": null
},
{
"code": null,
"e": 27099,
"s": 27091,
"text": "Output:"
},
{
"code": null,
"e": 27107,
"s": 27099,
"text": "#3399EE"
},
{
"code": null,
"e": 27128,
"s": 27107,
"text": "javascript-functions"
},
{
"code": null,
"e": 27149,
"s": 27128,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 27160,
"s": 27149,
"text": "JavaScript"
},
{
"code": null,
"e": 27177,
"s": 27160,
"text": "Web Technologies"
},
{
"code": null,
"e": 27275,
"s": 27177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27284,
"s": 27275,
"text": "Comments"
},
{
"code": null,
"e": 27297,
"s": 27284,
"text": "Old Comments"
},
{
"code": null,
"e": 27358,
"s": 27297,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27399,
"s": 27358,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27453,
"s": 27399,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27510,
"s": 27453,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27572,
"s": 27510,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27614,
"s": 27572,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27647,
"s": 27614,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27709,
"s": 27647,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27752,
"s": 27709,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference between strong and bold tag in HTML - GeeksforGeeks
|
03 Dec, 2020
HTML strong tag: The strong tag is one of the element of HTML used in formatting HTML texts. It is used to show importance of the text by making it bold or highlighting it semantically.
Syntax:
<strong> Contents... </strong>
HTML bold tag: The bold tag or <b> is also one of the formatting elements of HTML. The text written under <b> tag makes the text bold presentationally to draw attention.
Syntax:
<b> Contents... </b>
The main difference between these two tag is that the strong tag semantically emphasizes on the important word or section of words while the bold tag is just offset text conventionally styled in bold. Below is the code to show this difference.
Example 1:
HTML
<!DOCTYPE html><html> <head> <style> body { text-align:center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p><strong> This text is important! </strong></p> <p><b>This text is bold.</p></body> </html>
Output:
Though there is no difference in the display of both the tags but there is semantical difference between them.
Example 2:
HTML
<!DOCTYPE html><html> <head> <title>b tag</title> <style> body { text-align:center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Without <strong>internet</strong> we can not use gfg </p> <p> <b>GeeksforGeeks:</b> A computer science portal for geeks </p></body> </html>
Output:
We wanted to show the importance of the word “internet” so we used <strong> tag where as for the word “GeeksforGeeks”, we just simply wanted to format the text in bold.
Supported Browser: The browser supported by <b> and <strong> tag are listed below.
Chrome
Android
Firefox (Gecko)
Firefox Mobile (Gecko)
Internet Explorer (IE)
Edge Mobile
Opera
Opera Mobile
Safari (WebKit)
Safari Mobile
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24174,
"s": 24146,
"text": "\n03 Dec, 2020"
},
{
"code": null,
"e": 24360,
"s": 24174,
"text": "HTML strong tag: The strong tag is one of the element of HTML used in formatting HTML texts. It is used to show importance of the text by making it bold or highlighting it semantically."
},
{
"code": null,
"e": 24368,
"s": 24360,
"text": "Syntax:"
},
{
"code": null,
"e": 24399,
"s": 24368,
"text": "<strong> Contents... </strong>"
},
{
"code": null,
"e": 24569,
"s": 24399,
"text": "HTML bold tag: The bold tag or <b> is also one of the formatting elements of HTML. The text written under <b> tag makes the text bold presentationally to draw attention."
},
{
"code": null,
"e": 24577,
"s": 24569,
"text": "Syntax:"
},
{
"code": null,
"e": 24598,
"s": 24577,
"text": "<b> Contents... </b>"
},
{
"code": null,
"e": 24842,
"s": 24598,
"text": "The main difference between these two tag is that the strong tag semantically emphasizes on the important word or section of words while the bold tag is just offset text conventionally styled in bold. Below is the code to show this difference."
},
{
"code": null,
"e": 24853,
"s": 24842,
"text": "Example 1:"
},
{
"code": null,
"e": 24858,
"s": 24853,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align:center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p><strong> This text is important! </strong></p> <p><b>This text is bold.</p></body> </html> ",
"e": 25192,
"s": 24858,
"text": null
},
{
"code": null,
"e": 25200,
"s": 25192,
"text": "Output:"
},
{
"code": null,
"e": 25311,
"s": 25200,
"text": "Though there is no difference in the display of both the tags but there is semantical difference between them."
},
{
"code": null,
"e": 25322,
"s": 25311,
"text": "Example 2:"
},
{
"code": null,
"e": 25327,
"s": 25322,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>b tag</title> <style> body { text-align:center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Without <strong>internet</strong> we can not use gfg </p> <p> <b>GeeksforGeeks:</b> A computer science portal for geeks </p></body> </html> ",
"e": 25769,
"s": 25327,
"text": null
},
{
"code": null,
"e": 25777,
"s": 25769,
"text": "Output:"
},
{
"code": null,
"e": 25946,
"s": 25777,
"text": "We wanted to show the importance of the word “internet” so we used <strong> tag where as for the word “GeeksforGeeks”, we just simply wanted to format the text in bold."
},
{
"code": null,
"e": 26029,
"s": 25946,
"text": "Supported Browser: The browser supported by <b> and <strong> tag are listed below."
},
{
"code": null,
"e": 26036,
"s": 26029,
"text": "Chrome"
},
{
"code": null,
"e": 26044,
"s": 26036,
"text": "Android"
},
{
"code": null,
"e": 26060,
"s": 26044,
"text": "Firefox (Gecko)"
},
{
"code": null,
"e": 26083,
"s": 26060,
"text": "Firefox Mobile (Gecko)"
},
{
"code": null,
"e": 26106,
"s": 26083,
"text": "Internet Explorer (IE)"
},
{
"code": null,
"e": 26118,
"s": 26106,
"text": "Edge Mobile"
},
{
"code": null,
"e": 26124,
"s": 26118,
"text": "Opera"
},
{
"code": null,
"e": 26137,
"s": 26124,
"text": "Opera Mobile"
},
{
"code": null,
"e": 26153,
"s": 26137,
"text": "Safari (WebKit)"
},
{
"code": null,
"e": 26167,
"s": 26153,
"text": "Safari Mobile"
},
{
"code": null,
"e": 26304,
"s": 26167,
"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": 26314,
"s": 26304,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26319,
"s": 26314,
"text": "HTML"
},
{
"code": null,
"e": 26336,
"s": 26319,
"text": "Web Technologies"
},
{
"code": null,
"e": 26341,
"s": 26336,
"text": "HTML"
},
{
"code": null,
"e": 26439,
"s": 26341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26448,
"s": 26439,
"text": "Comments"
},
{
"code": null,
"e": 26461,
"s": 26448,
"text": "Old Comments"
},
{
"code": null,
"e": 26509,
"s": 26461,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26546,
"s": 26509,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26596,
"s": 26546,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26646,
"s": 26596,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26670,
"s": 26646,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26726,
"s": 26670,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26759,
"s": 26726,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26802,
"s": 26759,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26863,
"s": 26802,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
IN vs EXISTS in SQL - GeeksforGeeks
|
15 May, 2021
SQL stands for Structured Query Language. It is used for storing data in databases, modifying or manipulating data in databases and retrieving data from databases. We can say that SQL manages data in a relational database management system (RDBMS).
The instructions that are used to communicate with a database in order to perform tasks, functions, and queries with data are called SQL Statements. SQL is not case-sensitive. Generally, SQL keywords are written in uppercase.
To match an expression against a list of values, SQL provides IN Operator. So we do not need to use multiple OR conditions in SELECT, UPDATE, etc.
We can list values directly or we want to provide a query result to the IN operator.
Syntax : SELECT columnName(s) FROM tableName WHERE columnNamex IN (value1, value2, ...);
Here ColumnNameX is matched with every value (value1, value2,...) in the list. If the match occurs, then IN evaluates to be TRUE and if the mismatch occurs, then IN evaluates to be FALSE.
Suppose we have a table named “Customers” as :
Customer Table
Now we want to see the details of the customers whose id can be 1 or 2 or 5 or 6 or 7, we can use IN operator & give a set of values to check upon.
If the argument sub-query is non-empty, exists construct returns the value true, otherwise false. To check whether a row is returned through this sub-query or not, it is used. True is returned if one or more rows are returned by executing the sub-query, otherwise False when no rows are returned.
Syntax :
SELECT columnName(s) FROM tableName1 WHERE EXISTS
(subquery);
subquery is of the form : SELECT columnName FROM tableName2 WHERE condition
Here the sub-query is executed first.
The sub-query is a SELECT statement. The EXISTS condition will be met & it will return TRUE if the subquery returns at least one record in its result set, else, the EXISTS condition will not be met and it will return FALSE.
Note: The sub-query is returning for EVERY row in the outer query’s table.
Now, let up suppose we have another table: “Accounts” as :
Accounts Table
Now to see all the customers who’s any kind of account exists, we can make use of exists keyword as :
We here check: match for every CUSTOMERID in the customer table with the CUSTOMERID in the accounts table.
If CUSTOMER.CUSTOMERID = ACCOUNTS.CUSTOMERID evaluates to be true in the sub-query, one row is returned & thus the sub-query evaluates to be true & our outer query (Select * from Customer) get executed for that particular customer.
Note: To do the same thing, i.e., to see all the customers who’s any kind of account exists, we can make use of IN keyword also :
The key differences between IN & EXISTS Operator are :
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n15 May, 2021"
},
{
"code": null,
"e": 25762,
"s": 25513,
"text": "SQL stands for Structured Query Language. It is used for storing data in databases, modifying or manipulating data in databases and retrieving data from databases. We can say that SQL manages data in a relational database management system (RDBMS)."
},
{
"code": null,
"e": 25988,
"s": 25762,
"text": "The instructions that are used to communicate with a database in order to perform tasks, functions, and queries with data are called SQL Statements. SQL is not case-sensitive. Generally, SQL keywords are written in uppercase."
},
{
"code": null,
"e": 26135,
"s": 25988,
"text": "To match an expression against a list of values, SQL provides IN Operator. So we do not need to use multiple OR conditions in SELECT, UPDATE, etc."
},
{
"code": null,
"e": 26220,
"s": 26135,
"text": "We can list values directly or we want to provide a query result to the IN operator."
},
{
"code": null,
"e": 26309,
"s": 26220,
"text": "Syntax : SELECT columnName(s) FROM tableName WHERE columnNamex IN (value1, value2, ...);"
},
{
"code": null,
"e": 26497,
"s": 26309,
"text": "Here ColumnNameX is matched with every value (value1, value2,...) in the list. If the match occurs, then IN evaluates to be TRUE and if the mismatch occurs, then IN evaluates to be FALSE."
},
{
"code": null,
"e": 26544,
"s": 26497,
"text": "Suppose we have a table named “Customers” as :"
},
{
"code": null,
"e": 26559,
"s": 26544,
"text": "Customer Table"
},
{
"code": null,
"e": 26708,
"s": 26559,
"text": "Now we want to see the details of the customers whose id can be 1 or 2 or 5 or 6 or 7, we can use IN operator & give a set of values to check upon."
},
{
"code": null,
"e": 27005,
"s": 26708,
"text": "If the argument sub-query is non-empty, exists construct returns the value true, otherwise false. To check whether a row is returned through this sub-query or not, it is used. True is returned if one or more rows are returned by executing the sub-query, otherwise False when no rows are returned."
},
{
"code": null,
"e": 27153,
"s": 27005,
"text": "Syntax :\nSELECT columnName(s) FROM tableName1 WHERE EXISTS\n(subquery);\n\nsubquery is of the form : SELECT columnName FROM tableName2 WHERE condition"
},
{
"code": null,
"e": 27192,
"s": 27153,
"text": "Here the sub-query is executed first. "
},
{
"code": null,
"e": 27418,
"s": 27192,
"text": "The sub-query is a SELECT statement. The EXISTS condition will be met & it will return TRUE if the subquery returns at least one record in its result set, else, the EXISTS condition will not be met and it will return FALSE."
},
{
"code": null,
"e": 27493,
"s": 27418,
"text": "Note: The sub-query is returning for EVERY row in the outer query’s table."
},
{
"code": null,
"e": 27552,
"s": 27493,
"text": "Now, let up suppose we have another table: “Accounts” as :"
},
{
"code": null,
"e": 27567,
"s": 27552,
"text": "Accounts Table"
},
{
"code": null,
"e": 27669,
"s": 27567,
"text": "Now to see all the customers who’s any kind of account exists, we can make use of exists keyword as :"
},
{
"code": null,
"e": 27777,
"s": 27669,
"text": "We here check: match for every CUSTOMERID in the customer table with the CUSTOMERID in the accounts table. "
},
{
"code": null,
"e": 28009,
"s": 27777,
"text": "If CUSTOMER.CUSTOMERID = ACCOUNTS.CUSTOMERID evaluates to be true in the sub-query, one row is returned & thus the sub-query evaluates to be true & our outer query (Select * from Customer) get executed for that particular customer."
},
{
"code": null,
"e": 28139,
"s": 28009,
"text": "Note: To do the same thing, i.e., to see all the customers who’s any kind of account exists, we can make use of IN keyword also :"
},
{
"code": null,
"e": 28194,
"s": 28139,
"text": "The key differences between IN & EXISTS Operator are :"
},
{
"code": null,
"e": 28201,
"s": 28194,
"text": "Picked"
},
{
"code": null,
"e": 28211,
"s": 28201,
"text": "SQL-Query"
},
{
"code": null,
"e": 28215,
"s": 28211,
"text": "SQL"
},
{
"code": null,
"e": 28219,
"s": 28215,
"text": "SQL"
},
{
"code": null,
"e": 28317,
"s": 28219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28383,
"s": 28317,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28398,
"s": 28383,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28455,
"s": 28398,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28487,
"s": 28455,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28565,
"s": 28487,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28582,
"s": 28565,
"text": "SQL using Python"
},
{
"code": null,
"e": 28618,
"s": 28582,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28684,
"s": 28618,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28746,
"s": 28684,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Create Multiple frames with Grid manager using Tkinter - GeeksforGeeks
|
16 Mar, 2021
Prerequisites: Tkinter
Tkinter can support the creation of more than one widget in the same frame. Not just this it also supports a mechanism to align them relative to each other. One of the easiest ways of aligning the different widgets in the Tkinter is through grid manager. Apart from aligning various widgets, the grid manager can also be used for aligning the numerous frames.
In this article, we will be discussing the approach of aligning multiple frames with Grid Manager.
For this first the frames needs to be defined, and then they need to be aligned using grid().
Syntax:
frame1=LabelFrame(app, text=”#Text you want to give in frame”)
frame1.grid(row=#Row value, column=#Column value)
LabelFrame() is used to create a frame
grid() is used to apply grid manager to the widgets created
Import module
Create a GUI app using tkinter
Give a title to the app.(optional)
Now, create the first frame, i.e., frame1
Display the frame1 in grid manager by specifying row and column values.
Further, create a widget you wish to get display in the frame1.
Display the widget you made in previous step.
For creating more frames, repeat from steps 4 to 7. Repeat these steps n number of times for creating n number of frames. Don’t forget to change the row value and column value for every frame. You can change the row value and column value of the frames according to the given image.
Finally, make the loop for displaying the GUI app on the screen.
Program:
Python
# Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give a title to your appapp.title("Vinayak App") # Constructing the first frame, frame1frame1 = LabelFrame(app, text="Fruit", bg="green", fg="white", padx=15, pady=15) # Displaying the frame1 in row 0 and column 0frame1.grid(row=0, column=0) # Constructing the button b1 in frame1b1 = Button(frame1, text="Apple") # Displaying the button b1b1.pack() # Constructing the second frame, frame2frame2 = LabelFrame(app, text="Vegetable", bg="yellow", padx=15, pady=15) # Displaying the frame2 in row 0 and column 1frame2.grid(row=0, column=1) # Constructing the button in frame2b2 = Button(frame2, text="Tomato") # Displaying the button b2b2.pack() # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 25560,
"s": 25537,
"text": "Prerequisites: Tkinter"
},
{
"code": null,
"e": 25921,
"s": 25560,
"text": "Tkinter can support the creation of more than one widget in the same frame. Not just this it also supports a mechanism to align them relative to each other. One of the easiest ways of aligning the different widgets in the Tkinter is through grid manager. Apart from aligning various widgets, the grid manager can also be used for aligning the numerous frames. "
},
{
"code": null,
"e": 26020,
"s": 25921,
"text": "In this article, we will be discussing the approach of aligning multiple frames with Grid Manager."
},
{
"code": null,
"e": 26114,
"s": 26020,
"text": "For this first the frames needs to be defined, and then they need to be aligned using grid()."
},
{
"code": null,
"e": 26122,
"s": 26114,
"text": "Syntax:"
},
{
"code": null,
"e": 26185,
"s": 26122,
"text": "frame1=LabelFrame(app, text=”#Text you want to give in frame”)"
},
{
"code": null,
"e": 26235,
"s": 26185,
"text": "frame1.grid(row=#Row value, column=#Column value)"
},
{
"code": null,
"e": 26274,
"s": 26235,
"text": "LabelFrame() is used to create a frame"
},
{
"code": null,
"e": 26334,
"s": 26274,
"text": "grid() is used to apply grid manager to the widgets created"
},
{
"code": null,
"e": 26348,
"s": 26334,
"text": "Import module"
},
{
"code": null,
"e": 26379,
"s": 26348,
"text": "Create a GUI app using tkinter"
},
{
"code": null,
"e": 26414,
"s": 26379,
"text": "Give a title to the app.(optional)"
},
{
"code": null,
"e": 26456,
"s": 26414,
"text": "Now, create the first frame, i.e., frame1"
},
{
"code": null,
"e": 26528,
"s": 26456,
"text": "Display the frame1 in grid manager by specifying row and column values."
},
{
"code": null,
"e": 26592,
"s": 26528,
"text": "Further, create a widget you wish to get display in the frame1."
},
{
"code": null,
"e": 26638,
"s": 26592,
"text": "Display the widget you made in previous step."
},
{
"code": null,
"e": 26921,
"s": 26638,
"text": "For creating more frames, repeat from steps 4 to 7. Repeat these steps n number of times for creating n number of frames. Don’t forget to change the row value and column value for every frame. You can change the row value and column value of the frames according to the given image."
},
{
"code": null,
"e": 26986,
"s": 26921,
"text": "Finally, make the loop for displaying the GUI app on the screen."
},
{
"code": null,
"e": 26995,
"s": 26986,
"text": "Program:"
},
{
"code": null,
"e": 27002,
"s": 26995,
"text": "Python"
},
{
"code": "# Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give a title to your appapp.title(\"Vinayak App\") # Constructing the first frame, frame1frame1 = LabelFrame(app, text=\"Fruit\", bg=\"green\", fg=\"white\", padx=15, pady=15) # Displaying the frame1 in row 0 and column 0frame1.grid(row=0, column=0) # Constructing the button b1 in frame1b1 = Button(frame1, text=\"Apple\") # Displaying the button b1b1.pack() # Constructing the second frame, frame2frame2 = LabelFrame(app, text=\"Vegetable\", bg=\"yellow\", padx=15, pady=15) # Displaying the frame2 in row 0 and column 1frame2.grid(row=0, column=1) # Constructing the button in frame2b2 = Button(frame2, text=\"Tomato\") # Displaying the button b2b2.pack() # Make the loop for displaying appapp.mainloop()",
"e": 27805,
"s": 27002,
"text": null
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Output:"
},
{
"code": null,
"e": 27820,
"s": 27813,
"text": "Picked"
},
{
"code": null,
"e": 27835,
"s": 27820,
"text": "Python-tkinter"
},
{
"code": null,
"e": 27842,
"s": 27835,
"text": "Python"
},
{
"code": null,
"e": 27940,
"s": 27842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27972,
"s": 27940,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28014,
"s": 27972,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28056,
"s": 28014,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28083,
"s": 28056,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28139,
"s": 28083,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28178,
"s": 28139,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28200,
"s": 28178,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28231,
"s": 28200,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28260,
"s": 28231,
"text": "Create a directory in Python"
}
] |
Java Program to Print Smallest and Biggest Possible Palindrome Word in a Given String - GeeksforGeeks
|
04 Dec, 2020
A Palindrome String is a string whose reversed string is equal to the original string. In this Java Program, we are going to see the approach of printing the smallest and biggest palindrome word in a String.
Given a sentence of words in the form of a string, and we need to print the smallest and longest palindromic word out of those words.
Input: Wow madam is driving racecar.
Smallest Palindrome: Wow
Longest Palindrome: racecar
Explanation: The string contains three palindrome words (i.e., madam, Wow, racecar)
but the length of racecar is greatest and that of wow is smallest.
Input: "Nitin is a good guy"
Smallest Palindrome: a
Longest Palindrome: Nitin
Approach:
lengthPalindrome() function finds the longest and smallest palindrome word by extracting every word of the string and passing it to checkPalin() function and then updating the answer string for the smallest and longest string by comparing it with the length of the original string if it is a palindrome.
checkPalin() function checks if the word is palindrome. It returns true if word is palindrome else returns false. It makes sure that empty strings are not counted as palindrome as the user may enter more than one spaces in between or at the beginning of the string
Example:
Java
// Java program to print the smallest and// longest palindromic word out of the words of a sentence public class Main { // Function to check if a // word is palindrome public static boolean checkPalin(String word) { int n = word.length(); // making the check case // case insensitive word = word.toLowerCase(); // loop to check palindrome for (int i = 0; i < n; i++, n--) { if (word.charAt(i) != word.charAt(n - 1)) return false; } return true; } // Determine the smallest and biggest // palindromes in a given string public static void lengthPalindrome(int temp, String words[]) { int count = 0; String smallest = "", longest = ""; for (int i = 0; i < temp; i++) { if (checkPalin(words[i])) { count++; // Initialize smallest and longest // when first palindromic word // is found if (count == 1) smallest = longest = words[i]; // Compare smallest and longest with each // palindromic words else { // If length of smallest is greater // than next palindromic word then // Store that word in smallest if (smallest.length() > words[i].length()) smallest = words[i]; // If length of longest is less // than next palindromic word then // Store that word in longest if (longest.length() < words[i].length()) longest = words[i]; } } } if (count == 0) System.out.println("No palindrome found"); else { System.out.println("Smallest palindrome: " + smallest); System.out.println("Biggest palindrome: " + longest); } } public static void main(String[] args) { String string = "Wow Madam is driving racecar"; String word = ""; String[] words = new String[100]; int temp = 0; // Add extra space after string // to get the last word string = string + " "; for (int i = 0; i < string.length(); i++) { // Split the string into words if (string.charAt(i) != ' ') { word = word + string.charAt(i); } else { // Add word to array words words[temp] = word; temp++; word = ""; } } System.out.println("Inputted String : " + string); lengthPalindrome(temp, words); }}
Inputted String : Wow Madam is driving racecar
Smallest palindrome: Wow
Biggest palindrome: racecar
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Multidimensional Arrays in Java
Initialize an ArrayList in Java
LinkedList in Java
ArrayList in Java
Initializing a List in Java
Convert a String to Character Array in Java
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 25881,
"s": 25673,
"text": "A Palindrome String is a string whose reversed string is equal to the original string. In this Java Program, we are going to see the approach of printing the smallest and biggest palindrome word in a String."
},
{
"code": null,
"e": 26015,
"s": 25881,
"text": "Given a sentence of words in the form of a string, and we need to print the smallest and longest palindromic word out of those words."
},
{
"code": null,
"e": 26348,
"s": 26015,
"text": "Input: Wow madam is driving racecar.\n\nSmallest Palindrome: Wow\nLongest Palindrome: racecar\nExplanation: The string contains three palindrome words (i.e., madam, Wow, racecar) \n but the length of racecar is greatest and that of wow is smallest.\n\n\nInput: \"Nitin is a good guy\"\n\nSmallest Palindrome: a\nLongest Palindrome: Nitin"
},
{
"code": null,
"e": 26358,
"s": 26348,
"text": "Approach:"
},
{
"code": null,
"e": 26663,
"s": 26358,
"text": "lengthPalindrome() function finds the longest and smallest palindrome word by extracting every word of the string and passing it to checkPalin() function and then updating the answer string for the smallest and longest string by comparing it with the length of the original string if it is a palindrome. "
},
{
"code": null,
"e": 26928,
"s": 26663,
"text": "checkPalin() function checks if the word is palindrome. It returns true if word is palindrome else returns false. It makes sure that empty strings are not counted as palindrome as the user may enter more than one spaces in between or at the beginning of the string"
},
{
"code": null,
"e": 26937,
"s": 26928,
"text": "Example:"
},
{
"code": null,
"e": 26942,
"s": 26937,
"text": "Java"
},
{
"code": "// Java program to print the smallest and// longest palindromic word out of the words of a sentence public class Main { // Function to check if a // word is palindrome public static boolean checkPalin(String word) { int n = word.length(); // making the check case // case insensitive word = word.toLowerCase(); // loop to check palindrome for (int i = 0; i < n; i++, n--) { if (word.charAt(i) != word.charAt(n - 1)) return false; } return true; } // Determine the smallest and biggest // palindromes in a given string public static void lengthPalindrome(int temp, String words[]) { int count = 0; String smallest = \"\", longest = \"\"; for (int i = 0; i < temp; i++) { if (checkPalin(words[i])) { count++; // Initialize smallest and longest // when first palindromic word // is found if (count == 1) smallest = longest = words[i]; // Compare smallest and longest with each // palindromic words else { // If length of smallest is greater // than next palindromic word then // Store that word in smallest if (smallest.length() > words[i].length()) smallest = words[i]; // If length of longest is less // than next palindromic word then // Store that word in longest if (longest.length() < words[i].length()) longest = words[i]; } } } if (count == 0) System.out.println(\"No palindrome found\"); else { System.out.println(\"Smallest palindrome: \" + smallest); System.out.println(\"Biggest palindrome: \" + longest); } } public static void main(String[] args) { String string = \"Wow Madam is driving racecar\"; String word = \"\"; String[] words = new String[100]; int temp = 0; // Add extra space after string // to get the last word string = string + \" \"; for (int i = 0; i < string.length(); i++) { // Split the string into words if (string.charAt(i) != ' ') { word = word + string.charAt(i); } else { // Add word to array words words[temp] = word; temp++; word = \"\"; } } System.out.println(\"Inputted String : \" + string); lengthPalindrome(temp, words); }}",
"e": 29969,
"s": 26942,
"text": null
},
{
"code": null,
"e": 30070,
"s": 29969,
"text": "Inputted String : Wow Madam is driving racecar \nSmallest palindrome: Wow\nBiggest palindrome: racecar"
},
{
"code": null,
"e": 30091,
"s": 30070,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 30098,
"s": 30091,
"text": "Picked"
},
{
"code": null,
"e": 30103,
"s": 30098,
"text": "Java"
},
{
"code": null,
"e": 30117,
"s": 30103,
"text": "Java Programs"
},
{
"code": null,
"e": 30122,
"s": 30117,
"text": "Java"
},
{
"code": null,
"e": 30220,
"s": 30122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30250,
"s": 30220,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30282,
"s": 30250,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30314,
"s": 30282,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30333,
"s": 30314,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 30351,
"s": 30333,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30379,
"s": 30351,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 30423,
"s": 30379,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 30455,
"s": 30423,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 30503,
"s": 30455,
"text": "Iterate Over the Characters of a String in Java"
}
] |
Python - Convert String to Nested Dictionaries - GeeksforGeeks
|
14 May, 2020
Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let’s discuss certain way in which this task can be done.
Method : Using loop + recursionThis is way in which this task can be performed. In this, we recur for nesting of dictionary as we encounter a separator occurrence.
# Python3 code to demonstrate working of # Convert String to Nested Dictionaries# Using loop def helper_fnc(test_str, sep): if sep not in test_str: return test_str key, val = test_str.split(sep, 1) return {key: helper_fnc(val, sep)} # initializing stringtest_str = 'gfg_is_best_for_geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing separatorsep = '_' # Convert String to Nested Dictionaries# Using loopres = helper_fnc(test_str, sep) # printing result print("The nested dictionary is : " + str(res))
The original string is : gfg_is_best_for_geeks
The nested dictionary is : {'gfg': {'is': {'best': {'for': 'geeks'}}}}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 25943,
"s": 25627,
"text": "Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let’s discuss certain way in which this task can be done."
},
{
"code": null,
"e": 26107,
"s": 25943,
"text": "Method : Using loop + recursionThis is way in which this task can be performed. In this, we recur for nesting of dictionary as we encounter a separator occurrence."
},
{
"code": "# Python3 code to demonstrate working of # Convert String to Nested Dictionaries# Using loop def helper_fnc(test_str, sep): if sep not in test_str: return test_str key, val = test_str.split(sep, 1) return {key: helper_fnc(val, sep)} # initializing stringtest_str = 'gfg_is_best_for_geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing separatorsep = '_' # Convert String to Nested Dictionaries# Using loopres = helper_fnc(test_str, sep) # printing result print(\"The nested dictionary is : \" + str(res)) ",
"e": 26669,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26788,
"s": 26669,
"text": "The original string is : gfg_is_best_for_geeks\nThe nested dictionary is : {'gfg': {'is': {'best': {'for': 'geeks'}}}}\n"
},
{
"code": null,
"e": 26817,
"s": 26790,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26842,
"s": 26817,
"text": "Python-nested-dictionary"
},
{
"code": null,
"e": 26849,
"s": 26842,
"text": "Python"
},
{
"code": null,
"e": 26865,
"s": 26849,
"text": "Python Programs"
},
{
"code": null,
"e": 26963,
"s": 26865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26998,
"s": 26963,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27030,
"s": 26998,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27052,
"s": 27030,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27094,
"s": 27052,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27124,
"s": 27094,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27167,
"s": 27124,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27189,
"s": 27167,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27228,
"s": 27189,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27274,
"s": 27228,
"text": "Python | Split string into list of characters"
}
] |
Compute the integer absolute value (abs) without branching - GeeksforGeeks
|
24 Mar, 2022
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2’s complement form, to get the absolute value of a negative number we have to toggle bits of the number and add 1 to the result.For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is the sign bit. To get the absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e, 0 0 0 0 0 0 0 1 + 1 will give the absolute value of 1 1 1 1 1 1 1 0. Also remember, we need to do these operations only if the number is negative (sign bit is set).Method 1 1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number.
mask + n
3) XOR of mask +n and mask gives the absolute value.
(mask + n)^mask
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;#define CHARBIT 8 /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHARBIT - 1); return ((n + mask) ^ mask);} /* Driver program to test above function */int main(){ int n = -6; cout << "Absolute value of " << n << " is " << getAbs(n); return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>#define CHAR_BIT 8 /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n + mask) ^ mask);} /* Driver program to test above function */int main(){ int n = -6; printf("Absolute value of %d is %u", n, getAbs(n)); getchar(); return 0;}
// Java implementation of above approachclass GFG { static final int CHAR_BIT = 8; static final int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ public static void main(String[] args) { int n = -6; System.out.print("Absolute value of " + n + " is " + getAbs(n)); }} // This code is contributed by Rajput-Ji
# Python3 implementation of above approachCHARBIT = 8;SIZE_INT = 8; # This function will return# absolute value of ndef getAbs(n): mask = n >> (SIZE_INT * CHARBIT - 1); return ((n + mask) ^ mask); # Driver Coden = -6;print("Absolute value of",n,"is",getAbs(n)); # This code is contributed by mits
// C# implementation of above approachusing System; class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ static void Main() { int n = -6; Console.Write("Absolute value of " + n + " is " + getAbs(n)); }} // This code is contributed by mits
<?php// PHP implementation of above approach$CHARBIT = 8;$SIZE_INT = 8; // This function will return// absolute value of nfunction getAbs($n){ global $SIZE_INT, $CHARBIT; $mask = $n >> ($SIZE_INT * $CHARBIT - 1); return (($n + $mask) ^ $mask);} // Driver Code$n = -6;echo "Absolute value of " . $n . " is " . getAbs($n); // This code is contributed by mits?>
<script>// javascript implementation of above approach var CHAR_BIT = 8;var SIZE_INT = 8; /* This function will return absolute value of n */ function getAbs(n) { var mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ var n = -6; document.write("Absolute value of " + n + " is " + getAbs(n)); // This code is contributed by shikhasingrajput</script>
Output:
Absolute value of -6 is 6
Method 2: 1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) XOR the mask with number
mask ^ n
3) Subtract mask from result of step 2 and return the result.
(mask^n) - mask
Implementation:
C++
C
Java
Python3
C#
#include <bits/stdc++.h>using namespace std; /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask);} /* Driver program to test above function */int main(){ int n = -6; cout << "Absolute value of " << n << " is " << getAbs(n); return 0;} // This code is contributed by phalasi.
#include <stdio.h>#include <limits.h> //to include CHAR_BIT /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask);} /* Driver program to test above function */int main(){ int n = -6; printf("Absolute value of %d is %d\n", n, getAbs(n)); return 0;}
// Java implementation of above approachclass GFG { /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } } // This code is contributed by code_hunt.
import osimport sys # This function will return absolute value of ndef getAbs(n): mask = n >> (sys.getsizeof(int()) * os.sysconf('SC_CHAR_BIT') - 1) return ((n ^ mask) - mask) # Driver coden = -6print("The absolute value of", n, "is", getAbs(n)) # This code is contributed by phalasi.
// C# implementation of above approachusing System; public class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); }} // This code is contributed by Rajput-Ji
Output:
Absolute value of -6 is 6
On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.Please see this for more details about the above two methods.Please write comments if you find any of the above explanations/algorithms incorrect, or a better ways to solve the same problem.References: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
Rajput-Ji
rathbhupendra
Mithun Kumar
Akanksha_Rai
shikhasingrajput
simmytarika5
code_hunt
phasing17
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Find the size of Largest Subset with positive Bitwise AND
Check whether bitwise AND of a number with any subset of an array is zero or not
Write an Efficient Method to Check if a Number is Multiple of 3
Highest power of 2 less than or equal to given number
Swap two nibbles in a byte
Swap bits in a given number
Check for Integer Overflow
Reverse actual bits of the given number
Find one extra character in a string
|
[
{
"code": null,
"e": 26159,
"s": 26131,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 26905,
"s": 26159,
"text": "We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2’s complement form, to get the absolute value of a negative number we have to toggle bits of the number and add 1 to the result.For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is the sign bit. To get the absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e, 0 0 0 0 0 0 0 1 + 1 will give the absolute value of 1 1 1 1 1 1 1 0. Also remember, we need to do these operations only if the number is negative (sign bit is set).Method 1 1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits). "
},
{
"code": null,
"e": 26920,
"s": 26905,
"text": " mask = n>>31 "
},
{
"code": null,
"e": 27063,
"s": 26920,
"text": "2) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number. "
},
{
"code": null,
"e": 27074,
"s": 27063,
"text": " mask + n "
},
{
"code": null,
"e": 27129,
"s": 27074,
"text": "3) XOR of mask +n and mask gives the absolute value. "
},
{
"code": null,
"e": 27147,
"s": 27129,
"text": " (mask + n)^mask "
},
{
"code": null,
"e": 27164,
"s": 27147,
"text": "Implementation: "
},
{
"code": null,
"e": 27168,
"s": 27164,
"text": "C++"
},
{
"code": null,
"e": 27170,
"s": 27168,
"text": "C"
},
{
"code": null,
"e": 27175,
"s": 27170,
"text": "Java"
},
{
"code": null,
"e": 27183,
"s": 27175,
"text": "Python3"
},
{
"code": null,
"e": 27186,
"s": 27183,
"text": "C#"
},
{
"code": null,
"e": 27190,
"s": 27186,
"text": "PHP"
},
{
"code": null,
"e": 27201,
"s": 27190,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define CHARBIT 8 /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHARBIT - 1); return ((n + mask) ^ mask);} /* Driver program to test above function */int main(){ int n = -6; cout << \"Absolute value of \" << n << \" is \" << getAbs(n); return 0;} // This code is contributed by rathbhupendra",
"e": 27617,
"s": 27201,
"text": null
},
{
"code": "#include <stdio.h>#define CHAR_BIT 8 /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n + mask) ^ mask);} /* Driver program to test above function */int main(){ int n = -6; printf(\"Absolute value of %d is %u\", n, getAbs(n)); getchar(); return 0;}",
"e": 27973,
"s": 27617,
"text": null
},
{
"code": "// Java implementation of above approachclass GFG { static final int CHAR_BIT = 8; static final int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ public static void main(String[] args) { int n = -6; System.out.print(\"Absolute value of \" + n + \" is \" + getAbs(n)); }} // This code is contributed by Rajput-Ji",
"e": 28479,
"s": 27973,
"text": null
},
{
"code": "# Python3 implementation of above approachCHARBIT = 8;SIZE_INT = 8; # This function will return# absolute value of ndef getAbs(n): mask = n >> (SIZE_INT * CHARBIT - 1); return ((n + mask) ^ mask); # Driver Coden = -6;print(\"Absolute value of\",n,\"is\",getAbs(n)); # This code is contributed by mits",
"e": 28782,
"s": 28479,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ static void Main() { int n = -6; Console.Write(\"Absolute value of \" + n + \" is \" + getAbs(n)); }} // This code is contributed by mits",
"e": 29260,
"s": 28782,
"text": null
},
{
"code": "<?php// PHP implementation of above approach$CHARBIT = 8;$SIZE_INT = 8; // This function will return// absolute value of nfunction getAbs($n){ global $SIZE_INT, $CHARBIT; $mask = $n >> ($SIZE_INT * $CHARBIT - 1); return (($n + $mask) ^ $mask);} // Driver Code$n = -6;echo \"Absolute value of \" . $n . \" is \" . getAbs($n); // This code is contributed by mits?>",
"e": 29639,
"s": 29260,
"text": null
},
{
"code": "<script>// javascript implementation of above approach var CHAR_BIT = 8;var SIZE_INT = 8; /* This function will return absolute value of n */ function getAbs(n) { var mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } /* Driver code */ var n = -6; document.write(\"Absolute value of \" + n + \" is \" + getAbs(n)); // This code is contributed by shikhasingrajput</script>",
"e": 30072,
"s": 29639,
"text": null
},
{
"code": null,
"e": 30082,
"s": 30072,
"text": "Output: "
},
{
"code": null,
"e": 30108,
"s": 30082,
"text": "Absolute value of -6 is 6"
},
{
"code": null,
"e": 30214,
"s": 30108,
"text": "Method 2: 1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits). "
},
{
"code": null,
"e": 30229,
"s": 30214,
"text": " mask = n>>31 "
},
{
"code": null,
"e": 30259,
"s": 30229,
"text": "2) XOR the mask with number "
},
{
"code": null,
"e": 30270,
"s": 30259,
"text": " mask ^ n "
},
{
"code": null,
"e": 30334,
"s": 30270,
"text": "3) Subtract mask from result of step 2 and return the result. "
},
{
"code": null,
"e": 30352,
"s": 30334,
"text": " (mask^n) - mask "
},
{
"code": null,
"e": 30369,
"s": 30352,
"text": "Implementation: "
},
{
"code": null,
"e": 30373,
"s": 30369,
"text": "C++"
},
{
"code": null,
"e": 30375,
"s": 30373,
"text": "C"
},
{
"code": null,
"e": 30380,
"s": 30375,
"text": "Java"
},
{
"code": null,
"e": 30388,
"s": 30380,
"text": "Python3"
},
{
"code": null,
"e": 30391,
"s": 30388,
"text": "C#"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask);} /* Driver program to test above function */int main(){ int n = -6; cout << \"Absolute value of \" << n << \" is \" << getAbs(n); return 0;} // This code is contributed by phalasi.",
"e": 30786,
"s": 30391,
"text": null
},
{
"code": "#include <stdio.h>#include <limits.h> //to include CHAR_BIT /* This function will return absolute value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n ^ mask) - mask);} /* Driver program to test above function */int main(){ int n = -6; printf(\"Absolute value of %d is %d\\n\", n, getAbs(n)); return 0;}",
"e": 31152,
"s": 30786,
"text": null
},
{
"code": "// Java implementation of above approachclass GFG { /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); } } // This code is contributed by code_hunt.",
"e": 31426,
"s": 31152,
"text": null
},
{
"code": "import osimport sys # This function will return absolute value of ndef getAbs(n): mask = n >> (sys.getsizeof(int()) * os.sysconf('SC_CHAR_BIT') - 1) return ((n ^ mask) - mask) # Driver coden = -6print(\"The absolute value of\", n, \"is\", getAbs(n)) # This code is contributed by phalasi.",
"e": 31713,
"s": 31426,
"text": null
},
{
"code": "// C# implementation of above approachusing System; public class GFG { static int CHAR_BIT = 8; static int SIZE_INT = 8; /* This function will return absolute value of n*/ static int getAbs(int n) { int mask = n >> (SIZE_INT * CHAR_BIT - 1); return ((n + mask) ^ mask); }} // This code is contributed by Rajput-Ji",
"e": 32063,
"s": 31713,
"text": null
},
{
"code": null,
"e": 32072,
"s": 32063,
"text": "Output: "
},
{
"code": null,
"e": 32098,
"s": 32072,
"text": "Absolute value of -6 is 6"
},
{
"code": null,
"e": 32549,
"s": 32098,
"text": "On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.Please see this for more details about the above two methods.Please write comments if you find any of the above explanations/algorithms incorrect, or a better ways to solve the same problem.References: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs "
},
{
"code": null,
"e": 32559,
"s": 32549,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32573,
"s": 32559,
"text": "rathbhupendra"
},
{
"code": null,
"e": 32586,
"s": 32573,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32599,
"s": 32586,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32616,
"s": 32599,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 32629,
"s": 32616,
"text": "simmytarika5"
},
{
"code": null,
"e": 32639,
"s": 32629,
"text": "code_hunt"
},
{
"code": null,
"e": 32649,
"s": 32639,
"text": "phasing17"
},
{
"code": null,
"e": 32659,
"s": 32649,
"text": "Bit Magic"
},
{
"code": null,
"e": 32669,
"s": 32659,
"text": "Bit Magic"
},
{
"code": null,
"e": 32767,
"s": 32669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32818,
"s": 32767,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 32876,
"s": 32818,
"text": "Find the size of Largest Subset with positive Bitwise AND"
},
{
"code": null,
"e": 32957,
"s": 32876,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 33021,
"s": 32957,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 33075,
"s": 33021,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 33102,
"s": 33075,
"text": "Swap two nibbles in a byte"
},
{
"code": null,
"e": 33130,
"s": 33102,
"text": "Swap bits in a given number"
},
{
"code": null,
"e": 33157,
"s": 33130,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 33197,
"s": 33157,
"text": "Reverse actual bits of the given number"
}
] |
Suffix Array | Set 2 (nLogn Algorithm) - GeeksforGeeks
|
21 Apr, 2022
Given a string, the task is to construct a suffix array for the given string.
A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text.
Examples:
Input: str = “banana”Output: {5, 3, 1, 0, 4, 2}Explanation:Suffix per index Suffix sorted alphabetically———————– —————————————–0 banana 5 a1 anana Sort the Suffixes 3 ana2 nana ————————-> 1 anana 3 ana alphabetically 0 banana 4 na 4 na 5 a 2 nanaSo the suffix array for “banana” is {5, 3, 1, 0, 4, 2}
Input: str = “geeksforgeeks”Output: {10 9 2 1 5 8 0 11 3 6 7 12 4}Explanation:0 geeksforgeeks 10 eks1 eeksforgeeks 9 eeks2 eksforgeeks 2 eksforgeeks3 ksforgeeks 1 eeksforgeeks4 sforgeeks 5 forgeeks5 forgeeks 8 geeks6 orgeeks ——————> 0 geeksforgeeks7 rgeeks 11 ks8 geeks 3 ksforgeeks9 eeks 6 orgeeks10 eks 7 rgeeks11 ks 12 s12 s 4 sforgeeksSuffix array for “geeksforgeeks” is {10 9 2 1 5 8 0 11 3 6 7 12 4 }
Naive Approach: We have discussed Naive algorithm for construction of suffix array. The Naive algorithm is to consider all suffixes, sort them using a O(nLogn) sorting algorithm and while sorting, maintain original indexes. Time complexity: O(n2 log(n)), where n is the number of characters in the input string.
Optimised Approach: In this post, a O(nLogn) algorithm for suffix array construction is discussed. Let us first discuss a O(n * Logn * Logn) algorithm for simplicity. The idea is to use the fact that strings that are to be sorted are suffixes of a single string. We first sort all suffixes according to first character, then according to first 2 characters, then first 4 characters and so on while the number of characters to be considered is smaller than 2n. The important point is, if we have sorted suffixes according to first 2i characters, then we can sort suffixes according to first 2i+1 characters in O(nLogn) time using a nLogn sorting algorithm like Merge Sort. This is possible as two suffixes can be compared in O(1) time (we need to compare only two values, see the below example and code).
The sort function is called O(Logn) times (Note that we increase number of characters to be considered in powers of 2). Therefore overall time complexity becomes O(nLognLogn). See http://www.stanford.edu/class/cs97si/suffix-array.pdf for more details.
Let us build suffix array the example string “banana” using above algorithm.
Sort according to first two characters Assign a rank to all suffixes using ASCII value of first character. A simple way to assign rank is to do “str[i] – ‘a'” for ith suffix of strp[]
Index Suffix Rank
0 banana 1
1 anana 0
2 nana 13
3 ana 0
4 na 13
5 a 0
For every character, we also store rank of next adjacent character, i.e., the rank of character at str[i + 1] (This is needed to sort the suffixes according to first 2 characters). If a character is last character, we store next rank as -1
Index Suffix Rank Next Rank
0 banana 1 0
1 anana 0 13
2 nana 13 0
3 ana 0 13
4 na 13 0
5 a 0 -1
Sort all Suffixes according to rank and adjacent rank. Rank is considered as first digit or MSD, and adjacent rank is considered as second digit.
Index Suffix Rank Next Rank
5 a 0 -1
1 anana 0 13
3 ana 0 13
0 banana 1 0
2 nana 13 0
4 na 13 0
Sort according to first four character Assign new ranks to all suffixes. To assign new ranks, we consider the sorted suffixes one by one. Assign 0 as new rank to first suffix. For assigning ranks to remaining suffixes, we consider rank pair of suffix just before the current suffix. If previous rank pair of a suffix is same as previous rank of suffix just before it, then assign it same rank. Otherwise assign rank of previous suffix plus one.
Index Suffix Rank
5 a 0 [Assign 0 to first]
1 anana 1 (0, 13) is different from previous
3 ana 1 (0, 13) is same as previous
0 banana 2 (1, 0) is different from previous
2 nana 3 (13, 0) is different from previous
4 na 3 (13, 0) is same as previous
For every suffix str[i], also store rank of next suffix at str[i + 2]. If there is no next suffix at i + 2, we store next rank as -1
Index Suffix Rank Next Rank
5 a 0 -1
1 anana 1 1
3 ana 1 0
0 banana 2 3
2 nana 3 3
4 na 3 -1
Sort all Suffixes according to rank and next rank.
Index Suffix Rank Next Rank
5 a 0 -1
3 ana 1 0
1 anana 1 1
0 banana 2 3
4 na 3 -1
2 nana 3 3
C++
Java
Python3
Javascript
// C++ program for building suffix array of a given text#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next rank pair}; // A comparison function used by sort() to compare two suffixes// Compares two pairs, returns 1 if first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string 'txt' of size n as an// argument, builds and return the suffix array for the given stringint *buildSuffixArray(char *txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabetically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At this point, all suffixes are sorted according to first // 2 characters. Let us sort suffixes according to first 4 // characters, then first 8 and so on int ind[n]; // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as that of previous // suffix in array, assign the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix array int *suffixArr = new int[n]; for (int i = 0; i < n; i++) suffixArr[i] = suffixes[i].index; // Return the suffix array return suffixArr;} // A utility function to print an array of given sizevoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver program to test above functionsint main(){ char txt[] = "banana"; int n = strlen(txt); int *suffixArr = buildSuffixArray(txt, n); cout << "Following is suffix array for " << txt << endl; printArr(suffixArr, n); return 0;}
// Java program for building suffix array of a given textimport java.util.*;class GFG{ // Class to store information of a suffix public static class Suffix implements Comparable<Suffix> { int index; int rank; int next; public Suffix(int ind, int r, int nr) { index = ind; rank = r; next = nr; } // A comparison function used by sort() // to compare two suffixes. // Compares two pairs, returns 1 // if first pair is smaller public int compareTo(Suffix s) { if (rank != s.rank) return Integer.compare(rank, s.rank); return Integer.compare(next, s.next); } } // This is the main function that takes a string 'txt' // of size n as an argument, builds and return the // suffix array for the given string public static int[] suffixArray(String s) { int n = s.length(); Suffix[] su = new Suffix[n]; // Store suffixes and their indexes in // an array of classes. The class is needed // to sort the suffixes alphabetically and // maintain their old indexes while sorting for (int i = 0; i < n; i++) { su[i] = new Suffix(i, s.charAt(i) - '$', 0); } for (int i = 0; i < n; i++) su[i].next = (i + 1 < n ? su[i + 1].rank : -1); // Sort the suffixes using the comparison function // defined above. Arrays.sort(su); // At this point, all suffixes are sorted // according to first 2 characters. // Let us sort suffixes according to first 4 // characters, then first 8 and so on int[] ind = new int[n]; // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (int length = 4; length < 2 * n; length <<= 1) { // Assigning rank and index values to first suffix int rank = 0, prev = su[0].rank; su[0].rank = rank; ind[su[0].index] = 0; for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, // assign the same new rank to this suffix if (su[i].rank == prev && su[i].next == su[i - 1].next) { prev = su[i].rank; su[i].rank = rank; } else { // Otherwise increment rank and assign prev = su[i].rank; su[i].rank = ++rank; } ind[su[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextP = su[i].index + length / 2; su[i].next = nextP < n ? su[ind[nextP]].rank : -1; } // Sort the suffixes according // to first k characters Arrays.sort(su); } // Store indexes of all sorted // suffixes in the suffix array int[] suf = new int[n]; for (int i = 0; i < n; i++) suf[i] = su[i].index; // Return the suffix array return suf; } static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver Code public static void main(String[] args) { String txt = "banana"; int n = txt.length(); int[] suff_arr = suffixArray(txt); System.out.println("Following is suffix array for banana:"); printArr(suff_arr, n); }} // This code is contributed by AmanKumarSingh
# Python3 program for building suffix# array of a given text # Class to store information of a suffixclass suffix: def __init__(self): self.index = 0 self.rank = [0, 0] # This is the main function that takes a# string 'txt' of size n as an argument,# builds and return the suffix array for# the given stringdef buildSuffixArray(txt, n): # A structure to store suffixes # and their indexes suffixes = [suffix() for _ in range(n)] # Store suffixes and their indexes in # an array of structures. The structure # is needed to sort the suffixes alphabetically # and maintain their old indexes while sorting for i in range(n): suffixes[i].index = i suffixes[i].rank[0] = (ord(txt[i]) - ord("a")) suffixes[i].rank[1] = (ord(txt[i + 1]) - ord("a")) if ((i + 1) < n) else -1 # Sort the suffixes according to the rank # and next rank suffixes = sorted( suffixes, key = lambda x: ( x.rank[0], x.rank[1])) # At this point, all suffixes are sorted # according to first 2 characters. Let # us sort suffixes according to first 4 # characters, then first 8 and so on ind = [0] * n # This array is needed to get the # index in suffixes[] from original # index.This mapping is needed to get # next suffix. k = 4 while (k < 2 * n): # Assigning rank and index # values to first suffix rank = 0 prev_rank = suffixes[0].rank[0] suffixes[0].rank[0] = rank ind[suffixes[0].index] = 0 # Assigning rank to suffixes for i in range(1, n): # If first rank and next ranks are # same as that of previous suffix in # array, assign the same new rank to # this suffix if (suffixes[i].rank[0] == prev_rank and suffixes[i].rank[1] == suffixes[i - 1].rank[1]): prev_rank = suffixes[i].rank[0] suffixes[i].rank[0] = rank # Otherwise increment rank and assign else: prev_rank = suffixes[i].rank[0] rank += 1 suffixes[i].rank[0] = rank ind[suffixes[i].index] = i # Assign next rank to every suffix for i in range(n): nextindex = suffixes[i].index + k // 2 suffixes[i].rank[1] = suffixes[ind[nextindex]].rank[0] \ if (nextindex < n) else -1 # Sort the suffixes according to # first k characters suffixes = sorted( suffixes, key = lambda x: ( x.rank[0], x.rank[1])) k *= 2 # Store indexes of all sorted # suffixes in the suffix array suffixArr = [0] * n for i in range(n): suffixArr[i] = suffixes[i].index # Return the suffix array return suffixArr # A utility function to print an array# of given sizedef printArr(arr, n): for i in range(n): print(arr[i], end = " ") print() # Driver codeif __name__ == "__main__": txt = "banana" n = len(txt) suffixArr = buildSuffixArray(txt, n) print("Following is suffix array for", txt) printArr(suffixArr, n) # This code is contributed by debrc
<script>// Javascript program for building suffix array of a given text // Class to store information of a suffixclass Suffix{ constructor(ind,r,nr) { this.index = ind; this.rank = r; this.next = nr; } } // This is the main function that takes a string 'txt' // of size n as an argument, builds and return the // suffix array for the given stringfunction suffixArray(s){ let n = s.length; let su = new Array(n); // Store suffixes and their indexes in // an array of classes. The class is needed // to sort the suffixes alphabetically and // maintain their old indexes while sorting for (let i = 0; i < n; i++) { su[i] = new Suffix(i, s[i].charCodeAt(0) - '$'.charCodeAt(0), 0); } for (let i = 0; i < n; i++) su[i].next = (i + 1 < n ? su[i + 1].rank : -1); // Sort the suffixes using the comparison function // defined above. su.sort(function(a,b){ if(a.rank!=b.rank) return a.rank-b.rank; else return a.next-b.next; }); // At this point, all suffixes are sorted // according to first 2 characters. // Let us sort suffixes according to first 4 // characters, then first 8 and so on let ind = new Array(n); // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (let length = 4; length < 2 * n; length <<= 1) { // Assigning rank and index values to first suffix let rank = 0, prev = su[0].rank; su[0].rank = rank; ind[su[0].index] = 0; for (let i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, // assign the same new rank to this suffix if (su[i].rank == prev && su[i].next == su[i - 1].next) { prev = su[i].rank; su[i].rank = rank; } else { // Otherwise increment rank and assign prev = su[i].rank; su[i].rank = ++rank; } ind[su[i].index] = i; } // Assign next rank to every suffix for (let i = 0; i < n; i++) { let nextP = su[i].index + length / 2; su[i].next = nextP < n ? su[ind[nextP]].rank : -1; } // Sort the suffixes according // to first k characters su.sort(function(a,b){ if(a.rank!=b.rank) return a.rank-b.rank; else return a.next-b.next; }); } // Store indexes of all sorted // suffixes in the suffix array let suf = new Array(n); for (let i = 0; i < n; i++) suf[i] = su[i].index; // Return the suffix array return suf;} function printArr(arr,n){ for (let i = 0; i < n; i++) document.write(arr[i] + " "); document.write();} // Driver Codelet txt = "banana";let n = txt.length;let suff_arr = suffixArray(txt);document.write("Following is suffix array for banana:<br>");printArr(suff_arr, n); // This code is contributed by patel2127</script>
Following is suffix array for banana
5 3 1 0 4 2
Note that the above algorithm uses standard sort function and therefore time complexity is O(nLognLogn). We can use Radix Sort here to reduce the time complexity to O(nLogn).
Method 2:
The problem can also be solved using the map.
Algorithm:
1) Create a map with a key string and its value is an integer.
2) Iterate over the string in reverse order and create a new string(i.e from i = n – 1, 0).
3) Map new string with the last index position of I.
4) Create an array and assign all values of the map in the array.
C++14
// C++14 program to build a suffix array in O(nlogn) time; #include <bits/stdc++.h>using namespace std; int main(){ string s = "banana"; int n = s.length(); map<string, int> Map; int suffix[n]; // Mapping string with its index of // it's last letter. string sub = ""; for (int i = n - 1; i >= 0; i--) { sub = s[i] + sub; Map[sub] = i; } // Storing all values of map // in suffix array. int j = 0; for (auto x : Map) { suffix[j] = x.second; j++; } // printing suffix array. cout << "Suffix array for banana is" << endl; for (int i = 0; i < n; i++) { cout << suffix[i] << " "; } cout << endl; return 0;}
Suffix array for banana is
5 3 1 0 4 2
The time complexity of the algorithm is O(N log N). Please note that suffix arrays can be constructed in O(n) time also. We will soon be discussing O(n) algorithms.
References: http://www.stanford.edu/class/cs97si/suffix-array.pdf http://www.cbcb.umd.edu/confcour/Fall2012/lec14b.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akash Kumar 31
AmanKumarSingh
debrc
simmytarika5
patel2127
surindertarika1234
siddharthsingh7898
thilakreddy
Suffix-Array
Advanced Data Structure
Pattern Searching
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Ordered Set and GNU C++ PBDS
Insert Operation in B-Tree
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 26035,
"s": 26007,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 26113,
"s": 26035,
"text": "Given a string, the task is to construct a suffix array for the given string."
},
{
"code": null,
"e": 26282,
"s": 26113,
"text": "A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text."
},
{
"code": null,
"e": 26292,
"s": 26282,
"text": "Examples:"
},
{
"code": null,
"e": 26841,
"s": 26292,
"text": "Input: str = “banana”Output: {5, 3, 1, 0, 4, 2}Explanation:Suffix per index Suffix sorted alphabetically———————– —————————————–0 banana 5 a1 anana Sort the Suffixes 3 ana2 nana ————————-> 1 anana 3 ana alphabetically 0 banana 4 na 4 na 5 a 2 nanaSo the suffix array for “banana” is {5, 3, 1, 0, 4, 2}"
},
{
"code": null,
"e": 27824,
"s": 26841,
"text": "Input: str = “geeksforgeeks”Output: {10 9 2 1 5 8 0 11 3 6 7 12 4}Explanation:0 geeksforgeeks 10 eks1 eeksforgeeks 9 eeks2 eksforgeeks 2 eksforgeeks3 ksforgeeks 1 eeksforgeeks4 sforgeeks 5 forgeeks5 forgeeks 8 geeks6 orgeeks ——————> 0 geeksforgeeks7 rgeeks 11 ks8 geeks 3 ksforgeeks9 eeks 6 orgeeks10 eks 7 rgeeks11 ks 12 s12 s 4 sforgeeksSuffix array for “geeksforgeeks” is {10 9 2 1 5 8 0 11 3 6 7 12 4 }"
},
{
"code": null,
"e": 28136,
"s": 27824,
"text": "Naive Approach: We have discussed Naive algorithm for construction of suffix array. The Naive algorithm is to consider all suffixes, sort them using a O(nLogn) sorting algorithm and while sorting, maintain original indexes. Time complexity: O(n2 log(n)), where n is the number of characters in the input string."
},
{
"code": null,
"e": 28941,
"s": 28136,
"text": "Optimised Approach: In this post, a O(nLogn) algorithm for suffix array construction is discussed. Let us first discuss a O(n * Logn * Logn) algorithm for simplicity. The idea is to use the fact that strings that are to be sorted are suffixes of a single string. We first sort all suffixes according to first character, then according to first 2 characters, then first 4 characters and so on while the number of characters to be considered is smaller than 2n. The important point is, if we have sorted suffixes according to first 2i characters, then we can sort suffixes according to first 2i+1 characters in O(nLogn) time using a nLogn sorting algorithm like Merge Sort. This is possible as two suffixes can be compared in O(1) time (we need to compare only two values, see the below example and code). "
},
{
"code": null,
"e": 29193,
"s": 28941,
"text": "The sort function is called O(Logn) times (Note that we increase number of characters to be considered in powers of 2). Therefore overall time complexity becomes O(nLognLogn). See http://www.stanford.edu/class/cs97si/suffix-array.pdf for more details."
},
{
"code": null,
"e": 29270,
"s": 29193,
"text": "Let us build suffix array the example string “banana” using above algorithm."
},
{
"code": null,
"e": 29454,
"s": 29270,
"text": "Sort according to first two characters Assign a rank to all suffixes using ASCII value of first character. A simple way to assign rank is to do “str[i] – ‘a'” for ith suffix of strp[]"
},
{
"code": null,
"e": 29680,
"s": 29454,
"text": "Index Suffix Rank\n 0 banana 1 \n 1 anana 0 \n 2 nana 13 \n 3 ana 0\n 4 na 13\n 5 a 0"
},
{
"code": null,
"e": 29921,
"s": 29680,
"text": "For every character, we also store rank of next adjacent character, i.e., the rank of character at str[i + 1] (This is needed to sort the suffixes according to first 2 characters). If a character is last character, we store next rank as -1 "
},
{
"code": null,
"e": 30250,
"s": 29921,
"text": "Index Suffix Rank Next Rank \n 0 banana 1 0\n 1 anana 0 13 \n 2 nana 13 0\n 3 ana 0 13\n 4 na 13 0 \n 5 a 0 -1"
},
{
"code": null,
"e": 30397,
"s": 30250,
"text": "Sort all Suffixes according to rank and adjacent rank. Rank is considered as first digit or MSD, and adjacent rank is considered as second digit. "
},
{
"code": null,
"e": 30737,
"s": 30397,
"text": "Index Suffix Rank Next Rank \n 5 a 0 -1\n 1 anana 0 13 \n 3 ana 0 13\n 0 banana 1 0\n 2 nana 13 0\n 4 na 13 0"
},
{
"code": null,
"e": 31183,
"s": 30737,
"text": "Sort according to first four character Assign new ranks to all suffixes. To assign new ranks, we consider the sorted suffixes one by one. Assign 0 as new rank to first suffix. For assigning ranks to remaining suffixes, we consider rank pair of suffix just before the current suffix. If previous rank pair of a suffix is same as previous rank of suffix just before it, then assign it same rank. Otherwise assign rank of previous suffix plus one. "
},
{
"code": null,
"e": 31638,
"s": 31183,
"text": "Index Suffix Rank \n 5 a 0 [Assign 0 to first] \n 1 anana 1 (0, 13) is different from previous\n 3 ana 1 (0, 13) is same as previous \n 0 banana 2 (1, 0) is different from previous \n 2 nana 3 (13, 0) is different from previous \n 4 na 3 (13, 0) is same as previous"
},
{
"code": null,
"e": 31772,
"s": 31638,
"text": "For every suffix str[i], also store rank of next suffix at str[i + 2]. If there is no next suffix at i + 2, we store next rank as -1 "
},
{
"code": null,
"e": 32107,
"s": 31772,
"text": "Index Suffix Rank Next Rank\n 5 a 0 -1\n 1 anana 1 1 \n 3 ana 1 0 \n 0 banana 2 3\n 2 nana 3 3 \n 4 na 3 -1"
},
{
"code": null,
"e": 32159,
"s": 32107,
"text": "Sort all Suffixes according to rank and next rank. "
},
{
"code": null,
"e": 32492,
"s": 32159,
"text": "Index Suffix Rank Next Rank\n 5 a 0 -1\n 3 ana 1 0 \n 1 anana 1 1 \n 0 banana 2 3\n 4 na 3 -1\n 2 nana 3 3"
},
{
"code": null,
"e": 32496,
"s": 32492,
"text": "C++"
},
{
"code": null,
"e": 32501,
"s": 32496,
"text": "Java"
},
{
"code": null,
"e": 32509,
"s": 32501,
"text": "Python3"
},
{
"code": null,
"e": 32520,
"s": 32509,
"text": "Javascript"
},
{
"code": "// C++ program for building suffix array of a given text#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next rank pair}; // A comparison function used by sort() to compare two suffixes// Compares two pairs, returns 1 if first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string 'txt' of size n as an// argument, builds and return the suffix array for the given stringint *buildSuffixArray(char *txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabetically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At this point, all suffixes are sorted according to first // 2 characters. Let us sort suffixes according to first 4 // characters, then first 8 and so on int ind[n]; // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as that of previous // suffix in array, assign the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix array int *suffixArr = new int[n]; for (int i = 0; i < n; i++) suffixArr[i] = suffixes[i].index; // Return the suffix array return suffixArr;} // A utility function to print an array of given sizevoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver program to test above functionsint main(){ char txt[] = \"banana\"; int n = strlen(txt); int *suffixArr = buildSuffixArray(txt, n); cout << \"Following is suffix array for \" << txt << endl; printArr(suffixArr, n); return 0;}",
"e": 36097,
"s": 32520,
"text": null
},
{
"code": "// Java program for building suffix array of a given textimport java.util.*;class GFG{ // Class to store information of a suffix public static class Suffix implements Comparable<Suffix> { int index; int rank; int next; public Suffix(int ind, int r, int nr) { index = ind; rank = r; next = nr; } // A comparison function used by sort() // to compare two suffixes. // Compares two pairs, returns 1 // if first pair is smaller public int compareTo(Suffix s) { if (rank != s.rank) return Integer.compare(rank, s.rank); return Integer.compare(next, s.next); } } // This is the main function that takes a string 'txt' // of size n as an argument, builds and return the // suffix array for the given string public static int[] suffixArray(String s) { int n = s.length(); Suffix[] su = new Suffix[n]; // Store suffixes and their indexes in // an array of classes. The class is needed // to sort the suffixes alphabetically and // maintain their old indexes while sorting for (int i = 0; i < n; i++) { su[i] = new Suffix(i, s.charAt(i) - '$', 0); } for (int i = 0; i < n; i++) su[i].next = (i + 1 < n ? su[i + 1].rank : -1); // Sort the suffixes using the comparison function // defined above. Arrays.sort(su); // At this point, all suffixes are sorted // according to first 2 characters. // Let us sort suffixes according to first 4 // characters, then first 8 and so on int[] ind = new int[n]; // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (int length = 4; length < 2 * n; length <<= 1) { // Assigning rank and index values to first suffix int rank = 0, prev = su[0].rank; su[0].rank = rank; ind[su[0].index] = 0; for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, // assign the same new rank to this suffix if (su[i].rank == prev && su[i].next == su[i - 1].next) { prev = su[i].rank; su[i].rank = rank; } else { // Otherwise increment rank and assign prev = su[i].rank; su[i].rank = ++rank; } ind[su[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextP = su[i].index + length / 2; su[i].next = nextP < n ? su[ind[nextP]].rank : -1; } // Sort the suffixes according // to first k characters Arrays.sort(su); } // Store indexes of all sorted // suffixes in the suffix array int[] suf = new int[n]; for (int i = 0; i < n; i++) suf[i] = su[i].index; // Return the suffix array return suf; } static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver Code public static void main(String[] args) { String txt = \"banana\"; int n = txt.length(); int[] suff_arr = suffixArray(txt); System.out.println(\"Following is suffix array for banana:\"); printArr(suff_arr, n); }} // This code is contributed by AmanKumarSingh",
"e": 40019,
"s": 36097,
"text": null
},
{
"code": "# Python3 program for building suffix# array of a given text # Class to store information of a suffixclass suffix: def __init__(self): self.index = 0 self.rank = [0, 0] # This is the main function that takes a# string 'txt' of size n as an argument,# builds and return the suffix array for# the given stringdef buildSuffixArray(txt, n): # A structure to store suffixes # and their indexes suffixes = [suffix() for _ in range(n)] # Store suffixes and their indexes in # an array of structures. The structure # is needed to sort the suffixes alphabetically # and maintain their old indexes while sorting for i in range(n): suffixes[i].index = i suffixes[i].rank[0] = (ord(txt[i]) - ord(\"a\")) suffixes[i].rank[1] = (ord(txt[i + 1]) - ord(\"a\")) if ((i + 1) < n) else -1 # Sort the suffixes according to the rank # and next rank suffixes = sorted( suffixes, key = lambda x: ( x.rank[0], x.rank[1])) # At this point, all suffixes are sorted # according to first 2 characters. Let # us sort suffixes according to first 4 # characters, then first 8 and so on ind = [0] * n # This array is needed to get the # index in suffixes[] from original # index.This mapping is needed to get # next suffix. k = 4 while (k < 2 * n): # Assigning rank and index # values to first suffix rank = 0 prev_rank = suffixes[0].rank[0] suffixes[0].rank[0] = rank ind[suffixes[0].index] = 0 # Assigning rank to suffixes for i in range(1, n): # If first rank and next ranks are # same as that of previous suffix in # array, assign the same new rank to # this suffix if (suffixes[i].rank[0] == prev_rank and suffixes[i].rank[1] == suffixes[i - 1].rank[1]): prev_rank = suffixes[i].rank[0] suffixes[i].rank[0] = rank # Otherwise increment rank and assign else: prev_rank = suffixes[i].rank[0] rank += 1 suffixes[i].rank[0] = rank ind[suffixes[i].index] = i # Assign next rank to every suffix for i in range(n): nextindex = suffixes[i].index + k // 2 suffixes[i].rank[1] = suffixes[ind[nextindex]].rank[0] \\ if (nextindex < n) else -1 # Sort the suffixes according to # first k characters suffixes = sorted( suffixes, key = lambda x: ( x.rank[0], x.rank[1])) k *= 2 # Store indexes of all sorted # suffixes in the suffix array suffixArr = [0] * n for i in range(n): suffixArr[i] = suffixes[i].index # Return the suffix array return suffixArr # A utility function to print an array# of given sizedef printArr(arr, n): for i in range(n): print(arr[i], end = \" \") print() # Driver codeif __name__ == \"__main__\": txt = \"banana\" n = len(txt) suffixArr = buildSuffixArray(txt, n) print(\"Following is suffix array for\", txt) printArr(suffixArr, n) # This code is contributed by debrc",
"e": 43382,
"s": 40019,
"text": null
},
{
"code": "<script>// Javascript program for building suffix array of a given text // Class to store information of a suffixclass Suffix{ constructor(ind,r,nr) { this.index = ind; this.rank = r; this.next = nr; } } // This is the main function that takes a string 'txt' // of size n as an argument, builds and return the // suffix array for the given stringfunction suffixArray(s){ let n = s.length; let su = new Array(n); // Store suffixes and their indexes in // an array of classes. The class is needed // to sort the suffixes alphabetically and // maintain their old indexes while sorting for (let i = 0; i < n; i++) { su[i] = new Suffix(i, s[i].charCodeAt(0) - '$'.charCodeAt(0), 0); } for (let i = 0; i < n; i++) su[i].next = (i + 1 < n ? su[i + 1].rank : -1); // Sort the suffixes using the comparison function // defined above. su.sort(function(a,b){ if(a.rank!=b.rank) return a.rank-b.rank; else return a.next-b.next; }); // At this point, all suffixes are sorted // according to first 2 characters. // Let us sort suffixes according to first 4 // characters, then first 8 and so on let ind = new Array(n); // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (let length = 4; length < 2 * n; length <<= 1) { // Assigning rank and index values to first suffix let rank = 0, prev = su[0].rank; su[0].rank = rank; ind[su[0].index] = 0; for (let i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, // assign the same new rank to this suffix if (su[i].rank == prev && su[i].next == su[i - 1].next) { prev = su[i].rank; su[i].rank = rank; } else { // Otherwise increment rank and assign prev = su[i].rank; su[i].rank = ++rank; } ind[su[i].index] = i; } // Assign next rank to every suffix for (let i = 0; i < n; i++) { let nextP = su[i].index + length / 2; su[i].next = nextP < n ? su[ind[nextP]].rank : -1; } // Sort the suffixes according // to first k characters su.sort(function(a,b){ if(a.rank!=b.rank) return a.rank-b.rank; else return a.next-b.next; }); } // Store indexes of all sorted // suffixes in the suffix array let suf = new Array(n); for (let i = 0; i < n; i++) suf[i] = su[i].index; // Return the suffix array return suf;} function printArr(arr,n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write();} // Driver Codelet txt = \"banana\";let n = txt.length;let suff_arr = suffixArray(txt);document.write(\"Following is suffix array for banana:<br>\");printArr(suff_arr, n); // This code is contributed by patel2127</script>",
"e": 46925,
"s": 43382,
"text": null
},
{
"code": null,
"e": 46975,
"s": 46925,
"text": "Following is suffix array for banana\n5 3 1 0 4 2 "
},
{
"code": null,
"e": 47151,
"s": 46975,
"text": "Note that the above algorithm uses standard sort function and therefore time complexity is O(nLognLogn). We can use Radix Sort here to reduce the time complexity to O(nLogn). "
},
{
"code": null,
"e": 47161,
"s": 47151,
"text": "Method 2:"
},
{
"code": null,
"e": 47207,
"s": 47161,
"text": "The problem can also be solved using the map."
},
{
"code": null,
"e": 47218,
"s": 47207,
"text": "Algorithm:"
},
{
"code": null,
"e": 47281,
"s": 47218,
"text": "1) Create a map with a key string and its value is an integer."
},
{
"code": null,
"e": 47373,
"s": 47281,
"text": "2) Iterate over the string in reverse order and create a new string(i.e from i = n – 1, 0)."
},
{
"code": null,
"e": 47426,
"s": 47373,
"text": "3) Map new string with the last index position of I."
},
{
"code": null,
"e": 47492,
"s": 47426,
"text": "4) Create an array and assign all values of the map in the array."
},
{
"code": null,
"e": 47498,
"s": 47492,
"text": "C++14"
},
{
"code": "// C++14 program to build a suffix array in O(nlogn) time; #include <bits/stdc++.h>using namespace std; int main(){ string s = \"banana\"; int n = s.length(); map<string, int> Map; int suffix[n]; // Mapping string with its index of // it's last letter. string sub = \"\"; for (int i = n - 1; i >= 0; i--) { sub = s[i] + sub; Map[sub] = i; } // Storing all values of map // in suffix array. int j = 0; for (auto x : Map) { suffix[j] = x.second; j++; } // printing suffix array. cout << \"Suffix array for banana is\" << endl; for (int i = 0; i < n; i++) { cout << suffix[i] << \" \"; } cout << endl; return 0;}",
"e": 48198,
"s": 47498,
"text": null
},
{
"code": null,
"e": 48238,
"s": 48198,
"text": "Suffix array for banana is\n5 3 1 0 4 2 "
},
{
"code": null,
"e": 48403,
"s": 48238,
"text": "The time complexity of the algorithm is O(N log N). Please note that suffix arrays can be constructed in O(n) time also. We will soon be discussing O(n) algorithms."
},
{
"code": null,
"e": 48522,
"s": 48403,
"text": "References: http://www.stanford.edu/class/cs97si/suffix-array.pdf http://www.cbcb.umd.edu/confcour/Fall2012/lec14b.pdf"
},
{
"code": null,
"e": 48648,
"s": 48522,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 48663,
"s": 48648,
"text": "Akash Kumar 31"
},
{
"code": null,
"e": 48678,
"s": 48663,
"text": "AmanKumarSingh"
},
{
"code": null,
"e": 48684,
"s": 48678,
"text": "debrc"
},
{
"code": null,
"e": 48697,
"s": 48684,
"text": "simmytarika5"
},
{
"code": null,
"e": 48707,
"s": 48697,
"text": "patel2127"
},
{
"code": null,
"e": 48726,
"s": 48707,
"text": "surindertarika1234"
},
{
"code": null,
"e": 48745,
"s": 48726,
"text": "siddharthsingh7898"
},
{
"code": null,
"e": 48757,
"s": 48745,
"text": "thilakreddy"
},
{
"code": null,
"e": 48770,
"s": 48757,
"text": "Suffix-Array"
},
{
"code": null,
"e": 48794,
"s": 48770,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 48812,
"s": 48794,
"text": "Pattern Searching"
},
{
"code": null,
"e": 48830,
"s": 48812,
"text": "Pattern Searching"
},
{
"code": null,
"e": 48928,
"s": 48830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48968,
"s": 48928,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 49000,
"s": 48968,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 49029,
"s": 49000,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 49058,
"s": 49029,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 49085,
"s": 49058,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 49121,
"s": 49085,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 49164,
"s": 49121,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 49202,
"s": 49164,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 49244,
"s": 49202,
"text": "Check if a string is substring of another"
}
] |
Print matrix in antispiral form - GeeksforGeeks
|
22 Apr, 2021
Given a 2D array, the task is to print matrix in anti spiral form:Examples:
Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Input : arr[][4] = {1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
13, 14, 15, 16};
Output : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Input :arr[][6] = {1, 2, 3, 4, 5, 6
7, 8, 9, 10, 11, 12
13, 14, 15, 16, 17, 18};
Output : 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
The idea is simple, we traverse matrix in spiral form and put all traversed elements in a stack. Finally one by one elements from stack and print them.
C++
Java
Python 3
C#
Javascript
// C++ program to print matrix in anti-spiral form#include <bits/stdc++.h>using namespace std;#define R 4#define C 5 void antiSpiralTraversal(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ stack<int> stk; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { cout << stk.top() << " "; stk.pop(); }} /* Driver program to test above functions */int main(){ int mat[R][C] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(R-1, C-1, mat); return 0;}
// Java Code for Print matrix in antispiral formimport java.util.*; class GFG { public static void antiSpiralTraversal(int m, int n, int a[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ Stack<Integer> stk=new Stack<Integer>(); while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { System.out.print(stk.peek() + " "); stk.pop(); } } /* Driver program to test above function */ public static void main(String[] args) { int mat[][] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(mat.length - 1, mat[0].length - 1, mat); } }// This code is contributed by Arnav Kr. Mandal.
# Python 3 program to print# matrix in anti-spiral formR = 4C = 5 def antiSpiralTraversal(m, n, a): k = 0 l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator stk = [] while (k <= m and l <= n): # Print the first row # from the remaining rows for i in range(l, n + 1): stk.append(a[k][i]) k += 1 # Print the last column # from the remaining columns for i in range(k, m + 1): stk.append(a[i][n]) n -= 1 # Print the last row # from the remaining rows if ( k <= m): for i in range(n, l - 1, -1): stk.append(a[m][i]) m -= 1 # Print the first column # from the remaining columns if (l <= n): for i in range(m, k - 1, -1): stk.append(a[i][l]) l += 1 while len(stk) != 0: print(str(stk[-1]), end = " ") stk.pop() # Driver Codemat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(R - 1, C - 1, mat) # This code is contributed# by ChitraNayal
using System;using System.Collections.Generic; // C# Code for Print matrix in antispiral form public class GFG{ public static void antiSpiralTraversal(int m, int n, int[][] a) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ Stack<int> stk = new Stack<int>(); while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) { stk.Push(a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) { stk.Push(a[i][n]); } n--; /* Print the last row from the remaining rows */ if (k <= m) { for (i = n; i >= l; --i) { stk.Push(a[m][i]); } m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) { stk.Push(a[i][l]); } l++; } } while (stk.Count > 0) { Console.Write(stk.Peek() + " "); stk.Pop(); } } /* Driver program to test above function */ public static void Main(string[] args) { int[][] mat = new int[][] { new int[] {1, 2, 3, 4, 5}, new int[] {6, 7, 8, 9, 10}, new int[] {11, 12, 13, 14, 15}, new int[] {16, 17, 18, 19, 20} }; antiSpiralTraversal(mat.Length - 1, mat[0].Length - 1, mat); }} // This code is contributed by Shrikant13
<script> // Javascript Code for Print matrix in antispiral form function antiSpiralTraversal(m,n,a) { let i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ let stk=[]; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (stk.length!=0) { document.write(stk[stk.length-1] + " "); stk.pop(); } } /* Driver program to test above function */ let mat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(mat.length - 1, mat[0].length - 1, mat); // This code is contributed by avanitrachhadiya2155</script>
Output:
12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1
Diagonal traversal of Matrix
Print matrix in spiral form
Print a given matrix in zigzag form
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
shrikanth13
avanitrachhadiya2155
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Flood fill Algorithm - how to implement fill() in paint?
Check for possible path in 2D matrix
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26165,
"s": 26137,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 26243,
"s": 26165,
"text": "Given a 2D array, the task is to print matrix in anti spiral form:Examples: "
},
{
"code": null,
"e": 26291,
"s": 26243,
"text": "Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 "
},
{
"code": null,
"e": 26644,
"s": 26291,
"text": "Input : arr[][4] = {1, 2, 3, 4\n 5, 6, 7, 8\n 9, 10, 11, 12\n 13, 14, 15, 16};\nOutput : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1\n\nInput :arr[][6] = {1, 2, 3, 4, 5, 6\n 7, 8, 9, 10, 11, 12\n 13, 14, 15, 16, 17, 18};\nOutput : 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1"
},
{
"code": null,
"e": 26800,
"s": 26646,
"text": "The idea is simple, we traverse matrix in spiral form and put all traversed elements in a stack. Finally one by one elements from stack and print them. "
},
{
"code": null,
"e": 26804,
"s": 26800,
"text": "C++"
},
{
"code": null,
"e": 26809,
"s": 26804,
"text": "Java"
},
{
"code": null,
"e": 26818,
"s": 26809,
"text": "Python 3"
},
{
"code": null,
"e": 26821,
"s": 26818,
"text": "C#"
},
{
"code": null,
"e": 26832,
"s": 26821,
"text": "Javascript"
},
{
"code": "// C++ program to print matrix in anti-spiral form#include <bits/stdc++.h>using namespace std;#define R 4#define C 5 void antiSpiralTraversal(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ stack<int> stk; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { cout << stk.top() << \" \"; stk.pop(); }} /* Driver program to test above functions */int main(){ int mat[R][C] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(R-1, C-1, mat); return 0;}",
"e": 28209,
"s": 26832,
"text": null
},
{
"code": "// Java Code for Print matrix in antispiral formimport java.util.*; class GFG { public static void antiSpiralTraversal(int m, int n, int a[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ Stack<Integer> stk=new Stack<Integer>(); while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { System.out.print(stk.peek() + \" \"); stk.pop(); } } /* Driver program to test above function */ public static void main(String[] args) { int mat[][] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(mat.length - 1, mat[0].length - 1, mat); } }// This code is contributed by Arnav Kr. Mandal.",
"e": 30134,
"s": 28209,
"text": null
},
{
"code": "# Python 3 program to print# matrix in anti-spiral formR = 4C = 5 def antiSpiralTraversal(m, n, a): k = 0 l = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index # i - iterator stk = [] while (k <= m and l <= n): # Print the first row # from the remaining rows for i in range(l, n + 1): stk.append(a[k][i]) k += 1 # Print the last column # from the remaining columns for i in range(k, m + 1): stk.append(a[i][n]) n -= 1 # Print the last row # from the remaining rows if ( k <= m): for i in range(n, l - 1, -1): stk.append(a[m][i]) m -= 1 # Print the first column # from the remaining columns if (l <= n): for i in range(m, k - 1, -1): stk.append(a[i][l]) l += 1 while len(stk) != 0: print(str(stk[-1]), end = \" \") stk.pop() # Driver Codemat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(R - 1, C - 1, mat) # This code is contributed# by ChitraNayal",
"e": 31371,
"s": 30134,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# Code for Print matrix in antispiral form public class GFG{ public static void antiSpiralTraversal(int m, int n, int[][] a) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ Stack<int> stk = new Stack<int>(); while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) { stk.Push(a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) { stk.Push(a[i][n]); } n--; /* Print the last row from the remaining rows */ if (k <= m) { for (i = n; i >= l; --i) { stk.Push(a[m][i]); } m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) { stk.Push(a[i][l]); } l++; } } while (stk.Count > 0) { Console.Write(stk.Peek() + \" \"); stk.Pop(); } } /* Driver program to test above function */ public static void Main(string[] args) { int[][] mat = new int[][] { new int[] {1, 2, 3, 4, 5}, new int[] {6, 7, 8, 9, 10}, new int[] {11, 12, 13, 14, 15}, new int[] {16, 17, 18, 19, 20} }; antiSpiralTraversal(mat.Length - 1, mat[0].Length - 1, mat); }} // This code is contributed by Shrikant13",
"e": 33287,
"s": 31371,
"text": null
},
{
"code": "<script> // Javascript Code for Print matrix in antispiral form function antiSpiralTraversal(m,n,a) { let i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ let stk=[]; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (stk.length!=0) { document.write(stk[stk.length-1] + \" \"); stk.pop(); } } /* Driver program to test above function */ let mat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]; antiSpiralTraversal(mat.length - 1, mat[0].length - 1, mat); // This code is contributed by avanitrachhadiya2155</script>",
"e": 34960,
"s": 33287,
"text": null
},
{
"code": null,
"e": 34970,
"s": 34960,
"text": "Output: "
},
{
"code": null,
"e": 35022,
"s": 34970,
"text": "12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1 "
},
{
"code": null,
"e": 35053,
"s": 35024,
"text": "Diagonal traversal of Matrix"
},
{
"code": null,
"e": 35081,
"s": 35053,
"text": "Print matrix in spiral form"
},
{
"code": null,
"e": 35117,
"s": 35081,
"text": "Print a given matrix in zigzag form"
},
{
"code": null,
"e": 35541,
"s": 35117,
"text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35547,
"s": 35541,
"text": "ukasp"
},
{
"code": null,
"e": 35559,
"s": 35547,
"text": "shrikanth13"
},
{
"code": null,
"e": 35580,
"s": 35559,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35587,
"s": 35580,
"text": "Matrix"
},
{
"code": null,
"e": 35606,
"s": 35587,
"text": "School Programming"
},
{
"code": null,
"e": 35613,
"s": 35606,
"text": "Matrix"
},
{
"code": null,
"e": 35711,
"s": 35613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35761,
"s": 35711,
"text": "Efficiently compute sums of diagonals of a matrix"
},
{
"code": null,
"e": 35818,
"s": 35761,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 35855,
"s": 35818,
"text": "Check for possible path in 2D matrix"
},
{
"code": null,
"e": 35896,
"s": 35855,
"text": "Zigzag (or diagonal) traversal of Matrix"
},
{
"code": null,
"e": 35960,
"s": 35896,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 35978,
"s": 35960,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35994,
"s": 35978,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 36013,
"s": 35994,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 36038,
"s": 36013,
"text": "Reverse a string in Java"
}
] |
Python program to check whether a number is Prime or not - GeeksforGeeks
|
10 Nov, 2021
Given a positive integer N, The task is to write a Python program to check if the number is prime or not.Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ....}.
Examples :
Input: n = 11Output: true
Input: n = 15Output: false
Input: n = 1Output: false
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.
Below is the Python program to check if a number is prime:
Python3
# Python program to check if# given number is prime or not num = 11 # If given number is greater than 1if num > 1: # Iterate from 2 to n / 2 for i in range(2, int(num/2)+1): # If num is divisible by any number between # 2 and n / 2, it is not prime if (num % i) == 0: print(num, "is not a prime number") break else: print(num, "is a prime number") else: print(num, "is not a prime number")
11 is a prime number
Optimized Method We can do the following optimizations:
Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked.
Now lets see the code for the first optimization method ( i.e. checking till √n )
Python3
from math import sqrt# n is the number to be check whether it is prime or notn = 1 # no lets check from 2 to sqrt(n)# if we found any facto then we can print as not a prime number # this flag maintains status whether the n is prime or notprime_flag = 0 if(n > 1): for i in range(2, int(sqrt(n)) + 1): if (n % i == 0): prime_flag = 1 break if (prime_flag == 0): print("true") else: print("false")else: print("false")
false
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)
kumarakhilakak
daft
bindusri822
santhoshcharan
vsiddharth365
pulamolusaimohan
Prime Number
Python
Python Programs
School Programming
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 26303,
"s": 26275,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 26581,
"s": 26303,
"text": "Given a positive integer N, The task is to write a Python program to check if the number is prime or not.Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ....}."
},
{
"code": null,
"e": 26593,
"s": 26581,
"text": "Examples : "
},
{
"code": null,
"e": 26620,
"s": 26593,
"text": "Input: n = 11Output: true"
},
{
"code": null,
"e": 26648,
"s": 26620,
"text": "Input: n = 15Output: false"
},
{
"code": null,
"e": 26675,
"s": 26648,
"text": "Input: n = 1Output: false"
},
{
"code": null,
"e": 27002,
"s": 26675,
"text": "The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True."
},
{
"code": null,
"e": 27062,
"s": 27002,
"text": "Below is the Python program to check if a number is prime: "
},
{
"code": null,
"e": 27070,
"s": 27062,
"text": "Python3"
},
{
"code": "# Python program to check if# given number is prime or not num = 11 # If given number is greater than 1if num > 1: # Iterate from 2 to n / 2 for i in range(2, int(num/2)+1): # If num is divisible by any number between # 2 and n / 2, it is not prime if (num % i) == 0: print(num, \"is not a prime number\") break else: print(num, \"is a prime number\") else: print(num, \"is not a prime number\")",
"e": 27529,
"s": 27070,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27529,
"text": "11 is a prime number"
},
{
"code": null,
"e": 27607,
"s": 27550,
"text": "Optimized Method We can do the following optimizations: "
},
{
"code": null,
"e": 27755,
"s": 27607,
"text": "Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked."
},
{
"code": null,
"e": 27837,
"s": 27755,
"text": "Now lets see the code for the first optimization method ( i.e. checking till √n )"
},
{
"code": null,
"e": 27845,
"s": 27837,
"text": "Python3"
},
{
"code": "from math import sqrt# n is the number to be check whether it is prime or notn = 1 # no lets check from 2 to sqrt(n)# if we found any facto then we can print as not a prime number # this flag maintains status whether the n is prime or notprime_flag = 0 if(n > 1): for i in range(2, int(sqrt(n)) + 1): if (n % i == 0): prime_flag = 1 break if (prime_flag == 0): print(\"true\") else: print(\"false\")else: print(\"false\")",
"e": 28319,
"s": 27845,
"text": null
},
{
"code": null,
"e": 28325,
"s": 28319,
"text": "false"
},
{
"code": null,
"e": 28763,
"s": 28325,
"text": "The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)"
},
{
"code": null,
"e": 28778,
"s": 28763,
"text": "kumarakhilakak"
},
{
"code": null,
"e": 28783,
"s": 28778,
"text": "daft"
},
{
"code": null,
"e": 28795,
"s": 28783,
"text": "bindusri822"
},
{
"code": null,
"e": 28810,
"s": 28795,
"text": "santhoshcharan"
},
{
"code": null,
"e": 28824,
"s": 28810,
"text": "vsiddharth365"
},
{
"code": null,
"e": 28841,
"s": 28824,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 28854,
"s": 28841,
"text": "Prime Number"
},
{
"code": null,
"e": 28861,
"s": 28854,
"text": "Python"
},
{
"code": null,
"e": 28877,
"s": 28861,
"text": "Python Programs"
},
{
"code": null,
"e": 28896,
"s": 28877,
"text": "School Programming"
},
{
"code": null,
"e": 28909,
"s": 28896,
"text": "Prime Number"
},
{
"code": null,
"e": 29007,
"s": 28909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29039,
"s": 29007,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29061,
"s": 29039,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29103,
"s": 29061,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29129,
"s": 29103,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29158,
"s": 29129,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29180,
"s": 29158,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29219,
"s": 29180,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29265,
"s": 29219,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 29303,
"s": 29265,
"text": "Python | Convert a list to dictionary"
}
] |
CSS | :nth-last-child() Selector - GeeksforGeeks
|
07 Jan, 2019
The nth-last-child() selector in CSS is used to match elements based on their position among the group of siblings, counting from end.
Syntax:
:nth-last-child(number) {
//CSS Property
}
Where number is the argument that represents the pattern for matching elements counting from the end. It can be odd, even or in a functional notation.
odd: It represents elements whose position is odd in a series: 1, 3, 5, etc., counting from the end.
even: It represents the elements whose position is even in a series: 2, 4, 6, etc., counting from the end.
functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. The index of the first element, counting from the end, is 1.
Example-1: In this example every odd element is selected according to formula 2n+1, counting from the end.
<!DOCTYPE html><html> <head> <title>CSS :nth-last-child Selector</title> <style> p:nth-last-child(2n+1) { background: green; color:white; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> CSS :nth-last-child Selector </h2> <p>A computer science portal for geeks.</p> <p>Geeks classes an extensive classroom programme.</p> </body></html>
Output:Example-2:
<!DOCTYPE html><html> <head> <title>CSS :nth-last-child Selector</title> <style> table { border: 1px solid green; margin:auto; } /* Selects the last three element */ tr:nth-last-child(3) { background-color: green; color:white; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> CSS :nth-last-child Selector </h2> <table> <tbody> <tr> <td>Merge sort</td> </tr> <tr> <td>Quick sort</td> </tr> <tr> <td>Insertion sort</td> </tr> <tr> <td>Selection sort</td> </tr> </tbody> </table> </body></html>
Output:
Supported Browsers: The browser supported by :nth-last-child selector are listed below:
Apple Safari 3.2
Google Chrome 4.0
Firefox 3.5
Opera 9.6
Internet Explorer 9.0
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 update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 24897,
"s": 24869,
"text": "\n07 Jan, 2019"
},
{
"code": null,
"e": 25032,
"s": 24897,
"text": "The nth-last-child() selector in CSS is used to match elements based on their position among the group of siblings, counting from end."
},
{
"code": null,
"e": 25040,
"s": 25032,
"text": "Syntax:"
},
{
"code": null,
"e": 25087,
"s": 25040,
"text": ":nth-last-child(number) {\n //CSS Property\n}"
},
{
"code": null,
"e": 25238,
"s": 25087,
"text": "Where number is the argument that represents the pattern for matching elements counting from the end. It can be odd, even or in a functional notation."
},
{
"code": null,
"e": 25339,
"s": 25238,
"text": "odd: It represents elements whose position is odd in a series: 1, 3, 5, etc., counting from the end."
},
{
"code": null,
"e": 25446,
"s": 25339,
"text": "even: It represents the elements whose position is even in a series: 2, 4, 6, etc., counting from the end."
},
{
"code": null,
"e": 25660,
"s": 25446,
"text": "functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. The index of the first element, counting from the end, is 1."
},
{
"code": null,
"e": 25767,
"s": 25660,
"text": "Example-1: In this example every odd element is selected according to formula 2n+1, counting from the end."
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS :nth-last-child Selector</title> <style> p:nth-last-child(2n+1) { background: green; color:white; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> CSS :nth-last-child Selector </h2> <p>A computer science portal for geeks.</p> <p>Geeks classes an extensive classroom programme.</p> </body></html>",
"e": 26345,
"s": 25767,
"text": null
},
{
"code": null,
"e": 26363,
"s": 26345,
"text": "Output:Example-2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS :nth-last-child Selector</title> <style> table { border: 1px solid green; margin:auto; } /* Selects the last three element */ tr:nth-last-child(3) { background-color: green; color:white; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> CSS :nth-last-child Selector </h2> <table> <tbody> <tr> <td>Merge sort</td> </tr> <tr> <td>Quick sort</td> </tr> <tr> <td>Insertion sort</td> </tr> <tr> <td>Selection sort</td> </tr> </tbody> </table> </body></html>",
"e": 27336,
"s": 26363,
"text": null
},
{
"code": null,
"e": 27344,
"s": 27336,
"text": "Output:"
},
{
"code": null,
"e": 27432,
"s": 27344,
"text": "Supported Browsers: The browser supported by :nth-last-child selector are listed below:"
},
{
"code": null,
"e": 27449,
"s": 27432,
"text": "Apple Safari 3.2"
},
{
"code": null,
"e": 27467,
"s": 27449,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 27479,
"s": 27467,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 27489,
"s": 27479,
"text": "Opera 9.6"
},
{
"code": null,
"e": 27511,
"s": 27489,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 27525,
"s": 27511,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 27529,
"s": 27525,
"text": "CSS"
},
{
"code": null,
"e": 27546,
"s": 27529,
"text": "Web Technologies"
},
{
"code": null,
"e": 27644,
"s": 27546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27706,
"s": 27644,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27756,
"s": 27706,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27804,
"s": 27756,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27862,
"s": 27804,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27917,
"s": 27862,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 27957,
"s": 27917,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27990,
"s": 27957,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28035,
"s": 27990,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28078,
"s": 28035,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Program to Get System Name for Windows and Linux Machine - GeeksforGeeks
|
05 Jul, 2021
We can get the System name for a Windows or Linux machine using the getHostName() method of the InetAddress class of java.net package after getting the IP address of the system using getLocalHost() method of the same class. The class InetAddress gets the IP address of any hostname. getLocalHost() method of the InetAddress class gets the address of the local host. getHostName() gets the hostname for a given IP address or returns the textual representation of the IP address if the operation is not allowed by the security manager.
Syntax
public String getHostName()
Returns: The address of the host for a given IP address or the textual representation of the IP address if the operation is not allowed.
Example:
Java
// Java program to demonstrate getting// the System name of the user import java.net.InetAddress;public class GFG { public static void main(String[] args) { try { // get system name String SystemName = InetAddress.getLocalHost().getHostName(); // SystemName stores the name of the system System.out.println("System Name : " + SystemName); } catch (Exception E) { System.err.println(E.getMessage()); } }}
Output:
abhishek0719kadiyan
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
Exceptions in Java
Functional Interfaces in Java
Generics 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?
Iterate through List in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 25760,
"s": 25225,
"text": "We can get the System name for a Windows or Linux machine using the getHostName() method of the InetAddress class of java.net package after getting the IP address of the system using getLocalHost() method of the same class. The class InetAddress gets the IP address of any hostname. getLocalHost() method of the InetAddress class gets the address of the local host. getHostName() gets the hostname for a given IP address or returns the textual representation of the IP address if the operation is not allowed by the security manager."
},
{
"code": null,
"e": 25767,
"s": 25760,
"text": "Syntax"
},
{
"code": null,
"e": 25795,
"s": 25767,
"text": "public String getHostName()"
},
{
"code": null,
"e": 25932,
"s": 25795,
"text": "Returns: The address of the host for a given IP address or the textual representation of the IP address if the operation is not allowed."
},
{
"code": null,
"e": 25941,
"s": 25932,
"text": "Example:"
},
{
"code": null,
"e": 25946,
"s": 25941,
"text": "Java"
},
{
"code": "// Java program to demonstrate getting// the System name of the user import java.net.InetAddress;public class GFG { public static void main(String[] args) { try { // get system name String SystemName = InetAddress.getLocalHost().getHostName(); // SystemName stores the name of the system System.out.println(\"System Name : \" + SystemName); } catch (Exception E) { System.err.println(E.getMessage()); } }}",
"e": 26489,
"s": 25946,
"text": null
},
{
"code": null,
"e": 26501,
"s": 26493,
"text": "Output:"
},
{
"code": null,
"e": 26525,
"s": 26505,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 26532,
"s": 26525,
"text": "Picked"
},
{
"code": null,
"e": 26537,
"s": 26532,
"text": "Java"
},
{
"code": null,
"e": 26551,
"s": 26537,
"text": "Java Programs"
},
{
"code": null,
"e": 26556,
"s": 26551,
"text": "Java"
},
{
"code": null,
"e": 26654,
"s": 26556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26669,
"s": 26654,
"text": "Stream In Java"
},
{
"code": null,
"e": 26690,
"s": 26669,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26709,
"s": 26690,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26739,
"s": 26709,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26756,
"s": 26739,
"text": "Generics in Java"
},
{
"code": null,
"e": 26782,
"s": 26756,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26816,
"s": 26782,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26863,
"s": 26816,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 26895,
"s": 26863,
"text": "How to Iterate HashMap in Java?"
}
] |
Python Program to Check Prime Number - GeeksforGeeks
|
30 Nov, 2018
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,
Examples:
Input: n = 11
Output: true
Input: n = 15
Output: false
Input: n = 1
Output: false
School Method :
# A school method based Python3 # program to check if a number# is prime def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Driver Program to test above functionprint("true") if isPrime(11) else print("false")print("true") if isPrime(14) else print("false") # This code is contributed by Smitha Dinesh Semwal
Output:
true
false
Time complexity of this solution is O(n)
Optimized School Method :
# A optimized school method based # Python3 program to check # if a number is prime def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Driver Program if(isPrime(11)) : print(" true") else : print(" false") if(isPrime(15)) : print(" true") else : print(" false") # This code is contributed # by Nikita Tiwari.
Output:
true
false
Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Convert a list into a tuple
Python program to add two numbers
Python | Check if a variable is string
Add a key:value pair to dictionary in Python
Appending to list in Python dictionary
Python program to find sum of elements in list
|
[
{
"code": null,
"e": 26279,
"s": 26251,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 26490,
"s": 26279,
"text": "Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,"
},
{
"code": null,
"e": 26500,
"s": 26490,
"text": "Examples:"
},
{
"code": null,
"e": 26588,
"s": 26500,
"text": "Input: n = 11\nOutput: true\n\nInput: n = 15\nOutput: false\n\nInput: n = 1\nOutput: false\n"
},
{
"code": null,
"e": 26604,
"s": 26588,
"text": "School Method :"
},
{
"code": "# A school method based Python3 # program to check if a number# is prime def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Driver Program to test above functionprint(\"true\") if isPrime(11) else print(\"false\")print(\"true\") if isPrime(14) else print(\"false\") # This code is contributed by Smitha Dinesh Semwal",
"e": 27052,
"s": 26604,
"text": null
},
{
"code": null,
"e": 27060,
"s": 27052,
"text": "Output:"
},
{
"code": null,
"e": 27072,
"s": 27060,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 27113,
"s": 27072,
"text": "Time complexity of this solution is O(n)"
},
{
"code": null,
"e": 27139,
"s": 27113,
"text": "Optimized School Method :"
},
{
"code": "# A optimized school method based # Python3 program to check # if a number is prime def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True # Driver Program if(isPrime(11)) : print(\" true\") else : print(\" false\") if(isPrime(15)) : print(\" true\") else : print(\" false\") # This code is contributed # by Nikita Tiwari. ",
"e": 27861,
"s": 27139,
"text": null
},
{
"code": null,
"e": 27869,
"s": 27861,
"text": "Output:"
},
{
"code": null,
"e": 27881,
"s": 27869,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 27988,
"s": 27881,
"text": "Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!"
},
{
"code": null,
"e": 28004,
"s": 27988,
"text": "Python Programs"
},
{
"code": null,
"e": 28102,
"s": 28004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28151,
"s": 28102,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 28197,
"s": 28151,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 28238,
"s": 28197,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 28271,
"s": 28238,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 28308,
"s": 28271,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 28342,
"s": 28308,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 28381,
"s": 28342,
"text": "Python | Check if a variable is string"
},
{
"code": null,
"e": 28426,
"s": 28381,
"text": "Add a key:value pair to dictionary in Python"
},
{
"code": null,
"e": 28465,
"s": 28426,
"text": "Appending to list in Python dictionary"
}
] |
Flex (Fast Lexical Analyzer Generator )
|
28 Jun, 2022
FLEX (fast lexical analyzer generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. It is used together with Berkeley Yacc parser generator or GNU Bison parser generator. Flex and Bison both are more flexible than Lex and Yacc and produces faster code. Bison produces parser from the input file provided by the user. The function yylex() is automatically generated by the flex when it is provided with a .l file and this yylex() function is expected by parser to call to retrieve tokens from current/this token stream.
Note: The function yylex() is the main flex function that runs the Rule Section and extension (.l) is the extension used to save the programs.
Installing Flex on Ubuntu:
sudo apt-get update
sudo apt-get install flex
Note: If Update command is not run on the machine for a while, it’s better to run it first so that a newer version is installed as an older version might not work with the other packages installed or may not be present now.
Given image describes how the Flex is used:
Step 1: An input file describes the lexical analyzer to be generated named lex.l is written in lex language. The lex compiler transforms lex.l to C program, in a file that is always named lex.yy.c. Step 2: The C compiler compile lex.yy.c file into an executable file called a.out. Step 3: The output file a.out take a stream of input characters and produce a stream of tokens.
Program Structure:
In the input file, there are 3 sections:
1. Definition Section: The definition section contains the declaration of variables, regular definitions, manifest constants. In the definition section, text is enclosed in “%{ %}” brackets. Anything written in this brackets is copied directly to the file lex.yy.c
Syntax:
%{
// Definitions
%}
2. Rules Section: The rules section contains a series of rules in the form: pattern action and pattern must be unintended and action begin on the same line in {} brackets. The rule section is enclosed in “%% %%”.
Syntax:
%%
pattern action
%%
Examples: Table below shows some of the pattern matches.
3. User Code Section: This section contains C statements and additional functions. We can also compile these functions separately and load with the lexical analyzer.
Basic Program Structure:
%{
// Definitions
%}
%%
Rules
%%
User code section
How to run the program: To run the program, it should be first saved with the extension .l or .lex. Run the below commands on terminal in order to run the program file.
Step 1: lex filename.l or lex filename.lex depending on the extension file is saved with Step 2: gcc lex.yy.c Step 3: ./a.out Step 4: Provide the input to program in case it is required
Note: Press Ctrl+D or use some rule to stop taking inputs from the user. Please see the output images of below programs to clear if in doubt to run the programs.
Example 1: Count the number of characters in a string
C
/*** Definition Section has one variablewhich can be accessed inside yylex() and main() ***/%{int count = 0;%} /*** Rule Section has three rules, first rule matches with capital letters, second rulematches with any character except newline and third rule does not take input after the enter***/%%[A-Z] {printf("%s capital letter\n", yytext); count++;}. {printf("%s not a capital letter\n", yytext);}\n {return 0;}%% /*** Code Section prints the number ofcapital letter present in the given input***/int yywrap(){}int main(){ // Explanation:// yywrap() - wraps the above rule section/* yyin - takes the file pointer which contains the input*//* yylex() - this is the main flex function which runs the Rule Section*/// yytext is the text in the buffer // Uncomment the lines below // to take input from file// FILE *fp;// char filename[50];// printf("Enter the filename: \n");// scanf("%s",filename);// fp = fopen(filename,"r");// yyin = fp; yylex();printf("\nNumber of Capital letters " "in the given input - %d\n", count); return 0;}
Output:
Example 2: Count the number of characters and number of lines in the input
C
/* Declaring two counters one for number of lines other for number of characters */%{int no_of_lines = 0;int no_of_chars = 0;%} /***rule 1 counts the number of lines, rule 2 counts the number of characters and rule 3 specifies when to stop taking input***/%%\n ++no_of_lines;. ++no_of_chars;end return 0;%% /*** User code section***/int yywrap(){}int main(int argc, char **argv){ yylex();printf("number of lines = %d, number of chars = %d\n", no_of_lines, no_of_chars ); return 0;}
Output:
adnanirshad158
rajeev0719singh
vaibhavsinghtanwar
Lex program
C Programs
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Difference between Compiler and Interpreter
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 649,
"s": 52,
"text": "FLEX (fast lexical analyzer generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. It is used together with Berkeley Yacc parser generator or GNU Bison parser generator. Flex and Bison both are more flexible than Lex and Yacc and produces faster code. Bison produces parser from the input file provided by the user. The function yylex() is automatically generated by the flex when it is provided with a .l file and this yylex() function is expected by parser to call to retrieve tokens from current/this token stream. "
},
{
"code": null,
"e": 792,
"s": 649,
"text": "Note: The function yylex() is the main flex function that runs the Rule Section and extension (.l) is the extension used to save the programs."
},
{
"code": null,
"e": 820,
"s": 792,
"text": "Installing Flex on Ubuntu: "
},
{
"code": null,
"e": 866,
"s": 820,
"text": "sudo apt-get update\nsudo apt-get install flex"
},
{
"code": null,
"e": 1090,
"s": 866,
"text": "Note: If Update command is not run on the machine for a while, it’s better to run it first so that a newer version is installed as an older version might not work with the other packages installed or may not be present now."
},
{
"code": null,
"e": 1136,
"s": 1090,
"text": "Given image describes how the Flex is used: "
},
{
"code": null,
"e": 1514,
"s": 1136,
"text": "Step 1: An input file describes the lexical analyzer to be generated named lex.l is written in lex language. The lex compiler transforms lex.l to C program, in a file that is always named lex.yy.c. Step 2: The C compiler compile lex.yy.c file into an executable file called a.out. Step 3: The output file a.out take a stream of input characters and produce a stream of tokens. "
},
{
"code": null,
"e": 1534,
"s": 1514,
"text": "Program Structure: "
},
{
"code": null,
"e": 1576,
"s": 1534,
"text": "In the input file, there are 3 sections: "
},
{
"code": null,
"e": 1841,
"s": 1576,
"text": "1. Definition Section: The definition section contains the declaration of variables, regular definitions, manifest constants. In the definition section, text is enclosed in “%{ %}” brackets. Anything written in this brackets is copied directly to the file lex.yy.c"
},
{
"code": null,
"e": 1850,
"s": 1841,
"text": "Syntax: "
},
{
"code": null,
"e": 1874,
"s": 1850,
"text": "%{\n // Definitions\n%}"
},
{
"code": null,
"e": 2088,
"s": 1874,
"text": "2. Rules Section: The rules section contains a series of rules in the form: pattern action and pattern must be unintended and action begin on the same line in {} brackets. The rule section is enclosed in “%% %%”. "
},
{
"code": null,
"e": 2098,
"s": 2088,
"text": "Syntax: "
},
{
"code": null,
"e": 2120,
"s": 2098,
"text": "%%\npattern action\n%%"
},
{
"code": null,
"e": 2179,
"s": 2120,
"text": "Examples: Table below shows some of the pattern matches. "
},
{
"code": null,
"e": 2345,
"s": 2179,
"text": "3. User Code Section: This section contains C statements and additional functions. We can also compile these functions separately and load with the lexical analyzer."
},
{
"code": null,
"e": 2372,
"s": 2345,
"text": "Basic Program Structure: "
},
{
"code": null,
"e": 2425,
"s": 2372,
"text": "%{\n// Definitions\n%}\n\n%%\nRules\n%%\n\nUser code section"
},
{
"code": null,
"e": 2595,
"s": 2425,
"text": "How to run the program: To run the program, it should be first saved with the extension .l or .lex. Run the below commands on terminal in order to run the program file. "
},
{
"code": null,
"e": 2781,
"s": 2595,
"text": "Step 1: lex filename.l or lex filename.lex depending on the extension file is saved with Step 2: gcc lex.yy.c Step 3: ./a.out Step 4: Provide the input to program in case it is required"
},
{
"code": null,
"e": 2943,
"s": 2781,
"text": "Note: Press Ctrl+D or use some rule to stop taking inputs from the user. Please see the output images of below programs to clear if in doubt to run the programs."
},
{
"code": null,
"e": 2999,
"s": 2943,
"text": "Example 1: Count the number of characters in a string "
},
{
"code": null,
"e": 3001,
"s": 2999,
"text": "C"
},
{
"code": "/*** Definition Section has one variablewhich can be accessed inside yylex() and main() ***/%{int count = 0;%} /*** Rule Section has three rules, first rule matches with capital letters, second rulematches with any character except newline and third rule does not take input after the enter***/%%[A-Z] {printf(\"%s capital letter\\n\", yytext); count++;}. {printf(\"%s not a capital letter\\n\", yytext);}\\n {return 0;}%% /*** Code Section prints the number ofcapital letter present in the given input***/int yywrap(){}int main(){ // Explanation:// yywrap() - wraps the above rule section/* yyin - takes the file pointer which contains the input*//* yylex() - this is the main flex function which runs the Rule Section*/// yytext is the text in the buffer // Uncomment the lines below // to take input from file// FILE *fp;// char filename[50];// printf(\"Enter the filename: \\n\");// scanf(\"%s\",filename);// fp = fopen(filename,\"r\");// yyin = fp; yylex();printf(\"\\nNumber of Capital letters \" \"in the given input - %d\\n\", count); return 0;}",
"e": 4079,
"s": 3001,
"text": null
},
{
"code": null,
"e": 4088,
"s": 4079,
"text": "Output: "
},
{
"code": null,
"e": 4165,
"s": 4088,
"text": "Example 2: Count the number of characters and number of lines in the input "
},
{
"code": null,
"e": 4167,
"s": 4165,
"text": "C"
},
{
"code": "/* Declaring two counters one for number of lines other for number of characters */%{int no_of_lines = 0;int no_of_chars = 0;%} /***rule 1 counts the number of lines, rule 2 counts the number of characters and rule 3 specifies when to stop taking input***/%%\\n ++no_of_lines;. ++no_of_chars;end return 0;%% /*** User code section***/int yywrap(){}int main(int argc, char **argv){ yylex();printf(\"number of lines = %d, number of chars = %d\\n\", no_of_lines, no_of_chars ); return 0;}",
"e": 4674,
"s": 4167,
"text": null
},
{
"code": null,
"e": 4683,
"s": 4674,
"text": "Output: "
},
{
"code": null,
"e": 4700,
"s": 4685,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4716,
"s": 4700,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4735,
"s": 4716,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 4747,
"s": 4735,
"text": "Lex program"
},
{
"code": null,
"e": 4758,
"s": 4747,
"text": "C Programs"
},
{
"code": null,
"e": 4774,
"s": 4758,
"text": "Compiler Design"
},
{
"code": null,
"e": 4872,
"s": 4774,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4885,
"s": 4872,
"text": "Strings in C"
},
{
"code": null,
"e": 4926,
"s": 4885,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 4955,
"s": 4926,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 4993,
"s": 4955,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 5028,
"s": 4993,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 5069,
"s": 5028,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 5110,
"s": 5069,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 5168,
"s": 5110,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 5201,
"s": 5168,
"text": "Type Checking in Compiler Design"
}
] |
Java.util.zip.ZipInputStream class in Java
|
28 Jan, 2017
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.Constructors:
ZipInputStream(InputStream in) : Creates a new ZIP input stream.
ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream
Methods :
int available() : Returns 0 after EOF has reached for the current entry data, otherwise always return .Programs should not count on this method to return the actual number of bytesthat could be read without blocking.Syntax :public int available()
throws IOException
Overrides:
available in class InflaterInputStream
Returns:
1 before EOF and 0 after EOF has reached for current entry.
Programs should not count on this method to return the actual number
of bytes that could be read without blocking.
Throws:
IOException
Syntax :public int available()
throws IOException
Overrides:
available in class InflaterInputStream
Returns:
1 before EOF and 0 after EOF has reached for current entry.
Programs should not count on this method to return the actual number
of bytes that could be read without blocking.
Throws:
IOException
void close() : Closes this input stream and releases any system resources associated with the stream.Syntax :public void close()
throws IOException
Overrides:
close in class InflaterInputStream
Throws:
IOException
Syntax :public void close()
throws IOException
Overrides:
close in class InflaterInputStream
Throws:
IOException
void closeEntry() : Closes the current ZIP entry and positions the stream for reading the next entry.Syntax :public void closeEntry()
throws IOException
Throws:
ZipException
IOException
Syntax :public void closeEntry()
throws IOException
Throws:
ZipException
IOException
protected ZipEntry createZipEntry(String name) : Creates a new ZipEntry object for the specified entry name.Syntax :protected ZipEntry createZipEntry(String name)
Parameters:
name - the ZIP file entry name
Returns:
the ZipEntry just created
Syntax :protected ZipEntry createZipEntry(String name)
Parameters:
name - the ZIP file entry name
Returns:
the ZipEntry just created
ZipEntry getNextEntry() : Reads the next ZIP file entry and positions the stream at the beginning of the entry data.Syntax :public ZipEntry getNextEntry()
throws IOException
Returns:
the next ZIP file entry, or null if there are no more entries
Throws:
ZipException
IOException
Syntax :public ZipEntry getNextEntry()
throws IOException
Returns:
the next ZIP file entry, or null if there are no more entries
Throws:
ZipException
IOException
int read(byte[] b, int off, int len) : Reads from the current ZIP entry into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.Syntax :public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the buffer into which the data is read
off - the start offset in the destination array b
len - the maximum number of bytes read
Returns:
the actual number of bytes read, or -1 if the end of the entry is reached
Throws:
NullPointerException
IndexOutOfBoundsException
ZipException
IOException
Syntax :public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the buffer into which the data is read
off - the start offset in the destination array b
len - the maximum number of bytes read
Returns:
the actual number of bytes read, or -1 if the end of the entry is reached
Throws:
NullPointerException
IndexOutOfBoundsException
ZipException
IOException
long skip(long n) : Skips specified number of bytes in the current ZIP entry.Syntax :public long skip(long n)
throws IOException
Parameters:
n - the number of bytes to skip
Returns:
the actual number of bytes skipped
Throws:
ZipException
IOException
IllegalArgumentException
Syntax :public long skip(long n)
throws IOException
Parameters:
n - the number of bytes to skip
Returns:
the actual number of bytes skipped
Throws:
ZipException
IOException
IllegalArgumentException
//Java program demonstrating ZipInputStream methods import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Arrays;import java.util.jar.JarInputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;class ZipInputStreamDemo extends ZipInputStream{ public ZipInputStreamDemo(InputStream in) { super(in); } public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("Awesome CV.zip"); ZipInputStream zis = new JarInputStream(fis); ZipInputStreamDemo obj = new ZipInputStreamDemo(zis); //illustrating createZipEntry() ZipEntry ze = obj.createZipEntry("ZipEntry"); System.out.println(ze.getName()); //illustrating getNextEntry() ZipEntry je = zis.getNextEntry(); System.out.println(je.getName()); //illustrating skip() method zis.skip(3); //illustrating closeEntry() method zis.closeEntry(); zis.getNextEntry(); byte b[] = new byte[10]; //illustrating available() method //Reads up to byte.length bytes of data from this input stream if(zis.available() == 1) zis.read(b); System.out.println(Arrays.toString(b)); //closing the stream zis.close(); }}
Output :
ZipEntry
awesome-cv.cls
[35, 32, 65, 119, 101, 115, 111, 109, 101, 32]
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2017"
},
{
"code": null,
"e": 191,
"s": 28,
"text": "This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.Constructors:"
},
{
"code": null,
"e": 256,
"s": 191,
"text": "ZipInputStream(InputStream in) : Creates a new ZIP input stream."
},
{
"code": null,
"e": 337,
"s": 256,
"text": "ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream"
},
{
"code": null,
"e": 347,
"s": 337,
"text": "Methods :"
},
{
"code": null,
"e": 884,
"s": 347,
"text": "int available() : Returns 0 after EOF has reached for the current entry data, otherwise always return .Programs should not count on this method to return the actual number of bytesthat could be read without blocking.Syntax :public int available()\n throws IOException\nOverrides:\navailable in class InflaterInputStream\nReturns:\n1 before EOF and 0 after EOF has reached for current entry. \nPrograms should not count on this method to return the actual number \nof bytes that could be read without blocking.\nThrows:\nIOException "
},
{
"code": null,
"e": 1205,
"s": 884,
"text": "Syntax :public int available()\n throws IOException\nOverrides:\navailable in class InflaterInputStream\nReturns:\n1 before EOF and 0 after EOF has reached for current entry. \nPrograms should not count on this method to return the actual number \nof bytes that could be read without blocking.\nThrows:\nIOException "
},
{
"code": null,
"e": 1430,
"s": 1205,
"text": "void close() : Closes this input stream and releases any system resources associated with the stream.Syntax :public void close()\n throws IOException\nOverrides:\nclose in class InflaterInputStream\nThrows:\nIOException"
},
{
"code": null,
"e": 1554,
"s": 1430,
"text": "Syntax :public void close()\n throws IOException\nOverrides:\nclose in class InflaterInputStream\nThrows:\nIOException"
},
{
"code": null,
"e": 1758,
"s": 1554,
"text": "void closeEntry() : Closes the current ZIP entry and positions the stream for reading the next entry.Syntax :public void closeEntry()\n throws IOException\nThrows:\nZipException \nIOException "
},
{
"code": null,
"e": 1861,
"s": 1758,
"text": "Syntax :public void closeEntry()\n throws IOException\nThrows:\nZipException \nIOException "
},
{
"code": null,
"e": 2102,
"s": 1861,
"text": "protected ZipEntry createZipEntry(String name) : Creates a new ZipEntry object for the specified entry name.Syntax :protected ZipEntry createZipEntry(String name)\nParameters:\nname - the ZIP file entry name\nReturns:\nthe ZipEntry just created"
},
{
"code": null,
"e": 2235,
"s": 2102,
"text": "Syntax :protected ZipEntry createZipEntry(String name)\nParameters:\nname - the ZIP file entry name\nReturns:\nthe ZipEntry just created"
},
{
"code": null,
"e": 2537,
"s": 2235,
"text": "ZipEntry getNextEntry() : Reads the next ZIP file entry and positions the stream at the beginning of the entry data.Syntax :public ZipEntry getNextEntry()\n throws IOException\nReturns:\nthe next ZIP file entry, or null if there are no more entries\nThrows:\nZipException \nIOException "
},
{
"code": null,
"e": 2723,
"s": 2537,
"text": "Syntax :public ZipEntry getNextEntry()\n throws IOException\nReturns:\nthe next ZIP file entry, or null if there are no more entries\nThrows:\nZipException \nIOException "
},
{
"code": null,
"e": 3339,
"s": 2723,
"text": "int read(byte[] b, int off, int len) : Reads from the current ZIP entry into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.Syntax :public int read(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the buffer into which the data is read\noff - the start offset in the destination array b\nlen - the maximum number of bytes read\nReturns:\nthe actual number of bytes read, or -1 if the end of the entry is reached\nThrows:\nNullPointerException \nIndexOutOfBoundsException \nZipException \nIOException"
},
{
"code": null,
"e": 3743,
"s": 3339,
"text": "Syntax :public int read(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the buffer into which the data is read\noff - the start offset in the destination array b\nlen - the maximum number of bytes read\nReturns:\nthe actual number of bytes read, or -1 if the end of the entry is reached\nThrows:\nNullPointerException \nIndexOutOfBoundsException \nZipException \nIOException"
},
{
"code": null,
"e": 4029,
"s": 3743,
"text": "long skip(long n) : Skips specified number of bytes in the current ZIP entry.Syntax :public long skip(long n)\n throws IOException\nParameters:\nn - the number of bytes to skip\nReturns:\nthe actual number of bytes skipped\nThrows:\nZipException\nIOException\nIllegalArgumentException "
},
{
"code": null,
"e": 4238,
"s": 4029,
"text": "Syntax :public long skip(long n)\n throws IOException\nParameters:\nn - the number of bytes to skip\nReturns:\nthe actual number of bytes skipped\nThrows:\nZipException\nIOException\nIllegalArgumentException "
},
{
"code": "//Java program demonstrating ZipInputStream methods import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.Arrays;import java.util.jar.JarInputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;class ZipInputStreamDemo extends ZipInputStream{ public ZipInputStreamDemo(InputStream in) { super(in); } public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(\"Awesome CV.zip\"); ZipInputStream zis = new JarInputStream(fis); ZipInputStreamDemo obj = new ZipInputStreamDemo(zis); //illustrating createZipEntry() ZipEntry ze = obj.createZipEntry(\"ZipEntry\"); System.out.println(ze.getName()); //illustrating getNextEntry() ZipEntry je = zis.getNextEntry(); System.out.println(je.getName()); //illustrating skip() method zis.skip(3); //illustrating closeEntry() method zis.closeEntry(); zis.getNextEntry(); byte b[] = new byte[10]; //illustrating available() method //Reads up to byte.length bytes of data from this input stream if(zis.available() == 1) zis.read(b); System.out.println(Arrays.toString(b)); //closing the stream zis.close(); }}",
"e": 5589,
"s": 4238,
"text": null
},
{
"code": null,
"e": 5598,
"s": 5589,
"text": "Output :"
},
{
"code": null,
"e": 5670,
"s": 5598,
"text": "ZipEntry\nawesome-cv.cls\n[35, 32, 65, 119, 101, 115, 111, 109, 101, 32]\n"
},
{
"code": null,
"e": 5972,
"s": 5670,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6097,
"s": 5972,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6106,
"s": 6097,
"text": "Java-I/O"
},
{
"code": null,
"e": 6111,
"s": 6106,
"text": "Java"
},
{
"code": null,
"e": 6116,
"s": 6111,
"text": "Java"
},
{
"code": null,
"e": 6214,
"s": 6116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6229,
"s": 6214,
"text": "Stream In Java"
},
{
"code": null,
"e": 6250,
"s": 6229,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6271,
"s": 6250,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6290,
"s": 6271,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6307,
"s": 6290,
"text": "Generics in Java"
},
{
"code": null,
"e": 6337,
"s": 6307,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 6363,
"s": 6337,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6379,
"s": 6363,
"text": "Strings in Java"
},
{
"code": null,
"e": 6416,
"s": 6379,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to create a form using Django Forms ?
|
16 Aug, 2021
Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.
Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it.
In your forms.py Enter the following,
Python3
from django import forms # creating a formclass InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = "Enter 6 digit roll number" ) password = forms.CharField(widget = forms.PasswordInput())
Let’s explain what exactly is happening, left side denotes the name of the field and to the right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as
Syntax :
Field_name = forms.FieldType(attributes)
Now to render this form into a view, move to views.py and create a home_view as below.
Python3
from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, "home.html", context)
In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html
HTML
<form action = "" method = "post"> {% csrf_token %} {{form }} <input type="submit" value=Submit"></form>
All set to check if the form is working or not let’s visit http://localhost:8000/
The form is working properly but visuals are disappointing, Django provides some predefined ways to show forms in a convenient manner. In templates, the following will modify the inputs as,
{{ form.as_table }} will render them as table cells wrapped in <tr> tags
{{ form.as_p }} will render them wrapped in <p> tags
{{ form.as_ul }} will render them wrapped in <li> tags
One can modify these settings also and show fields as he wants using {{ form.field_name }} but this may alter the normal process of validation if some field is empty and hence needs extraordinary care. More – Django Forms
NaveenArora
ddeevviissaavviittaa
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 552,
"s": 53,
"text": "Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on. "
},
{
"code": null,
"e": 666,
"s": 552,
"text": "Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 755,
"s": 666,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 806,
"s": 755,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 839,
"s": 806,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1013,
"s": 839,
"text": "In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it. "
},
{
"code": null,
"e": 1052,
"s": 1013,
"text": "In your forms.py Enter the following, "
},
{
"code": null,
"e": 1060,
"s": 1052,
"text": "Python3"
},
{
"code": "from django import forms # creating a formclass InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) roll_number = forms.IntegerField( help_text = \"Enter 6 digit roll number\" ) password = forms.CharField(widget = forms.PasswordInput())",
"e": 1412,
"s": 1060,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1412,
"text": "Let’s explain what exactly is happening, left side denotes the name of the field and to the right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as "
},
{
"code": null,
"e": 1629,
"s": 1619,
"text": "Syntax : "
},
{
"code": null,
"e": 1670,
"s": 1629,
"text": "Field_name = forms.FieldType(attributes)"
},
{
"code": null,
"e": 1758,
"s": 1670,
"text": "Now to render this form into a view, move to views.py and create a home_view as below. "
},
{
"code": null,
"e": 1766,
"s": 1758,
"text": "Python3"
},
{
"code": "from django.shortcuts import renderfrom .forms import InputForm # Create your views here.def home_view(request): context ={} context['form']= InputForm() return render(request, \"home.html\", context)",
"e": 1974,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2103,
"s": 1974,
"text": "In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html "
},
{
"code": null,
"e": 2108,
"s": 2103,
"text": "HTML"
},
{
"code": "<form action = \"\" method = \"post\"> {% csrf_token %} {{form }} <input type=\"submit\" value=Submit\"></form>",
"e": 2222,
"s": 2108,
"text": null
},
{
"code": null,
"e": 2305,
"s": 2222,
"text": "All set to check if the form is working or not let’s visit http://localhost:8000/ "
},
{
"code": null,
"e": 2496,
"s": 2305,
"text": "The form is working properly but visuals are disappointing, Django provides some predefined ways to show forms in a convenient manner. In templates, the following will modify the inputs as, "
},
{
"code": null,
"e": 2569,
"s": 2496,
"text": "{{ form.as_table }} will render them as table cells wrapped in <tr> tags"
},
{
"code": null,
"e": 2622,
"s": 2569,
"text": "{{ form.as_p }} will render them wrapped in <p> tags"
},
{
"code": null,
"e": 2677,
"s": 2622,
"text": "{{ form.as_ul }} will render them wrapped in <li> tags"
},
{
"code": null,
"e": 2899,
"s": 2677,
"text": "One can modify these settings also and show fields as he wants using {{ form.field_name }} but this may alter the normal process of validation if some field is empty and hence needs extraordinary care. More – Django Forms"
},
{
"code": null,
"e": 2911,
"s": 2899,
"text": "NaveenArora"
},
{
"code": null,
"e": 2932,
"s": 2911,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 2945,
"s": 2932,
"text": "Django-forms"
},
{
"code": null,
"e": 2959,
"s": 2945,
"text": "Python Django"
},
{
"code": null,
"e": 2966,
"s": 2959,
"text": "Python"
}
] |
Finding sum of first n natural numbers in PL/SQL
|
07 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given a positive integer n and the task is to find the sum of first n natural number.Examples:
Input: n = 3
Output: 10
Input: n = 2
Output: 4
Approach is to take digits form 1 and to n and summing like done below-
Sum of first natural number: 1
Sum of first and second natural number: 1 + 2 = 3
Sum of first, second and third natural number = 1 + 2 + 3 = 6
Below is the required implementation:
--declaration section DECLARE x NUMBER; n NUMBER; i NUMBER; --function for finding sum FUNCTION Findmax(n IN NUMBER) RETURN NUMBER IS sums NUMBER := 0; BEGIN --for loop for n times iteration FOR i IN 1..n LOOP sums := sums + i*(i+1)/2; END LOOP; RETURN sums; END; BEGIN --driver code n := 4; x := findmax(n); dbms_output.Put_line('Sum: ' || x); END; --end of Program
Output:
Sum: 20
Time complexity = O(n)
An efficient solution is to use direct formula n(n+1)(n+2)/6
Mathematically, we need to find, Σ ((i * (i + 1))/2), where 1 <= i <= nSo, lets solve this summation,
Sum = Σ ((i * (i + 1))/2), where 1 <= i <= n
= (1/2) * Σ (i * (i + 1))
= (1/2) * Σ (i2 + i)
= (1/2) * (Σ i2 + Σ i)
We know Σ i2 = n * (n + 1) * (2*n + 1) / 6 and
Σ i = n * ( n + 1) / 2.
Substituting the value, we get,
Sum = (1/2) * ((n * (n + 1) * (2*n + 1) / 6) + (n * ( n + 1) / 2))
= n * (n + 1)/2 [(2n + 1)/6 + 1/2]
= n * (n + 1) * (n + 2) / 6
Below is the required implementation:
--declaration section DECLARE x NUMBER; n NUMBER; --utility function FUNCTION Findmax(n IN NUMBER) RETURN NUMBER IS z NUMBER; BEGIN -- formula for finding sum z := (n * (n + 1) * (n + 2)) / 6; RETURN z; END; BEGIN n := 4; x := findmax(n); dbms_output.Put_line(' Sum: ' || x); END; --end of program
Output:
Sum: 20
Time complexity = O(1)
SQL-PL/SQL
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": "\n07 Jul, 2018"
},
{
"code": null,
"e": 366,
"s": 28,
"text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given a positive integer n and the task is to find the sum of first n natural number.Examples:"
},
{
"code": null,
"e": 421,
"s": 366,
"text": "Input: n = 3\nOutput: 10\n \nInput: n = 2\nOutput: 4\n"
},
{
"code": null,
"e": 493,
"s": 421,
"text": "Approach is to take digits form 1 and to n and summing like done below-"
},
{
"code": null,
"e": 636,
"s": 493,
"text": "Sum of first natural number: 1\nSum of first and second natural number: 1 + 2 = 3\nSum of first, second and third natural number = 1 + 2 + 3 = 6"
},
{
"code": null,
"e": 674,
"s": 636,
"text": "Below is the required implementation:"
},
{
"code": "--declaration section DECLARE x NUMBER; n NUMBER; i NUMBER; --function for finding sum FUNCTION Findmax(n IN NUMBER) RETURN NUMBER IS sums NUMBER := 0; BEGIN --for loop for n times iteration FOR i IN 1..n LOOP sums := sums + i*(i+1)/2; END LOOP; RETURN sums; END; BEGIN --driver code n := 4; x := findmax(n); dbms_output.Put_line('Sum: ' || x); END; --end of Program",
"e": 1133,
"s": 674,
"text": null
},
{
"code": null,
"e": 1141,
"s": 1133,
"text": "Output:"
},
{
"code": null,
"e": 1149,
"s": 1141,
"text": "Sum: 20"
},
{
"code": null,
"e": 1172,
"s": 1149,
"text": "Time complexity = O(n)"
},
{
"code": null,
"e": 1233,
"s": 1172,
"text": "An efficient solution is to use direct formula n(n+1)(n+2)/6"
},
{
"code": null,
"e": 1335,
"s": 1233,
"text": "Mathematically, we need to find, Σ ((i * (i + 1))/2), where 1 <= i <= nSo, lets solve this summation,"
},
{
"code": null,
"e": 1707,
"s": 1335,
"text": "Sum = Σ ((i * (i + 1))/2), where 1 <= i <= n\n = (1/2) * Σ (i * (i + 1))\n = (1/2) * Σ (i2 + i)\n = (1/2) * (Σ i2 + Σ i)\n\nWe know Σ i2 = n * (n + 1) * (2*n + 1) / 6 and \nΣ i = n * ( n + 1) / 2.\nSubstituting the value, we get,\nSum = (1/2) * ((n * (n + 1) * (2*n + 1) / 6) + (n * ( n + 1) / 2)) \n = n * (n + 1)/2 [(2n + 1)/6 + 1/2]\n = n * (n + 1) * (n + 2) / 6"
},
{
"code": null,
"e": 1745,
"s": 1707,
"text": "Below is the required implementation:"
},
{
"code": "--declaration section DECLARE x NUMBER; n NUMBER; --utility function FUNCTION Findmax(n IN NUMBER) RETURN NUMBER IS z NUMBER; BEGIN -- formula for finding sum z := (n * (n + 1) * (n + 2)) / 6; RETURN z; END; BEGIN n := 4; x := findmax(n); dbms_output.Put_line(' Sum: ' || x); END; --end of program",
"e": 2111,
"s": 1745,
"text": null
},
{
"code": null,
"e": 2119,
"s": 2111,
"text": "Output:"
},
{
"code": null,
"e": 2127,
"s": 2119,
"text": "Sum: 20"
},
{
"code": null,
"e": 2150,
"s": 2127,
"text": "Time complexity = O(1)"
},
{
"code": null,
"e": 2161,
"s": 2150,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 2165,
"s": 2161,
"text": "SQL"
},
{
"code": null,
"e": 2169,
"s": 2165,
"text": "SQL"
}
] |
Difference between Active Attack and Passive Attack
|
07 Jul, 2022
Active Attacks: Active attacks are the type of attacks in which, The attacker efforts to change or modify the content of messages. Active Attack is danger for Integrity as well as availability. Due to active attack system is always damaged and System resources can be changed. The most important thing is that, In active attack, Victim gets informed about the attack.
Passive Attacks: Passive Attacks are the type of attacks in which, The attacker observes the content of messages or copy the content of messages. Passive Attack is a danger for Confidentiality. Due to passive attack, there is no any harm to the system. The most important thing is that In passive attack, Victim does not get informed about the attack.
Prerequisite - Types of Security attacks | Active and Passive attacks
Difference between Active Attack and Passive Attack:
ashushrma378
sayanc170
Information-Security
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 422,
"s": 54,
"text": "Active Attacks: Active attacks are the type of attacks in which, The attacker efforts to change or modify the content of messages. Active Attack is danger for Integrity as well as availability. Due to active attack system is always damaged and System resources can be changed. The most important thing is that, In active attack, Victim gets informed about the attack."
},
{
"code": null,
"e": 775,
"s": 422,
"text": "Passive Attacks: Passive Attacks are the type of attacks in which, The attacker observes the content of messages or copy the content of messages. Passive Attack is a danger for Confidentiality. Due to passive attack, there is no any harm to the system. The most important thing is that In passive attack, Victim does not get informed about the attack. "
},
{
"code": null,
"e": 846,
"s": 775,
"text": "Prerequisite - Types of Security attacks | Active and Passive attacks "
},
{
"code": null,
"e": 899,
"s": 846,
"text": "Difference between Active Attack and Passive Attack:"
},
{
"code": null,
"e": 912,
"s": 899,
"text": "ashushrma378"
},
{
"code": null,
"e": 922,
"s": 912,
"text": "sayanc170"
},
{
"code": null,
"e": 943,
"s": 922,
"text": "Information-Security"
},
{
"code": null,
"e": 961,
"s": 943,
"text": "Computer Networks"
},
{
"code": null,
"e": 980,
"s": 961,
"text": "Difference Between"
},
{
"code": null,
"e": 998,
"s": 980,
"text": "Computer Networks"
}
] |
Range sum queries without updates
|
12 Jun, 2022
Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.
Examples:
Input : arr[] = {1, 2, 3, 4, 5}
i = 1, j = 3
i = 2, j = 4
Output : 9
12
Input : arr[] = {1, 2, 3, 4, 5}
i = 0, j = 4
i = 1, j = 2
Output : 15
5
A Simple Solution is to compute the sum for every query.
An Efficient Solution is to precompute prefix sum. Let pre[i] stores sum of elements from arr[0] to arr[i]. To answer a query (i, j), we return pre[j] – pre[i-1].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find sum between two indexes// when there is no update.#include <bits/stdc++.h>using namespace std; void preCompute(int arr[], int n, int pre[]){ pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in arr[i..j]// It is assumed that i <= jint rangeSum(int i, int j, int pre[]){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; // Function call preCompute(arr, n, pre); cout << rangeSum(1, 3, pre) << endl; cout << rangeSum(2, 4, pre) << endl; return 0;}
// Java program to find sum between two indexes// when there is no update. import java.util.*;import java.lang.*; class GFG { public static void preCompute(int arr[], int n, int pre[]) { pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1]; } // Returns sum of elements in arr[i..j] // It is assumed that i <= j public static int rangeSum(int i, int j, int pre[]) { if (i == 0) return pre[j]; return pre[j] - pre[i - 1]; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int pre[] = new int[n]; preCompute(arr, n, pre); System.out.println(rangeSum(1, 3, pre)); System.out.println(rangeSum(2, 4, pre)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>
# Python program to find sum between two indexes# when there is no update. # Function to compute prefix sumdef preCompute(arr, n, prefix): prefix[0] = arr[0] for i in range(1, n): prefix[i] = prefix[i - 1] + arr[i] # Returns sum of elements in arr[i..j]# It is assumed that i <= jdef rangeSum(l, r): if l == 0: print(prefix[r]) return print(prefix[r] - prefix[l - 1]) # Driver codearr = [1, 2, 3, 4, 5]n = len(arr)prefix = [0 for i in range(n)] # preComputationpreCompute(arr, n, prefix) # Range QueriesrangeSum(1, 3)rangeSum(2, 4) # This code is contributed by dineshdkda31.
// Program to find sum between two// indexes when there is no update.using System; class GFG { public static void preCompute(int[] arr, int n, int[] pre) { pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1]; } // Returns sum of elements in // arr[i..j] // It is assumed that i <= j public static int rangeSum(int i, int j, int[] pre) { if (i == 0) return pre[j]; return pre[j] - pre[i - 1]; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; int[] pre = new int[n]; // Function call preCompute(arr, n, pre); Console.WriteLine(rangeSum(1, 3, pre)); Console.WriteLine(rangeSum(2, 4, pre)); }} // Code Contributed by Anant Agarwal.
<script> // JavaScript Program to find sum between two// indexes when there is no update. let pre = new Array(1000,0); function preCompute(arr, n){ pre[0] = arr[0]; for (let i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in// arr[i..j]// It is assumed that i <= jfunction rangeSum(i, j, pre){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codelet arr = [1, 2, 3, 4, 5];let n = arr.length; // Function callpreCompute(arr, n); document.write(rangeSum(1, 3, pre)+"<br>");document.write(rangeSum(2, 4, pre)); </script>
9
12
Here time complexity of every range sum query is O(1) and the overall time complexity is O(n).
Auxiliary Space required = O(n), where n is the size of the given array.
The question becomes complicated when updates are also allowed. In such situations when using advanced data structures like Segment Tree or Binary Indexed Tree.
This article is contributed by Rahul Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
deepak atariya
mohit kumar 29
dineshdkda31
tamanna17122007
array-range-queries
Arrays
Arrays
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
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 240,
"s": 54,
"text": "Given an array arr of integers of size n. We need to compute the sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times."
},
{
"code": null,
"e": 251,
"s": 240,
"text": "Examples: "
},
{
"code": null,
"e": 459,
"s": 251,
"text": "Input : arr[] = {1, 2, 3, 4, 5}\n i = 1, j = 3\n i = 2, j = 4\nOutput : 9\n 12 \n\nInput : arr[] = {1, 2, 3, 4, 5}\n i = 0, j = 4 \n i = 1, j = 2 \nOutput : 15\n 5"
},
{
"code": null,
"e": 516,
"s": 459,
"text": "A Simple Solution is to compute the sum for every query."
},
{
"code": null,
"e": 679,
"s": 516,
"text": "An Efficient Solution is to precompute prefix sum. Let pre[i] stores sum of elements from arr[0] to arr[i]. To answer a query (i, j), we return pre[j] – pre[i-1]."
},
{
"code": null,
"e": 730,
"s": 679,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 734,
"s": 730,
"text": "C++"
},
{
"code": null,
"e": 739,
"s": 734,
"text": "Java"
},
{
"code": null,
"e": 747,
"s": 739,
"text": "Python3"
},
{
"code": null,
"e": 750,
"s": 747,
"text": "C#"
},
{
"code": null,
"e": 761,
"s": 750,
"text": "Javascript"
},
{
"code": "// CPP program to find sum between two indexes// when there is no update.#include <bits/stdc++.h>using namespace std; void preCompute(int arr[], int n, int pre[]){ pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in arr[i..j]// It is assumed that i <= jint rangeSum(int i, int j, int pre[]){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; // Function call preCompute(arr, n, pre); cout << rangeSum(1, 3, pre) << endl; cout << rangeSum(2, 4, pre) << endl; return 0;}",
"e": 1453,
"s": 761,
"text": null
},
{
"code": "// Java program to find sum between two indexes// when there is no update. import java.util.*;import java.lang.*; class GFG { public static void preCompute(int arr[], int n, int pre[]) { pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1]; } // Returns sum of elements in arr[i..j] // It is assumed that i <= j public static int rangeSum(int i, int j, int pre[]) { if (i == 0) return pre[j]; return pre[j] - pre[i - 1]; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int pre[] = new int[n]; preCompute(arr, n, pre); System.out.println(rangeSum(1, 3, pre)); System.out.println(rangeSum(2, 4, pre)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 2351,
"s": 1453,
"text": null
},
{
"code": "# Python program to find sum between two indexes# when there is no update. # Function to compute prefix sumdef preCompute(arr, n, prefix): prefix[0] = arr[0] for i in range(1, n): prefix[i] = prefix[i - 1] + arr[i] # Returns sum of elements in arr[i..j]# It is assumed that i <= jdef rangeSum(l, r): if l == 0: print(prefix[r]) return print(prefix[r] - prefix[l - 1]) # Driver codearr = [1, 2, 3, 4, 5]n = len(arr)prefix = [0 for i in range(n)] # preComputationpreCompute(arr, n, prefix) # Range QueriesrangeSum(1, 3)rangeSum(2, 4) # This code is contributed by dineshdkda31.",
"e": 2947,
"s": 2351,
"text": null
},
{
"code": "// Program to find sum between two// indexes when there is no update.using System; class GFG { public static void preCompute(int[] arr, int n, int[] pre) { pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1]; } // Returns sum of elements in // arr[i..j] // It is assumed that i <= j public static int rangeSum(int i, int j, int[] pre) { if (i == 0) return pre[j]; return pre[j] - pre[i - 1]; } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; int[] pre = new int[n]; // Function call preCompute(arr, n, pre); Console.WriteLine(rangeSum(1, 3, pre)); Console.WriteLine(rangeSum(2, 4, pre)); }} // Code Contributed by Anant Agarwal.",
"e": 3820,
"s": 2947,
"text": null
},
{
"code": "<script> // JavaScript Program to find sum between two// indexes when there is no update. let pre = new Array(1000,0); function preCompute(arr, n){ pre[0] = arr[0]; for (let i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in// arr[i..j]// It is assumed that i <= jfunction rangeSum(i, j, pre){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codelet arr = [1, 2, 3, 4, 5];let n = arr.length; // Function callpreCompute(arr, n); document.write(rangeSum(1, 3, pre)+\"<br>\");document.write(rangeSum(2, 4, pre)); </script>",
"e": 4414,
"s": 3820,
"text": null
},
{
"code": null,
"e": 4419,
"s": 4414,
"text": "9\n12"
},
{
"code": null,
"e": 4514,
"s": 4419,
"text": "Here time complexity of every range sum query is O(1) and the overall time complexity is O(n)."
},
{
"code": null,
"e": 4587,
"s": 4514,
"text": "Auxiliary Space required = O(n), where n is the size of the given array."
},
{
"code": null,
"e": 4748,
"s": 4587,
"text": "The question becomes complicated when updates are also allowed. In such situations when using advanced data structures like Segment Tree or Binary Indexed Tree."
},
{
"code": null,
"e": 5044,
"s": 4748,
"text": "This article is contributed by Rahul Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5169,
"s": 5044,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5184,
"s": 5169,
"text": "deepak atariya"
},
{
"code": null,
"e": 5199,
"s": 5184,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 5212,
"s": 5199,
"text": "dineshdkda31"
},
{
"code": null,
"e": 5228,
"s": 5212,
"text": "tamanna17122007"
},
{
"code": null,
"e": 5248,
"s": 5228,
"text": "array-range-queries"
},
{
"code": null,
"e": 5255,
"s": 5248,
"text": "Arrays"
},
{
"code": null,
"e": 5262,
"s": 5255,
"text": "Arrays"
},
{
"code": null,
"e": 5360,
"s": 5262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5428,
"s": 5360,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5472,
"s": 5428,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5504,
"s": 5472,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5552,
"s": 5504,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5566,
"s": 5552,
"text": "Linear Search"
},
{
"code": null,
"e": 5651,
"s": 5566,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 5674,
"s": 5651,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 5730,
"s": 5674,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 5757,
"s": 5730,
"text": "Subset Sum Problem | DP-25"
}
] |
Simplify the directory path (Unix like)
|
07 Sep, 2021
Given an absolute path for a file (Unix-style), simplify it. Note that absolute path always begin with ‘/’ ( root directory ), a dot in path represent current directory and double dot represents parent directory.Examples:
"/a/./" --> means stay at the current directory 'a'
"/a/b/.." --> means jump to the parent directory
from 'b' to 'a'
"////" --> consecutive multiple '/' are a valid
path, they are equivalent to single "/".
Input : /home/
Output : /home
Input : /a/./b/../../c/
Output : /c
Input : /a/..
Output:/
Input : /a/../
Output : /
Input : /../../../../../a
Output : /a
Input : /a/./b/./c/./d/
Output : /a/b/c/d
Input : /a/../.././../../.
Output:/
Input : /a//b//c//////d
Output : /a/b/c/d
Note: The given input will always have a valid absolute path.
Approach 1:By looking at examples we can see that the above simplification process just behaves like a stack. Whenever we encounter any file’s name, we simply push it into the stack. when we come across ” . ” we do nothing. When we find “..” in our path, we simply pop the topmost element as we have to jump back to parent’s directory. When we see multiple “////” we just ignore them as they are equivalent to one single “/”. After iterating through the whole string the elements remaining in the stack is our simplified absolute path. We have to create another stack to reverse the elements stored inside the original stack and then store the result inside a string.
C++
Java
Python3
C#
Javascript
/* C++ program to simplify a Unix styled absolute path of a file */#include <bits/stdc++.h>using namespace std; // function to simplify a Unix - styled// absolute pathstring simplify(string A){ // stack to store the file's names. stack<string> st; // temporary string which stores the extracted // directory name or commands("." / "..") // Eg. "/a/b/../." // dir will contain "a", "b", "..", "."; string dir; // contains resultant simplifies string. string res; // every string starts from root directory. res.append("/"); // stores length of input string. int len_A = A.length(); for (int i = 0; i < len_A; i++) { // we will clear the temporary string // every time to accommodate new directory // name or command. dir.clear(); // skip all the multiple '/' Eg. "/////"" while (A[i] == '/') i++; // stores directory's name("a", "b" etc.) // or commands("."/"..") into dir while (i < len_A && A[i] != '/') { dir.push_back(A[i]); i++; } // if dir has ".." just pop the topmost // element if the stack is not empty // otherwise ignore. if (dir.compare("..") == 0) { if (!st.empty()) st.pop(); } // if dir has "." then simply continue // with the process. else if (dir.compare(".") == 0) continue; // pushes if it encounters directory's // name("a", "b"). else if (dir.length() != 0) st.push(dir); } // a temporary stack (st1) which will contain // the reverse of original stack(st). stack<string> st1; while (!st.empty()) { st1.push(st.top()); st.pop(); } // the st1 will contain the actual res. while (!st1.empty()) { string temp = st1.top(); // if it's the last element no need // to append "/" if (st1.size() != 1) res.append(temp + "/"); else res.append(temp); st1.pop(); } return res;} // Driver code.int main(){ // absolute path which we have to simplify. string str("/a/./b/../../c/"); string res = simplify(str); cout << res; return 0;}
/* Java program to simplify a Unixstyled absolute path of a file */import java.io.*;import java.util.*; class GFG{ public static void main(String []args) { // absolute path which we have to simplify. String str = new String("/a/./b/../../c/"); String res = simplify(str); System.out.println(res); } // function to simplify a Unix - styled // absolute path static String simplify(String A) { // Stack to store the file's names. Stack<String> st = new Stack<String>(); // temporary String which stores the extracted // directory name or commands("." / "..") // Eg. "/a/b/../." // contains resultant simplifies String. String res = ""; // every String starts from root directory. res += "/"; // stores length of input String. int len_A = A.length(); for (int i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain "a", "b", "..", "."; String dir = ""; // skip all the multiple '/' Eg. "/////"" while (i < len_A && A.charAt(i) == '/') i++; // stores directory's name("a", "b" etc.) // or commands("."/"..") into dir while (i < len_A && A.charAt(i) != '/') { dir += A.charAt(i); i++; } // if dir has ".." just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir.equals("..") == true) { if (!st.empty()) st.pop(); } // if dir has "." then simply continue // with the process. else if (dir.equals(".") == true) continue; // pushes if it encounters directory's // name("a", "b"). else if (dir.length() != 0) st.push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). Stack<String> st1 = new Stack<String>(); while (!st.empty()) { st1.push(st.pop()); // st.pop(); } // the st1 will contain the actual res. while (!st1.empty()) { // if it's the last element no need // to append "/" if (st1.size() != 1) res += (st1.pop() + "/"); else res += st1.pop(); // st1.pop(); } return res; } } // This code is contributed by ankush_953
# Python program to simplify a Unix# styled absolute path of a file # function to simplify a Unix - styled# absolute path def simplify(A): # stack to store the file's names. st = [] # temporary string which stores the extracted # directory name or commands("." / "..") # Eg. "/a/b/../." # dir will contain "a", "b", "..", "."; dir = "" # contains resultant simplifies string. res = "" # every string starts from root directory. res += "/" # stores length of input string. len_A = len(A) i = 0 while i < len_A: # we will clear the temporary string # every time to accommodate new directory # name or command. dir_str = "" # skip all the multiple '/' Eg. "##/"" while (i < len_A and A[i] == '/'): i += 1 # stores directory's name("a", "b" etc.) # or commands("."/"..") into dir while (i < len_A and A[i] != '/'): dir_str += A[i] i += 1 # if dir has ".." just pop the topmost # element if the stack is not empty # otherwise ignore. if dir_str == "..": if len(st): st.pop() # if dir has "." then simply continue # with the process. elif dir_str == '.': continue # pushes if it encounters directory's # name("a", "b"). elif len(dir_str) > 0: st.append(dir_str) i += 1 # a temporary stack (st1) which will contain # the reverse of original stack(st). st1 = [] while len(st): st1.append(st[-1]) st.pop() # the st1 will contain the actual res. while len(st1): temp = st1[-1] # if it's the last element no need # to append "/" if (len(st1) != 1): res += (temp + "/") else: res += temp st1.pop() return res # Driver code. # absolute path which we have to simplify.string = "/a/./b/../../c/"res = simplify(string)print(res) # This code is contributed by ankush_953
// C# program to simplify a Unix// styled absolute path of a fileusing System;using System.Collections.Generic; class GFG{ public static void Main(String []args) { // absolute path which we have to simplify. String str = ("/a/./b/../../c/"); String res = simplify(str); Console.WriteLine(res); } // function to simplify a Unix - styled // absolute path static String simplify(String A) { // Stack to store the file's names. Stack<String> st = new Stack<String>(); // temporary String which stores the extracted // directory name or commands("." / "..") // Eg. "/a/b/../." // contains resultant simplifies String. String res = ""; // every String starts from root directory. res += "/"; // stores length of input String. int len_A = A.Length; for (int i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain "a", "b", "..", "."; String dir = ""; // skip all the multiple '/' Eg. "/////"" while (i < len_A && A[i] == '/') i++; // stores directory's name("a", "b" etc.) // or commands("."/"..") into dir while (i < len_A && A[i] != '/') { dir += A[i]; i++; } // if dir has ".." just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir.Equals("..") == true) { if (st.Count!=0) st.Pop(); } // if dir has "." then simply continue // with the process. else if (dir.Equals(".") == true) continue; // pushes if it encounters directory's // name("a", "b"). else if (dir.Length != 0) st.Push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). Stack<String> st1 = new Stack<String>(); while (st.Count!=0) { st1.Push(st.Pop()); // st.pop(); } // the st1 will contain the actual res. while (st1.Count!=0) { // if it's the last element no need // to append "/" if (st1.Count!= 1) res += (st1.Pop() + "/"); else res += st1.Pop(); // st1.pop(); } return res; }} // This code is contributed by Rajput-Ji
<script> // Javascript program to simplify a Unix // styled absolute path of a file // function to simplify a Unix - styled // absolute path function simplify(A) { // Stack to store the file's names. let st = []; // temporary String which stores the extracted // directory name or commands("." / "..") // Eg. "/a/b/../." // contains resultant simplifies String. let res = ""; // every String starts from root directory. res += "/"; // stores length of input String. let len_A = A.length; for (let i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain "a", "b", "..", "."; let dir = ""; // skip all the multiple '/' Eg. "/////"" while (i < len_A && A[i] == '/') i++; // stores directory's name("a", "b" etc.) // or commands("."/"..") into dir while (i < len_A && A[i] != '/') { dir += A[i]; i++; } // if dir has ".." just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir == "..") { if (st.length!=0) st.pop(); } // if dir has "." then simply continue // with the process. else if (dir == ".") continue; // pushes if it encounters directory's // name("a", "b"). else if (dir.length != 0) st.push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). let st1 = []; while (st.length!=0) { st1.push(st[st.length - 1]); st.pop(); } // the st1 will contain the actual res. while (st1.length!=0) { // if it's the last element no need // to append "/" if (st1.length!= 1) { res += (st1[st1.length - 1] + "/"); st.pop(); } else { res += st1[st1.length - 1]; st1.pop(); } } return res; } // absolute path which we have to simplify. let str = ("/a/./b/../../c/"); let res = simplify(str); document.write(res); // This code is contributed by divyesh072019.</script>
/c
Time Complexity O(length of string).
Approach 2:
In approach 1, the directories so formed, are first pushed into the stack and then the stack is reversed to form the canonical path.The only optimization here is to reduce the number of stack operations and this can be done by using vectors in place of a stack.Push and pop operations can be done in vector using push_back() and pop_back() functions respectively and the canonical path can be generated by simply traversing the vector from left to right.
In approach 1, the directories so formed, are first pushed into the stack and then the stack is reversed to form the canonical path.
The only optimization here is to reduce the number of stack operations and this can be done by using vectors in place of a stack.
Push and pop operations can be done in vector using push_back() and pop_back() functions respectively and the canonical path can be generated by simply traversing the vector from left to right.
Below is the implementation of approach 1 using vectors.
C++
Java
Python3
C#
Javascript
// C++ implementation of optimized Approach 1#include <bits/stdc++.h>using namespace std; // function to simplify a Unix - styled// absolute pathstring simplify(string path){ // using vector in place of stack vector<string> v; int n = path.length(); string ans; for (int i = 0; i < n; i++) { string dir = ""; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if ".." , we pop. if (dir == "..") { if (!v.empty()) v.pop_back(); } else if (dir == "." || dir == "") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.push_back(dir); } } // forming the ans for (auto i : v) { ans += "/" + i; } // vector is empty if (ans == "") return "/"; return ans;} // Driver Codeint main(){ // absolute path which we have to simplify. string str("/a/./b/../../c/"); string res = simplify(str); cout << res; return 0;} // This code is contributed by yashbeersingh42
// Java implementation of optimized Approach 1import java.util.*;public class Main{ // function to simplify a Unix - styled // absolute path static String simplify(String path) { // using vector in place of stack Vector<String> v = new Vector<String>(); int n = path.length(); String ans = ""; for (int i = 0; i < n; i++) { String dir = ""; // forming the current directory. while (i < n && path.charAt(i) != '/') { dir += path.charAt(i); i++; } // if ".." , we pop. if (dir.equals("..")) { if (v.size() != 0) { v.remove(v.size() - 1); } } else if (dir.equals(".") || dir.equals("")) { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.add(dir); } } // forming the ans for(String i : v) { ans += "/" + i; } // vector is empty if (ans == "") return "/"; return ans; } public static void main(String[] args) { // absolute path which we have to simplify. String str = "/a/./b/../../c/"; String res = simplify(str); System.out.print(res); }} // This code is contributed by decode2207.
# Python3 implementation of optimized Approach 1 # function to simplify a Unix - styled# absolute pathdef simplify(path): # using vector in place of stack v = [] n = len(path) ans = "" for i in range(n): Dir = "" # forming the current directory. while (i < n and path[i] != '/'): Dir += path[i] i+=1 # if ".." , we pop. if (Dir == "..") : if (len(v) > 0): v.pop() elif (Dir == "." or Dir == ""): # do nothing (added for better understanding.) continue else: # push the current directory into the vector. v.append(Dir) # forming the ans for i in v: ans += "/" + i # vector is empty if (ans == ""): return "/" return ans # absolute path which we have to simplify.Str = "/a/./b/../../c/"res = simplify(Str)print(res) # This code is contributed by rameshtravel07
// C# implementation of optimized Approach 1using System;using System.Collections.Generic;class GFG { // function to simplify a Unix - styled // absolute path static string simplify(string path) { // using vector in place of stack List<string> v = new List<string>(); int n = path.Length; string ans = ""; for (int i = 0; i < n; i++) { string dir = ""; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if ".." , we pop. if (dir == "..") { if (v.Count != 0) v.RemoveAt(v.Count - 1); } else if (dir == "." || dir == "") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.Add(dir); } } // forming the ans foreach(string i in v) { ans += "/" + i; } // vector is empty if (ans == "") return "/"; return ans; } static void Main() { // absolute path which we have to simplify. string str = "/a/./b/../../c/"; string res = simplify(str); Console.Write(res); }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript implementation of optimized Approach 1 // function to simplify a Unix - styled // absolute path function simplify(path) { // using vector in place of stack let v = []; let n = path.length; let ans = ""; for (let i = 0; i < n; i++) { let dir = ""; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if ".." , we pop. if (dir == "..") { if (v.length > 0) v.pop(); } else if (dir == "." || dir == "") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.push(dir); } } // forming the ans for(let i of v) { ans += "/" + i; } // vector is empty if (ans == "") return "/"; return ans; } // absolute path which we have to simplify. let Str = "/a/./b/../../c/"; let res = simplify(Str); document.write(res); // This code is contributed by mukesh07.</script>
/c
Time Complexity: O(length of string).
This article is contributed by arshpreet soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
ankush_953
Rajput-Ji
preethisun
yashbeersingh42
clintra
rameshtravel07
mukesh07
divyeshrabadiya07
divyesh072019
decode2207
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Real-time application of Data Structures
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 277,
"s": 54,
"text": "Given an absolute path for a file (Unix-style), simplify it. Note that absolute path always begin with ‘/’ ( root directory ), a dot in path represent current directory and double dot represents parent directory.Examples: "
},
{
"code": null,
"e": 800,
"s": 277,
"text": "\"/a/./\" --> means stay at the current directory 'a'\n\"/a/b/..\" --> means jump to the parent directory\n from 'b' to 'a'\n\"////\" --> consecutive multiple '/' are a valid \n path, they are equivalent to single \"/\".\n\nInput : /home/\nOutput : /home\n\nInput : /a/./b/../../c/\nOutput : /c\n\nInput : /a/..\nOutput:/\n\nInput : /a/../\nOutput : /\n\nInput : /../../../../../a\nOutput : /a\n\nInput : /a/./b/./c/./d/\nOutput : /a/b/c/d\n\nInput : /a/../.././../../.\nOutput:/\n\nInput : /a//b//c//////d\nOutput : /a/b/c/d"
},
{
"code": null,
"e": 862,
"s": 800,
"text": "Note: The given input will always have a valid absolute path."
},
{
"code": null,
"e": 1531,
"s": 862,
"text": "Approach 1:By looking at examples we can see that the above simplification process just behaves like a stack. Whenever we encounter any file’s name, we simply push it into the stack. when we come across ” . ” we do nothing. When we find “..” in our path, we simply pop the topmost element as we have to jump back to parent’s directory. When we see multiple “////” we just ignore them as they are equivalent to one single “/”. After iterating through the whole string the elements remaining in the stack is our simplified absolute path. We have to create another stack to reverse the elements stored inside the original stack and then store the result inside a string. "
},
{
"code": null,
"e": 1535,
"s": 1531,
"text": "C++"
},
{
"code": null,
"e": 1540,
"s": 1535,
"text": "Java"
},
{
"code": null,
"e": 1548,
"s": 1540,
"text": "Python3"
},
{
"code": null,
"e": 1551,
"s": 1548,
"text": "C#"
},
{
"code": null,
"e": 1562,
"s": 1551,
"text": "Javascript"
},
{
"code": "/* C++ program to simplify a Unix styled absolute path of a file */#include <bits/stdc++.h>using namespace std; // function to simplify a Unix - styled// absolute pathstring simplify(string A){ // stack to store the file's names. stack<string> st; // temporary string which stores the extracted // directory name or commands(\".\" / \"..\") // Eg. \"/a/b/../.\" // dir will contain \"a\", \"b\", \"..\", \".\"; string dir; // contains resultant simplifies string. string res; // every string starts from root directory. res.append(\"/\"); // stores length of input string. int len_A = A.length(); for (int i = 0; i < len_A; i++) { // we will clear the temporary string // every time to accommodate new directory // name or command. dir.clear(); // skip all the multiple '/' Eg. \"/////\"\" while (A[i] == '/') i++; // stores directory's name(\"a\", \"b\" etc.) // or commands(\".\"/\"..\") into dir while (i < len_A && A[i] != '/') { dir.push_back(A[i]); i++; } // if dir has \"..\" just pop the topmost // element if the stack is not empty // otherwise ignore. if (dir.compare(\"..\") == 0) { if (!st.empty()) st.pop(); } // if dir has \".\" then simply continue // with the process. else if (dir.compare(\".\") == 0) continue; // pushes if it encounters directory's // name(\"a\", \"b\"). else if (dir.length() != 0) st.push(dir); } // a temporary stack (st1) which will contain // the reverse of original stack(st). stack<string> st1; while (!st.empty()) { st1.push(st.top()); st.pop(); } // the st1 will contain the actual res. while (!st1.empty()) { string temp = st1.top(); // if it's the last element no need // to append \"/\" if (st1.size() != 1) res.append(temp + \"/\"); else res.append(temp); st1.pop(); } return res;} // Driver code.int main(){ // absolute path which we have to simplify. string str(\"/a/./b/../../c/\"); string res = simplify(str); cout << res; return 0;}",
"e": 3850,
"s": 1562,
"text": null
},
{
"code": "/* Java program to simplify a Unixstyled absolute path of a file */import java.io.*;import java.util.*; class GFG{ public static void main(String []args) { // absolute path which we have to simplify. String str = new String(\"/a/./b/../../c/\"); String res = simplify(str); System.out.println(res); } // function to simplify a Unix - styled // absolute path static String simplify(String A) { // Stack to store the file's names. Stack<String> st = new Stack<String>(); // temporary String which stores the extracted // directory name or commands(\".\" / \"..\") // Eg. \"/a/b/../.\" // contains resultant simplifies String. String res = \"\"; // every String starts from root directory. res += \"/\"; // stores length of input String. int len_A = A.length(); for (int i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain \"a\", \"b\", \"..\", \".\"; String dir = \"\"; // skip all the multiple '/' Eg. \"/////\"\" while (i < len_A && A.charAt(i) == '/') i++; // stores directory's name(\"a\", \"b\" etc.) // or commands(\".\"/\"..\") into dir while (i < len_A && A.charAt(i) != '/') { dir += A.charAt(i); i++; } // if dir has \"..\" just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir.equals(\"..\") == true) { if (!st.empty()) st.pop(); } // if dir has \".\" then simply continue // with the process. else if (dir.equals(\".\") == true) continue; // pushes if it encounters directory's // name(\"a\", \"b\"). else if (dir.length() != 0) st.push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). Stack<String> st1 = new Stack<String>(); while (!st.empty()) { st1.push(st.pop()); // st.pop(); } // the st1 will contain the actual res. while (!st1.empty()) { // if it's the last element no need // to append \"/\" if (st1.size() != 1) res += (st1.pop() + \"/\"); else res += st1.pop(); // st1.pop(); } return res; } } // This code is contributed by ankush_953",
"e": 6610,
"s": 3850,
"text": null
},
{
"code": "# Python program to simplify a Unix# styled absolute path of a file # function to simplify a Unix - styled# absolute path def simplify(A): # stack to store the file's names. st = [] # temporary string which stores the extracted # directory name or commands(\".\" / \"..\") # Eg. \"/a/b/../.\" # dir will contain \"a\", \"b\", \"..\", \".\"; dir = \"\" # contains resultant simplifies string. res = \"\" # every string starts from root directory. res += \"/\" # stores length of input string. len_A = len(A) i = 0 while i < len_A: # we will clear the temporary string # every time to accommodate new directory # name or command. dir_str = \"\" # skip all the multiple '/' Eg. \"##/\"\" while (i < len_A and A[i] == '/'): i += 1 # stores directory's name(\"a\", \"b\" etc.) # or commands(\".\"/\"..\") into dir while (i < len_A and A[i] != '/'): dir_str += A[i] i += 1 # if dir has \"..\" just pop the topmost # element if the stack is not empty # otherwise ignore. if dir_str == \"..\": if len(st): st.pop() # if dir has \".\" then simply continue # with the process. elif dir_str == '.': continue # pushes if it encounters directory's # name(\"a\", \"b\"). elif len(dir_str) > 0: st.append(dir_str) i += 1 # a temporary stack (st1) which will contain # the reverse of original stack(st). st1 = [] while len(st): st1.append(st[-1]) st.pop() # the st1 will contain the actual res. while len(st1): temp = st1[-1] # if it's the last element no need # to append \"/\" if (len(st1) != 1): res += (temp + \"/\") else: res += temp st1.pop() return res # Driver code. # absolute path which we have to simplify.string = \"/a/./b/../../c/\"res = simplify(string)print(res) # This code is contributed by ankush_953",
"e": 8646,
"s": 6610,
"text": null
},
{
"code": "// C# program to simplify a Unix// styled absolute path of a fileusing System;using System.Collections.Generic; class GFG{ public static void Main(String []args) { // absolute path which we have to simplify. String str = (\"/a/./b/../../c/\"); String res = simplify(str); Console.WriteLine(res); } // function to simplify a Unix - styled // absolute path static String simplify(String A) { // Stack to store the file's names. Stack<String> st = new Stack<String>(); // temporary String which stores the extracted // directory name or commands(\".\" / \"..\") // Eg. \"/a/b/../.\" // contains resultant simplifies String. String res = \"\"; // every String starts from root directory. res += \"/\"; // stores length of input String. int len_A = A.Length; for (int i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain \"a\", \"b\", \"..\", \".\"; String dir = \"\"; // skip all the multiple '/' Eg. \"/////\"\" while (i < len_A && A[i] == '/') i++; // stores directory's name(\"a\", \"b\" etc.) // or commands(\".\"/\"..\") into dir while (i < len_A && A[i] != '/') { dir += A[i]; i++; } // if dir has \"..\" just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir.Equals(\"..\") == true) { if (st.Count!=0) st.Pop(); } // if dir has \".\" then simply continue // with the process. else if (dir.Equals(\".\") == true) continue; // pushes if it encounters directory's // name(\"a\", \"b\"). else if (dir.Length != 0) st.Push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). Stack<String> st1 = new Stack<String>(); while (st.Count!=0) { st1.Push(st.Pop()); // st.pop(); } // the st1 will contain the actual res. while (st1.Count!=0) { // if it's the last element no need // to append \"/\" if (st1.Count!= 1) res += (st1.Pop() + \"/\"); else res += st1.Pop(); // st1.pop(); } return res; }} // This code is contributed by Rajput-Ji",
"e": 11374,
"s": 8646,
"text": null
},
{
"code": "<script> // Javascript program to simplify a Unix // styled absolute path of a file // function to simplify a Unix - styled // absolute path function simplify(A) { // Stack to store the file's names. let st = []; // temporary String which stores the extracted // directory name or commands(\".\" / \"..\") // Eg. \"/a/b/../.\" // contains resultant simplifies String. let res = \"\"; // every String starts from root directory. res += \"/\"; // stores length of input String. let len_A = A.length; for (let i = 0; i < len_A; i++) { // we will clear the temporary String // every time to accommodate new directory // name or command. // dir will contain \"a\", \"b\", \"..\", \".\"; let dir = \"\"; // skip all the multiple '/' Eg. \"/////\"\" while (i < len_A && A[i] == '/') i++; // stores directory's name(\"a\", \"b\" etc.) // or commands(\".\"/\"..\") into dir while (i < len_A && A[i] != '/') { dir += A[i]; i++; } // if dir has \"..\" just pop the topmost // element if the Stack is not empty // otherwise ignore. if (dir == \"..\") { if (st.length!=0) st.pop(); } // if dir has \".\" then simply continue // with the process. else if (dir == \".\") continue; // pushes if it encounters directory's // name(\"a\", \"b\"). else if (dir.length != 0) st.push(dir); } // a temporary Stack (st1) which will contain // the reverse of original Stack(st). let st1 = []; while (st.length!=0) { st1.push(st[st.length - 1]); st.pop(); } // the st1 will contain the actual res. while (st1.length!=0) { // if it's the last element no need // to append \"/\" if (st1.length!= 1) { res += (st1[st1.length - 1] + \"/\"); st.pop(); } else { res += st1[st1.length - 1]; st1.pop(); } } return res; } // absolute path which we have to simplify. let str = (\"/a/./b/../../c/\"); let res = simplify(str); document.write(res); // This code is contributed by divyesh072019.</script>",
"e": 14046,
"s": 11374,
"text": null
},
{
"code": null,
"e": 14049,
"s": 14046,
"text": "/c"
},
{
"code": null,
"e": 14086,
"s": 14049,
"text": "Time Complexity O(length of string)."
},
{
"code": null,
"e": 14098,
"s": 14086,
"text": "Approach 2:"
},
{
"code": null,
"e": 14553,
"s": 14098,
"text": "In approach 1, the directories so formed, are first pushed into the stack and then the stack is reversed to form the canonical path.The only optimization here is to reduce the number of stack operations and this can be done by using vectors in place of a stack.Push and pop operations can be done in vector using push_back() and pop_back() functions respectively and the canonical path can be generated by simply traversing the vector from left to right."
},
{
"code": null,
"e": 14686,
"s": 14553,
"text": "In approach 1, the directories so formed, are first pushed into the stack and then the stack is reversed to form the canonical path."
},
{
"code": null,
"e": 14816,
"s": 14686,
"text": "The only optimization here is to reduce the number of stack operations and this can be done by using vectors in place of a stack."
},
{
"code": null,
"e": 15010,
"s": 14816,
"text": "Push and pop operations can be done in vector using push_back() and pop_back() functions respectively and the canonical path can be generated by simply traversing the vector from left to right."
},
{
"code": null,
"e": 15067,
"s": 15010,
"text": "Below is the implementation of approach 1 using vectors."
},
{
"code": null,
"e": 15071,
"s": 15067,
"text": "C++"
},
{
"code": null,
"e": 15076,
"s": 15071,
"text": "Java"
},
{
"code": null,
"e": 15084,
"s": 15076,
"text": "Python3"
},
{
"code": null,
"e": 15087,
"s": 15084,
"text": "C#"
},
{
"code": null,
"e": 15098,
"s": 15087,
"text": "Javascript"
},
{
"code": "// C++ implementation of optimized Approach 1#include <bits/stdc++.h>using namespace std; // function to simplify a Unix - styled// absolute pathstring simplify(string path){ // using vector in place of stack vector<string> v; int n = path.length(); string ans; for (int i = 0; i < n; i++) { string dir = \"\"; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if \"..\" , we pop. if (dir == \"..\") { if (!v.empty()) v.pop_back(); } else if (dir == \".\" || dir == \"\") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.push_back(dir); } } // forming the ans for (auto i : v) { ans += \"/\" + i; } // vector is empty if (ans == \"\") return \"/\"; return ans;} // Driver Codeint main(){ // absolute path which we have to simplify. string str(\"/a/./b/../../c/\"); string res = simplify(str); cout << res; return 0;} // This code is contributed by yashbeersingh42",
"e": 16274,
"s": 15098,
"text": null
},
{
"code": "// Java implementation of optimized Approach 1import java.util.*;public class Main{ // function to simplify a Unix - styled // absolute path static String simplify(String path) { // using vector in place of stack Vector<String> v = new Vector<String>(); int n = path.length(); String ans = \"\"; for (int i = 0; i < n; i++) { String dir = \"\"; // forming the current directory. while (i < n && path.charAt(i) != '/') { dir += path.charAt(i); i++; } // if \"..\" , we pop. if (dir.equals(\"..\")) { if (v.size() != 0) { v.remove(v.size() - 1); } } else if (dir.equals(\".\") || dir.equals(\"\")) { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.add(dir); } } // forming the ans for(String i : v) { ans += \"/\" + i; } // vector is empty if (ans == \"\") return \"/\"; return ans; } public static void main(String[] args) { // absolute path which we have to simplify. String str = \"/a/./b/../../c/\"; String res = simplify(str); System.out.print(res); }} // This code is contributed by decode2207.",
"e": 17779,
"s": 16274,
"text": null
},
{
"code": "# Python3 implementation of optimized Approach 1 # function to simplify a Unix - styled# absolute pathdef simplify(path): # using vector in place of stack v = [] n = len(path) ans = \"\" for i in range(n): Dir = \"\" # forming the current directory. while (i < n and path[i] != '/'): Dir += path[i] i+=1 # if \"..\" , we pop. if (Dir == \"..\") : if (len(v) > 0): v.pop() elif (Dir == \".\" or Dir == \"\"): # do nothing (added for better understanding.) continue else: # push the current directory into the vector. v.append(Dir) # forming the ans for i in v: ans += \"/\" + i # vector is empty if (ans == \"\"): return \"/\" return ans # absolute path which we have to simplify.Str = \"/a/./b/../../c/\"res = simplify(Str)print(res) # This code is contributed by rameshtravel07",
"e": 18743,
"s": 17779,
"text": null
},
{
"code": "// C# implementation of optimized Approach 1using System;using System.Collections.Generic;class GFG { // function to simplify a Unix - styled // absolute path static string simplify(string path) { // using vector in place of stack List<string> v = new List<string>(); int n = path.Length; string ans = \"\"; for (int i = 0; i < n; i++) { string dir = \"\"; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if \"..\" , we pop. if (dir == \"..\") { if (v.Count != 0) v.RemoveAt(v.Count - 1); } else if (dir == \".\" || dir == \"\") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.Add(dir); } } // forming the ans foreach(string i in v) { ans += \"/\" + i; } // vector is empty if (ans == \"\") return \"/\"; return ans; } static void Main() { // absolute path which we have to simplify. string str = \"/a/./b/../../c/\"; string res = simplify(str); Console.Write(res); }} // This code is contributed by divyeshrabadiya07.",
"e": 20167,
"s": 18743,
"text": null
},
{
"code": "<script> // Javascript implementation of optimized Approach 1 // function to simplify a Unix - styled // absolute path function simplify(path) { // using vector in place of stack let v = []; let n = path.length; let ans = \"\"; for (let i = 0; i < n; i++) { let dir = \"\"; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if \"..\" , we pop. if (dir == \"..\") { if (v.length > 0) v.pop(); } else if (dir == \".\" || dir == \"\") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.push(dir); } } // forming the ans for(let i of v) { ans += \"/\" + i; } // vector is empty if (ans == \"\") return \"/\"; return ans; } // absolute path which we have to simplify. let Str = \"/a/./b/../../c/\"; let res = simplify(Str); document.write(res); // This code is contributed by mukesh07.</script>",
"e": 21431,
"s": 20167,
"text": null
},
{
"code": null,
"e": 21434,
"s": 21431,
"text": "/c"
},
{
"code": null,
"e": 21476,
"s": 21434,
"text": " Time Complexity: O(length of string)."
},
{
"code": null,
"e": 21900,
"s": 21476,
"text": "This article is contributed by arshpreet soodan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 21913,
"s": 21900,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 21924,
"s": 21913,
"text": "ankush_953"
},
{
"code": null,
"e": 21934,
"s": 21924,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 21945,
"s": 21934,
"text": "preethisun"
},
{
"code": null,
"e": 21961,
"s": 21945,
"text": "yashbeersingh42"
},
{
"code": null,
"e": 21969,
"s": 21961,
"text": "clintra"
},
{
"code": null,
"e": 21984,
"s": 21969,
"text": "rameshtravel07"
},
{
"code": null,
"e": 21993,
"s": 21984,
"text": "mukesh07"
},
{
"code": null,
"e": 22011,
"s": 21993,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 22025,
"s": 22011,
"text": "divyesh072019"
},
{
"code": null,
"e": 22036,
"s": 22025,
"text": "decode2207"
},
{
"code": null,
"e": 22042,
"s": 22036,
"text": "Stack"
},
{
"code": null,
"e": 22050,
"s": 22042,
"text": "Strings"
},
{
"code": null,
"e": 22058,
"s": 22050,
"text": "Strings"
},
{
"code": null,
"e": 22064,
"s": 22058,
"text": "Stack"
},
{
"code": null,
"e": 22162,
"s": 22064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22194,
"s": 22162,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 22258,
"s": 22194,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 22307,
"s": 22258,
"text": "Design a stack with operations on middle element"
},
{
"code": null,
"e": 22364,
"s": 22307,
"text": "How to efficiently implement k stacks in a single array?"
},
{
"code": null,
"e": 22405,
"s": 22364,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 22451,
"s": 22405,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 22476,
"s": 22451,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 22536,
"s": 22476,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 22551,
"s": 22536,
"text": "C++ Data Types"
}
] |
Making a Port-Scanner in Kali Linux Terminal Using Python
|
17 Dec, 2021
In computer networking, a port is a virtual point where network connections start and end. It’s like an open door of your home, If you don’t close this then anyone can Enter your home. A port scanner is a program that is searching ports in a network and tries to find which ports are virtually open and close. It is common technique hackers or cyber-security experts used to discover open doors or weak points in a network.
This program sends a network request throw network and tries to connect to a specific TCP or UDP port on a computer and records the response.
The three types of responses are below:
Open, Accepted: When ports are open, and you can access this system by them.Closed, Not Listening: When this port is in use or unavailable at this timeFiltered, Dropped, Blocked: The computer doesn’t even bother to respond.
Open, Accepted: When ports are open, and you can access this system by them.
Closed, Not Listening: When this port is in use or unavailable at this time
Filtered, Dropped, Blocked: The computer doesn’t even bother to respond.
Step 1: Design a Program
At the very first we need to open Our Kali Linux terminal and the very first thing that we should do is find out where our python interpreter is so we command
Syntax:
which python
where is our python interpreter
That’s going to be important when we do this very next step.
Next step we need to open the shell because in there we are going to type our code, so we can type nano command and hit enter.
Syntax:
nano (name).extension
Example:
nano port-scanner.py
give our program a name
Now In here at first we need to assign our Python interpreter Location
#!//usr/bin/python
location of Python interpreter
Now our main program start, we want to import sockets, sockets will tell us the ports how to operate and essentially how to transmit data.
import socket
Then we need to input IP addresses and after that, we also need a program to ask for which port we are looking for
ip = raw_input("enter the IP Address: ")
port = input("Enter the Port Number: ")
Now we want to Define the socket what type of transmitted data are we are looking for to be more specific what Protocol are we asking for to see.
socket.AF_INET this socket allows us to see TCP connection
SOCK_STREAM this allows us to look at UDP protocol that’s essentially streaming video and audio
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
Now we are going to print how our program shows us if the specific port open or either IP is down or The port is closed.
if sock.connect_ex((ip,port)):
print "Port ",port, "is closed"
else:
print"Port",port,"is OPEN"
full program
Now save this program press control key + x key to save this program
Syntax:
cnrl+x
Step 2: Compile and Run The program
We all Know How to Run a Script on the Kali Linux terminal
Example
./script name . extension
Syntax
./port-scanner.py
Program Didn’t Run
Look here is the tricky part, We write Our program Perfectly, but it’s Not compiled and Run. So It’s time to give our System Permission.
Chmod 775 is a Linux command which sets permission so that User/Owner can Read, Write and execute. Group can Read Write and execute. Others can Read But can’t Write and execute.
Syntax
chmod 775 ./port-scanner.py
chmod 775 gives you permission
Now we can Run Our program again, and it will compile and Run Successfully
Syntax
./port-scanner.py
Run successfully
So for port scanning, We need a specific IP, and we need to Tell Our Program which port we are Looking For after Input Hit Enter
Example
Enter Your Ip Address : 192.168.43.1
Enter The Port Number : 80
Port scanning Successfully
anikaseth98
simmytarika5
arorakashish0911
Kali-Linux
Linux-Unix
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 Dec, 2021"
},
{
"code": null,
"e": 479,
"s": 54,
"text": "In computer networking, a port is a virtual point where network connections start and end. It’s like an open door of your home, If you don’t close this then anyone can Enter your home. A port scanner is a program that is searching ports in a network and tries to find which ports are virtually open and close. It is common technique hackers or cyber-security experts used to discover open doors or weak points in a network. "
},
{
"code": null,
"e": 621,
"s": 479,
"text": "This program sends a network request throw network and tries to connect to a specific TCP or UDP port on a computer and records the response."
},
{
"code": null,
"e": 661,
"s": 621,
"text": "The three types of responses are below:"
},
{
"code": null,
"e": 885,
"s": 661,
"text": "Open, Accepted: When ports are open, and you can access this system by them.Closed, Not Listening: When this port is in use or unavailable at this timeFiltered, Dropped, Blocked: The computer doesn’t even bother to respond."
},
{
"code": null,
"e": 962,
"s": 885,
"text": "Open, Accepted: When ports are open, and you can access this system by them."
},
{
"code": null,
"e": 1038,
"s": 962,
"text": "Closed, Not Listening: When this port is in use or unavailable at this time"
},
{
"code": null,
"e": 1111,
"s": 1038,
"text": "Filtered, Dropped, Blocked: The computer doesn’t even bother to respond."
},
{
"code": null,
"e": 1137,
"s": 1111,
"text": "Step 1: Design a Program "
},
{
"code": null,
"e": 1296,
"s": 1137,
"text": "At the very first we need to open Our Kali Linux terminal and the very first thing that we should do is find out where our python interpreter is so we command"
},
{
"code": null,
"e": 1304,
"s": 1296,
"text": "Syntax:"
},
{
"code": null,
"e": 1317,
"s": 1304,
"text": "which python"
},
{
"code": null,
"e": 1349,
"s": 1317,
"text": "where is our python interpreter"
},
{
"code": null,
"e": 1411,
"s": 1349,
"text": "That’s going to be important when we do this very next step. "
},
{
"code": null,
"e": 1538,
"s": 1411,
"text": "Next step we need to open the shell because in there we are going to type our code, so we can type nano command and hit enter."
},
{
"code": null,
"e": 1547,
"s": 1538,
"text": "Syntax: "
},
{
"code": null,
"e": 1569,
"s": 1547,
"text": "nano (name).extension"
},
{
"code": null,
"e": 1579,
"s": 1569,
"text": "Example: "
},
{
"code": null,
"e": 1600,
"s": 1579,
"text": "nano port-scanner.py"
},
{
"code": null,
"e": 1625,
"s": 1600,
"text": "give our program a name "
},
{
"code": null,
"e": 1696,
"s": 1625,
"text": "Now In here at first we need to assign our Python interpreter Location"
},
{
"code": null,
"e": 1715,
"s": 1696,
"text": "#!//usr/bin/python"
},
{
"code": null,
"e": 1747,
"s": 1715,
"text": "location of Python interpreter "
},
{
"code": null,
"e": 1886,
"s": 1747,
"text": "Now our main program start, we want to import sockets, sockets will tell us the ports how to operate and essentially how to transmit data."
},
{
"code": null,
"e": 1900,
"s": 1886,
"text": "import socket"
},
{
"code": null,
"e": 2016,
"s": 1900,
"text": "Then we need to input IP addresses and after that, we also need a program to ask for which port we are looking for"
},
{
"code": null,
"e": 2097,
"s": 2016,
"text": "ip = raw_input(\"enter the IP Address: \")\nport = input(\"Enter the Port Number: \")"
},
{
"code": null,
"e": 2243,
"s": 2097,
"text": "Now we want to Define the socket what type of transmitted data are we are looking for to be more specific what Protocol are we asking for to see."
},
{
"code": null,
"e": 2302,
"s": 2243,
"text": "socket.AF_INET this socket allows us to see TCP connection"
},
{
"code": null,
"e": 2400,
"s": 2302,
"text": "SOCK_STREAM this allows us to look at UDP protocol that’s essentially streaming video and audio"
},
{
"code": null,
"e": 2456,
"s": 2400,
"text": "sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)"
},
{
"code": null,
"e": 2577,
"s": 2456,
"text": "Now we are going to print how our program shows us if the specific port open or either IP is down or The port is closed."
},
{
"code": null,
"e": 2689,
"s": 2577,
"text": "if sock.connect_ex((ip,port)):\n print \"Port \",port, \"is closed\"\nelse:\n print\"Port\",port,\"is OPEN\""
},
{
"code": null,
"e": 2703,
"s": 2689,
"text": "full program "
},
{
"code": null,
"e": 2772,
"s": 2703,
"text": "Now save this program press control key + x key to save this program"
},
{
"code": null,
"e": 2781,
"s": 2772,
"text": "Syntax: "
},
{
"code": null,
"e": 2788,
"s": 2781,
"text": "cnrl+x"
},
{
"code": null,
"e": 2825,
"s": 2788,
"text": "Step 2: Compile and Run The program "
},
{
"code": null,
"e": 2885,
"s": 2825,
"text": "We all Know How to Run a Script on the Kali Linux terminal "
},
{
"code": null,
"e": 2894,
"s": 2885,
"text": "Example "
},
{
"code": null,
"e": 2920,
"s": 2894,
"text": "./script name . extension"
},
{
"code": null,
"e": 2927,
"s": 2920,
"text": "Syntax"
},
{
"code": null,
"e": 2945,
"s": 2927,
"text": "./port-scanner.py"
},
{
"code": null,
"e": 2965,
"s": 2945,
"text": "Program Didn’t Run "
},
{
"code": null,
"e": 3103,
"s": 2965,
"text": "Look here is the tricky part, We write Our program Perfectly, but it’s Not compiled and Run. So It’s time to give our System Permission. "
},
{
"code": null,
"e": 3286,
"s": 3103,
"text": "Chmod 775 is a Linux command which sets permission so that User/Owner can Read, Write and execute. Group can Read Write and execute. Others can Read But can’t Write and execute. "
},
{
"code": null,
"e": 3293,
"s": 3286,
"text": "Syntax"
},
{
"code": null,
"e": 3321,
"s": 3293,
"text": "chmod 775 ./port-scanner.py"
},
{
"code": null,
"e": 3353,
"s": 3321,
"text": "chmod 775 gives you permission "
},
{
"code": null,
"e": 3429,
"s": 3353,
"text": "Now we can Run Our program again, and it will compile and Run Successfully "
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "Syntax "
},
{
"code": null,
"e": 3455,
"s": 3437,
"text": "./port-scanner.py"
},
{
"code": null,
"e": 3473,
"s": 3455,
"text": "Run successfully "
},
{
"code": null,
"e": 3604,
"s": 3473,
"text": "So for port scanning, We need a specific IP, and we need to Tell Our Program which port we are Looking For after Input Hit Enter "
},
{
"code": null,
"e": 3613,
"s": 3604,
"text": "Example "
},
{
"code": null,
"e": 3677,
"s": 3613,
"text": "Enter Your Ip Address : 192.168.43.1\nEnter The Port Number : 80"
},
{
"code": null,
"e": 3705,
"s": 3677,
"text": "Port scanning Successfully "
},
{
"code": null,
"e": 3717,
"s": 3705,
"text": "anikaseth98"
},
{
"code": null,
"e": 3730,
"s": 3717,
"text": "simmytarika5"
},
{
"code": null,
"e": 3747,
"s": 3730,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3758,
"s": 3747,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3769,
"s": 3758,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3776,
"s": 3769,
"text": "Python"
}
] |
How to add/update an attribute to an HTML element using JavaScript?
|
01 Sep, 2021
We can use two approaches to modify an attribute of an HTML element using JavaScript.Approach 1: We can use the inbuilt setAttribute() function of JavaScript.Syntax:
var elementVar = document.getElementById("element_id");
elementVar.setAttribute("attribute", "value");
So what basically we are doing is initializing the element in JavaScript by getting its id and then using setAttribute() to modify its attribute.Example: Below is the implementation of above approach.
html
<!DOCTYPE html><html> <head> <title>Modify attributes method 1</title> <script> function modify() { //update style attribute of element "heading" var heading = document.getElementById("heading"); heading.setAttribute("style", "color:green"); //add style attribute to element "tagLine" var tagLine = document.getElementById("tagLine"); tagLine.setAttribute("style", "color:blue"); } </script></head> <body> <h1 style="color:black" id="heading" align="center"> GeeksForGeeks </h1> <p id="tagLine" align="center"> - Society Of Geeks <br> <br> <button onclick="modify()"> Click to modify </button> </p> </body> </html>
Output:
Before clicking the button:
After clicking the button:
We can modify HTML attributes even without using setAttribute() function as follows :
document.getElementById("element_id").attribute = attribute_value;
Example: Below is the implementation of above approach:
html
<!DOCTYPE html><html> <head> <title>Modify attributes method 2</title> <script> function add() { //get the values of fNum and sNum using getAttribute() var fNum = Number(document.getElementById("fNum").value); var sNum = Number(document.getElementById("sNum").value); var result = fNum + sNum; //output the result in green colour var output = "Sum of two numbers is " + result; document.getElementById("result").style = "color:green"; document.getElementById("result").innerHTML = output; /*note the way we have updated innerHTML and added style attribute of "result" element */ } </script></head> <body> <h1 style="color:green" align="center">GeeksForGeeks</h1> <p align="center"> <b>Enter first number :- </b> <input type="number" id="fNum"> <br> <br> <b>Enter second number :- </b> <input type="number" id="sNum"> <br> <br> <button onclick="add()">Add</button> <b><p id="result" align="center"></p></b> </p> </body> </html>
Output:
Before clicking the button:
After clicking the button:
clintra
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "We can use two approaches to modify an attribute of an HTML element using JavaScript.Approach 1: We can use the inbuilt setAttribute() function of JavaScript.Syntax: "
},
{
"code": null,
"e": 299,
"s": 196,
"text": "var elementVar = document.getElementById(\"element_id\");\nelementVar.setAttribute(\"attribute\", \"value\");"
},
{
"code": null,
"e": 502,
"s": 299,
"text": "So what basically we are doing is initializing the element in JavaScript by getting its id and then using setAttribute() to modify its attribute.Example: Below is the implementation of above approach. "
},
{
"code": null,
"e": 507,
"s": 502,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Modify attributes method 1</title> <script> function modify() { //update style attribute of element \"heading\" var heading = document.getElementById(\"heading\"); heading.setAttribute(\"style\", \"color:green\"); //add style attribute to element \"tagLine\" var tagLine = document.getElementById(\"tagLine\"); tagLine.setAttribute(\"style\", \"color:blue\"); } </script></head> <body> <h1 style=\"color:black\" id=\"heading\" align=\"center\"> GeeksForGeeks </h1> <p id=\"tagLine\" align=\"center\"> - Society Of Geeks <br> <br> <button onclick=\"modify()\"> Click to modify </button> </p> </body> </html>",
"e": 1267,
"s": 507,
"text": null
},
{
"code": null,
"e": 1277,
"s": 1267,
"text": "Output: "
},
{
"code": null,
"e": 1307,
"s": 1277,
"text": "Before clicking the button: "
},
{
"code": null,
"e": 1336,
"s": 1307,
"text": "After clicking the button: "
},
{
"code": null,
"e": 1426,
"s": 1338,
"text": "We can modify HTML attributes even without using setAttribute() function as follows : "
},
{
"code": null,
"e": 1493,
"s": 1426,
"text": "document.getElementById(\"element_id\").attribute = attribute_value;"
},
{
"code": null,
"e": 1551,
"s": 1493,
"text": "Example: Below is the implementation of above approach: "
},
{
"code": null,
"e": 1556,
"s": 1551,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Modify attributes method 2</title> <script> function add() { //get the values of fNum and sNum using getAttribute() var fNum = Number(document.getElementById(\"fNum\").value); var sNum = Number(document.getElementById(\"sNum\").value); var result = fNum + sNum; //output the result in green colour var output = \"Sum of two numbers is \" + result; document.getElementById(\"result\").style = \"color:green\"; document.getElementById(\"result\").innerHTML = output; /*note the way we have updated innerHTML and added style attribute of \"result\" element */ } </script></head> <body> <h1 style=\"color:green\" align=\"center\">GeeksForGeeks</h1> <p align=\"center\"> <b>Enter first number :- </b> <input type=\"number\" id=\"fNum\"> <br> <br> <b>Enter second number :- </b> <input type=\"number\" id=\"sNum\"> <br> <br> <button onclick=\"add()\">Add</button> <b><p id=\"result\" align=\"center\"></p></b> </p> </body> </html>",
"e": 2705,
"s": 1556,
"text": null
},
{
"code": null,
"e": 2715,
"s": 2705,
"text": "Output: "
},
{
"code": null,
"e": 2745,
"s": 2715,
"text": "Before clicking the button: "
},
{
"code": null,
"e": 2774,
"s": 2745,
"text": "After clicking the button: "
},
{
"code": null,
"e": 2784,
"s": 2776,
"text": "clintra"
},
{
"code": null,
"e": 2800,
"s": 2784,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2807,
"s": 2800,
"text": "Picked"
},
{
"code": null,
"e": 2818,
"s": 2807,
"text": "JavaScript"
},
{
"code": null,
"e": 2835,
"s": 2818,
"text": "Web Technologies"
},
{
"code": null,
"e": 2862,
"s": 2835,
"text": "Web technologies Questions"
}
] |
Merging two unsorted arrays in sorted order
|
27 Jan, 2022
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.
Examples :
Input : a[] = {10, 5, 15}
b[] = {20, 3, 2}
Output : Merge List :
{2, 3, 5, 10, 15, 20}
Input : a[] = {1, 10, 5, 15}
b[] = {20, 0, 2}
Output : Merge List :
{0, 1, 2, 5, 10, 15, 20}
There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally, there’s the problem of starting the result list empty and building it up while going through ‘a’ and ‘b’.
Method 1 (first Concatenate then Sort)
In this case, we first append the two unsorted lists. Then we simply sort the concatenated list.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to merge two unsorted lists// in sorted order#include <bits/stdc++.h>using namespace std; // Function to merge array in sorted ordervoid sortedMerge(int a[], int b[], int res[], int n, int m){ // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i += 1; k += 1; } while (j < m) { res[k] = b[j]; j += 1; k += 1; } // sorting the res array sort(res, res + n + m);} // Driver codeint main(){ int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // Final merge list int res[n + m]; sortedMerge(a, b, res, n, m); cout << "Sorted merged list :"; for (int i = 0; i < n + m; i++) cout << " " << res[i]; cout << "n"; return 0;}
// Java Code for Merging two unsorted// arrays in sorted orderimport java.util.*; class GFG { // Function to merge array in sorted order public static void sortedMerge(int a[], int b[], int res[], int n, int m) { // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i++; k++; } while (j < m) { res[k] = b[j]; j++; k++; } // sorting the res array Arrays.sort(res); } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = a.length; int m = b.length; // Final merge list int res[]=new int[n + m]; sortedMerge(a, b, res, n, m); System.out.print("Sorted merged list :"); for (int i = 0; i < n + m; i++) System.out.print(" " + res[i]); }} // This code is contributed by Arnav Kr. Mandal.
# Python program to merge two unsorted lists# in sorted order # Function to merge array in sorted orderdef sortedMerge(a, b, res, n, m): # Concatenate two arrays i, j, k = 0, 0, 0 while (i < n): res[k] = a[i] i += 1 k += 1 while (j < m): res[k] = b[j] j += 1 k += 1 # sorting the res array res.sort() # Driver codea = [ 10, 5, 15 ]b = [ 20, 3, 2, 12 ]n = len(a)m = len(b) # Final merge listres = [0 for i in range(n + m)]sortedMerge(a, b, res, n, m)print ("Sorted merged list :")for i in range(n + m): print(res[i],end=" ") # This code is contributed by Sachin Bisht
// C# Code for Merging two// unsorted arrays in sorted orderusing System; class GFG { // Function to merge array in sorted order public static void sortedMerge(int []a, int []b, int []res, int n, int m) { // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i++; k++; } while (j < m) { res[k] = b[j]; j++; k++; } // sorting the res array Array.Sort(res); } /* Driver program to test above function */ public static void Main() { int []a = {10, 5, 15}; int []b = {20, 3, 2, 12}; int n = a.Length; int m = b.Length; // Final merge list int []res=new int[n + m]; sortedMerge(a, b, res, n, m); Console.Write("Sorted merged list :"); for (int i = 0; i < n + m; i++) Console.Write(" " + res[i]); }} // This code is contributed by nitin mittal.
<?php// PHP program to merge two unsorted lists// in sorted order // Function to merge array in sorted orderfunction sortedMerge($a, $b, $n, $m){ // Concatenate two arrays $res = array(); $i = 0; $j = 0; $k = 0; while ($i < $n) { $res[$k] = $a[$i]; $i += 1; $k += 1; } while ($j < $m) { $res[$k] = $b[$j]; $j += 1; $k += 1; } // sorting the res array sort($res); echo "Sorted merged list :"; for ($i = 0; $i < count($res); $i++) echo $res[$i] . " ";} // Driver code$a = array( 10, 5, 15 );$b = array( 20, 3, 2, 12 );$n = count($a);$m = count($b); // Final merge list sortedMerge($a, $b, $n, $m); // This code is contributed by Rajput-Ji.?>
<script> // Javascript program to merge two unsorted lists// in sorted order // Function to merge array in sorted orderfunction sortedMerge(a, b, res, n, m){ // Sorting a[] and b[] a.sort((a,b) => a-b); b.sort((a,b) => a-b); // Merge two sorted arrays into res[] let i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; }} // Driver code let a = [ 10, 5, 15 ]; let b = [ 20, 3, 2, 12 ]; let n = a.length; let m = b.length; // Final merge list let res = new Array(n + m); sortedMerge(a, b, res, n, m); document.write("Sorted merge list :"); for (let i = 0; i < n + m; i++) document.write(" " + res[i]); //This code is contributed by Mayank Tyagi</script>
Output:
Sorted merged list : 2 3 5 10 12 15 20
Time Complexity: O ( (n + m) (log(n + m)) ) Auxiliary Space: O ( (n + m) )
Method 2 (First Sort then Merge)
We first sort both the given arrays separately. Then we simply merge two sorted arrays.
C++
Java
Python3
C#
Javascript
// CPP program to merge two unsorted lists// in sorted order#include <bits/stdc++.h>using namespace std; // Function to merge array in sorted ordervoid sortedMerge(int a[], int b[], int res[], int n, int m){ // Sorting a[] and b[] sort(a, a + n); sort(b, b + m); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; }} // Driver codeint main(){ int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // Final merge list int res[n + m]; sortedMerge(a, b, res, n, m); cout << "Sorted merge list :"; for (int i = 0; i < n + m; i++) cout << " " << res[i]; cout << "n"; return 0;}
// JAVA Code for Merging two unsorted// arrays in sorted orderimport java.util.*; class GFG { // Function to merge array in sorted order public static void sortedMerge(int a[], int b[], int res[], int n, int m) { // Sorting a[] and b[] Arrays.sort(a); Arrays.sort(b); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; } } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = a.length; int m = b.length; // Final merge list int res[] = new int[n + m]; sortedMerge(a, b, res, n, m); System.out.print( "Sorted merged list :"); for (int i = 0; i < n + m; i++) System.out.print(" " + res[i]); }}// This code is contributed by Arnav Kr. Mandal.
# Python program to merge two unsorted lists# in sorted order # Function to merge array in sorted orderdef sortedMerge(a, b, res, n, m): # Sorting a[] and b[] a.sort() b.sort() # Merge two sorted arrays into res[] i, j, k = 0, 0, 0 while (i < n and j < m): if (a[i] <= b[j]): res[k] = a[i] i += 1 k += 1 else: res[k] = b[j] j += 1 k += 1 while (i < n): # Merging remaining # elements of a[] (if any) res[k] = a[i] i += 1 k += 1 while (j < m): # Merging remaining # elements of b[] (if any) res[k] = b[j] j += 1 k += 1 # Driver codea = [ 10, 5, 15 ]b = [ 20, 3, 2, 12 ]n = len(a)m = len(b) # Final merge listres = [0 for i in range(n + m)]sortedMerge(a, b, res, n, m)print ("Sorted merged list :")for i in range(n + m): print(res[i],end=" ") # This code is contributed by Sachin Bisht
// C# Code for Merging two unsorted// arrays in sorted orderusing System; class GFG { // Function to merge array in // sorted order static void sortedMerge(int []a, int []b, int []res, int n, int m) { // Sorting a[] and b[] Array.Sort(a); Array.Sort(b); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; } } /* Driver program to test above function */ public static void Main() { int []a = { 10, 5, 15 }; int []b = { 20, 3, 2, 12 }; int n = a.Length; int m = b.Length; // Final merge list int []res = new int[n + m]; sortedMerge(a, b, res, n, m); Console.Write( "Sorted merged list :"); for (int i = 0; i < n + m; i++) Console.Write(" " + res[i]); }} // This code is contributed by nitin mittal.
<script> // JavaScript program to merge two unsorted// lists in sorted order // Function to merge array in sorted orderfunction sortedMerge(a, b, res, n, m){ // Sorting a[] and b[] a.sort((a, b) => a - b); b.sort((a, b) => a - b); // Merge two sorted arrays into res[] let i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } // Merging remaining // elements of a[] (if any) while (i < n) { res[k] = a[i]; i += 1; k += 1; } // Merging remaining // elements of b[] (if any) while (j < m) { res[k] = b[j]; j += 1; k += 1; }} // Driver codelet a = [ 10, 5, 15 ];let b = [ 20, 3, 2, 12 ];let n = a.length;let m = b.length; // Final merge listlet res = new Array(n + m); sortedMerge(a, b, res, n, m); document.write("Sorted merge list :");for(let i = 0; i < n + m; i++) document.write(" " + res[i]); // This code is contributed by Surbhi Tyagi. </script>
Output:
Sorted merge list : 2 3 5 10 12 15 20
Time Complexity: O (nlogn + mlogm + (n + m)) Space Complexity: O ( (n + m) )
It is obvious from above time complexities that method 2 is better than method 1.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Rajput-Ji
mayanktyagi1709
surbhityagi15
amartyaghoshgfg
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Move all negative numbers to beginning and positive to end with constant extra space
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 259,
"s": 52,
"text": "Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list."
},
{
"code": null,
"e": 271,
"s": 259,
"text": "Examples : "
},
{
"code": null,
"e": 484,
"s": 271,
"text": "Input : a[] = {10, 5, 15}\n b[] = {20, 3, 2}\nOutput : Merge List :\n {2, 3, 5, 10, 15, 20}\n\nInput : a[] = {1, 10, 5, 15}\n b[] = {20, 0, 2}\nOutput : Merge List :\n {0, 1, 2, 5, 10, 15, 20}"
},
{
"code": null,
"e": 725,
"s": 484,
"text": "There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally, there’s the problem of starting the result list empty and building it up while going through ‘a’ and ‘b’."
},
{
"code": null,
"e": 764,
"s": 725,
"text": "Method 1 (first Concatenate then Sort)"
},
{
"code": null,
"e": 862,
"s": 764,
"text": "In this case, we first append the two unsorted lists. Then we simply sort the concatenated list. "
},
{
"code": null,
"e": 866,
"s": 862,
"text": "C++"
},
{
"code": null,
"e": 871,
"s": 866,
"text": "Java"
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Python3"
},
{
"code": null,
"e": 882,
"s": 879,
"text": "C#"
},
{
"code": null,
"e": 886,
"s": 882,
"text": "PHP"
},
{
"code": null,
"e": 897,
"s": 886,
"text": "Javascript"
},
{
"code": "// CPP program to merge two unsorted lists// in sorted order#include <bits/stdc++.h>using namespace std; // Function to merge array in sorted ordervoid sortedMerge(int a[], int b[], int res[], int n, int m){ // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i += 1; k += 1; } while (j < m) { res[k] = b[j]; j += 1; k += 1; } // sorting the res array sort(res, res + n + m);} // Driver codeint main(){ int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // Final merge list int res[n + m]; sortedMerge(a, b, res, n, m); cout << \"Sorted merged list :\"; for (int i = 0; i < n + m; i++) cout << \" \" << res[i]; cout << \"n\"; return 0;}",
"e": 1769,
"s": 897,
"text": null
},
{
"code": "// Java Code for Merging two unsorted// arrays in sorted orderimport java.util.*; class GFG { // Function to merge array in sorted order public static void sortedMerge(int a[], int b[], int res[], int n, int m) { // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i++; k++; } while (j < m) { res[k] = b[j]; j++; k++; } // sorting the res array Arrays.sort(res); } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = a.length; int m = b.length; // Final merge list int res[]=new int[n + m]; sortedMerge(a, b, res, n, m); System.out.print(\"Sorted merged list :\"); for (int i = 0; i < n + m; i++) System.out.print(\" \" + res[i]); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 2890,
"s": 1769,
"text": null
},
{
"code": "# Python program to merge two unsorted lists# in sorted order # Function to merge array in sorted orderdef sortedMerge(a, b, res, n, m): # Concatenate two arrays i, j, k = 0, 0, 0 while (i < n): res[k] = a[i] i += 1 k += 1 while (j < m): res[k] = b[j] j += 1 k += 1 # sorting the res array res.sort() # Driver codea = [ 10, 5, 15 ]b = [ 20, 3, 2, 12 ]n = len(a)m = len(b) # Final merge listres = [0 for i in range(n + m)]sortedMerge(a, b, res, n, m)print (\"Sorted merged list :\")for i in range(n + m): print(res[i],end=\" \") # This code is contributed by Sachin Bisht ",
"e": 3530,
"s": 2890,
"text": null
},
{
"code": "// C# Code for Merging two// unsorted arrays in sorted orderusing System; class GFG { // Function to merge array in sorted order public static void sortedMerge(int []a, int []b, int []res, int n, int m) { // Concatenate two arrays int i = 0, j = 0, k = 0; while (i < n) { res[k] = a[i]; i++; k++; } while (j < m) { res[k] = b[j]; j++; k++; } // sorting the res array Array.Sort(res); } /* Driver program to test above function */ public static void Main() { int []a = {10, 5, 15}; int []b = {20, 3, 2, 12}; int n = a.Length; int m = b.Length; // Final merge list int []res=new int[n + m]; sortedMerge(a, b, res, n, m); Console.Write(\"Sorted merged list :\"); for (int i = 0; i < n + m; i++) Console.Write(\" \" + res[i]); }} // This code is contributed by nitin mittal.",
"e": 4615,
"s": 3530,
"text": null
},
{
"code": "<?php// PHP program to merge two unsorted lists// in sorted order // Function to merge array in sorted orderfunction sortedMerge($a, $b, $n, $m){ // Concatenate two arrays $res = array(); $i = 0; $j = 0; $k = 0; while ($i < $n) { $res[$k] = $a[$i]; $i += 1; $k += 1; } while ($j < $m) { $res[$k] = $b[$j]; $j += 1; $k += 1; } // sorting the res array sort($res); echo \"Sorted merged list :\"; for ($i = 0; $i < count($res); $i++) echo $res[$i] . \" \";} // Driver code$a = array( 10, 5, 15 );$b = array( 20, 3, 2, 12 );$n = count($a);$m = count($b); // Final merge list sortedMerge($a, $b, $n, $m); // This code is contributed by Rajput-Ji.?>",
"e": 5349,
"s": 4615,
"text": null
},
{
"code": "<script> // Javascript program to merge two unsorted lists// in sorted order // Function to merge array in sorted orderfunction sortedMerge(a, b, res, n, m){ // Sorting a[] and b[] a.sort((a,b) => a-b); b.sort((a,b) => a-b); // Merge two sorted arrays into res[] let i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; }} // Driver code let a = [ 10, 5, 15 ]; let b = [ 20, 3, 2, 12 ]; let n = a.length; let m = b.length; // Final merge list let res = new Array(n + m); sortedMerge(a, b, res, n, m); document.write(\"Sorted merge list :\"); for (let i = 0; i < n + m; i++) document.write(\" \" + res[i]); //This code is contributed by Mayank Tyagi</script>",
"e": 6562,
"s": 5349,
"text": null
},
{
"code": null,
"e": 6572,
"s": 6562,
"text": "Output: "
},
{
"code": null,
"e": 6611,
"s": 6572,
"text": "Sorted merged list : 2 3 5 10 12 15 20"
},
{
"code": null,
"e": 6687,
"s": 6611,
"text": "Time Complexity: O ( (n + m) (log(n + m)) ) Auxiliary Space: O ( (n + m) ) "
},
{
"code": null,
"e": 6720,
"s": 6687,
"text": "Method 2 (First Sort then Merge)"
},
{
"code": null,
"e": 6810,
"s": 6720,
"text": "We first sort both the given arrays separately. Then we simply merge two sorted arrays. "
},
{
"code": null,
"e": 6814,
"s": 6810,
"text": "C++"
},
{
"code": null,
"e": 6819,
"s": 6814,
"text": "Java"
},
{
"code": null,
"e": 6827,
"s": 6819,
"text": "Python3"
},
{
"code": null,
"e": 6830,
"s": 6827,
"text": "C#"
},
{
"code": null,
"e": 6841,
"s": 6830,
"text": "Javascript"
},
{
"code": "// CPP program to merge two unsorted lists// in sorted order#include <bits/stdc++.h>using namespace std; // Function to merge array in sorted ordervoid sortedMerge(int a[], int b[], int res[], int n, int m){ // Sorting a[] and b[] sort(a, a + n); sort(b, b + m); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; }} // Driver codeint main(){ int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // Final merge list int res[n + m]; sortedMerge(a, b, res, n, m); cout << \"Sorted merge list :\"; for (int i = 0; i < n + m; i++) cout << \" \" << res[i]; cout << \"n\"; return 0;}",
"e": 8094,
"s": 6841,
"text": null
},
{
"code": "// JAVA Code for Merging two unsorted// arrays in sorted orderimport java.util.*; class GFG { // Function to merge array in sorted order public static void sortedMerge(int a[], int b[], int res[], int n, int m) { // Sorting a[] and b[] Arrays.sort(a); Arrays.sort(b); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; } } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 10, 5, 15 }; int b[] = { 20, 3, 2, 12 }; int n = a.length; int m = b.length; // Final merge list int res[] = new int[n + m]; sortedMerge(a, b, res, n, m); System.out.print( \"Sorted merged list :\"); for (int i = 0; i < n + m; i++) System.out.print(\" \" + res[i]); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 9689,
"s": 8094,
"text": null
},
{
"code": "# Python program to merge two unsorted lists# in sorted order # Function to merge array in sorted orderdef sortedMerge(a, b, res, n, m): # Sorting a[] and b[] a.sort() b.sort() # Merge two sorted arrays into res[] i, j, k = 0, 0, 0 while (i < n and j < m): if (a[i] <= b[j]): res[k] = a[i] i += 1 k += 1 else: res[k] = b[j] j += 1 k += 1 while (i < n): # Merging remaining # elements of a[] (if any) res[k] = a[i] i += 1 k += 1 while (j < m): # Merging remaining # elements of b[] (if any) res[k] = b[j] j += 1 k += 1 # Driver codea = [ 10, 5, 15 ]b = [ 20, 3, 2, 12 ]n = len(a)m = len(b) # Final merge listres = [0 for i in range(n + m)]sortedMerge(a, b, res, n, m)print (\"Sorted merged list :\")for i in range(n + m): print(res[i],end=\" \") # This code is contributed by Sachin Bisht ",
"e": 10697,
"s": 9689,
"text": null
},
{
"code": "// C# Code for Merging two unsorted// arrays in sorted orderusing System; class GFG { // Function to merge array in // sorted order static void sortedMerge(int []a, int []b, int []res, int n, int m) { // Sorting a[] and b[] Array.Sort(a); Array.Sort(b); // Merge two sorted arrays into res[] int i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } while (i < n) { // Merging remaining // elements of a[] (if any) res[k] = a[i]; i += 1; k += 1; } while (j < m) { // Merging remaining // elements of b[] (if any) res[k] = b[j]; j += 1; k += 1; } } /* Driver program to test above function */ public static void Main() { int []a = { 10, 5, 15 }; int []b = { 20, 3, 2, 12 }; int n = a.Length; int m = b.Length; // Final merge list int []res = new int[n + m]; sortedMerge(a, b, res, n, m); Console.Write( \"Sorted merged list :\"); for (int i = 0; i < n + m; i++) Console.Write(\" \" + res[i]); }} // This code is contributed by nitin mittal.",
"e": 12286,
"s": 10697,
"text": null
},
{
"code": "<script> // JavaScript program to merge two unsorted// lists in sorted order // Function to merge array in sorted orderfunction sortedMerge(a, b, res, n, m){ // Sorting a[] and b[] a.sort((a, b) => a - b); b.sort((a, b) => a - b); // Merge two sorted arrays into res[] let i = 0, j = 0, k = 0; while (i < n && j < m) { if (a[i] <= b[j]) { res[k] = a[i]; i += 1; k += 1; } else { res[k] = b[j]; j += 1; k += 1; } } // Merging remaining // elements of a[] (if any) while (i < n) { res[k] = a[i]; i += 1; k += 1; } // Merging remaining // elements of b[] (if any) while (j < m) { res[k] = b[j]; j += 1; k += 1; }} // Driver codelet a = [ 10, 5, 15 ];let b = [ 20, 3, 2, 12 ];let n = a.length;let m = b.length; // Final merge listlet res = new Array(n + m); sortedMerge(a, b, res, n, m); document.write(\"Sorted merge list :\");for(let i = 0; i < n + m; i++) document.write(\" \" + res[i]); // This code is contributed by Surbhi Tyagi. </script>",
"e": 13447,
"s": 12286,
"text": null
},
{
"code": null,
"e": 13456,
"s": 13447,
"text": "Output: "
},
{
"code": null,
"e": 13494,
"s": 13456,
"text": "Sorted merge list : 2 3 5 10 12 15 20"
},
{
"code": null,
"e": 13571,
"s": 13494,
"text": "Time Complexity: O (nlogn + mlogm + (n + m)) Space Complexity: O ( (n + m) )"
},
{
"code": null,
"e": 14073,
"s": 13571,
"text": "It is obvious from above time complexities that method 2 is better than method 1.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 14086,
"s": 14073,
"text": "nitin mittal"
},
{
"code": null,
"e": 14096,
"s": 14086,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14112,
"s": 14096,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 14126,
"s": 14112,
"text": "surbhityagi15"
},
{
"code": null,
"e": 14142,
"s": 14126,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14149,
"s": 14142,
"text": "Arrays"
},
{
"code": null,
"e": 14157,
"s": 14149,
"text": "Sorting"
},
{
"code": null,
"e": 14164,
"s": 14157,
"text": "Arrays"
},
{
"code": null,
"e": 14172,
"s": 14164,
"text": "Sorting"
},
{
"code": null,
"e": 14270,
"s": 14172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14302,
"s": 14270,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 14349,
"s": 14302,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 14374,
"s": 14349,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 14405,
"s": 14374,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 14490,
"s": 14405,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 14501,
"s": 14490,
"text": "Merge Sort"
},
{
"code": null,
"e": 14523,
"s": 14501,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 14533,
"s": 14523,
"text": "QuickSort"
},
{
"code": null,
"e": 14548,
"s": 14533,
"text": "Insertion Sort"
}
] |
Graph Data Structure And Algorithms - GeeksforGeeks
|
18 Jun, 2022
Data Structure and Algorithms CoursePractice Problems on GraphsRecent Articles on Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as,
A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, locale etc.
Introduction, DFS and BFS
Graph Cycle
Topological Sorting
Minimum Spanning Tree
BackTracking
Shortest Paths
Connectivity
Maximum Flow
STL Implementation of Algorithms
Hard Problems
Misc
Quick Links
Graph and its representationsBreadth First Traversal for a GraphDepth First Traversal for a GraphApplications of Depth First SearchApplications of Breadth First TraversalGraph representations using set and hashFind Mother Vertex in a GraphTransitive Closure of a Graph using DFSFind K cores of an undirected GraphIterative Depth First SearchCount the number of nodes at given level in a tree using BFSCount all possible paths between two verticesMinimum initial vertices to traverse whole matrix with given conditionsShortest path to reach one prime to other by changing single digit at a timeWater Jug problem using BFSCount number of trees in a forestBFS using vectors & queue as per the algorithm of CLRSLevel of Each node in a Tree from source nodeConstruct binary palindrome by repeated appending and trimmingTranspose graphPath in a Rectangle with CirclesHeight of a generic tree from parent arrayBFS using STL for competitive codingDFS for a n-ary tree (acyclic graph) represented as adjacency listMaximum number of edges to be added to a tree so that it stays a Bipartite graphA Peterson Graph ProblemImplementation of Graph in JavaScriptPrint all paths from a given source to a destination using BFSMinimum number of edges between two vertices of a GraphCount nodes within K-distance from all nodes in a setBidirectional SearchMinimum edge reversals to make a rootBFS for Disconnected GraphMove weighting scale alternate under given constraintsBest First Search (Informed Search)Number of pair of positions in matrix which are not accessibleMaximum product of two non-intersecting paths in a treeDelete Edge to minimize subtree sum differenceFind the minimum number of moves needed to move from one cell of matrix to anotherMinimum steps to reach target by a Knight | Set 1Minimum number of operation required to convert number x into yMinimum steps to reach end of array under constraintsFind the smallest binary digit multiple of given numberRoots of a tree which give minimum heightStepping NumbersClone an Undirected GraphSum of the minimum elements in all connected components of an undirected graphCheck if two nodes are on same path in a treeA matrix probability questionFind length of the largest region in Boolean MatrixIterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Graph and its representations
Breadth First Traversal for a Graph
Depth First Traversal for a Graph
Applications of Depth First Search
Applications of Breadth First Traversal
Graph representations using set and hash
Find Mother Vertex in a Graph
Transitive Closure of a Graph using DFS
Find K cores of an undirected Graph
Iterative Depth First Search
Count the number of nodes at given level in a tree using BFS
Count all possible paths between two vertices
Minimum initial vertices to traverse whole matrix with given conditions
Shortest path to reach one prime to other by changing single digit at a time
Water Jug problem using BFS
Count number of trees in a forest
BFS using vectors & queue as per the algorithm of CLRS
Level of Each node in a Tree from source node
Construct binary palindrome by repeated appending and trimming
Transpose graph
Path in a Rectangle with Circles
Height of a generic tree from parent array
BFS using STL for competitive coding
DFS for a n-ary tree (acyclic graph) represented as adjacency list
Maximum number of edges to be added to a tree so that it stays a Bipartite graph
A Peterson Graph Problem
Implementation of Graph in JavaScript
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
Move weighting scale alternate under given constraints
Best First Search (Informed Search)
Number of pair of positions in matrix which are not accessible
Maximum product of two non-intersecting paths in a tree
Delete Edge to minimize subtree sum difference
Find the minimum number of moves needed to move from one cell of matrix to another
Minimum steps to reach target by a Knight | Set 1
Minimum number of operation required to convert number x into y
Minimum steps to reach end of array under constraints
Find the smallest binary digit multiple of given number
Roots of a tree which give minimum height
Stepping Numbers
Clone an Undirected Graph
Sum of the minimum elements in all connected components of an undirected graph
Check if two nodes are on same path in a tree
A matrix probability question
Find length of the largest region in Boolean Matrix
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Graph Cycle :
Detect Cycle in a Directed GraphDetect cycle in an undirected graphDetect cycle in a direct graph using colorsAssign directions to edges so that the directed graph remains acyclicDetect a negative cycle in a Graph | (Bellman Ford)Cycles of length n in an undirected and connected graphDetecting negative cycle using Floyd WarshallCheck if there is a cycle with odd weight sum in an undirected graphCheck if a graphs has a cycle of odd lengthClone a Directed Acyclic GraphCheck loop in array according to given constraintsDisjoint Set (Or Union-Find) | Set 1Union-Find Algorithm | Set 2Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)Magical Indices in an array
Detect Cycle in a Directed Graph
Detect cycle in an undirected graph
Detect cycle in a direct graph using colors
Assign directions to edges so that the directed graph remains acyclic
Detect a negative cycle in a Graph | (Bellman Ford)
Cycles of length n in an undirected and connected graph
Detecting negative cycle using Floyd Warshall
Check if there is a cycle with odd weight sum in an undirected graph
Check if a graphs has a cycle of odd length
Clone a Directed Acyclic Graph
Check loop in array according to given constraints
Disjoint Set (Or Union-Find) | Set 1
Union-Find Algorithm | Set 2
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Magical Indices in an array
Topological Sorting :
Topological SortingAll topological sorts of a Directed Acyclic GraphKahn’s Algorithm for Topological SortingMaximum edges that can be added to DAG so that is remains DAGLongest path between any pair of verticesLongest Path in a Directed Acyclic GraphLongest Path in a Directed Acyclic Graph | Set 2Topological Sort of a graph using departure time of vertexGiven a sorted dictionary of an alien language, find order of characters
Topological Sorting
All topological sorts of a Directed Acyclic Graph
Kahn’s Algorithm for Topological Sorting
Maximum edges that can be added to DAG so that is remains DAG
Longest path between any pair of vertices
Longest Path in a Directed Acyclic Graph
Longest Path in a Directed Acyclic Graph | Set 2
Topological Sort of a graph using departure time of vertex
Given a sorted dictionary of an alien language, find order of characters
Minimum Spanning Tree :
Prim’s Minimum Spanning Tree (MST))Applications of Minimum Spanning Tree ProblemPrim’s MST for Adjacency List RepresentationKruskal’s Minimum Spanning Tree AlgorithmBoruvka’s algorithm for Minimum Spanning TreeMinimum cost to connect all citiesSteiner TreeReverse Delete Algorithm for Minimum Spanning TreeTotal number of Spanning Trees in a GraphMinimum Product Spanning Tree
Prim’s Minimum Spanning Tree (MST))
Applications of Minimum Spanning Tree Problem
Prim’s MST for Adjacency List Representation
Kruskal’s Minimum Spanning Tree Algorithm
Boruvka’s algorithm for Minimum Spanning Tree
Minimum cost to connect all cities
Steiner Tree
Reverse Delete Algorithm for Minimum Spanning Tree
Total number of Spanning Trees in a Graph
Minimum Product Spanning Tree
BackTracking :
Find if there is a path of more than k length from a sourceTug of WarThe Knight-Tour ProblemRat in a Mazen-Queen’s Problemm Coloring ProblemHamiltonian CyclePermutation of numbers such that sum of two consecutive numbers is a perfect square
Find if there is a path of more than k length from a source
Tug of War
The Knight-Tour Problem
Rat in a Maze
n-Queen’s Problem
m Coloring Problem
Hamiltonian Cycle
Permutation of numbers such that sum of two consecutive numbers is a perfect square
Shortest Paths :
Dijkstra’s shortest path algorithmDijkstra’s Algorithm for Adjacency List RepresentationBellman–Ford AlgorithmFloyd Warshall AlgorithmJohnson’s algorithm for All-pairs shortest pathsShortest Path in Directed Acyclic GraphShortest path with exactly k edges in a directed and weighted graphDial’s AlgorithmPrinting paths in Dijsktra’s AlgorithmShortest path of a weighted graph where weight is 1 or 2Multistage Graph (Shortest Path)Shortest path in an unweighted graphMinimize the number of weakly connected nodesBetweenness Centrality (Centrality Measure)Comparison of Dijkstra’s and Floyd–Warshall algorithmsKarp’s minimum mean (or average) weight cycle algorithm0-1 BFS (Shortest Path in a Binary Weight Graph)Find minimum weight cycle in an undirected graphMinimum Cost Path with Left, Right, Bottom and Up moves allowedMinimum edges to reverse to make path from a src to a destFind Shortest distance from a guard in a Bank
Dijkstra’s shortest path algorithm
Dijkstra’s Algorithm for Adjacency List Representation
Bellman–Ford Algorithm
Floyd Warshall Algorithm
Johnson’s algorithm for All-pairs shortest paths
Shortest Path in Directed Acyclic Graph
Shortest path with exactly k edges in a directed and weighted graph
Dial’s Algorithm
Printing paths in Dijsktra’s Algorithm
Shortest path of a weighted graph where weight is 1 or 2
Multistage Graph (Shortest Path)
Shortest path in an unweighted graph
Minimize the number of weakly connected nodes
Betweenness Centrality (Centrality Measure)
Comparison of Dijkstra’s and Floyd–Warshall algorithms
Karp’s minimum mean (or average) weight cycle algorithm
0-1 BFS (Shortest Path in a Binary Weight Graph)
Find minimum weight cycle in an undirected graph
Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Minimum edges to reverse to make path from a src to a dest
Find Shortest distance from a guard in a Bank
Connectivity :
Find if there is a path between two vertices in a directed graphConnectivity in a directed graphArticulation Points (or Cut Vertices) in a GraphBiconnected ComponentsBiconnected graphBridges in a graphEulerian path and circuitFleury’s Algorithm for printing Eulerian Path or CircuitStrongly Connected ComponentsTransitive closure of a graphFind the number of islandsFind the number of Islands | Set 2 (Using Disjoint Set)Count all possible walks from a source to a destination with exactly k edgesEuler Circuit in a Directed GraphCount the number of non-reachable nodesFind the Degree of a Particular vertex in a GraphCheck if a given graph is tree or notMinimum edges required to add to make Euler CircuitEulerian Path in undirected graphFind if there is a path of more than k lengthLength of shortest chain to reach the target wordPrint all paths from a given source to destinationFind minimum cost to reach destination using trainFind if an array of strings can be chained to form a circle | Set 1Find if an array of strings can be chained to form a circle | Set 2Tarjan’s Algorithm to find strongly connected ComponentsNumber of loops of size k starting from a specific nodePaths to travel each nodes using each edge (Seven Bridges of Königsberg)Number of cyclic elements in an array where we can jump according to valueNumber of groups formed in a graph of friendsMinimum cost to connect weighted nodes represented as arrayCount single node isolated sub-graphs in a disconnected graphCalculate number of nodes between two vertices in an acyclic Graph by Disjoint Union methodDynamic Connectivity | Set 1 (Incremental)Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)Check if removing a given edge disconnects a graphFind all reachable nodes from every node present in a given setConnected Components in an undirected graphk’th heaviest adjacent node in a graph where each vertex has weight
Find if there is a path between two vertices in a directed graph
Connectivity in a directed graph
Articulation Points (or Cut Vertices) in a Graph
Biconnected Components
Biconnected graph
Bridges in a graph
Eulerian path and circuit
Fleury’s Algorithm for printing Eulerian Path or Circuit
Strongly Connected Components
Transitive closure of a graph
Find the number of islands
Find the number of Islands | Set 2 (Using Disjoint Set)
Count all possible walks from a source to a destination with exactly k edges
Euler Circuit in a Directed Graph
Count the number of non-reachable nodes
Find the Degree of a Particular vertex in a Graph
Check if a given graph is tree or not
Minimum edges required to add to make Euler Circuit
Eulerian Path in undirected graph
Find if there is a path of more than k length
Length of shortest chain to reach the target word
Print all paths from a given source to destination
Find minimum cost to reach destination using train
Find if an array of strings can be chained to form a circle | Set 1
Find if an array of strings can be chained to form a circle | Set 2
Tarjan’s Algorithm to find strongly connected Components
Number of loops of size k starting from a specific node
Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
Number of cyclic elements in an array where we can jump according to value
Number of groups formed in a graph of friends
Minimum cost to connect weighted nodes represented as array
Count single node isolated sub-graphs in a disconnected graph
Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
Dynamic Connectivity | Set 1 (Incremental)
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
Check if removing a given edge disconnects a graph
Find all reachable nodes from every node present in a given set
Connected Components in an undirected graph
k’th heaviest adjacent node in a graph where each vertex has weight
Maximum Flow :
Ford-Fulkerson Algorithm for Maximum Flow ProblemFind maximum number of edge disjoint paths between two verticesFind minimum s-t cut in a flow networkMaximum Bipartite MatchingChannel Assignment ProblemPush Relabel- Set 1-IntroductionPush Relabel- Set 2- ImplementationKarger’s Algorithm- Set 1- Introduction and ImplementationKarger’s Algorithm- Set 2 – Analysis and ApplicationsDinic’s algorithm for Maximum FlowMax Flow Problem Introduction
Ford-Fulkerson Algorithm for Maximum Flow Problem
Find maximum number of edge disjoint paths between two vertices
Find minimum s-t cut in a flow network
Maximum Bipartite Matching
Channel Assignment Problem
Push Relabel- Set 1-Introduction
Push Relabel- Set 2- Implementation
Karger’s Algorithm- Set 1- Introduction and Implementation
Karger’s Algorithm- Set 2 – Analysis and Applications
Dinic’s algorithm for Maximum Flow
Max Flow Problem Introduction
STL Implementation of Algorithms :
Kruskal’s Minimum Spanning Tree using STL in C++Prim’s Algorithm using Priority Queue STLDijkstra’s Shortest Path Algorithm using STLDijkstra’s Shortest Path Algorithm using set in STLGraph implementation using STL for competitive programming | Set 2 (Weighted graph)
Kruskal’s Minimum Spanning Tree using STL in C++
Prim’s Algorithm using Priority Queue STL
Dijkstra’s Shortest Path Algorithm using STL
Dijkstra’s Shortest Path Algorithm using set in STL
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Hard Problems :
Graph Coloring (Introduction and Applications)Greedy Algorithm for Graph ColoringTraveling Salesman Problem (TSP) ImplementationTravelling Salesman Problem (Naive and Dynamic Programming)Travelling Salesman Problem (Approximate using MST)Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)K Centers Problem | Set 1 (Greedy Approximate Algorithm)Erdos Renyl Model (for generating Random Graphs)Clustering Coefficient in Graph TheoryChinese Postman or Route Inspection | Set 1 (introduction)Hierholzer’s Algorithm for directed graph
Graph Coloring (Introduction and Applications)
Greedy Algorithm for Graph Coloring
Traveling Salesman Problem (TSP) Implementation
Travelling Salesman Problem (Naive and Dynamic Programming)
Travelling Salesman Problem (Approximate using MST)
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Erdos Renyl Model (for generating Random Graphs)
Clustering Coefficient in Graph Theory
Chinese Postman or Route Inspection | Set 1 (introduction)
Hierholzer’s Algorithm for directed graph
Misc :
Number of triangles in an undirected GraphNumber of triangles in directed and undirected GraphCheck whether a given graph is Bipartite or notSnake and Ladder ProblemMinimize Cash Flow among a given set of friends who have borrowed money from each otherBoggle (Find all possible words in a board of characters)Hopcroft Karp Algorithm for Maximum Matching-IntroductionHopcroft Karp Algorithm for Maximum Matching-ImplementationMinimum Time to rot all orangesFind same contents in a list of contactsHypercube GraphCheck for star graphOptimal read list for a given number of daysPrint all jumping numbers smaller than or equal to a given valueFibonacci Cube GraphBarabasi Albert Graph (for Scale Free Models)Construct a graph from given degrees of all verticesDegree Centrality (Centrality Measure)Katz Centrality (Centrality Measure)Mathematics | Graph theory practice questions2-Satisfiability (2-SAT) ProblemDetermine whether a universal sink exists in a directed graphNumber of sink nodes in a graphLargest subset of Graph vertices with edges of 2 or more colorsNetworkX : Python software package for study of complex networksGenerate a graph using Dictionary in PythonCount number of edges in an undirected graphTwo Clique Problem (Check if Graph can be divided in two Cliques)Check whether given degrees of vertices represent a Graph or TreeFinding minimum vertex cover size of a graph using binary searchStable Marriage ProblemSum of dependencies in a graph
Number of triangles in an undirected Graph
Number of triangles in directed and undirected Graph
Check whether a given graph is Bipartite or not
Snake and Ladder Problem
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Boggle (Find all possible words in a board of characters)
Hopcroft Karp Algorithm for Maximum Matching-Introduction
Hopcroft Karp Algorithm for Maximum Matching-Implementation
Minimum Time to rot all oranges
Find same contents in a list of contacts
Hypercube Graph
Check for star graph
Optimal read list for a given number of days
Print all jumping numbers smaller than or equal to a given value
Fibonacci Cube Graph
Barabasi Albert Graph (for Scale Free Models)
Construct a graph from given degrees of all vertices
Degree Centrality (Centrality Measure)
Katz Centrality (Centrality Measure)
Mathematics | Graph theory practice questions
2-Satisfiability (2-SAT) Problem
Determine whether a universal sink exists in a directed graph
Number of sink nodes in a graph
Largest subset of Graph vertices with edges of 2 or more colors
NetworkX : Python software package for study of complex networks
Generate a graph using Dictionary in Python
Count number of edges in an undirected graph
Two Clique Problem (Check if Graph can be divided in two Cliques)
Check whether given degrees of vertices represent a Graph or Tree
Finding minimum vertex cover size of a graph using binary search
Stable Marriage Problem
Sum of dependencies in a graph
Quick Links :
Top 10 Interview Questions on Depth First Search (DFS)
Some interesting shortest path questions
Quizzes on Graph Traversal
Quizzes on Graph Shortest Path
Quizzes on Graph Minimum Spanning Tree
Quizzes on Graphs
Practice Problems on Graphs
Videos on Graphs
1. Language Foundation Courses [C++ / JAVA / Python ]Learn any programming language from scratch and understand all its fundamentals concepts for a strong programming foundation in the easiest possible manner with help of GeeksforGeeks Language Foundation Courses – Java Foundation | Python Foundation | C++ Foundation
2. Geeks Classes LiveGet interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session
3. Complete Interview PreparationGet fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices.
4. DSA Self PacedStart learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience.
5. Company Specific Courses – Amazon, Microsoft, TCS & WiproCrack the interview of any product-based giant company by specifically preparing with the questions that these companies usually ask in their coding interview round. Refer GeeksforGeeks Company Specific Courses: Amazon SDE Test Series, etc.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Floyd’s Cycle Finding Algorithm
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Git in VS Code?
Git - Difference Between Git Fetch and Git Pull
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
|
[
{
"code": null,
"e": 26165,
"s": 26137,
"text": "\n18 Jun, 2022"
},
{
"code": null,
"e": 26253,
"s": 26165,
"text": "Data Structure and Algorithms CoursePractice Problems on GraphsRecent Articles on Graph"
},
{
"code": null,
"e": 26490,
"s": 26253,
"text": "A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as,"
},
{
"code": null,
"e": 26593,
"s": 26490,
"text": "A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes."
},
{
"code": null,
"e": 26696,
"s": 26593,
"text": "A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes."
},
{
"code": null,
"e": 26807,
"s": 26696,
"text": "In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}."
},
{
"code": null,
"e": 27212,
"s": 26807,
"text": "Graphs are used to solve many real-life problems. Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a vertex(or node). Each node is a structure and contains information like person id, name, gender, locale etc."
},
{
"code": null,
"e": 27238,
"s": 27212,
"text": "Introduction, DFS and BFS"
},
{
"code": null,
"e": 27250,
"s": 27238,
"text": "Graph Cycle"
},
{
"code": null,
"e": 27270,
"s": 27250,
"text": "Topological Sorting"
},
{
"code": null,
"e": 27292,
"s": 27270,
"text": "Minimum Spanning Tree"
},
{
"code": null,
"e": 27305,
"s": 27292,
"text": "BackTracking"
},
{
"code": null,
"e": 27320,
"s": 27305,
"text": "Shortest Paths"
},
{
"code": null,
"e": 27333,
"s": 27320,
"text": "Connectivity"
},
{
"code": null,
"e": 27346,
"s": 27333,
"text": "Maximum Flow"
},
{
"code": null,
"e": 27379,
"s": 27346,
"text": "STL Implementation of Algorithms"
},
{
"code": null,
"e": 27393,
"s": 27379,
"text": "Hard Problems"
},
{
"code": null,
"e": 27398,
"s": 27393,
"text": "Misc"
},
{
"code": null,
"e": 27410,
"s": 27398,
"text": "Quick Links"
},
{
"code": null,
"e": 29729,
"s": 27410,
"text": "Graph and its representationsBreadth First Traversal for a GraphDepth First Traversal for a GraphApplications of Depth First SearchApplications of Breadth First TraversalGraph representations using set and hashFind Mother Vertex in a GraphTransitive Closure of a Graph using DFSFind K cores of an undirected GraphIterative Depth First SearchCount the number of nodes at given level in a tree using BFSCount all possible paths between two verticesMinimum initial vertices to traverse whole matrix with given conditionsShortest path to reach one prime to other by changing single digit at a timeWater Jug problem using BFSCount number of trees in a forestBFS using vectors & queue as per the algorithm of CLRSLevel of Each node in a Tree from source nodeConstruct binary palindrome by repeated appending and trimmingTranspose graphPath in a Rectangle with CirclesHeight of a generic tree from parent arrayBFS using STL for competitive codingDFS for a n-ary tree (acyclic graph) represented as adjacency listMaximum number of edges to be added to a tree so that it stays a Bipartite graphA Peterson Graph ProblemImplementation of Graph in JavaScriptPrint all paths from a given source to a destination using BFSMinimum number of edges between two vertices of a GraphCount nodes within K-distance from all nodes in a setBidirectional SearchMinimum edge reversals to make a rootBFS for Disconnected GraphMove weighting scale alternate under given constraintsBest First Search (Informed Search)Number of pair of positions in matrix which are not accessibleMaximum product of two non-intersecting paths in a treeDelete Edge to minimize subtree sum differenceFind the minimum number of moves needed to move from one cell of matrix to anotherMinimum steps to reach target by a Knight | Set 1Minimum number of operation required to convert number x into yMinimum steps to reach end of array under constraintsFind the smallest binary digit multiple of given numberRoots of a tree which give minimum heightStepping NumbersClone an Undirected GraphSum of the minimum elements in all connected components of an undirected graphCheck if two nodes are on same path in a treeA matrix probability questionFind length of the largest region in Boolean MatrixIterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
},
{
"code": null,
"e": 29759,
"s": 29729,
"text": "Graph and its representations"
},
{
"code": null,
"e": 29795,
"s": 29759,
"text": "Breadth First Traversal for a Graph"
},
{
"code": null,
"e": 29829,
"s": 29795,
"text": "Depth First Traversal for a Graph"
},
{
"code": null,
"e": 29864,
"s": 29829,
"text": "Applications of Depth First Search"
},
{
"code": null,
"e": 29904,
"s": 29864,
"text": "Applications of Breadth First Traversal"
},
{
"code": null,
"e": 29945,
"s": 29904,
"text": "Graph representations using set and hash"
},
{
"code": null,
"e": 29975,
"s": 29945,
"text": "Find Mother Vertex in a Graph"
},
{
"code": null,
"e": 30015,
"s": 29975,
"text": "Transitive Closure of a Graph using DFS"
},
{
"code": null,
"e": 30051,
"s": 30015,
"text": "Find K cores of an undirected Graph"
},
{
"code": null,
"e": 30080,
"s": 30051,
"text": "Iterative Depth First Search"
},
{
"code": null,
"e": 30141,
"s": 30080,
"text": "Count the number of nodes at given level in a tree using BFS"
},
{
"code": null,
"e": 30187,
"s": 30141,
"text": "Count all possible paths between two vertices"
},
{
"code": null,
"e": 30259,
"s": 30187,
"text": "Minimum initial vertices to traverse whole matrix with given conditions"
},
{
"code": null,
"e": 30336,
"s": 30259,
"text": "Shortest path to reach one prime to other by changing single digit at a time"
},
{
"code": null,
"e": 30364,
"s": 30336,
"text": "Water Jug problem using BFS"
},
{
"code": null,
"e": 30398,
"s": 30364,
"text": "Count number of trees in a forest"
},
{
"code": null,
"e": 30453,
"s": 30398,
"text": "BFS using vectors & queue as per the algorithm of CLRS"
},
{
"code": null,
"e": 30499,
"s": 30453,
"text": "Level of Each node in a Tree from source node"
},
{
"code": null,
"e": 30562,
"s": 30499,
"text": "Construct binary palindrome by repeated appending and trimming"
},
{
"code": null,
"e": 30578,
"s": 30562,
"text": "Transpose graph"
},
{
"code": null,
"e": 30611,
"s": 30578,
"text": "Path in a Rectangle with Circles"
},
{
"code": null,
"e": 30654,
"s": 30611,
"text": "Height of a generic tree from parent array"
},
{
"code": null,
"e": 30691,
"s": 30654,
"text": "BFS using STL for competitive coding"
},
{
"code": null,
"e": 30758,
"s": 30691,
"text": "DFS for a n-ary tree (acyclic graph) represented as adjacency list"
},
{
"code": null,
"e": 30839,
"s": 30758,
"text": "Maximum number of edges to be added to a tree so that it stays a Bipartite graph"
},
{
"code": null,
"e": 30864,
"s": 30839,
"text": "A Peterson Graph Problem"
},
{
"code": null,
"e": 30902,
"s": 30864,
"text": "Implementation of Graph in JavaScript"
},
{
"code": null,
"e": 30965,
"s": 30902,
"text": "Print all paths from a given source to a destination using BFS"
},
{
"code": null,
"e": 31021,
"s": 30965,
"text": "Minimum number of edges between two vertices of a Graph"
},
{
"code": null,
"e": 31075,
"s": 31021,
"text": "Count nodes within K-distance from all nodes in a set"
},
{
"code": null,
"e": 31096,
"s": 31075,
"text": "Bidirectional Search"
},
{
"code": null,
"e": 31134,
"s": 31096,
"text": "Minimum edge reversals to make a root"
},
{
"code": null,
"e": 31161,
"s": 31134,
"text": "BFS for Disconnected Graph"
},
{
"code": null,
"e": 31216,
"s": 31161,
"text": "Move weighting scale alternate under given constraints"
},
{
"code": null,
"e": 31252,
"s": 31216,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 31315,
"s": 31252,
"text": "Number of pair of positions in matrix which are not accessible"
},
{
"code": null,
"e": 31371,
"s": 31315,
"text": "Maximum product of two non-intersecting paths in a tree"
},
{
"code": null,
"e": 31418,
"s": 31371,
"text": "Delete Edge to minimize subtree sum difference"
},
{
"code": null,
"e": 31501,
"s": 31418,
"text": "Find the minimum number of moves needed to move from one cell of matrix to another"
},
{
"code": null,
"e": 31551,
"s": 31501,
"text": "Minimum steps to reach target by a Knight | Set 1"
},
{
"code": null,
"e": 31615,
"s": 31551,
"text": "Minimum number of operation required to convert number x into y"
},
{
"code": null,
"e": 31669,
"s": 31615,
"text": "Minimum steps to reach end of array under constraints"
},
{
"code": null,
"e": 31725,
"s": 31669,
"text": "Find the smallest binary digit multiple of given number"
},
{
"code": null,
"e": 31767,
"s": 31725,
"text": "Roots of a tree which give minimum height"
},
{
"code": null,
"e": 31784,
"s": 31767,
"text": "Stepping Numbers"
},
{
"code": null,
"e": 31810,
"s": 31784,
"text": "Clone an Undirected Graph"
},
{
"code": null,
"e": 31889,
"s": 31810,
"text": "Sum of the minimum elements in all connected components of an undirected graph"
},
{
"code": null,
"e": 31935,
"s": 31889,
"text": "Check if two nodes are on same path in a tree"
},
{
"code": null,
"e": 31965,
"s": 31935,
"text": "A matrix probability question"
},
{
"code": null,
"e": 32017,
"s": 31965,
"text": "Find length of the largest region in Boolean Matrix"
},
{
"code": null,
"e": 32098,
"s": 32017,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
},
{
"code": null,
"e": 32112,
"s": 32098,
"text": "Graph Cycle :"
},
{
"code": null,
"e": 32802,
"s": 32112,
"text": "Detect Cycle in a Directed GraphDetect cycle in an undirected graphDetect cycle in a direct graph using colorsAssign directions to edges so that the directed graph remains acyclicDetect a negative cycle in a Graph | (Bellman Ford)Cycles of length n in an undirected and connected graphDetecting negative cycle using Floyd WarshallCheck if there is a cycle with odd weight sum in an undirected graphCheck if a graphs has a cycle of odd lengthClone a Directed Acyclic GraphCheck loop in array according to given constraintsDisjoint Set (Or Union-Find) | Set 1Union-Find Algorithm | Set 2Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)Magical Indices in an array"
},
{
"code": null,
"e": 32835,
"s": 32802,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 32871,
"s": 32835,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 32915,
"s": 32871,
"text": "Detect cycle in a direct graph using colors"
},
{
"code": null,
"e": 32985,
"s": 32915,
"text": "Assign directions to edges so that the directed graph remains acyclic"
},
{
"code": null,
"e": 33037,
"s": 32985,
"text": "Detect a negative cycle in a Graph | (Bellman Ford)"
},
{
"code": null,
"e": 33093,
"s": 33037,
"text": "Cycles of length n in an undirected and connected graph"
},
{
"code": null,
"e": 33139,
"s": 33093,
"text": "Detecting negative cycle using Floyd Warshall"
},
{
"code": null,
"e": 33208,
"s": 33139,
"text": "Check if there is a cycle with odd weight sum in an undirected graph"
},
{
"code": null,
"e": 33252,
"s": 33208,
"text": "Check if a graphs has a cycle of odd length"
},
{
"code": null,
"e": 33283,
"s": 33252,
"text": "Clone a Directed Acyclic Graph"
},
{
"code": null,
"e": 33334,
"s": 33283,
"text": "Check loop in array according to given constraints"
},
{
"code": null,
"e": 33371,
"s": 33334,
"text": "Disjoint Set (Or Union-Find) | Set 1"
},
{
"code": null,
"e": 33400,
"s": 33371,
"text": "Union-Find Algorithm | Set 2"
},
{
"code": null,
"e": 33478,
"s": 33400,
"text": "Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)"
},
{
"code": null,
"e": 33506,
"s": 33478,
"text": "Magical Indices in an array"
},
{
"code": null,
"e": 33528,
"s": 33506,
"text": "Topological Sorting :"
},
{
"code": null,
"e": 33957,
"s": 33528,
"text": "Topological SortingAll topological sorts of a Directed Acyclic GraphKahn’s Algorithm for Topological SortingMaximum edges that can be added to DAG so that is remains DAGLongest path between any pair of verticesLongest Path in a Directed Acyclic GraphLongest Path in a Directed Acyclic Graph | Set 2Topological Sort of a graph using departure time of vertexGiven a sorted dictionary of an alien language, find order of characters"
},
{
"code": null,
"e": 33977,
"s": 33957,
"text": "Topological Sorting"
},
{
"code": null,
"e": 34027,
"s": 33977,
"text": "All topological sorts of a Directed Acyclic Graph"
},
{
"code": null,
"e": 34068,
"s": 34027,
"text": "Kahn’s Algorithm for Topological Sorting"
},
{
"code": null,
"e": 34130,
"s": 34068,
"text": "Maximum edges that can be added to DAG so that is remains DAG"
},
{
"code": null,
"e": 34172,
"s": 34130,
"text": "Longest path between any pair of vertices"
},
{
"code": null,
"e": 34213,
"s": 34172,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 34262,
"s": 34213,
"text": "Longest Path in a Directed Acyclic Graph | Set 2"
},
{
"code": null,
"e": 34321,
"s": 34262,
"text": "Topological Sort of a graph using departure time of vertex"
},
{
"code": null,
"e": 34394,
"s": 34321,
"text": "Given a sorted dictionary of an alien language, find order of characters"
},
{
"code": null,
"e": 34418,
"s": 34394,
"text": "Minimum Spanning Tree :"
},
{
"code": null,
"e": 34795,
"s": 34418,
"text": "Prim’s Minimum Spanning Tree (MST))Applications of Minimum Spanning Tree ProblemPrim’s MST for Adjacency List RepresentationKruskal’s Minimum Spanning Tree AlgorithmBoruvka’s algorithm for Minimum Spanning TreeMinimum cost to connect all citiesSteiner TreeReverse Delete Algorithm for Minimum Spanning TreeTotal number of Spanning Trees in a GraphMinimum Product Spanning Tree"
},
{
"code": null,
"e": 34831,
"s": 34795,
"text": "Prim’s Minimum Spanning Tree (MST))"
},
{
"code": null,
"e": 34877,
"s": 34831,
"text": "Applications of Minimum Spanning Tree Problem"
},
{
"code": null,
"e": 34922,
"s": 34877,
"text": "Prim’s MST for Adjacency List Representation"
},
{
"code": null,
"e": 34964,
"s": 34922,
"text": "Kruskal’s Minimum Spanning Tree Algorithm"
},
{
"code": null,
"e": 35010,
"s": 34964,
"text": "Boruvka’s algorithm for Minimum Spanning Tree"
},
{
"code": null,
"e": 35045,
"s": 35010,
"text": "Minimum cost to connect all cities"
},
{
"code": null,
"e": 35058,
"s": 35045,
"text": "Steiner Tree"
},
{
"code": null,
"e": 35109,
"s": 35058,
"text": "Reverse Delete Algorithm for Minimum Spanning Tree"
},
{
"code": null,
"e": 35151,
"s": 35109,
"text": "Total number of Spanning Trees in a Graph"
},
{
"code": null,
"e": 35181,
"s": 35151,
"text": "Minimum Product Spanning Tree"
},
{
"code": null,
"e": 35196,
"s": 35181,
"text": "BackTracking :"
},
{
"code": null,
"e": 35437,
"s": 35196,
"text": "Find if there is a path of more than k length from a sourceTug of WarThe Knight-Tour ProblemRat in a Mazen-Queen’s Problemm Coloring ProblemHamiltonian CyclePermutation of numbers such that sum of two consecutive numbers is a perfect square"
},
{
"code": null,
"e": 35497,
"s": 35437,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 35508,
"s": 35497,
"text": "Tug of War"
},
{
"code": null,
"e": 35532,
"s": 35508,
"text": "The Knight-Tour Problem"
},
{
"code": null,
"e": 35546,
"s": 35532,
"text": "Rat in a Maze"
},
{
"code": null,
"e": 35564,
"s": 35546,
"text": "n-Queen’s Problem"
},
{
"code": null,
"e": 35583,
"s": 35564,
"text": "m Coloring Problem"
},
{
"code": null,
"e": 35601,
"s": 35583,
"text": "Hamiltonian Cycle"
},
{
"code": null,
"e": 35685,
"s": 35601,
"text": "Permutation of numbers such that sum of two consecutive numbers is a perfect square"
},
{
"code": null,
"e": 35702,
"s": 35685,
"text": "Shortest Paths :"
},
{
"code": null,
"e": 36628,
"s": 35702,
"text": "Dijkstra’s shortest path algorithmDijkstra’s Algorithm for Adjacency List RepresentationBellman–Ford AlgorithmFloyd Warshall AlgorithmJohnson’s algorithm for All-pairs shortest pathsShortest Path in Directed Acyclic GraphShortest path with exactly k edges in a directed and weighted graphDial’s AlgorithmPrinting paths in Dijsktra’s AlgorithmShortest path of a weighted graph where weight is 1 or 2Multistage Graph (Shortest Path)Shortest path in an unweighted graphMinimize the number of weakly connected nodesBetweenness Centrality (Centrality Measure)Comparison of Dijkstra’s and Floyd–Warshall algorithmsKarp’s minimum mean (or average) weight cycle algorithm0-1 BFS (Shortest Path in a Binary Weight Graph)Find minimum weight cycle in an undirected graphMinimum Cost Path with Left, Right, Bottom and Up moves allowedMinimum edges to reverse to make path from a src to a destFind Shortest distance from a guard in a Bank"
},
{
"code": null,
"e": 36663,
"s": 36628,
"text": "Dijkstra’s shortest path algorithm"
},
{
"code": null,
"e": 36718,
"s": 36663,
"text": "Dijkstra’s Algorithm for Adjacency List Representation"
},
{
"code": null,
"e": 36741,
"s": 36718,
"text": "Bellman–Ford Algorithm"
},
{
"code": null,
"e": 36766,
"s": 36741,
"text": "Floyd Warshall Algorithm"
},
{
"code": null,
"e": 36815,
"s": 36766,
"text": "Johnson’s algorithm for All-pairs shortest paths"
},
{
"code": null,
"e": 36855,
"s": 36815,
"text": "Shortest Path in Directed Acyclic Graph"
},
{
"code": null,
"e": 36923,
"s": 36855,
"text": "Shortest path with exactly k edges in a directed and weighted graph"
},
{
"code": null,
"e": 36940,
"s": 36923,
"text": "Dial’s Algorithm"
},
{
"code": null,
"e": 36979,
"s": 36940,
"text": "Printing paths in Dijsktra’s Algorithm"
},
{
"code": null,
"e": 37036,
"s": 36979,
"text": "Shortest path of a weighted graph where weight is 1 or 2"
},
{
"code": null,
"e": 37069,
"s": 37036,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 37106,
"s": 37069,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 37152,
"s": 37106,
"text": "Minimize the number of weakly connected nodes"
},
{
"code": null,
"e": 37196,
"s": 37152,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 37251,
"s": 37196,
"text": "Comparison of Dijkstra’s and Floyd–Warshall algorithms"
},
{
"code": null,
"e": 37307,
"s": 37251,
"text": "Karp’s minimum mean (or average) weight cycle algorithm"
},
{
"code": null,
"e": 37356,
"s": 37307,
"text": "0-1 BFS (Shortest Path in a Binary Weight Graph)"
},
{
"code": null,
"e": 37405,
"s": 37356,
"text": "Find minimum weight cycle in an undirected graph"
},
{
"code": null,
"e": 37469,
"s": 37405,
"text": "Minimum Cost Path with Left, Right, Bottom and Up moves allowed"
},
{
"code": null,
"e": 37528,
"s": 37469,
"text": "Minimum edges to reverse to make path from a src to a dest"
},
{
"code": null,
"e": 37574,
"s": 37528,
"text": "Find Shortest distance from a guard in a Bank"
},
{
"code": null,
"e": 37589,
"s": 37574,
"text": "Connectivity :"
},
{
"code": null,
"e": 39585,
"s": 37589,
"text": "Find if there is a path between two vertices in a directed graphConnectivity in a directed graphArticulation Points (or Cut Vertices) in a GraphBiconnected ComponentsBiconnected graphBridges in a graphEulerian path and circuitFleury’s Algorithm for printing Eulerian Path or CircuitStrongly Connected ComponentsTransitive closure of a graphFind the number of islandsFind the number of Islands | Set 2 (Using Disjoint Set)Count all possible walks from a source to a destination with exactly k edgesEuler Circuit in a Directed GraphCount the number of non-reachable nodesFind the Degree of a Particular vertex in a GraphCheck if a given graph is tree or notMinimum edges required to add to make Euler CircuitEulerian Path in undirected graphFind if there is a path of more than k lengthLength of shortest chain to reach the target wordPrint all paths from a given source to destinationFind minimum cost to reach destination using trainFind if an array of strings can be chained to form a circle | Set 1Find if an array of strings can be chained to form a circle | Set 2Tarjan’s Algorithm to find strongly connected ComponentsNumber of loops of size k starting from a specific nodePaths to travel each nodes using each edge (Seven Bridges of Königsberg)Number of cyclic elements in an array where we can jump according to valueNumber of groups formed in a graph of friendsMinimum cost to connect weighted nodes represented as arrayCount single node isolated sub-graphs in a disconnected graphCalculate number of nodes between two vertices in an acyclic Graph by Disjoint Union methodDynamic Connectivity | Set 1 (Incremental)Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)Check if removing a given edge disconnects a graphFind all reachable nodes from every node present in a given setConnected Components in an undirected graphk’th heaviest adjacent node in a graph where each vertex has weight"
},
{
"code": null,
"e": 39650,
"s": 39585,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 39683,
"s": 39650,
"text": "Connectivity in a directed graph"
},
{
"code": null,
"e": 39732,
"s": 39683,
"text": "Articulation Points (or Cut Vertices) in a Graph"
},
{
"code": null,
"e": 39755,
"s": 39732,
"text": "Biconnected Components"
},
{
"code": null,
"e": 39773,
"s": 39755,
"text": "Biconnected graph"
},
{
"code": null,
"e": 39792,
"s": 39773,
"text": "Bridges in a graph"
},
{
"code": null,
"e": 39818,
"s": 39792,
"text": "Eulerian path and circuit"
},
{
"code": null,
"e": 39875,
"s": 39818,
"text": "Fleury’s Algorithm for printing Eulerian Path or Circuit"
},
{
"code": null,
"e": 39905,
"s": 39875,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 39935,
"s": 39905,
"text": "Transitive closure of a graph"
},
{
"code": null,
"e": 39962,
"s": 39935,
"text": "Find the number of islands"
},
{
"code": null,
"e": 40018,
"s": 39962,
"text": "Find the number of Islands | Set 2 (Using Disjoint Set)"
},
{
"code": null,
"e": 40095,
"s": 40018,
"text": "Count all possible walks from a source to a destination with exactly k edges"
},
{
"code": null,
"e": 40129,
"s": 40095,
"text": "Euler Circuit in a Directed Graph"
},
{
"code": null,
"e": 40169,
"s": 40129,
"text": "Count the number of non-reachable nodes"
},
{
"code": null,
"e": 40219,
"s": 40169,
"text": "Find the Degree of a Particular vertex in a Graph"
},
{
"code": null,
"e": 40257,
"s": 40219,
"text": "Check if a given graph is tree or not"
},
{
"code": null,
"e": 40309,
"s": 40257,
"text": "Minimum edges required to add to make Euler Circuit"
},
{
"code": null,
"e": 40343,
"s": 40309,
"text": "Eulerian Path in undirected graph"
},
{
"code": null,
"e": 40389,
"s": 40343,
"text": "Find if there is a path of more than k length"
},
{
"code": null,
"e": 40439,
"s": 40389,
"text": "Length of shortest chain to reach the target word"
},
{
"code": null,
"e": 40490,
"s": 40439,
"text": "Print all paths from a given source to destination"
},
{
"code": null,
"e": 40541,
"s": 40490,
"text": "Find minimum cost to reach destination using train"
},
{
"code": null,
"e": 40609,
"s": 40541,
"text": "Find if an array of strings can be chained to form a circle | Set 1"
},
{
"code": null,
"e": 40677,
"s": 40609,
"text": "Find if an array of strings can be chained to form a circle | Set 2"
},
{
"code": null,
"e": 40734,
"s": 40677,
"text": "Tarjan’s Algorithm to find strongly connected Components"
},
{
"code": null,
"e": 40790,
"s": 40734,
"text": "Number of loops of size k starting from a specific node"
},
{
"code": null,
"e": 40864,
"s": 40790,
"text": "Paths to travel each nodes using each edge (Seven Bridges of Königsberg)"
},
{
"code": null,
"e": 40939,
"s": 40864,
"text": "Number of cyclic elements in an array where we can jump according to value"
},
{
"code": null,
"e": 40985,
"s": 40939,
"text": "Number of groups formed in a graph of friends"
},
{
"code": null,
"e": 41045,
"s": 40985,
"text": "Minimum cost to connect weighted nodes represented as array"
},
{
"code": null,
"e": 41107,
"s": 41045,
"text": "Count single node isolated sub-graphs in a disconnected graph"
},
{
"code": null,
"e": 41199,
"s": 41107,
"text": "Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method"
},
{
"code": null,
"e": 41242,
"s": 41199,
"text": "Dynamic Connectivity | Set 1 (Incremental)"
},
{
"code": null,
"e": 41310,
"s": 41242,
"text": "Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)"
},
{
"code": null,
"e": 41393,
"s": 41310,
"text": "Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)"
},
{
"code": null,
"e": 41444,
"s": 41393,
"text": "Check if removing a given edge disconnects a graph"
},
{
"code": null,
"e": 41508,
"s": 41444,
"text": "Find all reachable nodes from every node present in a given set"
},
{
"code": null,
"e": 41552,
"s": 41508,
"text": "Connected Components in an undirected graph"
},
{
"code": null,
"e": 41620,
"s": 41552,
"text": "k’th heaviest adjacent node in a graph where each vertex has weight"
},
{
"code": null,
"e": 41635,
"s": 41620,
"text": "Maximum Flow :"
},
{
"code": null,
"e": 42079,
"s": 41635,
"text": "Ford-Fulkerson Algorithm for Maximum Flow ProblemFind maximum number of edge disjoint paths between two verticesFind minimum s-t cut in a flow networkMaximum Bipartite MatchingChannel Assignment ProblemPush Relabel- Set 1-IntroductionPush Relabel- Set 2- ImplementationKarger’s Algorithm- Set 1- Introduction and ImplementationKarger’s Algorithm- Set 2 – Analysis and ApplicationsDinic’s algorithm for Maximum FlowMax Flow Problem Introduction"
},
{
"code": null,
"e": 42129,
"s": 42079,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 42193,
"s": 42129,
"text": "Find maximum number of edge disjoint paths between two vertices"
},
{
"code": null,
"e": 42232,
"s": 42193,
"text": "Find minimum s-t cut in a flow network"
},
{
"code": null,
"e": 42259,
"s": 42232,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 42286,
"s": 42259,
"text": "Channel Assignment Problem"
},
{
"code": null,
"e": 42319,
"s": 42286,
"text": "Push Relabel- Set 1-Introduction"
},
{
"code": null,
"e": 42355,
"s": 42319,
"text": "Push Relabel- Set 2- Implementation"
},
{
"code": null,
"e": 42414,
"s": 42355,
"text": "Karger’s Algorithm- Set 1- Introduction and Implementation"
},
{
"code": null,
"e": 42468,
"s": 42414,
"text": "Karger’s Algorithm- Set 2 – Analysis and Applications"
},
{
"code": null,
"e": 42503,
"s": 42468,
"text": "Dinic’s algorithm for Maximum Flow"
},
{
"code": null,
"e": 42533,
"s": 42503,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 42568,
"s": 42533,
"text": "STL Implementation of Algorithms :"
},
{
"code": null,
"e": 42836,
"s": 42568,
"text": "Kruskal’s Minimum Spanning Tree using STL in C++Prim’s Algorithm using Priority Queue STLDijkstra’s Shortest Path Algorithm using STLDijkstra’s Shortest Path Algorithm using set in STLGraph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 42885,
"s": 42836,
"text": "Kruskal’s Minimum Spanning Tree using STL in C++"
},
{
"code": null,
"e": 42927,
"s": 42885,
"text": "Prim’s Algorithm using Priority Queue STL"
},
{
"code": null,
"e": 42972,
"s": 42927,
"text": "Dijkstra’s Shortest Path Algorithm using STL"
},
{
"code": null,
"e": 43024,
"s": 42972,
"text": "Dijkstra’s Shortest Path Algorithm using set in STL"
},
{
"code": null,
"e": 43108,
"s": 43024,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 43124,
"s": 43108,
"text": "Hard Problems :"
},
{
"code": null,
"e": 43673,
"s": 43124,
"text": "Graph Coloring (Introduction and Applications)Greedy Algorithm for Graph ColoringTraveling Salesman Problem (TSP) ImplementationTravelling Salesman Problem (Naive and Dynamic Programming)Travelling Salesman Problem (Approximate using MST)Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)K Centers Problem | Set 1 (Greedy Approximate Algorithm)Erdos Renyl Model (for generating Random Graphs)Clustering Coefficient in Graph TheoryChinese Postman or Route Inspection | Set 1 (introduction)Hierholzer’s Algorithm for directed graph"
},
{
"code": null,
"e": 43720,
"s": 43673,
"text": "Graph Coloring (Introduction and Applications)"
},
{
"code": null,
"e": 43756,
"s": 43720,
"text": "Greedy Algorithm for Graph Coloring"
},
{
"code": null,
"e": 43804,
"s": 43756,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 43864,
"s": 43804,
"text": "Travelling Salesman Problem (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43916,
"s": 43864,
"text": "Travelling Salesman Problem (Approximate using MST)"
},
{
"code": null,
"e": 43986,
"s": 43916,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 44043,
"s": 43986,
"text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)"
},
{
"code": null,
"e": 44092,
"s": 44043,
"text": "Erdos Renyl Model (for generating Random Graphs)"
},
{
"code": null,
"e": 44131,
"s": 44092,
"text": "Clustering Coefficient in Graph Theory"
},
{
"code": null,
"e": 44190,
"s": 44131,
"text": "Chinese Postman or Route Inspection | Set 1 (introduction)"
},
{
"code": null,
"e": 44232,
"s": 44190,
"text": "Hierholzer’s Algorithm for directed graph"
},
{
"code": null,
"e": 44239,
"s": 44232,
"text": "Misc :"
},
{
"code": null,
"e": 45700,
"s": 44239,
"text": "Number of triangles in an undirected GraphNumber of triangles in directed and undirected GraphCheck whether a given graph is Bipartite or notSnake and Ladder ProblemMinimize Cash Flow among a given set of friends who have borrowed money from each otherBoggle (Find all possible words in a board of characters)Hopcroft Karp Algorithm for Maximum Matching-IntroductionHopcroft Karp Algorithm for Maximum Matching-ImplementationMinimum Time to rot all orangesFind same contents in a list of contactsHypercube GraphCheck for star graphOptimal read list for a given number of daysPrint all jumping numbers smaller than or equal to a given valueFibonacci Cube GraphBarabasi Albert Graph (for Scale Free Models)Construct a graph from given degrees of all verticesDegree Centrality (Centrality Measure)Katz Centrality (Centrality Measure)Mathematics | Graph theory practice questions2-Satisfiability (2-SAT) ProblemDetermine whether a universal sink exists in a directed graphNumber of sink nodes in a graphLargest subset of Graph vertices with edges of 2 or more colorsNetworkX : Python software package for study of complex networksGenerate a graph using Dictionary in PythonCount number of edges in an undirected graphTwo Clique Problem (Check if Graph can be divided in two Cliques)Check whether given degrees of vertices represent a Graph or TreeFinding minimum vertex cover size of a graph using binary searchStable Marriage ProblemSum of dependencies in a graph"
},
{
"code": null,
"e": 45743,
"s": 45700,
"text": "Number of triangles in an undirected Graph"
},
{
"code": null,
"e": 45796,
"s": 45743,
"text": "Number of triangles in directed and undirected Graph"
},
{
"code": null,
"e": 45844,
"s": 45796,
"text": "Check whether a given graph is Bipartite or not"
},
{
"code": null,
"e": 45869,
"s": 45844,
"text": "Snake and Ladder Problem"
},
{
"code": null,
"e": 45957,
"s": 45869,
"text": "Minimize Cash Flow among a given set of friends who have borrowed money from each other"
},
{
"code": null,
"e": 46015,
"s": 45957,
"text": "Boggle (Find all possible words in a board of characters)"
},
{
"code": null,
"e": 46073,
"s": 46015,
"text": "Hopcroft Karp Algorithm for Maximum Matching-Introduction"
},
{
"code": null,
"e": 46133,
"s": 46073,
"text": "Hopcroft Karp Algorithm for Maximum Matching-Implementation"
},
{
"code": null,
"e": 46165,
"s": 46133,
"text": "Minimum Time to rot all oranges"
},
{
"code": null,
"e": 46206,
"s": 46165,
"text": "Find same contents in a list of contacts"
},
{
"code": null,
"e": 46222,
"s": 46206,
"text": "Hypercube Graph"
},
{
"code": null,
"e": 46243,
"s": 46222,
"text": "Check for star graph"
},
{
"code": null,
"e": 46288,
"s": 46243,
"text": "Optimal read list for a given number of days"
},
{
"code": null,
"e": 46353,
"s": 46288,
"text": "Print all jumping numbers smaller than or equal to a given value"
},
{
"code": null,
"e": 46374,
"s": 46353,
"text": "Fibonacci Cube Graph"
},
{
"code": null,
"e": 46420,
"s": 46374,
"text": "Barabasi Albert Graph (for Scale Free Models)"
},
{
"code": null,
"e": 46473,
"s": 46420,
"text": "Construct a graph from given degrees of all vertices"
},
{
"code": null,
"e": 46512,
"s": 46473,
"text": "Degree Centrality (Centrality Measure)"
},
{
"code": null,
"e": 46549,
"s": 46512,
"text": "Katz Centrality (Centrality Measure)"
},
{
"code": null,
"e": 46595,
"s": 46549,
"text": "Mathematics | Graph theory practice questions"
},
{
"code": null,
"e": 46628,
"s": 46595,
"text": "2-Satisfiability (2-SAT) Problem"
},
{
"code": null,
"e": 46690,
"s": 46628,
"text": "Determine whether a universal sink exists in a directed graph"
},
{
"code": null,
"e": 46722,
"s": 46690,
"text": "Number of sink nodes in a graph"
},
{
"code": null,
"e": 46786,
"s": 46722,
"text": "Largest subset of Graph vertices with edges of 2 or more colors"
},
{
"code": null,
"e": 46851,
"s": 46786,
"text": "NetworkX : Python software package for study of complex networks"
},
{
"code": null,
"e": 46895,
"s": 46851,
"text": "Generate a graph using Dictionary in Python"
},
{
"code": null,
"e": 46940,
"s": 46895,
"text": "Count number of edges in an undirected graph"
},
{
"code": null,
"e": 47006,
"s": 46940,
"text": "Two Clique Problem (Check if Graph can be divided in two Cliques)"
},
{
"code": null,
"e": 47072,
"s": 47006,
"text": "Check whether given degrees of vertices represent a Graph or Tree"
},
{
"code": null,
"e": 47137,
"s": 47072,
"text": "Finding minimum vertex cover size of a graph using binary search"
},
{
"code": null,
"e": 47161,
"s": 47137,
"text": "Stable Marriage Problem"
},
{
"code": null,
"e": 47192,
"s": 47161,
"text": "Sum of dependencies in a graph"
},
{
"code": null,
"e": 47206,
"s": 47192,
"text": "Quick Links :"
},
{
"code": null,
"e": 47261,
"s": 47206,
"text": "Top 10 Interview Questions on Depth First Search (DFS)"
},
{
"code": null,
"e": 47302,
"s": 47261,
"text": "Some interesting shortest path questions"
},
{
"code": null,
"e": 47329,
"s": 47302,
"text": "Quizzes on Graph Traversal"
},
{
"code": null,
"e": 47360,
"s": 47329,
"text": "Quizzes on Graph Shortest Path"
},
{
"code": null,
"e": 47399,
"s": 47360,
"text": "Quizzes on Graph Minimum Spanning Tree"
},
{
"code": null,
"e": 47417,
"s": 47399,
"text": "Quizzes on Graphs"
},
{
"code": null,
"e": 47445,
"s": 47417,
"text": "Practice Problems on Graphs"
},
{
"code": null,
"e": 47462,
"s": 47445,
"text": "Videos on Graphs"
},
{
"code": null,
"e": 47781,
"s": 47462,
"text": "1. Language Foundation Courses [C++ / JAVA / Python ]Learn any programming language from scratch and understand all its fundamentals concepts for a strong programming foundation in the easiest possible manner with help of GeeksforGeeks Language Foundation Courses – Java Foundation | Python Foundation | C++ Foundation"
},
{
"code": null,
"e": 48083,
"s": 47781,
"text": "2. Geeks Classes LiveGet interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session"
},
{
"code": null,
"e": 48373,
"s": 48083,
"text": "3. Complete Interview PreparationGet fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices."
},
{
"code": null,
"e": 48665,
"s": 48373,
"text": "4. DSA Self PacedStart learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience."
},
{
"code": null,
"e": 48966,
"s": 48665,
"text": "5. Company Specific Courses – Amazon, Microsoft, TCS & WiproCrack the interview of any product-based giant company by specifically preparing with the questions that these companies usually ask in their coding interview round. Refer GeeksforGeeks Company Specific Courses: Amazon SDE Test Series, etc."
},
{
"code": null,
"e": 49091,
"s": 48966,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 49189,
"s": 49091,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 49263,
"s": 49189,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 49316,
"s": 49263,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 49348,
"s": 49316,
"text": "Floyd’s Cycle Finding Algorithm"
},
{
"code": null,
"e": 49418,
"s": 49348,
"text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!"
},
{
"code": null,
"e": 49444,
"s": 49418,
"text": "Spring Boot - Annotations"
},
{
"code": null,
"e": 49502,
"s": 49444,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 49533,
"s": 49502,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 49581,
"s": 49533,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 49608,
"s": 49581,
"text": "ReactJS useNavigate() Hook"
}
] |
How to run PowerShell commands in Background?
|
To run commands in the background in the PowerShell, you need to use Background job cmdlets. Background job means running commands/job in the background without occupying the console.
Start-Job is one of the job scheduler cmdlets for PowerShell which runs PowerShell commands in the background without interacting with the current user session as a Job so that users can work in the PowerShell console without losing the control of the console while the command is running in the background.
When PowerShell's job starts using Start-Job, a job returns the object immediately even if the job takes an extended time.
Start-Job is designed to run on the local computer because it doesn’t have the remote job parameter. To run the job remotely you need to use Invoke-Command with -AsJob parameter.
Start-Job -ScriptBlock{Get-EventLog -LogName System}
Once you run the command, the below output will be generated immediately.
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
1 Job1 BackgroundJob Running True localhost
If you check the above output, the job state is running. More commands you specify in the scriptblock, more PowerShell jobs run in the background, and more memory consumes.
To run multiple commands,
Start-Job -ScriptBlock{Get-EventLog -LogName System; Get-Process}
You can also use Invoke-Command to run the Job in the background with -AsJob parameter. As InvokeCommand is designed to run commands on the remote computers, you can run background jobs for the remote servers.
$sb = {Get-EventLog -LogName System; Get-Process}
Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb -AsJob
You can also specify the name of the job using -JobName parameter.
$sb = {Get-EventLog -LogName System; Get-Process}
Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb -
AsJob -JobName NewJob
To check the Job status, use Get-Job command.
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
21 NewJob RemoteJob Running True Test1-Win2k16,Te
The above output is truncated.
Every job has at least one parent job and a child job. The number of child jobs running in the background depends on the number of remote computers. To get all the child jobs, use -IncludeChildJob parameter in Get-Job cmdlet.
Get-Job -IncludeChildJob
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
21 NewJob RemoteJob Completed True Test1-Win2k16,T...
22 Job22 Completed True Test1-Win2k16
23 Job23 Completed True Test1-Win2k12
By the time we ran above command, the job is completed and the same can be visible in State property. Here 22 and 23 job IDs are child jobs which are running on the remote computers and 21 is the parent job.
To get the job output immediately after the job is scheduled, the Receive-Job command is used. This command can be run even the Job status is running.
You need to use Receive-Job command with Job with Name, ID, Job name variable, or any other supported parameter.
Start-Job -Command {Get-Service Spooler, W32Time}
Receive-Job -Name Job5
To retrieve job using ID,
Receive-Job -ID 5
|
[
{
"code": null,
"e": 1371,
"s": 1187,
"text": "To run commands in the background in the PowerShell, you need to use Background job cmdlets. Background job means running commands/job in the background without occupying the console."
},
{
"code": null,
"e": 1679,
"s": 1371,
"text": "Start-Job is one of the job scheduler cmdlets for PowerShell which runs PowerShell commands in the background without interacting with the current user session as a Job so that users can work in the PowerShell console without losing the control of the console while the command is running in the background."
},
{
"code": null,
"e": 1802,
"s": 1679,
"text": "When PowerShell's job starts using Start-Job, a job returns the object immediately even if the job takes an extended time."
},
{
"code": null,
"e": 1981,
"s": 1802,
"text": "Start-Job is designed to run on the local computer because it doesn’t have the remote job parameter. To run the job remotely you need to use Invoke-Command with -AsJob parameter."
},
{
"code": null,
"e": 2034,
"s": 1981,
"text": "Start-Job -ScriptBlock{Get-EventLog -LogName System}"
},
{
"code": null,
"e": 2108,
"s": 2034,
"text": "Once you run the command, the below output will be generated immediately."
},
{
"code": null,
"e": 2300,
"s": 2108,
"text": "Id Name PSJobTypeName State HasMoreData Location\n-- ---- ------------- ----- ----------- --------\n1 Job1 BackgroundJob Running True localhost"
},
{
"code": null,
"e": 2473,
"s": 2300,
"text": "If you check the above output, the job state is running. More commands you specify in the scriptblock, more PowerShell jobs run in the background, and more memory consumes."
},
{
"code": null,
"e": 2499,
"s": 2473,
"text": "To run multiple commands,"
},
{
"code": null,
"e": 2565,
"s": 2499,
"text": "Start-Job -ScriptBlock{Get-EventLog -LogName System; Get-Process}"
},
{
"code": null,
"e": 2775,
"s": 2565,
"text": "You can also use Invoke-Command to run the Job in the background with -AsJob parameter. As InvokeCommand is designed to run commands on the remote computers, you can run background jobs for the remote servers."
},
{
"code": null,
"e": 2906,
"s": 2775,
"text": "$sb = {Get-EventLog -LogName System; Get-Process}\nInvoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb -AsJob"
},
{
"code": null,
"e": 2973,
"s": 2906,
"text": "You can also specify the name of the job using -JobName parameter."
},
{
"code": null,
"e": 3121,
"s": 2973,
"text": "$sb = {Get-EventLog -LogName System; Get-Process}\nInvoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb -\nAsJob -JobName NewJob"
},
{
"code": null,
"e": 3167,
"s": 3121,
"text": "To check the Job status, use Get-Job command."
},
{
"code": null,
"e": 3365,
"s": 3167,
"text": "Id Name PSJobTypeName State HasMoreData Location\n-- ---- ------------- ----- ----------- --------\n21 NewJob RemoteJob Running True Test1-Win2k16,Te"
},
{
"code": null,
"e": 3396,
"s": 3365,
"text": "The above output is truncated."
},
{
"code": null,
"e": 3622,
"s": 3396,
"text": "Every job has at least one parent job and a child job. The number of child jobs running in the background depends on the number of remote computers. To get all the child jobs, use -IncludeChildJob parameter in Get-Job cmdlet."
},
{
"code": null,
"e": 3647,
"s": 3622,
"text": "Get-Job -IncludeChildJob"
},
{
"code": null,
"e": 3981,
"s": 3647,
"text": "Id Name PSJobTypeName State HasMoreData Location\n-- ---- ------------- ----- ----------- --------\n21 NewJob RemoteJob Completed True Test1-Win2k16,T...\n22 Job22 Completed True Test1-Win2k16\n23 Job23 Completed True Test1-Win2k12"
},
{
"code": null,
"e": 4189,
"s": 3981,
"text": "By the time we ran above command, the job is completed and the same can be visible in State property. Here 22 and 23 job IDs are child jobs which are running on the remote computers and 21 is the parent job."
},
{
"code": null,
"e": 4340,
"s": 4189,
"text": "To get the job output immediately after the job is scheduled, the Receive-Job command is used. This command can be run even the Job status is running."
},
{
"code": null,
"e": 4453,
"s": 4340,
"text": "You need to use Receive-Job command with Job with Name, ID, Job name variable, or any other supported parameter."
},
{
"code": null,
"e": 4526,
"s": 4453,
"text": "Start-Job -Command {Get-Service Spooler, W32Time}\nReceive-Job -Name Job5"
},
{
"code": null,
"e": 4552,
"s": 4526,
"text": "To retrieve job using ID,"
},
{
"code": null,
"e": 4570,
"s": 4552,
"text": "Receive-Job -ID 5"
}
] |
Payload in Computer Networks
|
19 Oct, 2020
Payload During the transmission of the data with the Internet Protocol from the sender to receiver. Data is sent in terms of packets and individual packets contain a header and the data which is sent by the sender this data is called Payload. Headers are appended to the payload for transport and then discarded when they successfully reach their destination. The main their source of transfer Virus is Payload
IPv6 :
This is the format of the latest IPv6 Header Format. The length of the payload is 16bits.
Payload length :
The Payload Length column shows the length of the data payload in 1Pv6.The Payload Length field is the length of the IPv6 in the above diagram not including the length of the header Hop limit but these fields are in the Payload Length field.The 16-bits size of this field limits its maximum value to 65,535 (64KB), which applies to the payload length.
The Payload Length column shows the length of the data payload in 1Pv6.
The Payload Length field is the length of the IPv6 in the above diagram not including the length of the header Hop limit but these fields are in the Payload Length field.
The 16-bits size of this field limits its maximum value to 65,535 (64KB), which applies to the payload length.
IPv4 :
Length of entire IP Packet (including IP header and IP Payload).
IP packet encapsulates the data unit received from the network layer and adds to its own header information. The encapsulated data is referred to as IP Payload.
16-bits size of this field length.
Examples of the Payload :
In Programming sending the data is terms of JSON Format and XML Format :{ “data”: { “message”: “Welcome, GFG!” } } In the Internet, Security Payload is like the most important tool for hackers after finding the vulnerability of a particular System they execute malware and called Malware Payload. They distribute with the help of Phishing email and they bind the payload with some other application. Today’s Hacker encrypts the payload so that Internet Security and System Security cannot able to find the signature of the Payload.Payloads include data destruction, messages with insulting text, or bulk email messages sent to a large number of people.
In Programming sending the data is terms of JSON Format and XML Format :{ “data”: { “message”: “Welcome, GFG!” } }
{ “data”: { “message”: “Welcome, GFG!” } }
In the Internet, Security Payload is like the most important tool for hackers after finding the vulnerability of a particular System they execute malware and called Malware Payload. They distribute with the help of Phishing email and they bind the payload with some other application. Today’s Hacker encrypts the payload so that Internet Security and System Security cannot able to find the signature of the Payload.
Payloads include data destruction, messages with insulting text, or bulk email messages sent to a large number of people.
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Oct, 2020"
},
{
"code": null,
"e": 463,
"s": 52,
"text": "Payload During the transmission of the data with the Internet Protocol from the sender to receiver. Data is sent in terms of packets and individual packets contain a header and the data which is sent by the sender this data is called Payload. Headers are appended to the payload for transport and then discarded when they successfully reach their destination. The main their source of transfer Virus is Payload"
},
{
"code": null,
"e": 470,
"s": 463,
"text": "IPv6 :"
},
{
"code": null,
"e": 560,
"s": 470,
"text": "This is the format of the latest IPv6 Header Format. The length of the payload is 16bits."
},
{
"code": null,
"e": 577,
"s": 560,
"text": "Payload length :"
},
{
"code": null,
"e": 929,
"s": 577,
"text": "The Payload Length column shows the length of the data payload in 1Pv6.The Payload Length field is the length of the IPv6 in the above diagram not including the length of the header Hop limit but these fields are in the Payload Length field.The 16-bits size of this field limits its maximum value to 65,535 (64KB), which applies to the payload length."
},
{
"code": null,
"e": 1001,
"s": 929,
"text": "The Payload Length column shows the length of the data payload in 1Pv6."
},
{
"code": null,
"e": 1172,
"s": 1001,
"text": "The Payload Length field is the length of the IPv6 in the above diagram not including the length of the header Hop limit but these fields are in the Payload Length field."
},
{
"code": null,
"e": 1283,
"s": 1172,
"text": "The 16-bits size of this field limits its maximum value to 65,535 (64KB), which applies to the payload length."
},
{
"code": null,
"e": 1290,
"s": 1283,
"text": "IPv4 :"
},
{
"code": null,
"e": 1355,
"s": 1290,
"text": "Length of entire IP Packet (including IP header and IP Payload)."
},
{
"code": null,
"e": 1516,
"s": 1355,
"text": "IP packet encapsulates the data unit received from the network layer and adds to its own header information. The encapsulated data is referred to as IP Payload."
},
{
"code": null,
"e": 1551,
"s": 1516,
"text": "16-bits size of this field length."
},
{
"code": null,
"e": 1577,
"s": 1551,
"text": "Examples of the Payload :"
},
{
"code": null,
"e": 2230,
"s": 1577,
"text": "In Programming sending the data is terms of JSON Format and XML Format :{ “data”: { “message”: “Welcome, GFG!” } } In the Internet, Security Payload is like the most important tool for hackers after finding the vulnerability of a particular System they execute malware and called Malware Payload. They distribute with the help of Phishing email and they bind the payload with some other application. Today’s Hacker encrypts the payload so that Internet Security and System Security cannot able to find the signature of the Payload.Payloads include data destruction, messages with insulting text, or bulk email messages sent to a large number of people."
},
{
"code": null,
"e": 2346,
"s": 2230,
"text": "In Programming sending the data is terms of JSON Format and XML Format :{ “data”: { “message”: “Welcome, GFG!” } } "
},
{
"code": null,
"e": 2390,
"s": 2346,
"text": "{ “data”: { “message”: “Welcome, GFG!” } } "
},
{
"code": null,
"e": 2807,
"s": 2390,
"text": "In the Internet, Security Payload is like the most important tool for hackers after finding the vulnerability of a particular System they execute malware and called Malware Payload. They distribute with the help of Phishing email and they bind the payload with some other application. Today’s Hacker encrypts the payload so that Internet Security and System Security cannot able to find the signature of the Payload."
},
{
"code": null,
"e": 2929,
"s": 2807,
"text": "Payloads include data destruction, messages with insulting text, or bulk email messages sent to a large number of people."
},
{
"code": null,
"e": 2947,
"s": 2929,
"text": "Computer Networks"
},
{
"code": null,
"e": 2955,
"s": 2947,
"text": "GATE CS"
},
{
"code": null,
"e": 2973,
"s": 2955,
"text": "Computer Networks"
},
{
"code": null,
"e": 3071,
"s": 2973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3101,
"s": 3071,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 3127,
"s": 3101,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 3157,
"s": 3127,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 3197,
"s": 3157,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 3243,
"s": 3197,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 3267,
"s": 3243,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 3294,
"s": 3267,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 3315,
"s": 3294,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 3364,
"s": 3315,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
SQL MIN() and MAX()
|
14 Aug, 2020
SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)
FROM table_name
WHERE condition;
SQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)
FROM table_name
WHERE condition;
SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)
FROM table_name
WHERE condition;
MIN() Syntax –
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)
FROM table_name
WHERE condition;
MAX() Syntax –
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Let us assume, we have below table “GeeksTable” :
MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750
MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900
SELECT MIN(Salary) FROM GeeksTable;
Output –
2900
MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750
SELECT MAX(Price) FROM GeeksTable;
Output –
8750
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 344,
"s": 28,
"text": "SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)\nFROM table_name\nWHERE condition;\nSQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 503,
"s": 344,
"text": "SQL MIN() FunctionsThe MIN() function provides the smallest value of the chosen column.MIN() Syntax –SELECT MIN(column_name)\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 518,
"s": 503,
"text": "MIN() Syntax –"
},
{
"code": null,
"e": 576,
"s": 518,
"text": "SELECT MIN(column_name)\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 734,
"s": 576,
"text": "SQL MAX() FunctionsThe MAX() function provides the largest value of the chosen column.MAX() Syntax –SELECT MAX(column_name)\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 749,
"s": 734,
"text": "MAX() Syntax –"
},
{
"code": null,
"e": 807,
"s": 749,
"text": "SELECT MAX(column_name)\nFROM table_name\nWHERE condition;\n"
},
{
"code": null,
"e": 857,
"s": 807,
"text": "Let us assume, we have below table “GeeksTable” :"
},
{
"code": null,
"e": 1098,
"s": 857,
"text": "MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750\n"
},
{
"code": null,
"e": 1222,
"s": 1098,
"text": "MIN() Example :The following SQL statement finds the lowest salary product :SELECT MIN(Salary) FROM GeeksTable;Output –2900"
},
{
"code": null,
"e": 1258,
"s": 1222,
"text": "SELECT MIN(Salary) FROM GeeksTable;"
},
{
"code": null,
"e": 1267,
"s": 1258,
"text": "Output –"
},
{
"code": null,
"e": 1272,
"s": 1267,
"text": "2900"
},
{
"code": null,
"e": 1390,
"s": 1272,
"text": "MAX() Example :The following SQL statement finds the highest salary :SELECT MAX(Price) FROM GeeksTable; Output –8750\n"
},
{
"code": null,
"e": 1426,
"s": 1390,
"text": "SELECT MAX(Price) FROM GeeksTable; "
},
{
"code": null,
"e": 1435,
"s": 1426,
"text": "Output –"
},
{
"code": null,
"e": 1441,
"s": 1435,
"text": "8750\n"
},
{
"code": null,
"e": 1450,
"s": 1441,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1454,
"s": 1450,
"text": "SQL"
},
{
"code": null,
"e": 1458,
"s": 1454,
"text": "SQL"
},
{
"code": null,
"e": 1556,
"s": 1458,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1622,
"s": 1556,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1646,
"s": 1622,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1679,
"s": 1646,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1711,
"s": 1679,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1728,
"s": 1711,
"text": "SQL using Python"
},
{
"code": null,
"e": 1806,
"s": 1728,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 1842,
"s": 1806,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 1872,
"s": 1842,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 1903,
"s": 1872,
"text": "SQL Query to Compare Two Dates"
}
] |
Python hash() method
|
17 Sep, 2021
Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary.
Syntax : hash(obj)
Parameters : obj : The object which we need to convert into hash.
Returns : Returns the hashed value if possible.
Objects hashed using hash() are irreversible, leading to loss of information.
hash() returns hashed value only for immutable objects, hence can be used as an indicator to check for mutable/immutable objects.
Python3
# Python 3 code to demonstrate# working of hash() # initializing objectsint_val = 4str_val = 'GeeksforGeeks'flt_val = 24.56 # Printing the hash values.# Notice Integer value doesn't change# You'l have answer later in article.print("The integer hash value is : " + str(hash(int_val)))print("The string hash value is : " + str(hash(str_val)))print("The float hash value is : " + str(hash(flt_val)))
Output:
The integer hash value is : 4
The string hash value is : -5570917502994512005
The float hash value is : 1291272085159665688
Python3
# Python 3 code to demonstrate# property of hash() # initializing objects# tuple are immutabletuple_val = (1, 2, 3, 4, 5) # list are mutablelist_val = [1, 2, 3, 4, 5] # Printing the hash values.# Notice exception when trying# to convert mutable objectprint("The tuple hash value is : " + str(hash(tuple_val)))print("The list hash value is : " + str(hash(list_val)))
Output:
The tuple hash value is : 8315274433719620810
Exceptions :
Traceback (most recent call last):
File "/home/eb7e39084e3d151114ce5ed3e43babb8.py", line 15, in
print ("The list hash value is : " + str(hash(list_val)))
TypeError: unhashable type: 'list'
Python3
# hash() for immutable tuple objectvar = ('G','E','E','K') print(hash(var))
Output:
5434435027328283763
hash() method used by on immutable object, if we use this on a mutable object like list, set, dictionaries then it will generate an error.
Python3
l = [1, 2, 3, 4]print(hash(l))
Output:
TypeError: unhashable type: 'list'
Here we will override the __hash()__ methods to call the hash(), and __eq__() method will check the equality of the two custom objects.
Python3
class Emp: def __init__(self, emp_name, id): self.emp_name = emp_name self.id = id def __eq__(self, other): # Equality Comparison between two objects return self.emp_name == other.emp_name and self.id == other.id def __hash__(self): # hash(custom_object) return hash((self.emp_name, self.id)) emp = Emp('Ragav', 12)print("The hash is: %d" % hash(emp)) # We'll check if two objects with the same# attribute values have the same hashemp_copy = Emp('Ragav', 12)print("The hash is: %d" % hash(emp_copy))
Output:
The hash is: -674930604243231063
The hash is: -674930604243231063
WaahModiJiWaah
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 264,
"s": 54,
"text": "Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary."
},
{
"code": null,
"e": 283,
"s": 264,
"text": "Syntax : hash(obj)"
},
{
"code": null,
"e": 350,
"s": 283,
"text": "Parameters : obj : The object which we need to convert into hash."
},
{
"code": null,
"e": 399,
"s": 350,
"text": "Returns : Returns the hashed value if possible. "
},
{
"code": null,
"e": 477,
"s": 399,
"text": "Objects hashed using hash() are irreversible, leading to loss of information."
},
{
"code": null,
"e": 607,
"s": 477,
"text": "hash() returns hashed value only for immutable objects, hence can be used as an indicator to check for mutable/immutable objects."
},
{
"code": null,
"e": 615,
"s": 607,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# working of hash() # initializing objectsint_val = 4str_val = 'GeeksforGeeks'flt_val = 24.56 # Printing the hash values.# Notice Integer value doesn't change# You'l have answer later in article.print(\"The integer hash value is : \" + str(hash(int_val)))print(\"The string hash value is : \" + str(hash(str_val)))print(\"The float hash value is : \" + str(hash(flt_val)))",
"e": 1012,
"s": 615,
"text": null
},
{
"code": null,
"e": 1021,
"s": 1012,
"text": "Output: "
},
{
"code": null,
"e": 1145,
"s": 1021,
"text": "The integer hash value is : 4\nThe string hash value is : -5570917502994512005\nThe float hash value is : 1291272085159665688"
},
{
"code": null,
"e": 1153,
"s": 1145,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# property of hash() # initializing objects# tuple are immutabletuple_val = (1, 2, 3, 4, 5) # list are mutablelist_val = [1, 2, 3, 4, 5] # Printing the hash values.# Notice exception when trying# to convert mutable objectprint(\"The tuple hash value is : \" + str(hash(tuple_val)))print(\"The list hash value is : \" + str(hash(list_val)))",
"e": 1519,
"s": 1153,
"text": null
},
{
"code": null,
"e": 1528,
"s": 1519,
"text": "Output: "
},
{
"code": null,
"e": 1574,
"s": 1528,
"text": "The tuple hash value is : 8315274433719620810"
},
{
"code": null,
"e": 1588,
"s": 1574,
"text": "Exceptions : "
},
{
"code": null,
"e": 1785,
"s": 1588,
"text": "Traceback (most recent call last):\n File \"/home/eb7e39084e3d151114ce5ed3e43babb8.py\", line 15, in \n print (\"The list hash value is : \" + str(hash(list_val)))\nTypeError: unhashable type: 'list'"
},
{
"code": null,
"e": 1793,
"s": 1785,
"text": "Python3"
},
{
"code": "# hash() for immutable tuple objectvar = ('G','E','E','K') print(hash(var))",
"e": 1869,
"s": 1793,
"text": null
},
{
"code": null,
"e": 1877,
"s": 1869,
"text": "Output:"
},
{
"code": null,
"e": 1897,
"s": 1877,
"text": "5434435027328283763"
},
{
"code": null,
"e": 2036,
"s": 1897,
"text": "hash() method used by on immutable object, if we use this on a mutable object like list, set, dictionaries then it will generate an error."
},
{
"code": null,
"e": 2044,
"s": 2036,
"text": "Python3"
},
{
"code": "l = [1, 2, 3, 4]print(hash(l))",
"e": 2075,
"s": 2044,
"text": null
},
{
"code": null,
"e": 2083,
"s": 2075,
"text": "Output:"
},
{
"code": null,
"e": 2118,
"s": 2083,
"text": "TypeError: unhashable type: 'list'"
},
{
"code": null,
"e": 2254,
"s": 2118,
"text": "Here we will override the __hash()__ methods to call the hash(), and __eq__() method will check the equality of the two custom objects."
},
{
"code": null,
"e": 2262,
"s": 2254,
"text": "Python3"
},
{
"code": "class Emp: def __init__(self, emp_name, id): self.emp_name = emp_name self.id = id def __eq__(self, other): # Equality Comparison between two objects return self.emp_name == other.emp_name and self.id == other.id def __hash__(self): # hash(custom_object) return hash((self.emp_name, self.id)) emp = Emp('Ragav', 12)print(\"The hash is: %d\" % hash(emp)) # We'll check if two objects with the same# attribute values have the same hashemp_copy = Emp('Ragav', 12)print(\"The hash is: %d\" % hash(emp_copy))",
"e": 2829,
"s": 2262,
"text": null
},
{
"code": null,
"e": 2837,
"s": 2829,
"text": "Output:"
},
{
"code": null,
"e": 2903,
"s": 2837,
"text": "The hash is: -674930604243231063\nThe hash is: -674930604243231063"
},
{
"code": null,
"e": 2918,
"s": 2903,
"text": "WaahModiJiWaah"
},
{
"code": null,
"e": 2931,
"s": 2918,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2957,
"s": 2931,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2964,
"s": 2957,
"text": "Python"
},
{
"code": null,
"e": 3062,
"s": 2964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3080,
"s": 3062,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3122,
"s": 3080,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3144,
"s": 3122,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3170,
"s": 3144,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3202,
"s": 3170,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3231,
"s": 3202,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3258,
"s": 3231,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3294,
"s": 3258,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3325,
"s": 3294,
"text": "Python | os.path.join() method"
}
] |
Servlets - Form Data
|
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? (question mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.
A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.
Servlets handles form data parsing automatically using the following methods depending on the situation −
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
Here is a simple URL which will pass two values to HelloForm program using GET method.
Given below is the HelloForm.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
}
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser's Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result −
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
First Name: ZARA
Last Name: ALI
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same Servlet HelloForm to handle this input.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.
Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows −
<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action = "CheckBox" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" />
Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
The result of this code is the following form
Given below is the CheckBox.java servlet program to handle input given by web browser for checkbox button.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CheckBox extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Checkbox Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
For the above example, it would display following result −
Reading Checkbox Data
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order
Once we have an Enumeration, we can loop down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ReadParams extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now, try the above servlet with the following form −
<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
Now calling servlet using the above form would generate the following result −
Reading All Form Parameters
Param Name
Param Value(s)
maths
on
chemistry
on
You can try the above servlet to read any other form's data having other objects like text box, radio button or drop down box etc.
|
[
{
"code": null,
"e": 2587,
"s": 2319,
"text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method."
},
{
"code": null,
"e": 2763,
"s": 2587,
"text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? (question mark) symbol as follows −"
},
{
"code": null,
"e": 2818,
"s": 2763,
"text": "http://www.test.com/hello?key1 = value1&key2 = value2\n"
},
{
"code": null,
"e": 3167,
"s": 2818,
"text": "The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be used in a request string."
},
{
"code": null,
"e": 3349,
"s": 3167,
"text": "This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method."
},
{
"code": null,
"e": 3816,
"s": 3349,
"text": "A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method."
},
{
"code": null,
"e": 3922,
"s": 3816,
"text": "Servlets handles form data parsing automatically using the following methods depending on the situation −"
},
{
"code": null,
"e": 4016,
"s": 3922,
"text": "getParameter() − You call request.getParameter() method to get the value of a form parameter."
},
{
"code": null,
"e": 4110,
"s": 4016,
"text": "getParameter() − You call request.getParameter() method to get the value of a form parameter."
},
{
"code": null,
"e": 4241,
"s": 4110,
"text": "getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox."
},
{
"code": null,
"e": 4372,
"s": 4241,
"text": "getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox."
},
{
"code": null,
"e": 4481,
"s": 4372,
"text": "getParameterNames() − Call this method if you want a complete list of all parameters in the current request."
},
{
"code": null,
"e": 4590,
"s": 4481,
"text": "getParameterNames() − Call this method if you want a complete list of all parameters in the current request."
},
{
"code": null,
"e": 4677,
"s": 4590,
"text": "Here is a simple URL which will pass two values to HelloForm program using GET method."
},
{
"code": null,
"e": 4863,
"s": 4677,
"text": "Given below is the HelloForm.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information −"
},
{
"code": null,
"e": 6027,
"s": 4863,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\n// Extend HttpServlet class\npublic class HelloForm extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Using GET Method to Read Form Data\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<ul>\\n\" +\n \" <li><b>First Name</b>: \"\n + request.getParameter(\"first_name\") + \"\\n\" +\n \" <li><b>Last Name</b>: \"\n + request.getParameter(\"last_name\") + \"\\n\" +\n \"</ul>\\n\" +\n \"</body>\" +\n \"</html>\"\n );\n }\n}"
},
{
"code": null,
"e": 6109,
"s": 6027,
"text": "Assuming your environment is set up properly, compile HelloForm.java as follows −"
},
{
"code": null,
"e": 6132,
"s": 6109,
"text": "$ javac HelloForm.java"
},
{
"code": null,
"e": 6428,
"s": 6132,
"text": "If everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/"
},
{
"code": null,
"e": 6656,
"s": 6428,
"text": "<servlet>\n <servlet-name>HelloForm</servlet-name>\n <servlet-class>HelloForm</servlet-class>\n</servlet>\n\n<servlet-mapping>\n <servlet-name>HelloForm</servlet-name>\n <url-pattern>/HelloForm</url-pattern>\n</servlet-mapping>"
},
{
"code": null,
"e": 6890,
"s": 6656,
"text": "Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser's Location:box and make sure you already started tomcat server, before firing above command in the browser. This would generate following result −"
},
{
"code": null,
"e": 6960,
"s": 6890,
"text": "Using GET Method to Read Form Data\n\nFirst Name: ZARA\nLast Name: ALI\n\n"
},
{
"code": null,
"e": 6977,
"s": 6960,
"text": "First Name: ZARA"
},
{
"code": null,
"e": 6992,
"s": 6977,
"text": "Last Name: ALI"
},
{
"code": null,
"e": 7141,
"s": 6992,
"text": "Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same Servlet HelloForm to handle this input."
},
{
"code": null,
"e": 7434,
"s": 7141,
"text": "<html>\n <body>\n <form action = \"HelloForm\" method = \"GET\">\n First Name: <input type = \"text\" name = \"first_name\">\n <br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 7638,
"s": 7434,
"text": "Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form."
},
{
"code": null,
"e": 7866,
"s": 7638,
"text": "Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example."
},
{
"code": null,
"e": 8073,
"s": 7866,
"text": "Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods."
},
{
"code": null,
"e": 9494,
"s": 8073,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\n// Extend HttpServlet class\npublic class HelloForm extends HttpServlet {\n\n // Method to handle GET method request.\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Using GET Method to Read Form Data\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" +\n \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<ul>\\n\" +\n \" <li><b>First Name</b>: \"\n + request.getParameter(\"first_name\") + \"\\n\" +\n \" <li><b>Last Name</b>: \"\n + request.getParameter(\"last_name\") + \"\\n\" +\n \"</ul>\\n\" +\n \"</body>\"\n \"</html>\"\n );\n }\n\n // Method to handle POST method request.\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n\n doGet(request, response);\n }\n}"
},
{
"code": null,
"e": 9597,
"s": 9494,
"text": "Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows −"
},
{
"code": null,
"e": 9891,
"s": 9597,
"text": "<html>\n <body>\n <form action = \"HelloForm\" method = \"POST\">\n First Name: <input type = \"text\" name = \"first_name\">\n <br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 10063,
"s": 9891,
"text": "Here is the actual output of the above form, Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running."
},
{
"code": null,
"e": 10161,
"s": 10063,
"text": "Based on the input provided, it would generate similar result as mentioned in the above examples."
},
{
"code": null,
"e": 10235,
"s": 10161,
"text": "Checkboxes are used when more than one option is required to be selected."
},
{
"code": null,
"e": 10307,
"s": 10235,
"text": "Here is example HTML code, CheckBox.htm, for a form with two checkboxes"
},
{
"code": null,
"e": 10754,
"s": 10307,
"text": "<html>\n <body>\n <form action = \"CheckBox\" method = \"POST\" target = \"_blank\">\n <input type = \"checkbox\" name = \"maths\" checked = \"checked\" /> Maths\n <input type = \"checkbox\" name = \"physics\" /> Physics\n <input type = \"checkbox\" name = \"chemistry\" checked = \"checked\" /> \n Chemistry\n <input type = \"submit\" value = \"Select Subject\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 10800,
"s": 10754,
"text": "The result of this code is the following form"
},
{
"code": null,
"e": 10907,
"s": 10800,
"text": "Given below is the CheckBox.java servlet program to handle input given by web browser for checkbox button."
},
{
"code": null,
"e": 12419,
"s": 10907,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\n// Extend HttpServlet class\npublic class CheckBox extends HttpServlet {\n \n // Method to handle GET method request.\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Reading Checkbox Data\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n\n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<ul>\\n\" +\n \" <li><b>Maths Flag : </b>: \"\n + request.getParameter(\"maths\") + \"\\n\" +\n \" <li><b>Physics Flag: </b>: \"\n + request.getParameter(\"physics\") + \"\\n\" +\n \" <li><b>Chemistry Flag: </b>: \"\n + request.getParameter(\"chemistry\") + \"\\n\" +\n \"</ul>\\n\" +\n \"</body>\"\n \"</html>\"\n );\n }\n\n // Method to handle POST method request.\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n doGet(request, response);\n }\n}"
},
{
"code": null,
"e": 12478,
"s": 12419,
"text": "For the above example, it would display following result −"
},
{
"code": null,
"e": 12563,
"s": 12478,
"text": "Reading Checkbox Data\n\nMaths Flag : : on\nPhysics Flag: : null\nChemistry Flag: : on\n\n"
},
{
"code": null,
"e": 12581,
"s": 12563,
"text": "Maths Flag : : on"
},
{
"code": null,
"e": 12602,
"s": 12581,
"text": "Physics Flag: : null"
},
{
"code": null,
"e": 12623,
"s": 12602,
"text": "Chemistry Flag: : on"
},
{
"code": null,
"e": 12852,
"s": 12623,
"text": "Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order"
},
{
"code": null,
"e": 13050,
"s": 12852,
"text": "Once we have an Enumeration, we can loop down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name."
},
{
"code": null,
"e": 15261,
"s": 13050,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\nimport java.util.*;\n\n// Extend HttpServlet class\npublic class ReadParams extends HttpServlet {\n \n // Method to handle GET method request.\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Reading All Form Parameters\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n\n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<table width = \\\"100%\\\" border = \\\"1\\\" align = \\\"center\\\">\\n\" +\n \"<tr bgcolor = \\\"#949494\\\">\\n\" +\n \"<th>Param Name</th>\"\n \"<th>Param Value(s)</th>\\n\"+\n \"</tr>\\n\"\n );\n\n Enumeration paramNames = request.getParameterNames();\n\n while(paramNames.hasMoreElements()) {\n String paramName = (String)paramNames.nextElement();\n out.print(\"<tr><td>\" + paramName + \"</td>\\n<td>\");\n String[] paramValues = request.getParameterValues(paramName);\n\n // Read single valued data\n if (paramValues.length == 1) {\n String paramValue = paramValues[0];\n if (paramValue.length() == 0)\n out.println(\"<i>No Value</i>\");\n else\n out.println(paramValue);\n } else {\n // Read multiple valued data\n out.println(\"<ul>\");\n\n for(int i = 0; i < paramValues.length; i++) {\n out.println(\"<li>\" + paramValues[i]);\n }\n out.println(\"</ul>\");\n }\n }\n out.println(\"</tr>\\n</table>\\n</body></html>\");\n }\n \n // Method to handle POST method request.\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n doGet(request, response);\n }\n}"
},
{
"code": null,
"e": 15314,
"s": 15261,
"text": "Now, try the above servlet with the following form −"
},
{
"code": null,
"e": 15715,
"s": 15314,
"text": "<html>\n <body>\n <form action = \"ReadParams\" method = \"POST\" target = \"_blank\">\n <input type = \"checkbox\" name = \"maths\" checked = \"checked\" /> Maths\n <input type = \"checkbox\" name = \"physics\" /> Physics\n <input type = \"checkbox\" name = \"chemistry\" checked = \"checked\" /> Chem\n <input type = \"submit\" value = \"Select Subject\" />\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 15794,
"s": 15715,
"text": "Now calling servlet using the above form would generate the following result −"
},
{
"code": null,
"e": 15879,
"s": 15794,
"text": "Reading All Form Parameters\n\n\nParam Name\nParam Value(s)\n\n\nmaths\non\n\n\nchemistry\non\n\n\n"
}
] |
Juggler Sequence
|
21 Jun, 2022
Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : Juggler Sequence starting with number 3: 5, 11, 36, 6, 2, 1Juggler Sequence starting with number 9: 9, 27, 140, 11, 36, 6, 2, 1Given a number n we have to print the Juggler Sequence for this number as the first term of the sequence. Examples:
Input: 9
Output: 9, 27, 140, 11, 36, 6, 2, 1
We start with 9 and use above formula to get
next terms.
Input: 6
Output: 6, 2, 1
C++
C
Java
Python3
C#
PHP
Javascript
// C++ implementation of Juggler Sequence#include <bits/stdc++.h>using namespace std; // This function prints the juggler Sequencevoid printJuggler(long long n){ long long a = n; // print the first term cout << a << " "; // calculate terms until // last term is not 1 while (a != 1) { long long b = 0; // Check if previous term // is even or odd if (a % 2 == 0) // calculate next term b = floor(sqrt(a)); else // for odd previous term // calculate next term b = floor(sqrt(a) * sqrt(a) * sqrt(a)); cout << b << " "; a = b; }} // Driver Codeint main(){ printJuggler(37); cout <<"\n"; printJuggler(9); return 0;} // This code is contributed by shubhamsingh10
// C implementation of Juggler Sequence#include<stdio.h>#include<math.h> // This function prints the juggler Sequencevoid printJuggler(int n){ int a = n; // print the first term printf("%d ", a); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = floor(sqrt(a)); else // for odd previous term calculate // next term b = floor(sqrt(a)*sqrt(a)*sqrt(a)); printf("%d ", b); a = b; }} //driver program to test above functionint main(){ printJuggler(3); printf("\n"); printJuggler(9); return 0;}
// Java implementation of Juggler Sequenceimport java.io.*;import java.math.*; class GFG { // This function prints the juggler Sequence static void printJuggler(int n) { int a = n; // print the first term System.out.print(a+" "); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = (int)Math.floor(Math.sqrt(a)); else // for odd previous term calculate // next term b =(int) Math.floor(Math.sqrt(a) * Math.sqrt(a) * Math.sqrt(a)); System.out.print( b+" "); a = b; } } // Driver program to test above functionpublic static void main (String[] args) { printJuggler(3); System.out.println(); printJuggler(9); }} //This code is contributed by Nikita Tiwari.
import math #This function prints the juggler Sequencedef printJuggler(n) : a = n # print the first term print (a,end=" ") # calculate terms until last term is not 1 while (a != 1) : b = 0 # Check if previous term is even or odd if (a%2 == 0) : # calculate next term b = (int)(math.floor(math.sqrt(a))) else : # for odd previous term calculate # next term b = (int) (math.floor(math.sqrt(a)*math.sqrt(a)* math.sqrt(a))) print (b,end=" ") a = b printJuggler(3)print()printJuggler(9) # This code is contributed by Nikita Tiwari.
// C# implementation of Juggler Sequenceusing System; class GFG { // This function prints the juggler Sequence static void printJuggler(int n) { int a = n; // print the first term Console.Write(a+" "); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = (int)Math.Floor(Math.Sqrt(a)); else // for odd previous term calculate // next term b =(int) Math.Floor(Math.Sqrt(a) * Math.Sqrt(a) * Math.Sqrt(a)); Console.Write( b+" "); a = b; } } // Driver Codepublic static void Main () { printJuggler(3); Console.WriteLine(); printJuggler(9); }} // This code is contributed by Nitin Mittal
<?php// PHP implementation of// Juggler Sequence // function prints the// juggler Sequencefunction printJuggler($n){ $a = $n; // print the first term echo($a . " "); // calculate terms until // last term is not 1 while ($a != 1) { $b = 0; // Check if previous // term is even or odd if ($a % 2 == 0) // calculate next term $b = floor(sqrt($a)); else // for odd previous term // calculate next term $b = floor(sqrt($a) * sqrt($a) * sqrt($a)); echo($b . " "); $a = $b; }} // Driver CodeprintJuggler(3);echo("\n");printJuggler(9); // This code is contributed by Ajit.?>
<script> // Javascript implementation of Juggler Sequence // This function prints the juggler Sequence function printJuggler(n) { let a = n; // print the first term document.write(a+" "); // calculate terms until last term is not 1 while (a != 1) { let b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = Math.floor(Math.sqrt(a)); else // for odd previous term calculate // next term b = Math.floor(Math.sqrt(a) * Math.sqrt(a) * Math.sqrt(a)); document.write( b+" "); a = b; } } // Driver code to test above methods printJuggler(3); document.write("<br/>"); printJuggler(9); // This code is contributed by avijitmondal1998.</script>
Output:
3 5 11 36 6 2 1
9 27 140 11 36 6 2 1
Time complexity: O(nlogn) since using a single while loop and finding square root takes logarithmic time.
Space complexity: O(1) for constant variables
Important Points:
The terms in Juggler Sequence first increase to a peak value and then start decreasing.
The last term in Juggler Sequence is always 1.
Reference: https://en.wikipedia.org/wiki/Juggler_sequence This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
SHUBHAMSINGH10
avijitmondal1998
dpbangara
amartyaghoshgfg
technophpfij
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 518,
"s": 53,
"text": "Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : Juggler Sequence starting with number 3: 5, 11, 36, 6, 2, 1Juggler Sequence starting with number 9: 9, 27, 140, 11, 36, 6, 2, 1Given a number n we have to print the Juggler Sequence for this number as the first term of the sequence. Examples: "
},
{
"code": null,
"e": 646,
"s": 518,
"text": "Input: 9\nOutput: 9, 27, 140, 11, 36, 6, 2, 1\nWe start with 9 and use above formula to get\nnext terms.\n\nInput: 6\nOutput: 6, 2, 1"
},
{
"code": null,
"e": 650,
"s": 646,
"text": "C++"
},
{
"code": null,
"e": 652,
"s": 650,
"text": "C"
},
{
"code": null,
"e": 657,
"s": 652,
"text": "Java"
},
{
"code": null,
"e": 665,
"s": 657,
"text": "Python3"
},
{
"code": null,
"e": 668,
"s": 665,
"text": "C#"
},
{
"code": null,
"e": 672,
"s": 668,
"text": "PHP"
},
{
"code": null,
"e": 683,
"s": 672,
"text": "Javascript"
},
{
"code": "// C++ implementation of Juggler Sequence#include <bits/stdc++.h>using namespace std; // This function prints the juggler Sequencevoid printJuggler(long long n){ long long a = n; // print the first term cout << a << \" \"; // calculate terms until // last term is not 1 while (a != 1) { long long b = 0; // Check if previous term // is even or odd if (a % 2 == 0) // calculate next term b = floor(sqrt(a)); else // for odd previous term // calculate next term b = floor(sqrt(a) * sqrt(a) * sqrt(a)); cout << b << \" \"; a = b; }} // Driver Codeint main(){ printJuggler(37); cout <<\"\\n\"; printJuggler(9); return 0;} // This code is contributed by shubhamsingh10",
"e": 1508,
"s": 683,
"text": null
},
{
"code": "// C implementation of Juggler Sequence#include<stdio.h>#include<math.h> // This function prints the juggler Sequencevoid printJuggler(int n){ int a = n; // print the first term printf(\"%d \", a); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = floor(sqrt(a)); else // for odd previous term calculate // next term b = floor(sqrt(a)*sqrt(a)*sqrt(a)); printf(\"%d \", b); a = b; }} //driver program to test above functionint main(){ printJuggler(3); printf(\"\\n\"); printJuggler(9); return 0;}",
"e": 2239,
"s": 1508,
"text": null
},
{
"code": "// Java implementation of Juggler Sequenceimport java.io.*;import java.math.*; class GFG { // This function prints the juggler Sequence static void printJuggler(int n) { int a = n; // print the first term System.out.print(a+\" \"); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = (int)Math.floor(Math.sqrt(a)); else // for odd previous term calculate // next term b =(int) Math.floor(Math.sqrt(a) * Math.sqrt(a) * Math.sqrt(a)); System.out.print( b+\" \"); a = b; } } // Driver program to test above functionpublic static void main (String[] args) { printJuggler(3); System.out.println(); printJuggler(9); }} //This code is contributed by Nikita Tiwari.",
"e": 3241,
"s": 2239,
"text": null
},
{
"code": "import math #This function prints the juggler Sequencedef printJuggler(n) : a = n # print the first term print (a,end=\" \") # calculate terms until last term is not 1 while (a != 1) : b = 0 # Check if previous term is even or odd if (a%2 == 0) : # calculate next term b = (int)(math.floor(math.sqrt(a))) else : # for odd previous term calculate # next term b = (int) (math.floor(math.sqrt(a)*math.sqrt(a)* math.sqrt(a))) print (b,end=\" \") a = b printJuggler(3)print()printJuggler(9) # This code is contributed by Nikita Tiwari.",
"e": 3957,
"s": 3241,
"text": null
},
{
"code": "// C# implementation of Juggler Sequenceusing System; class GFG { // This function prints the juggler Sequence static void printJuggler(int n) { int a = n; // print the first term Console.Write(a+\" \"); // calculate terms until last term is not 1 while (a != 1) { int b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = (int)Math.Floor(Math.Sqrt(a)); else // for odd previous term calculate // next term b =(int) Math.Floor(Math.Sqrt(a) * Math.Sqrt(a) * Math.Sqrt(a)); Console.Write( b+\" \"); a = b; } } // Driver Codepublic static void Main () { printJuggler(3); Console.WriteLine(); printJuggler(9); }} // This code is contributed by Nitin Mittal",
"e": 4839,
"s": 3957,
"text": null
},
{
"code": "<?php// PHP implementation of// Juggler Sequence // function prints the// juggler Sequencefunction printJuggler($n){ $a = $n; // print the first term echo($a . \" \"); // calculate terms until // last term is not 1 while ($a != 1) { $b = 0; // Check if previous // term is even or odd if ($a % 2 == 0) // calculate next term $b = floor(sqrt($a)); else // for odd previous term // calculate next term $b = floor(sqrt($a) * sqrt($a) * sqrt($a)); echo($b . \" \"); $a = $b; }} // Driver CodeprintJuggler(3);echo(\"\\n\");printJuggler(9); // This code is contributed by Ajit.?>",
"e": 5574,
"s": 4839,
"text": null
},
{
"code": "<script> // Javascript implementation of Juggler Sequence // This function prints the juggler Sequence function printJuggler(n) { let a = n; // print the first term document.write(a+\" \"); // calculate terms until last term is not 1 while (a != 1) { let b = 0; // Check if previous term is even or odd if (a%2 == 0) // calculate next term b = Math.floor(Math.sqrt(a)); else // for odd previous term calculate // next term b = Math.floor(Math.sqrt(a) * Math.sqrt(a) * Math.sqrt(a)); document.write( b+\" \"); a = b; } } // Driver code to test above methods printJuggler(3); document.write(\"<br/>\"); printJuggler(9); // This code is contributed by avijitmondal1998.</script>",
"e": 6498,
"s": 5574,
"text": null
},
{
"code": null,
"e": 6508,
"s": 6498,
"text": "Output: "
},
{
"code": null,
"e": 6546,
"s": 6508,
"text": "3 5 11 36 6 2 1 \n9 27 140 11 36 6 2 1"
},
{
"code": null,
"e": 6652,
"s": 6546,
"text": "Time complexity: O(nlogn) since using a single while loop and finding square root takes logarithmic time."
},
{
"code": null,
"e": 6698,
"s": 6652,
"text": "Space complexity: O(1) for constant variables"
},
{
"code": null,
"e": 6717,
"s": 6698,
"text": "Important Points: "
},
{
"code": null,
"e": 6805,
"s": 6717,
"text": "The terms in Juggler Sequence first increase to a peak value and then start decreasing."
},
{
"code": null,
"e": 6852,
"s": 6805,
"text": "The last term in Juggler Sequence is always 1."
},
{
"code": null,
"e": 7332,
"s": 6852,
"text": "Reference: https://en.wikipedia.org/wiki/Juggler_sequence This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7345,
"s": 7332,
"text": "nitin mittal"
},
{
"code": null,
"e": 7351,
"s": 7345,
"text": "jit_t"
},
{
"code": null,
"e": 7366,
"s": 7351,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 7383,
"s": 7366,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 7393,
"s": 7383,
"text": "dpbangara"
},
{
"code": null,
"e": 7409,
"s": 7393,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 7422,
"s": 7409,
"text": "technophpfij"
},
{
"code": null,
"e": 7429,
"s": 7422,
"text": "series"
},
{
"code": null,
"e": 7442,
"s": 7429,
"text": "Mathematical"
},
{
"code": null,
"e": 7455,
"s": 7442,
"text": "Mathematical"
},
{
"code": null,
"e": 7462,
"s": 7455,
"text": "series"
}
] |
Python | Write multiple files data to master file
|
06 May, 2019
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file.
Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having structure same as source files.
Taking three input files as example, named emp_1.txt, emp_2.txt, emp_3.txt, output will contain data from all the input files.
Input:
Output:
Method #1: Using os module
import os# list the files in directorylis = os.listdir('D:\\python' '\\data_files\\data_files')print(lis)tgt = os.listdir('D:\\python' '\\data_files\\target_file') file_dir ='D:\\python\\data_files\\data_files'out_file = r'D:\\python\\data_files\\target_file\\master.txt'ct = 0 print('target file :', tgt)try: # check for if file exists # if yes delete the file # otherwise data will be appended to existing file if len(tgt)>0: os.remove('D:\\python' '\\data_files\\target_file\\master.txt') open(tgt, 'a').close() else: # create an empty file open(tgt, 'a').close()except: head = open('D:\\python' '\\data_files\\target_file\\master.txt', 'a+') line ='empno, ename, sal' # write header to output print(head, line) head.close() # below loop to write data to output file for line1 in lis: f_dir = file_dir+'\\'+line1 # open files in read mode in_file = open(f_dir, 'r+') # open output in append mode w = open(out_file, 'a+') d = in_file.readline() d = in_file.readlines() w.write("\n") for line2 in d: print(line2) w.write(line2) ct = ct + 1 w.close()
Output:
Method #2: Using pandas
import pandas as pd# pd.read_csv creates dataframesdf1 = pd.read_csv('D:\python\data_files\data_files\emp_1.txt')df2 = pd.read_csv('D:\python\data_files\data_files\emp_2.txt')df3 = pd.read_csv('D:\python\data_files\data_files\emp_3.txt') frames = [df1, df2, df3] # concat function concatenates the frames result = pd.concat(frames)# to_csv function writes output to fileresult.to_csv('D:\\python\\data_files' '\\target_file\\master.txt', encoding ='utf-8', index = False)
Output:
python-utility
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
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2019"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file."
},
{
"code": null,
"e": 411,
"s": 174,
"text": "Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having structure same as source files."
},
{
"code": null,
"e": 538,
"s": 411,
"text": "Taking three input files as example, named emp_1.txt, emp_2.txt, emp_3.txt, output will contain data from all the input files."
},
{
"code": null,
"e": 560,
"s": 538,
"text": "Input: \n\n\n\n\nOutput: \n"
},
{
"code": null,
"e": 589,
"s": 562,
"text": "Method #1: Using os module"
},
{
"code": "import os# list the files in directorylis = os.listdir('D:\\\\python' '\\\\data_files\\\\data_files')print(lis)tgt = os.listdir('D:\\\\python' '\\\\data_files\\\\target_file') file_dir ='D:\\\\python\\\\data_files\\\\data_files'out_file = r'D:\\\\python\\\\data_files\\\\target_file\\\\master.txt'ct = 0 print('target file :', tgt)try: # check for if file exists # if yes delete the file # otherwise data will be appended to existing file if len(tgt)>0: os.remove('D:\\\\python' '\\\\data_files\\\\target_file\\\\master.txt') open(tgt, 'a').close() else: # create an empty file open(tgt, 'a').close()except: head = open('D:\\\\python' '\\\\data_files\\\\target_file\\\\master.txt', 'a+') line ='empno, ename, sal' # write header to output print(head, line) head.close() # below loop to write data to output file for line1 in lis: f_dir = file_dir+'\\\\'+line1 # open files in read mode in_file = open(f_dir, 'r+') # open output in append mode w = open(out_file, 'a+') d = in_file.readline() d = in_file.readlines() w.write(\"\\n\") for line2 in d: print(line2) w.write(line2) ct = ct + 1 w.close() ",
"e": 1892,
"s": 589,
"text": null
},
{
"code": null,
"e": 1900,
"s": 1892,
"text": "Output:"
},
{
"code": null,
"e": 1925,
"s": 1900,
"text": " Method #2: Using pandas"
},
{
"code": "import pandas as pd# pd.read_csv creates dataframesdf1 = pd.read_csv('D:\\python\\data_files\\data_files\\emp_1.txt')df2 = pd.read_csv('D:\\python\\data_files\\data_files\\emp_2.txt')df3 = pd.read_csv('D:\\python\\data_files\\data_files\\emp_3.txt') frames = [df1, df2, df3] # concat function concatenates the frames result = pd.concat(frames)# to_csv function writes output to fileresult.to_csv('D:\\\\python\\\\data_files' '\\\\target_file\\\\master.txt', encoding ='utf-8', index = False)",
"e": 2412,
"s": 1925,
"text": null
},
{
"code": null,
"e": 2420,
"s": 2412,
"text": "Output:"
},
{
"code": null,
"e": 2435,
"s": 2420,
"text": "python-utility"
},
{
"code": null,
"e": 2442,
"s": 2435,
"text": "Python"
},
{
"code": null,
"e": 2458,
"s": 2442,
"text": "Python Programs"
},
{
"code": null,
"e": 2556,
"s": 2458,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2574,
"s": 2556,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2616,
"s": 2574,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2638,
"s": 2616,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2664,
"s": 2638,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2696,
"s": 2664,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2739,
"s": 2696,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2761,
"s": 2739,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2800,
"s": 2761,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2838,
"s": 2800,
"text": "Python | Convert a list to dictionary"
}
] |
C# | Deconstructors with Tuples
|
28 Aug, 2019
A tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. But if you are trying to retrieve multiple fields or property values from the tuple is more difficult. So, to overcome this problem deconstructor was introduced in C# 7.0. It is used to divide the variable values or tuple into parts and assigns those values to the new variables. It also used with classes and structures. Here we only discuss the working of deconstructor with tuples.
In Tuples, deconstructor is used to divide a tuple into parts and assign these parts individually into new variables. So, you can access an individual field or property value. You can deconstruct a tuple in four different ways:
1. You can deconstruct a tuple simply by explicitly declare the type of each field inside the parentheses. But you are not allowed to specify a specific type outside the parentheses even every field in the tuple is of the same type. If you try to do, then you will get an error.
Example:
// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Deconstruct the given tuple // So that we can directly access individual fields // By explicitly declaring types (string type, string name, int height, int age, string color) = g.PetDetails("Dog", "Dollar", 124, 3, "White"); Console.WriteLine("Pet Details:"); Console.WriteLine("Type: " + type); Console.WriteLine("Name: " + name); Console.WriteLine("Height: " + height); Console.WriteLine("Age: " + age); Console.WriteLine("Color: " + color); Console.ReadLine(); }}}
Output:
2. You can deconstruct a tuple by using var keyword so that C# infers the type of each variable. You can use the var keyword in two different ways:
You are allowed to place the var keyword outside of the parentheses.
You are allowed to place the var keyword individually inside the parentheses with some or all variables.
Example:
// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Deconstruct the given tuple // So that we can directly // access individual fields // Using var keyword var(type1, name1, height1, age1, color1) = g.PetDetails("Dog", "Dollar", 124, 3, "White"); Console.WriteLine("Pet Details:"); Console.WriteLine("Type: " + type1); Console.WriteLine("Name: " + name1); Console.WriteLine("Height: " + height1); Console.WriteLine("Age: " + age1); Console.WriteLine("Color: " + color1); (var type2, var name2, var height2, var age2, var color2) = g.PetDetails("Cat", "Poo", 104, 1, "Black&White"); Console.WriteLine("\nPet Details:"); Console.WriteLine("Type: " + type2); Console.WriteLine("Name: " + name2); Console.WriteLine("Height: " + height2); Console.WriteLine("Age: " + age2); Console.WriteLine("Color: " + color2); Console.ReadLine(); }}}
Output:
3. You can deconstruct a tuple into a variable that are already declared. As shown in the below example:
Example:
// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Declaring and initializing variables string type = "Cow"; string name = "BooBoo"; int height = 234; int age = 4; string color = "Black&white"; // Deconstruct the given tuple // So that we can directly // access individual fields // By declaring variables (type, name, height, age, color) = g.PetDetails("Cat", "Mew", 105, 2, "Brown"); Console.WriteLine("Pet Details:"); Console.WriteLine("Type: " + type); Console.WriteLine("Name: " + name); Console.WriteLine("Height: " + height); Console.WriteLine("Age: " + age); Console.WriteLine("Color: " + color); Console.ReadLine(); }}}
Output:
4. You can also use discards in deconstruction. Discards are write-only variables whose values are meant to be ignored. And discards are designated by using an underscore character (“_”) in an assignment. You are allowed to discard as many values as you want and all are represented by the single discard, _.
Syntax:
(var1, _, var3, _, var5) = method_name(var1_values, var2_values, var3_value, var4_values, var5_value);
Example:
// C# program to illustrate the concept// of deconstruction with tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns // the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Discarding field values // in deconstruction (string type, _, int height, _, string color) = g.PetDetails("Dog", "Dollar", 124, 3, "White"); Console.WriteLine("Pet Details:"); Console.WriteLine("Type: " + type); Console.WriteLine("Height: " + height); Console.WriteLine("Color: " + color); Console.ReadLine(); }}}
Output:
Note: In deconstruction, you need to assign each element to a variable if you eliminate any element, then the compiler will give an error. And you are not allowed to mix declarations and assignments to existing variables on the left-hand side of a deconstruction if you eliminate any element, then the compiler will give an error.
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 566,
"s": 28,
"text": "A tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. But if you are trying to retrieve multiple fields or property values from the tuple is more difficult. So, to overcome this problem deconstructor was introduced in C# 7.0. It is used to divide the variable values or tuple into parts and assigns those values to the new variables. It also used with classes and structures. Here we only discuss the working of deconstructor with tuples."
},
{
"code": null,
"e": 794,
"s": 566,
"text": "In Tuples, deconstructor is used to divide a tuple into parts and assign these parts individually into new variables. So, you can access an individual field or property value. You can deconstruct a tuple in four different ways:"
},
{
"code": null,
"e": 1073,
"s": 794,
"text": "1. You can deconstruct a tuple simply by explicitly declare the type of each field inside the parentheses. But you are not allowed to specify a specific type outside the parentheses even every field in the tuple is of the same type. If you try to do, then you will get an error."
},
{
"code": null,
"e": 1082,
"s": 1073,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Deconstruct the given tuple // So that we can directly access individual fields // By explicitly declaring types (string type, string name, int height, int age, string color) = g.PetDetails(\"Dog\", \"Dollar\", 124, 3, \"White\"); Console.WriteLine(\"Pet Details:\"); Console.WriteLine(\"Type: \" + type); Console.WriteLine(\"Name: \" + name); Console.WriteLine(\"Height: \" + height); Console.WriteLine(\"Age: \" + age); Console.WriteLine(\"Color: \" + color); Console.ReadLine(); }}}",
"e": 2446,
"s": 1082,
"text": null
},
{
"code": null,
"e": 2454,
"s": 2446,
"text": "Output:"
},
{
"code": null,
"e": 2602,
"s": 2454,
"text": "2. You can deconstruct a tuple by using var keyword so that C# infers the type of each variable. You can use the var keyword in two different ways:"
},
{
"code": null,
"e": 2671,
"s": 2602,
"text": "You are allowed to place the var keyword outside of the parentheses."
},
{
"code": null,
"e": 2776,
"s": 2671,
"text": "You are allowed to place the var keyword individually inside the parentheses with some or all variables."
},
{
"code": null,
"e": 2785,
"s": 2776,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Deconstruct the given tuple // So that we can directly // access individual fields // Using var keyword var(type1, name1, height1, age1, color1) = g.PetDetails(\"Dog\", \"Dollar\", 124, 3, \"White\"); Console.WriteLine(\"Pet Details:\"); Console.WriteLine(\"Type: \" + type1); Console.WriteLine(\"Name: \" + name1); Console.WriteLine(\"Height: \" + height1); Console.WriteLine(\"Age: \" + age1); Console.WriteLine(\"Color: \" + color1); (var type2, var name2, var height2, var age2, var color2) = g.PetDetails(\"Cat\", \"Poo\", 104, 1, \"Black&White\"); Console.WriteLine(\"\\nPet Details:\"); Console.WriteLine(\"Type: \" + type2); Console.WriteLine(\"Name: \" + name2); Console.WriteLine(\"Height: \" + height2); Console.WriteLine(\"Age: \" + age2); Console.WriteLine(\"Color: \" + color2); Console.ReadLine(); }}}",
"e": 4555,
"s": 2785,
"text": null
},
{
"code": null,
"e": 4563,
"s": 4555,
"text": "Output:"
},
{
"code": null,
"e": 4668,
"s": 4563,
"text": "3. You can deconstruct a tuple into a variable that are already declared. As shown in the below example:"
},
{
"code": null,
"e": 4677,
"s": 4668,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept // of deconstruction with the tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Declaring and initializing variables string type = \"Cow\"; string name = \"BooBoo\"; int height = 234; int age = 4; string color = \"Black&white\"; // Deconstruct the given tuple // So that we can directly // access individual fields // By declaring variables (type, name, height, age, color) = g.PetDetails(\"Cat\", \"Mew\", 105, 2, \"Brown\"); Console.WriteLine(\"Pet Details:\"); Console.WriteLine(\"Type: \" + type); Console.WriteLine(\"Name: \" + name); Console.WriteLine(\"Height: \" + height); Console.WriteLine(\"Age: \" + age); Console.WriteLine(\"Color: \" + color); Console.ReadLine(); }}}",
"e": 6177,
"s": 4677,
"text": null
},
{
"code": null,
"e": 6185,
"s": 6177,
"text": "Output:"
},
{
"code": null,
"e": 6494,
"s": 6185,
"text": "4. You can also use discards in deconstruction. Discards are write-only variables whose values are meant to be ignored. And discards are designated by using an underscore character (“_”) in an assignment. You are allowed to discard as many values as you want and all are represented by the single discard, _."
},
{
"code": null,
"e": 6502,
"s": 6494,
"text": "Syntax:"
},
{
"code": null,
"e": 6605,
"s": 6502,
"text": "(var1, _, var3, _, var5) = method_name(var1_values, var2_values, var3_value, var4_values, var5_value);"
},
{
"code": null,
"e": 6614,
"s": 6605,
"text": "Example:"
},
{
"code": "// C# program to illustrate the concept// of deconstruction with tupleusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ConsoleApp1 { class GFG { // This method returns // the Pet details public(string, string, int, int, string) PetDetails(string type, string name, int height, int age, string color) { string p_type = type; string p_name = name; int p_height = height; int p_age = age; string p_color = color; return (p_type, p_name, p_height, p_height, p_color); } // Main method static void Main(string[] args) { // Creating object of GFG class GFG g = new GFG(); // Discarding field values // in deconstruction (string type, _, int height, _, string color) = g.PetDetails(\"Dog\", \"Dollar\", 124, 3, \"White\"); Console.WriteLine(\"Pet Details:\"); Console.WriteLine(\"Type: \" + type); Console.WriteLine(\"Height: \" + height); Console.WriteLine(\"Color: \" + color); Console.ReadLine(); }}}",
"e": 7789,
"s": 6614,
"text": null
},
{
"code": null,
"e": 7797,
"s": 7789,
"text": "Output:"
},
{
"code": null,
"e": 8128,
"s": 7797,
"text": "Note: In deconstruction, you need to assign each element to a variable if you eliminate any element, then the compiler will give an error. And you are not allowed to mix declarations and assignments to existing variables on the left-hand side of a deconstruction if you eliminate any element, then the compiler will give an error."
},
{
"code": null,
"e": 8131,
"s": 8128,
"text": "C#"
},
{
"code": null,
"e": 8229,
"s": 8131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8272,
"s": 8229,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 8321,
"s": 8272,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 8344,
"s": 8321,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 8360,
"s": 8344,
"text": "C# | List Class"
},
{
"code": null,
"e": 8388,
"s": 8360,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 8449,
"s": 8388,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 8472,
"s": 8449,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 8494,
"s": 8472,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 8519,
"s": 8494,
"text": "Lambda Expressions in C#"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.