title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to set delay in android?
|
In some cases, after some time we need to update on UI to solve this problem, In this example demonstrate how to set a delay 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"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/textChanger"
android:layout_margin = "20dp"
android:textAlignment = "center"
android:text = "Initial text"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken text view, primary it shows "initial text" after some delay it will update with new text.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textChanger.setText("After some delay, it changed to new text");
}
}, 5000);
}
}
In the above code, we have used the handler to maintain delay as shown below -
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
textChanger.setText("After some delay, it changed to new text");
}
}, 5000);
In the above code after 5000ms it is updating 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 android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Initially, it will show text as shown above. after some time, it will update text as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "In some cases, after some time we need to update on UI to solve this problem, In this example demonstrate how to set a delay in android."
},
{
"code": null,
"e": 1328,
"s": 1199,
"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": 1392,
"s": 1328,
"text": "Step 2− Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2048,
"s": 1392,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/textChanger\"\n android:layout_margin = \"20dp\"\n android:textAlignment = \"center\"\n android:text = \"Initial text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2171,
"s": 2048,
"text": "In the above code, we have taken text view, primary it shows \"initial text\" after some delay it will update with new text."
},
{
"code": null,
"e": 2228,
"s": 2171,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3077,
"s": 2228,
"text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textChanger;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textChanger = findViewById(R.id.textChanger);\n Handler handler = new Handler();\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n textChanger.setText(\"After some delay, it changed to new text\");\n }\n }, 5000);\n }\n}"
},
{
"code": null,
"e": 3156,
"s": 3077,
"text": "In the above code, we have used the handler to maintain delay as shown below -"
},
{
"code": null,
"e": 3348,
"s": 3156,
"text": "Handler handler = new Handler();\nhandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n textChanger.setText(\"After some delay, it changed to new text\");\n }\n}, 5000);"
},
{
"code": null,
"e": 3748,
"s": 3348,
"text": "In the above code after 5000ms it is updating 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 android studio, open one of your project's activity files and click 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": 3847,
"s": 3748,
"text": "Initially, it will show text as shown above. after some time, it will update text as shown below -"
},
{
"code": null,
"e": 3887,
"s": 3847,
"text": "Click here to download the project code"
}
] |
Python break statement
|
13 Jun, 2022
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore some statements of the loop before continuing further in the loop. These can be done by loop control statements called jump statements. Loop control or jump statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control/jump statements.
continue statement
break statement
pass statement
In this article, the main focus will be on the break statement.
Break statement
break statement in Python is used to bring the control out of the loop when some external condition is triggered. break statement is put inside the loop body (generally after if condition). It terminates the current loop, i.e., the loop in which it appears, and resumes execution at the next statement immediately after the end of that loop. If the break statement is inside a nested loop, the break will terminate the innermost loop.
Syntax:
break
Example#1:
Python3
# Python program to# demonstrate break statement s = 'geeksforgeeks'# Using for loopfor letter in s: print(letter) # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print(& quot Out of for loop & quot )print() i = 0 # Using while loopwhile True: print(s[i]) # break the loop as soon it sees 'e' # or 's' if s[i] == 'e' or s[i] == 's': break i += 1 print(& quot Out of while loop & quot )
Output:
g
e
Out of for loop
g
e
Out of while loop
In the above example, both the loops are iterating the string ‘geeksforgeeks’ and as soon as they encounter the character ‘e’ or ‘s’, the if the condition becomes true and the flow of execution is brought out of the loop.
Example#2:
Python3
num = 0for i in range(10): num += 1 if num == 8: break print("The num has value:", num)print("Out of loop")
The num has value: 1
The num has value: 2
The num has value: 3
The num has value: 4
The num has value: 5
The num has value: 6
The num has value: 7
Out of loop
In the above example, after iterating till num=7, the value of num will be 8 and the break is encountered so the flow of the execution is brought out of the loop.
sheetal18june
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 613,
"s": 54,
"text": "Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore some statements of the loop before continuing further in the loop. These can be done by loop control statements called jump statements. Loop control or jump statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control/jump statements."
},
{
"code": null,
"e": 632,
"s": 613,
"text": "continue statement"
},
{
"code": null,
"e": 648,
"s": 632,
"text": "break statement"
},
{
"code": null,
"e": 663,
"s": 648,
"text": "pass statement"
},
{
"code": null,
"e": 727,
"s": 663,
"text": "In this article, the main focus will be on the break statement."
},
{
"code": null,
"e": 743,
"s": 727,
"text": "Break statement"
},
{
"code": null,
"e": 1179,
"s": 743,
"text": "break statement in Python is used to bring the control out of the loop when some external condition is triggered. break statement is put inside the loop body (generally after if condition). It terminates the current loop, i.e., the loop in which it appears, and resumes execution at the next statement immediately after the end of that loop. If the break statement is inside a nested loop, the break will terminate the innermost loop."
},
{
"code": null,
"e": 1189,
"s": 1181,
"text": "Syntax:"
},
{
"code": null,
"e": 1195,
"s": 1189,
"text": "break"
},
{
"code": null,
"e": 1207,
"s": 1195,
"text": "Example#1: "
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate break statement s = 'geeksforgeeks'# Using for loopfor letter in s: print(letter) # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print(& quot Out of for loop & quot )print() i = 0 # Using while loopwhile True: print(s[i]) # break the loop as soon it sees 'e' # or 's' if s[i] == 'e' or s[i] == 's': break i += 1 print(& quot Out of while loop & quot )",
"e": 1707,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1715,
"s": 1707,
"text": "Output:"
},
{
"code": null,
"e": 1758,
"s": 1715,
"text": "g\ne\nOut of for loop\n\ng\ne\nOut of while loop"
},
{
"code": null,
"e": 1980,
"s": 1758,
"text": "In the above example, both the loops are iterating the string ‘geeksforgeeks’ and as soon as they encounter the character ‘e’ or ‘s’, the if the condition becomes true and the flow of execution is brought out of the loop."
},
{
"code": null,
"e": 1991,
"s": 1980,
"text": "Example#2:"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "Python3"
},
{
"code": "num = 0for i in range(10): num += 1 if num == 8: break print(\"The num has value:\", num)print(\"Out of loop\")",
"e": 2123,
"s": 1999,
"text": null
},
{
"code": null,
"e": 2283,
"s": 2123,
"text": "The num has value: 1\nThe num has value: 2\nThe num has value: 3\nThe num has value: 4\nThe num has value: 5\nThe num has value: 6\nThe num has value: 7\nOut of loop\n"
},
{
"code": null,
"e": 2446,
"s": 2283,
"text": "In the above example, after iterating till num=7, the value of num will be 8 and the break is encountered so the flow of the execution is brought out of the loop."
},
{
"code": null,
"e": 2460,
"s": 2446,
"text": "sheetal18june"
},
{
"code": null,
"e": 2471,
"s": 2460,
"text": "Python-OOP"
},
{
"code": null,
"e": 2478,
"s": 2471,
"text": "Python"
}
] |
Dart – Fat Arrow Notation
|
07 Sep, 2021
In Dart, we have fat arrow notation ( => ). A fat arrow is used to define a single expression in a function. This is a cleaner way to write functions with a single statement.
Declaring Fat arrow expression in dart –
Syntax :
ReturnType FunctionName(Parameters...) => Expression;
In the above syntax:
ReturnType consists of datatypes like void,int,bool, etc..
FunctionName defines the name of the function.
Parameters are the list of parameters function requires.
Let’s see how we can write the below code in a more short way.
Dart
void main() { perimeterOfRectangle(47, 57); } void perimeterOfRectangle(int length, int breadth) { var perimeter = 2 * (length + breadth); print('The perimeter of rectangle is $perimeter');}
Output:
The perimeter of rectangle is 208
When the body of the function contains only one line, you can omit the curly braces and the return statement in favor of the “arrow syntax” as shown below:
Dart
void main() { perimeterOfRectangle(47, 57); } // Arrow Syntaxvoid perimeterOfRectangle(int length, int breadth) => print('The perimeter of rectangele is ${2 * (length + breadth)}');
Output:
The perimeter of rectangele is 208
If we compare the above code we got the same output with much less code using Fat arrow notation.
Example 1:
Consider the below code:
Dart
void sum (int x, int y) { // printing the result print( 'sum is ${x + y}');} void main (){ sum(5,2);}
Output:
sum is 7
The given functions can be optimized with the help of a fat arrow in Dart and the same output we can get:
Dart
void main(){ sum(2,5);} // Arrow Syntaxvoid sum(int x,int y) => print('sum is ${ x + y}');
Output:
sum is 7
Fat arrow is a clean way to write function expression in a single line.
Fat arrow notation doesn’t have statements body ‘ { } ‘ .
The statement body is replaced with ‘ => ‘ fat arrow which points to a single statement.
sweetyty
Dart Control-Flow
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 204,
"s": 28,
"text": "In Dart, we have fat arrow notation ( => ). A fat arrow is used to define a single expression in a function. This is a cleaner way to write functions with a single statement."
},
{
"code": null,
"e": 245,
"s": 204,
"text": "Declaring Fat arrow expression in dart –"
},
{
"code": null,
"e": 254,
"s": 245,
"text": "Syntax :"
},
{
"code": null,
"e": 308,
"s": 254,
"text": "ReturnType FunctionName(Parameters...) => Expression;"
},
{
"code": null,
"e": 329,
"s": 308,
"text": "In the above syntax:"
},
{
"code": null,
"e": 388,
"s": 329,
"text": "ReturnType consists of datatypes like void,int,bool, etc.."
},
{
"code": null,
"e": 435,
"s": 388,
"text": "FunctionName defines the name of the function."
},
{
"code": null,
"e": 492,
"s": 435,
"text": "Parameters are the list of parameters function requires."
},
{
"code": null,
"e": 555,
"s": 492,
"text": "Let’s see how we can write the below code in a more short way."
},
{
"code": null,
"e": 560,
"s": 555,
"text": "Dart"
},
{
"code": "void main() { perimeterOfRectangle(47, 57); } void perimeterOfRectangle(int length, int breadth) { var perimeter = 2 * (length + breadth); print('The perimeter of rectangle is $perimeter');}",
"e": 760,
"s": 560,
"text": null
},
{
"code": null,
"e": 768,
"s": 760,
"text": "Output:"
},
{
"code": null,
"e": 802,
"s": 768,
"text": "The perimeter of rectangle is 208"
},
{
"code": null,
"e": 958,
"s": 802,
"text": "When the body of the function contains only one line, you can omit the curly braces and the return statement in favor of the “arrow syntax” as shown below:"
},
{
"code": null,
"e": 963,
"s": 958,
"text": "Dart"
},
{
"code": "void main() { perimeterOfRectangle(47, 57); } // Arrow Syntaxvoid perimeterOfRectangle(int length, int breadth) => print('The perimeter of rectangele is ${2 * (length + breadth)}');",
"e": 1147,
"s": 963,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1147,
"text": "Output:"
},
{
"code": null,
"e": 1190,
"s": 1155,
"text": "The perimeter of rectangele is 208"
},
{
"code": null,
"e": 1288,
"s": 1190,
"text": "If we compare the above code we got the same output with much less code using Fat arrow notation."
},
{
"code": null,
"e": 1299,
"s": 1288,
"text": "Example 1:"
},
{
"code": null,
"e": 1324,
"s": 1299,
"text": "Consider the below code:"
},
{
"code": null,
"e": 1329,
"s": 1324,
"text": "Dart"
},
{
"code": "void sum (int x, int y) { // printing the result print( 'sum is ${x + y}');} void main (){ sum(5,2);}",
"e": 1437,
"s": 1329,
"text": null
},
{
"code": null,
"e": 1445,
"s": 1437,
"text": "Output:"
},
{
"code": null,
"e": 1454,
"s": 1445,
"text": "sum is 7"
},
{
"code": null,
"e": 1560,
"s": 1454,
"text": "The given functions can be optimized with the help of a fat arrow in Dart and the same output we can get:"
},
{
"code": null,
"e": 1565,
"s": 1560,
"text": "Dart"
},
{
"code": "void main(){ sum(2,5);} // Arrow Syntaxvoid sum(int x,int y) => print('sum is ${ x + y}');",
"e": 1657,
"s": 1565,
"text": null
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Output:"
},
{
"code": null,
"e": 1674,
"s": 1665,
"text": "sum is 7"
},
{
"code": null,
"e": 1746,
"s": 1674,
"text": "Fat arrow is a clean way to write function expression in a single line."
},
{
"code": null,
"e": 1804,
"s": 1746,
"text": "Fat arrow notation doesn’t have statements body ‘ { } ‘ ."
},
{
"code": null,
"e": 1895,
"s": 1804,
"text": "The statement body is replaced with ‘ => ‘ fat arrow which points to a single statement."
},
{
"code": null,
"e": 1904,
"s": 1895,
"text": "sweetyty"
},
{
"code": null,
"e": 1922,
"s": 1904,
"text": "Dart Control-Flow"
},
{
"code": null,
"e": 1927,
"s": 1922,
"text": "Dart"
}
] |
Python program to check if given string is pangram
|
05 Feb, 2019
Given a string, write a Python program to check if that string is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet.
Examples:
Input : The quick brown fox jumps over the lazy dog
Output : Yes
Input : abcdefgxyz
Output : No
We have already discussed the naive approach of pangram checking in this article. Now, let’s discuss the Pythonic approaches to do the same.
Approach #1 : Pythonic NaiveThis method uses a loop to check if each character of the string belongs to the alphabet set or not.
# Python3 program to# Check if the string is pangramimport string def ispangram(str): alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in str.lower(): return False return True # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print("Yes")else: print("No")
Yes
Approach #2 : Using Python SetConvert the given string into set and then check if the alphabet set is greater than or equal to it or not. If the string set is greater or equal, print ‘Yes’ otherwise ‘No’.
# Python3 program to# Check if the string is pangramimport string alphabet = set(string.ascii_lowercase) def ispangram(string): return set(string.lower()) >= alphabet # Driver codestring = "The quick brown fox jumps over the lazy dog"if(ispangram(string) == True): print("Yes")else: print("No")
Yes
Approach #3 : Alternative to set methodThis is another method that uses Python set to find if the string is Pangram or not. We make set of lowercase alphabets and the given string. If set of given string is subtracted from the set of alphabets, we get to know whether the string is pangram or not.
# Python3 program to# Check if the string is pangramimport string alphabet = set(string.ascii_lowercase) def ispangram(str): return not set(alphabet) - set(str) # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print("Yes")else: print("No")
Yes
Approach #4 : ASCII methodCheck if each character of the string lies between the ASCII range of lowercase alphabets i.e. 96 to 122.
# Python3 program to# Check if the string is pangramimport itertoolsimport string alphabet = set(string.ascii_lowercase) def ispangram(str): return sum(1 for i in set(str) if 96 < ord(i) <= 122) == 26 # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print("Yes")else: print("No")
Yes
Python string-programs
python-string
Python
Python Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 209,
"s": 54,
"text": "Given a string, write a Python program to check if that string is Pangram or not. A pangram is a sentence containing every letter in the English Alphabet."
},
{
"code": null,
"e": 219,
"s": 209,
"text": "Examples:"
},
{
"code": null,
"e": 317,
"s": 219,
"text": "Input : The quick brown fox jumps over the lazy dog\nOutput : Yes\n\nInput : abcdefgxyz\nOutput : No\n"
},
{
"code": null,
"e": 460,
"s": 319,
"text": "We have already discussed the naive approach of pangram checking in this article. Now, let’s discuss the Pythonic approaches to do the same."
},
{
"code": null,
"e": 589,
"s": 460,
"text": "Approach #1 : Pythonic NaiveThis method uses a loop to check if each character of the string belongs to the alphabet set or not."
},
{
"code": "# Python3 program to# Check if the string is pangramimport string def ispangram(str): alphabet = \"abcdefghijklmnopqrstuvwxyz\" for char in alphabet: if char not in str.lower(): return False return True # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print(\"Yes\")else: print(\"No\")",
"e": 959,
"s": 589,
"text": null
},
{
"code": null,
"e": 964,
"s": 959,
"text": "Yes\n"
},
{
"code": null,
"e": 1170,
"s": 964,
"text": " Approach #2 : Using Python SetConvert the given string into set and then check if the alphabet set is greater than or equal to it or not. If the string set is greater or equal, print ‘Yes’ otherwise ‘No’."
},
{
"code": "# Python3 program to# Check if the string is pangramimport string alphabet = set(string.ascii_lowercase) def ispangram(string): return set(string.lower()) >= alphabet # Driver codestring = \"The quick brown fox jumps over the lazy dog\"if(ispangram(string) == True): print(\"Yes\")else: print(\"No\")",
"e": 1481,
"s": 1170,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1481,
"text": "Yes\n"
},
{
"code": null,
"e": 1785,
"s": 1486,
"text": " Approach #3 : Alternative to set methodThis is another method that uses Python set to find if the string is Pangram or not. We make set of lowercase alphabets and the given string. If set of given string is subtracted from the set of alphabets, we get to know whether the string is pangram or not."
},
{
"code": "# Python3 program to# Check if the string is pangramimport string alphabet = set(string.ascii_lowercase) def ispangram(str): return not set(alphabet) - set(str) # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print(\"Yes\")else: print(\"No\")",
"e": 2091,
"s": 1785,
"text": null
},
{
"code": null,
"e": 2096,
"s": 2091,
"text": "Yes\n"
},
{
"code": null,
"e": 2229,
"s": 2096,
"text": " Approach #4 : ASCII methodCheck if each character of the string lies between the ASCII range of lowercase alphabets i.e. 96 to 122."
},
{
"code": "# Python3 program to# Check if the string is pangramimport itertoolsimport string alphabet = set(string.ascii_lowercase) def ispangram(str): return sum(1 for i in set(str) if 96 < ord(i) <= 122) == 26 # Driver codestring = 'the quick brown fox jumps over the lazy dog'if(ispangram(string) == True): print(\"Yes\")else: print(\"No\")",
"e": 2575,
"s": 2229,
"text": null
},
{
"code": null,
"e": 2580,
"s": 2575,
"text": "Yes\n"
},
{
"code": null,
"e": 2603,
"s": 2580,
"text": "Python string-programs"
},
{
"code": null,
"e": 2617,
"s": 2603,
"text": "python-string"
},
{
"code": null,
"e": 2624,
"s": 2617,
"text": "Python"
},
{
"code": null,
"e": 2640,
"s": 2624,
"text": "Python Programs"
},
{
"code": null,
"e": 2648,
"s": 2640,
"text": "Strings"
},
{
"code": null,
"e": 2656,
"s": 2648,
"text": "Strings"
}
] |
How to use Particle.js in JavaScript project ?
|
18 Aug, 2020
Particles.js is a lightweight JavaScript library used for creating particles which looks likes the vertices of polygon. We can also interact by hovering over the particles and create more particles by clicking on particles.
Here is the example of particle.js
We can use this library in our portfolios which will definitely attract many users and will look good in the website.
Installation process:
1. Download the particles.js library from the following link, unzip it and copy it into your project folder. https://vincentgarreau.com/particles.js/
2. Create two files index.html and style.css.
Write the following code in index.html file.
HTML
<!DOCTYPE html><html lang="en"> <head> <title>particles.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <!-- Particles.js div --> <div id="particles-js"> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> A computer Science portal for geeks </h3> </div> </div> <!-- Import Particles.js and app.js files --> <script src= "particles.js-master/particles.js"> </script> <script src= "/particles.js-master/demo/js/app.js"> </script></body> </html>
Filename: style.css
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont,
'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
'Open Sans', 'Helvetica Neue', sans-serif;
}
.heading {
position: absolute;
text-align: center;
top: 30%;
width: 100%;
}
.heading h1 {
color: limegreen;
font-size: 70px;
}
.heading h3 {
color: wheat;
font-size: 20px;
}
#particles-js {
background: black;
height: 100vh;
}
3. Save the above code in respective files and run index.html file.
Note: If you are using node app, then we can simply download particles.js node module by following command.
npm install particles.js
And import particles.js and app.js files from node_modules folder and write the html code.
HTML
<!DOCTYPE html><html lang="en"> <head> <title>particles.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <!-- Particles.js div --> <div id="particles-js"> <div class="heading"> <h1>GeeksforGeeks</h1> <h3>A computer Science portal for geeks</h3> </div> </div> <!-- Import Particles.js and app.js files --> <script src= "/node_modules/particles.js/particles.js"> </script> <script src= "/node_modules/particles.js/demo/js/app.js"> </script></body> </html>
We can change particles properties and interactivity by modifying app.js and then see the magic.
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 252,
"s": 28,
"text": "Particles.js is a lightweight JavaScript library used for creating particles which looks likes the vertices of polygon. We can also interact by hovering over the particles and create more particles by clicking on particles."
},
{
"code": null,
"e": 287,
"s": 252,
"text": "Here is the example of particle.js"
},
{
"code": null,
"e": 405,
"s": 287,
"text": "We can use this library in our portfolios which will definitely attract many users and will look good in the website."
},
{
"code": null,
"e": 427,
"s": 405,
"text": "Installation process:"
},
{
"code": null,
"e": 577,
"s": 427,
"text": "1. Download the particles.js library from the following link, unzip it and copy it into your project folder. https://vincentgarreau.com/particles.js/"
},
{
"code": null,
"e": 623,
"s": 577,
"text": "2. Create two files index.html and style.css."
},
{
"code": null,
"e": 668,
"s": 623,
"text": "Write the following code in index.html file."
},
{
"code": null,
"e": 673,
"s": 668,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>particles.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <!-- Particles.js div --> <div id=\"particles-js\"> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> A computer Science portal for geeks </h3> </div> </div> <!-- Import Particles.js and app.js files --> <script src= \"particles.js-master/particles.js\"> </script> <script src= \"/particles.js-master/demo/js/app.js\"> </script></body> </html>",
"e": 1315,
"s": 673,
"text": null
},
{
"code": null,
"e": 1335,
"s": 1315,
"text": "Filename: style.css"
},
{
"code": null,
"e": 1780,
"s": 1335,
"text": "body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, \n 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,\n 'Open Sans', 'Helvetica Neue', sans-serif;\n}\n.heading {\n position: absolute;\n text-align: center;\n top: 30%;\n width: 100%;\n}\n.heading h1 {\n color: limegreen;\n font-size: 70px;\n}\n.heading h3 {\n color: wheat;\n font-size: 20px;\n}\n#particles-js {\n background: black;\n height: 100vh;\n}"
},
{
"code": null,
"e": 1848,
"s": 1780,
"text": "3. Save the above code in respective files and run index.html file."
},
{
"code": null,
"e": 1956,
"s": 1848,
"text": "Note: If you are using node app, then we can simply download particles.js node module by following command."
},
{
"code": null,
"e": 1981,
"s": 1956,
"text": "npm install particles.js"
},
{
"code": null,
"e": 2072,
"s": 1981,
"text": "And import particles.js and app.js files from node_modules folder and write the html code."
},
{
"code": null,
"e": 2077,
"s": 2072,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>particles.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <!-- Particles.js div --> <div id=\"particles-js\"> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3>A computer Science portal for geeks</h3> </div> </div> <!-- Import Particles.js and app.js files --> <script src= \"/node_modules/particles.js/particles.js\"> </script> <script src= \"/node_modules/particles.js/demo/js/app.js\"> </script></body> </html>",
"e": 2686,
"s": 2077,
"text": null
},
{
"code": null,
"e": 2783,
"s": 2686,
"text": "We can change particles properties and interactivity by modifying app.js and then see the magic."
},
{
"code": null,
"e": 2791,
"s": 2783,
"text": "Output:"
},
{
"code": null,
"e": 2800,
"s": 2791,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2810,
"s": 2800,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2826,
"s": 2810,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2830,
"s": 2826,
"text": "CSS"
},
{
"code": null,
"e": 2835,
"s": 2830,
"text": "HTML"
},
{
"code": null,
"e": 2846,
"s": 2835,
"text": "JavaScript"
},
{
"code": null,
"e": 2863,
"s": 2846,
"text": "Web Technologies"
},
{
"code": null,
"e": 2890,
"s": 2863,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2895,
"s": 2890,
"text": "HTML"
}
] |
Python | Ways to split a string in different ways
|
22 Jun, 2022
The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples:
Input : Paras_Jain_Moengage_best Output : [‘Paras’, ‘Paras_Jain’, ‘Paras_Jain_Moengage’, ‘Paras_Jain_Moengage_best’] Input : chunky_2808_GFG_Codechef Output : [‘chunky’, ‘chunky_2808’, ‘chunky_2808_GFG’, ‘chunky_2808_GFG_Codechef’]
Below are some ways to do the task.
Method #1: Using Iteration
Python3
# Python code to split string in substring manner # Input initialisationInput = "Geeks_for_geeks_is_best" # Split initialisesplit_string = Input.split('_') # Output list initialiseOutput = [] # Iterationfor a in range(len(split_string)): temp = split_string[:a + 1] temp = "_".join(temp) Output.append(temp) # print outputprint(Output)
Method 2: Using Itertools
Python3
# Python code to split string in substring manner # Importingfrom itertools import accumulate # Input initialisationInput = "Geeks_for_geeks_is_best" # Using accumulateOutput = [*accumulate(Input.split('_'), lambda temp1, temp2 : '_'.join([temp1, temp2])), ] # Printing outputprint(Output)
Method#3 : Using re module and string slicing
Python3
# Python code to split string in substring manner# Importingimport re # Input initialisationInput = "Geeks_for_geeks_is_best" # Using re module with string slicing to generate substringans = []for i in re.finditer("(_)", Input): temp = Input[:i.span()[0]] ans.append(temp) # inserting last substringans.append(Input) # Printing outputprint(ans)
Output:
['Geeks', 'Geeks_for', 'Geeks_for_geeks', 'Geeks_for_geeks_is', 'Geeks_for_geeks_is_best']
gabaa406
satyam00so
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": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 316,
"s": 54,
"text": "The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples:"
},
{
"code": null,
"e": 548,
"s": 316,
"text": "Input : Paras_Jain_Moengage_best Output : [‘Paras’, ‘Paras_Jain’, ‘Paras_Jain_Moengage’, ‘Paras_Jain_Moengage_best’] Input : chunky_2808_GFG_Codechef Output : [‘chunky’, ‘chunky_2808’, ‘chunky_2808_GFG’, ‘chunky_2808_GFG_Codechef’]"
},
{
"code": null,
"e": 584,
"s": 548,
"text": "Below are some ways to do the task."
},
{
"code": null,
"e": 612,
"s": 584,
"text": "Method #1: Using Iteration "
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Python3"
},
{
"code": "# Python code to split string in substring manner # Input initialisationInput = \"Geeks_for_geeks_is_best\" # Split initialisesplit_string = Input.split('_') # Output list initialiseOutput = [] # Iterationfor a in range(len(split_string)): temp = split_string[:a + 1] temp = \"_\".join(temp) Output.append(temp) # print outputprint(Output)",
"e": 965,
"s": 620,
"text": null
},
{
"code": null,
"e": 992,
"s": 965,
"text": "Method 2: Using Itertools "
},
{
"code": null,
"e": 1000,
"s": 992,
"text": "Python3"
},
{
"code": "# Python code to split string in substring manner # Importingfrom itertools import accumulate # Input initialisationInput = \"Geeks_for_geeks_is_best\" # Using accumulateOutput = [*accumulate(Input.split('_'), lambda temp1, temp2 : '_'.join([temp1, temp2])), ] # Printing outputprint(Output)",
"e": 1324,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1370,
"s": 1324,
"text": "Method#3 : Using re module and string slicing"
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Python3"
},
{
"code": "# Python code to split string in substring manner# Importingimport re # Input initialisationInput = \"Geeks_for_geeks_is_best\" # Using re module with string slicing to generate substringans = []for i in re.finditer(\"(_)\", Input): temp = Input[:i.span()[0]] ans.append(temp) # inserting last substringans.append(Input) # Printing outputprint(ans)",
"e": 1733,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1741,
"s": 1733,
"text": "Output:"
},
{
"code": null,
"e": 1832,
"s": 1741,
"text": "['Geeks', 'Geeks_for', 'Geeks_for_geeks', 'Geeks_for_geeks_is', 'Geeks_for_geeks_is_best']"
},
{
"code": null,
"e": 1841,
"s": 1832,
"text": "gabaa406"
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": "satyam00so"
},
{
"code": null,
"e": 1873,
"s": 1852,
"text": "Python list-programs"
},
{
"code": null,
"e": 1880,
"s": 1873,
"text": "Python"
},
{
"code": null,
"e": 1896,
"s": 1880,
"text": "Python Programs"
}
] |
Hamiltonian Cycle | Backtracking-6
|
06 Jan, 2022
Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains, then prints the path. Following are the input and output of the required function.Input: A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.Output: An array path[V] that should contain the Hamiltonian Path. path[i] should represent the ith vertex in the Hamiltonian Path. The code should also return false if there is no Hamiltonian Cycle in the graph.For example, a Hamiltonian Cycle in the following graph is {0, 1, 2, 4, 3, 0}.
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4)
And the following graph doesn’t contain any Hamiltonian Cycle.
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4)
Naive Algorithm Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations.
while there are untried conflagrations
{
generate the next configuration
if ( there are edges between two consecutive vertices of this
configuration and there is an edge from the last vertex to
the first ).
{
print this configuration;
break;
}
}
Backtracking Algorithm Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the vertex as part of the solution. If we do not find a vertex then we return false.
Implementation of Backtracking solution Following are implementations of the Backtracking solution.
C++
C
Java
Python3
C#
PHP
Javascript
/* C++ program for solution of HamiltonianCycle problem using backtracking */#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 5 void printSolution(int path[]); /* A utility function to check ifthe vertex v can be added at index 'pos'in the Hamiltonian Cycle constructedso far (stored in 'path[]') */bool isSafe(int v, bool graph[V][V], int path[], int pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph [path[pos - 1]][ v ] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true;} /* A recursive utility functionto solve hamiltonian cycle problem */bool hamCycleUtil(bool graph[V][V], int path[], int pos){ /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the // last included vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate // in Hamiltonian Cycle. We don't try for 0 as // we included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added // to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil (graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problemusing Backtracking. It mainly uses hamCycleUtil() tosolve the problem. It returns false if there is noHamiltonian Cycle possible, otherwise return trueand prints the path. Please note that there may bemore than one solutions, this function prints oneof the feasible solutions. */bool hamCycle(bool graph[V][V]){ int *path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false ) { cout << "\nSolution does not exist"; return false; } printSolution(path); return true;} /* A utility function to print solution */void printSolution(int path[]){ cout << "Solution Exists:" " Following is one Hamiltonian Cycle \n"; for (int i = 0; i < V; i++) cout << path[i] << " "; // Let us print the first vertex again // to show the complete cycle cout << path[0] << " "; cout << endl;} // Driver Codeint main(){ /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) */ bool graph1[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}}; // Print the solution hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) */ bool graph2[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; // Print the solution hamCycle(graph2); return 0;} // This is code is contributed by rathbhupendra
/* C program for solution of Hamiltonian Cycle problem using backtracking */#include<stdio.h> // Number of vertices in the graph#define V 5 void printSolution(int path[]); /* A utility function to check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle constructed so far (stored in 'path[]') */bool isSafe(int v, bool graph[V][V], int path[], int pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph [ path[pos-1] ][ v ] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true;} /* A recursive utility function to solve hamiltonian cycle problem */bool hamCycleUtil(bool graph[V][V], int path[], int pos){ /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included vertex to the // first vertex if ( graph[ path[pos-1] ][ path[0] ] == 1 ) return true; else return false; } // Try different vertices as a next candidate in Hamiltonian Cycle. // We don't try for 0 as we included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil (graph, path, pos+1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */bool hamCycle(bool graph[V][V]){ int *path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if ( hamCycleUtil(graph, path, 1) == false ) { printf("\nSolution does not exist"); return false; } printSolution(path); return true;} /* A utility function to print solution */void printSolution(int path[]){ printf ("Solution Exists:" " Following is one Hamiltonian Cycle \n"); for (int i = 0; i < V; i++) printf(" %d ", path[i]); // Let us print the first vertex again to show the complete cycle printf(" %d ", path[0]); printf("\n");} // driver program to test above functionint main(){ /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) */ bool graph1[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) */ bool graph2[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamCycle(graph2); return 0;}
/* Java program for solution of Hamiltonian Cycle problem using backtracking */class HamiltonianCycle{ final int V = 5; int path[]; /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ boolean isSafe(int v, int graph[][], int path[], int pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1]][v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ boolean hamCycleUtil(int graph[][], int path[], int pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ int hamCycle(int graph[][]) { path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false) { System.out.println("\nSolution does not exist"); return 0; } printSolution(path); return 1; } /* A utility function to print solution */ void printSolution(int path[]) { System.out.println("Solution Exists: Following" + " is one Hamiltonian Cycle"); for (int i = 0; i < V; i++) System.out.print(" " + path[i] + " "); // Let us print the first vertex again to show the // complete cycle System.out.println(" " + path[0] + " "); } // driver program to test above function public static void main(String args[]) { HamiltonianCycle hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) */ int graph1[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) */ int graph2[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamiltonian.hamCycle(graph2); }}// This code is contributed by Abhishek Shankhadhar
# Python program for solution of# hamiltonian cycle problem class Graph(): def __init__(self, vertices): self.graph = [[0 for column in range(vertices)] for row in range(vertices)] self.V = vertices ''' Check if this vertex is an adjacent vertex of the previously added vertex and is not included in the path earlier ''' def isSafe(self, v, pos, path): # Check if current vertex and last vertex # in path are adjacent if self.graph[ path[pos-1] ][v] == 0: return False # Check if current vertex not already in path for vertex in path: if vertex == v: return False return True # A recursive utility function to solve # hamiltonian cycle problem def hamCycleUtil(self, path, pos): # base case: if all vertices are # included in the path if pos == self.V: # Last vertex must be adjacent to the # first vertex in path to make a cycle if self.graph[ path[pos-1] ][ path[0] ] == 1: return True else: return False # Try different vertices as a next candidate # in Hamiltonian Cycle. We don't try for 0 as # we included 0 as starting point in hamCycle() for v in range(1,self.V): if self.isSafe(v, pos, path) == True: path[pos] = v if self.hamCycleUtil(path, pos+1) == True: return True # Remove current vertex if it doesn't # lead to a solution path[pos] = -1 return False def hamCycle(self): path = [-1] * self.V ''' Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected ''' path[0] = 0 if self.hamCycleUtil(path,1) == False: print ("Solution does not exist\n") return False self.printSolution(path) return True def printSolution(self, path): print ("Solution Exists: Following", "is one Hamiltonian Cycle") for vertex in path: print (vertex, end = " ") print (path[0], "\n") # Driver Code ''' Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) '''g1 = Graph(5)g1.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1,],[1, 1, 0, 0, 1], [0, 1, 1, 1, 0], ] # Print the solutiong1.hamCycle(); ''' Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) '''g2 = Graph(5)g2.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0], ] # Print the solutiong2.hamCycle(); # This code is contributed by Divyanshu Mehta
// C# program for solution of Hamiltonian// Cycle problem using backtrackingusing System; public class HamiltonianCycle{ readonly int V = 5; int []path; /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ bool isSafe(int v, int [,]graph, int []path, int pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1], v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ bool hamCycleUtil(int [,]graph, int []path, int pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1],path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ int hamCycle(int [,]graph) { path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false) { Console.WriteLine("\nSolution does not exist"); return 0; } printSolution(path); return 1; } /* A utility function to print solution */ void printSolution(int []path) { Console.WriteLine("Solution Exists: Following" + " is one Hamiltonian Cycle"); for (int i = 0; i < V; i++) Console.Write(" " + path[i] + " "); // Let us print the first vertex again // to show the complete cycle Console.WriteLine(" " + path[0] + " "); } // Driver code public static void Main(String []args) { HamiltonianCycle hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) */ int [,]graph1= {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) */ int [,]graph2 = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamiltonian.hamCycle(graph2); }} // This code contributed by Rajput-Ji
<?php// PHP program for solution of// Hamiltonian Cycle problem// using backtracking$V = 5; /* A utility function to check ifthe vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far(stored in 'path[]') */function isSafe($v, $graph, &$path, $pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if ($graph[$path[$pos - 1]][$v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for ($i = 0; $i < $pos; $i++) if ($path[$i] == $v) return false; return true;} /* A recursive utility functionto solve hamiltonian cycle problem */function hamCycleUtil($graph, &$path, $pos){ global $V; /* base case: If all vertices are included in Hamiltonian Cycle */ if ($pos == $V) { // And if there is an edge from the // last included vertex to the first vertex if ($graph[$path[$pos - 1]][$path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point hamCycle() for ($v = 1; $v < $V; $v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe($v, $graph, $path, $pos)) { $path[$pos] = $v; /* recur to construct rest of the path */ if (hamCycleUtil($graph, $path, $pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ $path[$pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problem usingBacktracking. It mainly uses hamCycleUtil() to solve theproblem. It returns false if there is no Hamiltonian Cyclepossible, otherwise return true and prints the path.Please note that there may be more than one solutions,this function prints one of the feasible solutions. */function hamCycle($graph){ global $V; $path = array_fill(0, $V, 0); for ($i = 0; $i < $V; $i++) $path[$i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ $path[0] = 0; if (hamCycleUtil($graph, $path, 1) == false) { echo("\nSolution does not exist"); return 0; } printSolution($path); return 1;} /* A utility function to print solution */function printSolution($path){ global $V; echo("Solution Exists: Following is ". "one Hamiltonian Cycle\n"); for ($i = 0; $i < $V; $i++) echo(" ".$path[$i]." "); // Let us print the first vertex again to show the // complete cycle echo(" ".$path[0]." \n");} // Driver Code /* Let us create the following graph(0)--(1)--(2) | / \ | | / \ | | / \ |(3)-------(4) */$graph1 = array(array(0, 1, 0, 1, 0), array(1, 0, 1, 1, 1), array(0, 1, 0, 0, 1), array(1, 1, 0, 0, 1), array(0, 1, 1, 1, 0),); // Print the solutionhamCycle($graph1); /* Let us create the following graph(0)--(1)--(2) | / \ | | / \ | | / \ |(3) (4) */$graph2 = array(array(0, 1, 0, 1, 0), array(1, 0, 1, 1, 1), array(0, 1, 0, 0, 1), array(1, 1, 0, 0, 0), array(0, 1, 1, 0, 0)); // Print the solutionhamCycle($graph2); // This code is contributed by mits?>
<script> // JavaScript program for solution of Hamiltonian // Cycle problem using backtracking class HamiltonianCycle { constructor() { this.V = 5; this.path = []; } /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ isSafe(v, graph, path, pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1]][v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (var i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ hamCycleUtil(graph, path, pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == this.V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (var v = 1; v < this.V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (this.isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (this.hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ hamCycle(graph) { this.path = new Array(this.V).fill(0); for (var i = 0; i < this.V; i++) this.path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ this.path[0] = 0; if (this.hamCycleUtil(graph, this.path, 1) == false) { document.write("<br>Solution does not exist"); return 0; } this.printSolution(this.path); return 1; } /* A utility function to print solution */ printSolution(path) { document.write( "Solution Exists: Following" + " is one Hamiltonian Cycle <br>" ); for (var i = 0; i < this.V; i++) document.write(" " + path[i] + " "); // Let us print the first vertex again // to show the complete cycle document.write(" " + path[0] + " <br>"); } } // Driver code var hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3)-------(4) */ var graph1 = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0], ]; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \ | | / \ | | / \ | (3) (4) */ var graph2 = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0], ]; // Print the solution hamiltonian.hamCycle(graph2); // This code is contributed by rdtank. </script>
Output:
Solution Exists: Following is one Hamiltonian Cycle
0 1 2 4 3 0
Solution does not exist
Note that the above code always prints a cycle starting from 0. The starting point should not matter as the cycle can be started from any point. If you want to change the starting point, you should make two changes to the above code. Change “path[0] = 0;” to “path[0] = s;” where s is your new starting point. Also change loop “for (int v = 1; v < V; v++)” in hamCycleUtil() to “for (int v = 0; v < V; v++)”.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vidhayak_Chacha
Rajput-Ji
rathbhupendra
md1844
Mithun Kumar
Akanksha_Rai
rdtank
rajeev0719singh
germanshephered48
Amazon
DFS
Backtracking
Graph
Amazon
DFS
Graph
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Generate all the binary strings of N bits
Print all paths from a given source to a destination
Print all permutations of a string in Java
Find if there is a path of more than k length from a source
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Find if there is a path between two vertices in a directed graph
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 1000,
"s": 52,
"text": "Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains, then prints the path. Following are the input and output of the required function.Input: A 2D array graph[V][V] where V is the number of vertices in graph and graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.Output: An array path[V] that should contain the Hamiltonian Path. path[i] should represent the ith vertex in the Hamiltonian Path. The code should also return false if there is no Hamiltonian Cycle in the graph.For example, a Hamiltonian Cycle in the following graph is {0, 1, 2, 4, 3, 0}."
},
{
"code": null,
"e": 1068,
"s": 1000,
"text": "(0)--(1)--(2)\n | / \\ |\n | / \\ | \n | / \\ |\n(3)-------(4)"
},
{
"code": null,
"e": 1131,
"s": 1068,
"text": "And the following graph doesn’t contain any Hamiltonian Cycle."
},
{
"code": null,
"e": 1199,
"s": 1131,
"text": "(0)--(1)--(2)\n | / \\ |\n | / \\ | \n | / \\ |\n(3) (4) "
},
{
"code": null,
"e": 1375,
"s": 1199,
"text": "Naive Algorithm Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations."
},
{
"code": null,
"e": 1658,
"s": 1375,
"text": "while there are untried conflagrations\n{\n generate the next configuration\n if ( there are edges between two consecutive vertices of this\n configuration and there is an edge from the last vertex to \n the first ).\n {\n print this configuration;\n break;\n }\n}"
},
{
"code": null,
"e": 2009,
"s": 1658,
"text": "Backtracking Algorithm Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the vertex as part of the solution. If we do not find a vertex then we return false."
},
{
"code": null,
"e": 2111,
"s": 2009,
"text": "Implementation of Backtracking solution Following are implementations of the Backtracking solution. "
},
{
"code": null,
"e": 2115,
"s": 2111,
"text": "C++"
},
{
"code": null,
"e": 2117,
"s": 2115,
"text": "C"
},
{
"code": null,
"e": 2122,
"s": 2117,
"text": "Java"
},
{
"code": null,
"e": 2130,
"s": 2122,
"text": "Python3"
},
{
"code": null,
"e": 2133,
"s": 2130,
"text": "C#"
},
{
"code": null,
"e": 2137,
"s": 2133,
"text": "PHP"
},
{
"code": null,
"e": 2148,
"s": 2137,
"text": "Javascript"
},
{
"code": "/* C++ program for solution of HamiltonianCycle problem using backtracking */#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 5 void printSolution(int path[]); /* A utility function to check ifthe vertex v can be added at index 'pos'in the Hamiltonian Cycle constructedso far (stored in 'path[]') */bool isSafe(int v, bool graph[V][V], int path[], int pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph [path[pos - 1]][ v ] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true;} /* A recursive utility functionto solve hamiltonian cycle problem */bool hamCycleUtil(bool graph[V][V], int path[], int pos){ /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the // last included vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate // in Hamiltonian Cycle. We don't try for 0 as // we included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added // to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil (graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problemusing Backtracking. It mainly uses hamCycleUtil() tosolve the problem. It returns false if there is noHamiltonian Cycle possible, otherwise return trueand prints the path. Please note that there may bemore than one solutions, this function prints oneof the feasible solutions. */bool hamCycle(bool graph[V][V]){ int *path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false ) { cout << \"\\nSolution does not exist\"; return false; } printSolution(path); return true;} /* A utility function to print solution */void printSolution(int path[]){ cout << \"Solution Exists:\" \" Following is one Hamiltonian Cycle \\n\"; for (int i = 0; i < V; i++) cout << path[i] << \" \"; // Let us print the first vertex again // to show the complete cycle cout << path[0] << \" \"; cout << endl;} // Driver Codeint main(){ /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) */ bool graph1[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}}; // Print the solution hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) */ bool graph2[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}}; // Print the solution hamCycle(graph2); return 0;} // This is code is contributed by rathbhupendra",
"e": 6090,
"s": 2148,
"text": null
},
{
"code": "/* C program for solution of Hamiltonian Cycle problem using backtracking */#include<stdio.h> // Number of vertices in the graph#define V 5 void printSolution(int path[]); /* A utility function to check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle constructed so far (stored in 'path[]') */bool isSafe(int v, bool graph[V][V], int path[], int pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph [ path[pos-1] ][ v ] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true;} /* A recursive utility function to solve hamiltonian cycle problem */bool hamCycleUtil(bool graph[V][V], int path[], int pos){ /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included vertex to the // first vertex if ( graph[ path[pos-1] ][ path[0] ] == 1 ) return true; else return false; } // Try different vertices as a next candidate in Hamiltonian Cycle. // We don't try for 0 as we included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil (graph, path, pos+1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */bool hamCycle(bool graph[V][V]){ int *path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if ( hamCycleUtil(graph, path, 1) == false ) { printf(\"\\nSolution does not exist\"); return false; } printSolution(path); return true;} /* A utility function to print solution */void printSolution(int path[]){ printf (\"Solution Exists:\" \" Following is one Hamiltonian Cycle \\n\"); for (int i = 0; i < V; i++) printf(\" %d \", path[i]); // Let us print the first vertex again to show the complete cycle printf(\" %d \", path[0]); printf(\"\\n\");} // driver program to test above functionint main(){ /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) */ bool graph1[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) */ bool graph2[V][V] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamCycle(graph2); return 0;}",
"e": 10018,
"s": 6090,
"text": null
},
{
"code": "/* Java program for solution of Hamiltonian Cycle problem using backtracking */class HamiltonianCycle{ final int V = 5; int path[]; /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ boolean isSafe(int v, int graph[][], int path[], int pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1]][v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ boolean hamCycleUtil(int graph[][], int path[], int pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ int hamCycle(int graph[][]) { path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false) { System.out.println(\"\\nSolution does not exist\"); return 0; } printSolution(path); return 1; } /* A utility function to print solution */ void printSolution(int path[]) { System.out.println(\"Solution Exists: Following\" + \" is one Hamiltonian Cycle\"); for (int i = 0; i < V; i++) System.out.print(\" \" + path[i] + \" \"); // Let us print the first vertex again to show the // complete cycle System.out.println(\" \" + path[0] + \" \"); } // driver program to test above function public static void main(String args[]) { HamiltonianCycle hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) */ int graph1[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) */ int graph2[][] = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamiltonian.hamCycle(graph2); }}// This code is contributed by Abhishek Shankhadhar",
"e": 14513,
"s": 10018,
"text": null
},
{
"code": "# Python program for solution of# hamiltonian cycle problem class Graph(): def __init__(self, vertices): self.graph = [[0 for column in range(vertices)] for row in range(vertices)] self.V = vertices ''' Check if this vertex is an adjacent vertex of the previously added vertex and is not included in the path earlier ''' def isSafe(self, v, pos, path): # Check if current vertex and last vertex # in path are adjacent if self.graph[ path[pos-1] ][v] == 0: return False # Check if current vertex not already in path for vertex in path: if vertex == v: return False return True # A recursive utility function to solve # hamiltonian cycle problem def hamCycleUtil(self, path, pos): # base case: if all vertices are # included in the path if pos == self.V: # Last vertex must be adjacent to the # first vertex in path to make a cycle if self.graph[ path[pos-1] ][ path[0] ] == 1: return True else: return False # Try different vertices as a next candidate # in Hamiltonian Cycle. We don't try for 0 as # we included 0 as starting point in hamCycle() for v in range(1,self.V): if self.isSafe(v, pos, path) == True: path[pos] = v if self.hamCycleUtil(path, pos+1) == True: return True # Remove current vertex if it doesn't # lead to a solution path[pos] = -1 return False def hamCycle(self): path = [-1] * self.V ''' Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected ''' path[0] = 0 if self.hamCycleUtil(path,1) == False: print (\"Solution does not exist\\n\") return False self.printSolution(path) return True def printSolution(self, path): print (\"Solution Exists: Following\", \"is one Hamiltonian Cycle\") for vertex in path: print (vertex, end = \" \") print (path[0], \"\\n\") # Driver Code ''' Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) '''g1 = Graph(5)g1.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1,],[1, 1, 0, 0, 1], [0, 1, 1, 1, 0], ] # Print the solutiong1.hamCycle(); ''' Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) '''g2 = Graph(5)g2.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0], ] # Print the solutiong2.hamCycle(); # This code is contributed by Divyanshu Mehta",
"e": 17468,
"s": 14513,
"text": null
},
{
"code": "// C# program for solution of Hamiltonian// Cycle problem using backtrackingusing System; public class HamiltonianCycle{ readonly int V = 5; int []path; /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ bool isSafe(int v, int [,]graph, int []path, int pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1], v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (int i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ bool hamCycleUtil(int [,]graph, int []path, int pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1],path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (int v = 1; v < V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ int hamCycle(int [,]graph) { path = new int[V]; for (int i = 0; i < V; i++) path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ path[0] = 0; if (hamCycleUtil(graph, path, 1) == false) { Console.WriteLine(\"\\nSolution does not exist\"); return 0; } printSolution(path); return 1; } /* A utility function to print solution */ void printSolution(int []path) { Console.WriteLine(\"Solution Exists: Following\" + \" is one Hamiltonian Cycle\"); for (int i = 0; i < V; i++) Console.Write(\" \" + path[i] + \" \"); // Let us print the first vertex again // to show the complete cycle Console.WriteLine(\" \" + path[0] + \" \"); } // Driver code public static void Main(String []args) { HamiltonianCycle hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) */ int [,]graph1= {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {0, 1, 1, 1, 0}, }; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) */ int [,]graph2 = {{0, 1, 0, 1, 0}, {1, 0, 1, 1, 1}, {0, 1, 0, 0, 1}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, }; // Print the solution hamiltonian.hamCycle(graph2); }} // This code contributed by Rajput-Ji",
"e": 21880,
"s": 17468,
"text": null
},
{
"code": "<?php// PHP program for solution of// Hamiltonian Cycle problem// using backtracking$V = 5; /* A utility function to check ifthe vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far(stored in 'path[]') */function isSafe($v, $graph, &$path, $pos){ /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if ($graph[$path[$pos - 1]][$v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for ($i = 0; $i < $pos; $i++) if ($path[$i] == $v) return false; return true;} /* A recursive utility functionto solve hamiltonian cycle problem */function hamCycleUtil($graph, &$path, $pos){ global $V; /* base case: If all vertices are included in Hamiltonian Cycle */ if ($pos == $V) { // And if there is an edge from the // last included vertex to the first vertex if ($graph[$path[$pos - 1]][$path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point hamCycle() for ($v = 1; $v < $V; $v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (isSafe($v, $graph, $path, $pos)) { $path[$pos] = $v; /* recur to construct rest of the path */ if (hamCycleUtil($graph, $path, $pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ $path[$pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false;} /* This function solves the Hamiltonian Cycle problem usingBacktracking. It mainly uses hamCycleUtil() to solve theproblem. It returns false if there is no Hamiltonian Cyclepossible, otherwise return true and prints the path.Please note that there may be more than one solutions,this function prints one of the feasible solutions. */function hamCycle($graph){ global $V; $path = array_fill(0, $V, 0); for ($i = 0; $i < $V; $i++) $path[$i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ $path[0] = 0; if (hamCycleUtil($graph, $path, 1) == false) { echo(\"\\nSolution does not exist\"); return 0; } printSolution($path); return 1;} /* A utility function to print solution */function printSolution($path){ global $V; echo(\"Solution Exists: Following is \". \"one Hamiltonian Cycle\\n\"); for ($i = 0; $i < $V; $i++) echo(\" \".$path[$i].\" \"); // Let us print the first vertex again to show the // complete cycle echo(\" \".$path[0].\" \\n\");} // Driver Code /* Let us create the following graph(0)--(1)--(2) | / \\ | | / \\ | | / \\ |(3)-------(4) */$graph1 = array(array(0, 1, 0, 1, 0), array(1, 0, 1, 1, 1), array(0, 1, 0, 0, 1), array(1, 1, 0, 0, 1), array(0, 1, 1, 1, 0),); // Print the solutionhamCycle($graph1); /* Let us create the following graph(0)--(1)--(2) | / \\ | | / \\ | | / \\ |(3) (4) */$graph2 = array(array(0, 1, 0, 1, 0), array(1, 0, 1, 1, 1), array(0, 1, 0, 0, 1), array(1, 1, 0, 0, 0), array(0, 1, 1, 0, 0)); // Print the solutionhamCycle($graph2); // This code is contributed by mits?>",
"e": 25552,
"s": 21880,
"text": null
},
{
"code": "<script> // JavaScript program for solution of Hamiltonian // Cycle problem using backtracking class HamiltonianCycle { constructor() { this.V = 5; this.path = []; } /* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian Cycle constructed so far (stored in 'path[]') */ isSafe(v, graph, path, pos) { /* Check if this vertex is an adjacent vertex of the previously added vertex. */ if (graph[path[pos - 1]][v] == 0) return false; /* Check if the vertex has already been included. This step can be optimized by creating an array of size V */ for (var i = 0; i < pos; i++) if (path[i] == v) return false; return true; } /* A recursive utility function to solve hamiltonian cycle problem */ hamCycleUtil(graph, path, pos) { /* base case: If all vertices are included in Hamiltonian Cycle */ if (pos == this.V) { // And if there is an edge from the last included // vertex to the first vertex if (graph[path[pos - 1]][path[0]] == 1) return true; else return false; } // Try different vertices as a next candidate in // Hamiltonian Cycle. We don't try for 0 as we // included 0 as starting point in hamCycle() for (var v = 1; v < this.V; v++) { /* Check if this vertex can be added to Hamiltonian Cycle */ if (this.isSafe(v, graph, path, pos)) { path[pos] = v; /* recur to construct rest of the path */ if (this.hamCycleUtil(graph, path, pos + 1) == true) return true; /* If adding vertex v doesn't lead to a solution, then remove it */ path[pos] = -1; } } /* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */ return false; } /* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ hamCycle(graph) { this.path = new Array(this.V).fill(0); for (var i = 0; i < this.V; i++) this.path[i] = -1; /* Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected */ this.path[0] = 0; if (this.hamCycleUtil(graph, this.path, 1) == false) { document.write(\"<br>Solution does not exist\"); return 0; } this.printSolution(this.path); return 1; } /* A utility function to print solution */ printSolution(path) { document.write( \"Solution Exists: Following\" + \" is one Hamiltonian Cycle <br>\" ); for (var i = 0; i < this.V; i++) document.write(\" \" + path[i] + \" \"); // Let us print the first vertex again // to show the complete cycle document.write(\" \" + path[0] + \" <br>\"); } } // Driver code var hamiltonian = new HamiltonianCycle(); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3)-------(4) */ var graph1 = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0], ]; // Print the solution hamiltonian.hamCycle(graph1); /* Let us create the following graph (0)--(1)--(2) | / \\ | | / \\ | | / \\ | (3) (4) */ var graph2 = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 0, 1], [1, 1, 0, 0, 0], [0, 1, 1, 0, 0], ]; // Print the solution hamiltonian.hamCycle(graph2); // This code is contributed by rdtank. </script>",
"e": 29852,
"s": 25552,
"text": null
},
{
"code": null,
"e": 29861,
"s": 29852,
"text": "Output: "
},
{
"code": null,
"e": 29956,
"s": 29861,
"text": "Solution Exists: Following is one Hamiltonian Cycle\n 0 1 2 4 3 0\n\nSolution does not exist"
},
{
"code": null,
"e": 30490,
"s": 29956,
"text": "Note that the above code always prints a cycle starting from 0. The starting point should not matter as the cycle can be started from any point. If you want to change the starting point, you should make two changes to the above code. Change “path[0] = 0;” to “path[0] = s;” where s is your new starting point. Also change loop “for (int v = 1; v < V; v++)” in hamCycleUtil() to “for (int v = 0; v < V; v++)”.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30506,
"s": 30490,
"text": "Vidhayak_Chacha"
},
{
"code": null,
"e": 30516,
"s": 30506,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 30530,
"s": 30516,
"text": "rathbhupendra"
},
{
"code": null,
"e": 30537,
"s": 30530,
"text": "md1844"
},
{
"code": null,
"e": 30550,
"s": 30537,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30563,
"s": 30550,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30570,
"s": 30563,
"text": "rdtank"
},
{
"code": null,
"e": 30586,
"s": 30570,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 30604,
"s": 30586,
"text": "germanshephered48"
},
{
"code": null,
"e": 30611,
"s": 30604,
"text": "Amazon"
},
{
"code": null,
"e": 30615,
"s": 30611,
"text": "DFS"
},
{
"code": null,
"e": 30628,
"s": 30615,
"text": "Backtracking"
},
{
"code": null,
"e": 30634,
"s": 30628,
"text": "Graph"
},
{
"code": null,
"e": 30641,
"s": 30634,
"text": "Amazon"
},
{
"code": null,
"e": 30645,
"s": 30641,
"text": "DFS"
},
{
"code": null,
"e": 30651,
"s": 30645,
"text": "Graph"
},
{
"code": null,
"e": 30664,
"s": 30651,
"text": "Backtracking"
},
{
"code": null,
"e": 30762,
"s": 30664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30847,
"s": 30762,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 30889,
"s": 30847,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 30942,
"s": 30889,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 30985,
"s": 30942,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 31045,
"s": 30985,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 31085,
"s": 31045,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 31123,
"s": 31085,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 31174,
"s": 31123,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 31239,
"s": 31174,
"text": "Find if there is a path between two vertices in a directed graph"
}
] |
Count number of trailing zeros in Binary representation of a number using Bitset
|
09 Jun, 2022
Given a number. The task is to count the number of Trailing Zero in Binary representation of a number using bitset.Examples:
Input : N = 16
Output : 4
Binary representation of N is 10000. Therefore,
number of zeroes at the end is 4.
Input : N = 8
Output : 3
Approach: We simply set the number in the bitset and then we iterate from 0 indexes of bitset, as soon as we get 1 we will break the loop because there is no trailing zero after that.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to count number of trailing zeros// in Binary representation of a number// using Bitset #include <bits/stdc++.h>using namespace std; // Function to count number of trailing zeros in// Binary representation of a number// using Bitsetint CountTrailingZeros(int n){ // declare bitset of 64 bits bitset<64> bit; // set bitset with the value bit |= n; int zero = 0; for (int i = 0; i < 64; i++) { if (bit[i] == 0) zero++; // if '1' comes then break else break; } return zero;} // Driver Codeint main(){ int n = 4; int ans = CountTrailingZeros(n); cout << ans << "\n"; return 0;}
// Java program to count number of trailing zeros// in Binary representation of a number// using Bitsetimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to count number of trailing zeros in // Binary representation of a number // using Bitset static int CountTrailingZeros(int n) { String bit = Integer.toBinaryString(n); StringBuilder bit1 = new StringBuilder(); bit1.append(bit); bit1=bit1.reverse(); int zero = 0; for (int i = 0; i < 64; i++) { if (bit1.charAt(i) == '0') zero++; // if '1' comes then break else break; } return zero; } // Driver Code public static void main(String []args) { int n = 4; int ans = CountTrailingZeros(n); System.out.println(ans); }} // This code is contributed by chitranayal
# Python3 program to count# number of trailing zeros in# Binary representation of a number # Function to count number of# trailing zeros in Binary# representation of a numberdef CountTrailingZeros(n): # declare bitset of 64 bits bit = bin(n)[2:] bit = bit[::-1] zero = 0; for i in range(len(bit)): if (bit[i] == '0'): zero += 1 # if '1' comes then break else: break return zero # Driver Coden = 4 ans = CountTrailingZeros(n) print(ans) # This code is contributed# by Mohit Kumar
// C# program to count number of trailing zeros// in Binary representation of a number// using Bitsetusing System;class GFG{ // Function to count number of trailing zeros in // Binary representation of a number // using Bitset static int CountTrailingZeros(int n) { string bit=Convert.ToString(n, 2); char[] charArray = bit.ToCharArray(); Array.Reverse( charArray ); string bit1 = new string( charArray ); int zero = 0; for (int i = 0; i < 64; i++) { if (bit1[i] == '0') { zero++; } // if '1' comes then break else { break; } } return zero; } // Driver Code static public void Main () { int n = 4; int ans = CountTrailingZeros(n); Console.WriteLine(ans); }} // This code is contributed by avanitrachhadiya2155
<script> // JavaScript program to count number of trailing zeros// in Binary representation of a number// using Bitset // Function to count number of trailing zeros in // Binary representation of a number // using Bitset function CountTrailingZeros(n) { let bit = n.toString(2); let bit1=bit.split(""); bit1=bit1.reverse(); let zero = 0; for (let i = 0; i < 64; i++) { if (bit1[i] == '0') zero++; // if '1' comes then break else break; } return zero; } // Driver Code let n = 4; let ans = CountTrailingZeros(n); document.write(ans); // This code is contributed by rag2127 </script>
2
Time Complexity: O(1)Auxiliary Space: O(1)
mohit kumar 29
ukasp
avanitrachhadiya2155
rag2127
hmaazul25
nishanthsmenon
subham348
number-theory
Bit Magic
Mathematical
number-theory
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Given a number. The task is to count the number of Trailing Zero in Binary representation of a number using bitset.Examples: "
},
{
"code": null,
"e": 289,
"s": 155,
"text": "Input : N = 16\nOutput : 4\nBinary representation of N is 10000. Therefore,\nnumber of zeroes at the end is 4.\n\nInput : N = 8\nOutput : 3"
},
{
"code": null,
"e": 523,
"s": 291,
"text": "Approach: We simply set the number in the bitset and then we iterate from 0 indexes of bitset, as soon as we get 1 we will break the loop because there is no trailing zero after that.Below is the implementation of above approach: "
},
{
"code": null,
"e": 527,
"s": 523,
"text": "C++"
},
{
"code": null,
"e": 532,
"s": 527,
"text": "Java"
},
{
"code": null,
"e": 540,
"s": 532,
"text": "Python3"
},
{
"code": null,
"e": 543,
"s": 540,
"text": "C#"
},
{
"code": null,
"e": 554,
"s": 543,
"text": "Javascript"
},
{
"code": "// C++ program to count number of trailing zeros// in Binary representation of a number// using Bitset #include <bits/stdc++.h>using namespace std; // Function to count number of trailing zeros in// Binary representation of a number// using Bitsetint CountTrailingZeros(int n){ // declare bitset of 64 bits bitset<64> bit; // set bitset with the value bit |= n; int zero = 0; for (int i = 0; i < 64; i++) { if (bit[i] == 0) zero++; // if '1' comes then break else break; } return zero;} // Driver Codeint main(){ int n = 4; int ans = CountTrailingZeros(n); cout << ans << \"\\n\"; return 0;}",
"e": 1229,
"s": 554,
"text": null
},
{
"code": "// Java program to count number of trailing zeros// in Binary representation of a number// using Bitsetimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to count number of trailing zeros in // Binary representation of a number // using Bitset static int CountTrailingZeros(int n) { String bit = Integer.toBinaryString(n); StringBuilder bit1 = new StringBuilder(); bit1.append(bit); bit1=bit1.reverse(); int zero = 0; for (int i = 0; i < 64; i++) { if (bit1.charAt(i) == '0') zero++; // if '1' comes then break else break; } return zero; } // Driver Code public static void main(String []args) { int n = 4; int ans = CountTrailingZeros(n); System.out.println(ans); }} // This code is contributed by chitranayal",
"e": 2183,
"s": 1229,
"text": null
},
{
"code": "# Python3 program to count# number of trailing zeros in# Binary representation of a number # Function to count number of# trailing zeros in Binary# representation of a numberdef CountTrailingZeros(n): # declare bitset of 64 bits bit = bin(n)[2:] bit = bit[::-1] zero = 0; for i in range(len(bit)): if (bit[i] == '0'): zero += 1 # if '1' comes then break else: break return zero # Driver Coden = 4 ans = CountTrailingZeros(n) print(ans) # This code is contributed# by Mohit Kumar",
"e": 2744,
"s": 2183,
"text": null
},
{
"code": "// C# program to count number of trailing zeros// in Binary representation of a number// using Bitsetusing System;class GFG{ // Function to count number of trailing zeros in // Binary representation of a number // using Bitset static int CountTrailingZeros(int n) { string bit=Convert.ToString(n, 2); char[] charArray = bit.ToCharArray(); Array.Reverse( charArray ); string bit1 = new string( charArray ); int zero = 0; for (int i = 0; i < 64; i++) { if (bit1[i] == '0') { zero++; } // if '1' comes then break else { break; } } return zero; } // Driver Code static public void Main () { int n = 4; int ans = CountTrailingZeros(n); Console.WriteLine(ans); }} // This code is contributed by avanitrachhadiya2155",
"e": 3552,
"s": 2744,
"text": null
},
{
"code": "<script> // JavaScript program to count number of trailing zeros// in Binary representation of a number// using Bitset // Function to count number of trailing zeros in // Binary representation of a number // using Bitset function CountTrailingZeros(n) { let bit = n.toString(2); let bit1=bit.split(\"\"); bit1=bit1.reverse(); let zero = 0; for (let i = 0; i < 64; i++) { if (bit1[i] == '0') zero++; // if '1' comes then break else break; } return zero; } // Driver Code let n = 4; let ans = CountTrailingZeros(n); document.write(ans); // This code is contributed by rag2127 </script>",
"e": 4306,
"s": 3552,
"text": null
},
{
"code": null,
"e": 4308,
"s": 4306,
"text": "2"
},
{
"code": null,
"e": 4353,
"s": 4310,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4368,
"s": 4353,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4374,
"s": 4368,
"text": "ukasp"
},
{
"code": null,
"e": 4395,
"s": 4374,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 4403,
"s": 4395,
"text": "rag2127"
},
{
"code": null,
"e": 4413,
"s": 4403,
"text": "hmaazul25"
},
{
"code": null,
"e": 4428,
"s": 4413,
"text": "nishanthsmenon"
},
{
"code": null,
"e": 4438,
"s": 4428,
"text": "subham348"
},
{
"code": null,
"e": 4452,
"s": 4438,
"text": "number-theory"
},
{
"code": null,
"e": 4462,
"s": 4452,
"text": "Bit Magic"
},
{
"code": null,
"e": 4475,
"s": 4462,
"text": "Mathematical"
},
{
"code": null,
"e": 4489,
"s": 4475,
"text": "number-theory"
},
{
"code": null,
"e": 4502,
"s": 4489,
"text": "Mathematical"
},
{
"code": null,
"e": 4512,
"s": 4502,
"text": "Bit Magic"
}
] |
How to globally replace a forward slash in a JavaScript string ?
|
16 Oct, 2019
Method 1: Using replace() method with a regular expression: The replace() method is used to replace the given pattern with another string. The pattern string can be a string or a regular expression. This function will return a new string with the replaced string.
A regular expression is used to replace all the forward slashes. As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\). Also, to replace all the forward slashes on the string, the global modifier (g) is used. It will replace all the forward slashes in the given string.
Syntax:
originalString.replace(/\//g, replacementString)
Example:
<!DOCTYPE html><html><head> <title> How to globally replace a forward slash in a JavaScript string? </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to globally replace a forward slash in a JavaScript string? </b> <p> The original string is: string / with some // slashes / </p> <p> The string after replacing the forward slashes is: <span class="output"></span> </p> <button onclick="replaceSlashes()"> Replace Slashes </button> <script type="text/javascript"> function replaceSlashes() { let origString = 'string / with some // slashes /'; let replacementString = '*'; let replacedString = origString.replace(/\//g, replacementString); document.querySelector('.output').textContent = replacedString; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Splitting in place of the forward-slash and joining it back with required string: The split() method is used to separate a string into an array of strings based on the separator. The string is first separated on the basis of the forward slash as the separator. It will give an array of strings separated at the point where the forward slash was present.The join() method is used to concatenate an array of strings with a specified separator. The required character to be used instead of the forward character is passed as a parameter here. This will replace all the forward slashes in the given string.
Syntax:
origString.split('/').join(replacementString)
Example:
<!DOCTYPE html><html> <head> <title> How to globally replace a forward slash in a JavaScript string? </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to globally replace a forward slash in a JavaScript string? </b> <p> The original string is: string / with some // slashes / </p> <p> The string after replacing the forward slashes is: <span class="output"></span> </p> <button onclick="replaceSlashes()"> Replace Slashes </button> <script type="text/javascript"> function replaceSlashes() { let origString = 'string / with some // slashes /'; let replacementString = '*'; let replacedString = origString.split('/').join(replacementString); document.querySelector('.output').textContent = replacedString; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
javascript-string
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
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": "\n16 Oct, 2019"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "Method 1: Using replace() method with a regular expression: The replace() method is used to replace the given pattern with another string. The pattern string can be a string or a regular expression. This function will return a new string with the replaced string."
},
{
"code": null,
"e": 625,
"s": 292,
"text": "A regular expression is used to replace all the forward slashes. As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\\). Also, to replace all the forward slashes on the string, the global modifier (g) is used. It will replace all the forward slashes in the given string."
},
{
"code": null,
"e": 633,
"s": 625,
"text": "Syntax:"
},
{
"code": null,
"e": 682,
"s": 633,
"text": "originalString.replace(/\\//g, replacementString)"
},
{
"code": null,
"e": 691,
"s": 682,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> How to globally replace a forward slash in a JavaScript string? </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to globally replace a forward slash in a JavaScript string? </b> <p> The original string is: string / with some // slashes / </p> <p> The string after replacing the forward slashes is: <span class=\"output\"></span> </p> <button onclick=\"replaceSlashes()\"> Replace Slashes </button> <script type=\"text/javascript\"> function replaceSlashes() { let origString = 'string / with some // slashes /'; let replacementString = '*'; let replacedString = origString.replace(/\\//g, replacementString); document.querySelector('.output').textContent = replacedString; } </script></body> </html>",
"e": 1710,
"s": 691,
"text": null
},
{
"code": null,
"e": 1718,
"s": 1710,
"text": "Output:"
},
{
"code": null,
"e": 1746,
"s": 1718,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1773,
"s": 1746,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2386,
"s": 1773,
"text": "Method 2: Splitting in place of the forward-slash and joining it back with required string: The split() method is used to separate a string into an array of strings based on the separator. The string is first separated on the basis of the forward slash as the separator. It will give an array of strings separated at the point where the forward slash was present.The join() method is used to concatenate an array of strings with a specified separator. The required character to be used instead of the forward character is passed as a parameter here. This will replace all the forward slashes in the given string."
},
{
"code": null,
"e": 2394,
"s": 2386,
"text": "Syntax:"
},
{
"code": null,
"e": 2440,
"s": 2394,
"text": "origString.split('/').join(replacementString)"
},
{
"code": null,
"e": 2449,
"s": 2440,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to globally replace a forward slash in a JavaScript string? </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to globally replace a forward slash in a JavaScript string? </b> <p> The original string is: string / with some // slashes / </p> <p> The string after replacing the forward slashes is: <span class=\"output\"></span> </p> <button onclick=\"replaceSlashes()\"> Replace Slashes </button> <script type=\"text/javascript\"> function replaceSlashes() { let origString = 'string / with some // slashes /'; let replacementString = '*'; let replacedString = origString.split('/').join(replacementString); document.querySelector('.output').textContent = replacedString; } </script></body> </html>",
"e": 3476,
"s": 2449,
"text": null
},
{
"code": null,
"e": 3484,
"s": 3476,
"text": "Output:"
},
{
"code": null,
"e": 3512,
"s": 3484,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3539,
"s": 3512,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3557,
"s": 3539,
"text": "javascript-string"
},
{
"code": null,
"e": 3564,
"s": 3557,
"text": "Picked"
},
{
"code": null,
"e": 3575,
"s": 3564,
"text": "JavaScript"
},
{
"code": null,
"e": 3592,
"s": 3575,
"text": "Web Technologies"
},
{
"code": null,
"e": 3619,
"s": 3592,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3717,
"s": 3619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3778,
"s": 3717,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3818,
"s": 3778,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3890,
"s": 3818,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3932,
"s": 3890,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3973,
"s": 3932,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4006,
"s": 3973,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4068,
"s": 4006,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4129,
"s": 4068,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4179,
"s": 4129,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to generate a random color for a Matplotlib plot in Python?
|
11 Dec, 2020
Handling huge dataset requires libraries and methods that can be used to store, analyze and manipulate the datasets. Python is a popular choice when it comes to data science and analytics. Data scientists prefer Python due to its wide library support that contains functions which can be used to work with datasets to create graphs and charts. Matplotlib is a data visualization library in Python. Matplotlib works similar to Matlab and produces interactive charts and graphs. Matplotlib offers variety of chart types to choose from. The chart properties can be set explicitly using the inbuilt methods and attributes. To generate random colors for a Matplotlib plot in Python the matplotlib.pyplot and random libraries of Python are used. Following is an example to generate random colors for a Matplotlib plot :
First Approach
A dataset is created with a teams array and wincount array. The teams array is plotted against the X axis and wincount array is plotted against the Y axis. Matplotlib supports RGB or RGBA with float values in the range 0-1.Now RGB or RGBA values that range between 0-1 determine the color for the chart.In this example, in-order to create random values ranging between 0 and 1. The red ‘r’, green ‘g’ and blue ‘b’ values obtained are then passed into a tuple color which forms the final color.This tuple is next assigned to the color attribute of plot() method. The X and Y axis are labeled and a title is provided to the chart using the xlabel() , ylabel() and title() method of matplotlib.pyplot library.
A dataset is created with a teams array and wincount array.
The teams array is plotted against the X axis and wincount array is plotted against the Y axis. Matplotlib supports RGB or RGBA with float values in the range 0-1.
Now RGB or RGBA values that range between 0-1 determine the color for the chart.
In this example, in-order to create random values ranging between 0 and 1. The red ‘r’, green ‘g’ and blue ‘b’ values obtained are then passed into a tuple color which forms the final color.
This tuple is next assigned to the color attribute of plot() method.
The X and Y axis are labeled and a title is provided to the chart using the xlabel() , ylabel() and title() method of matplotlib.pyplot library.
Code Implementation:
Python3
import random as randomimport matplotlib.pyplot as plt teams = ['Kolkata', 'Delhi', 'Mumbai', 'Punjab', 'Hyderabad', 'Bangalore', 'Rajasthan', 'Chennai'] wincount = [2, 0, 6, 0, 1, 0, 1, 4] r = random.random()b = random.random()g = random.random() color = (r, g, b) plt.xlabel("Teams")plt.ylabel("Winning Count")plt.title("IPL RECORDS")plt.plot(teams, wincount, c=color)
Output:
Second Approach
In the second approach, a bar chart is demonstrated. An empty list is declared to hold the color tuples.The X and Y axis are labeled and a title is set for the chart. To append different colors for n records a for loop is executed. The random.choice() method of numpy library is used to create tuples of size 3 with values between 0 and 1. The teams and wincount array are plotted against the X and Y axis.The color attribute of bar() method of matplotlib.pyplot is assigned the list of tuples. Random tuples are chosen from the list for each bar.
In the second approach, a bar chart is demonstrated. An empty list is declared to hold the color tuples.
The X and Y axis are labeled and a title is set for the chart.
To append different colors for n records a for loop is executed.
The random.choice() method of numpy library is used to create tuples of size 3 with values between 0 and 1.
The teams and wincount array are plotted against the X and Y axis.
The color attribute of bar() method of matplotlib.pyplot is assigned the list of tuples. Random tuples are chosen from the list for each bar.
Code Implementation
Python3
import random as randomimport matplotlib.pyplot as pltimport numpy as np l = []teams = ['Kolkata', 'Delhi', 'Mumbai', 'Punjab', 'Hyderabad', 'Bangalore', 'Rajasthan', 'Chennai'] wincount = [2, 0, 6, 0, 1, 0, 1, 4] plt.xlabel("Teams")plt.ylabel("Winning Count")plt.title("IPL RECORDS") for i in range(0, len(teams)+1): l.append(tuple(np.random.choice(range(0, 2), size=3))) plt.bar(teams, wincount, color=l)
Output:
However the disadvantage of using random colors is in case white is chosen, the particular bar or line becomes invisible.
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 842,
"s": 28,
"text": "Handling huge dataset requires libraries and methods that can be used to store, analyze and manipulate the datasets. Python is a popular choice when it comes to data science and analytics. Data scientists prefer Python due to its wide library support that contains functions which can be used to work with datasets to create graphs and charts. Matplotlib is a data visualization library in Python. Matplotlib works similar to Matlab and produces interactive charts and graphs. Matplotlib offers variety of chart types to choose from. The chart properties can be set explicitly using the inbuilt methods and attributes. To generate random colors for a Matplotlib plot in Python the matplotlib.pyplot and random libraries of Python are used. Following is an example to generate random colors for a Matplotlib plot :"
},
{
"code": null,
"e": 857,
"s": 842,
"text": "First Approach"
},
{
"code": null,
"e": 1564,
"s": 857,
"text": "A dataset is created with a teams array and wincount array. The teams array is plotted against the X axis and wincount array is plotted against the Y axis. Matplotlib supports RGB or RGBA with float values in the range 0-1.Now RGB or RGBA values that range between 0-1 determine the color for the chart.In this example, in-order to create random values ranging between 0 and 1. The red ‘r’, green ‘g’ and blue ‘b’ values obtained are then passed into a tuple color which forms the final color.This tuple is next assigned to the color attribute of plot() method. The X and Y axis are labeled and a title is provided to the chart using the xlabel() , ylabel() and title() method of matplotlib.pyplot library."
},
{
"code": null,
"e": 1625,
"s": 1564,
"text": "A dataset is created with a teams array and wincount array. "
},
{
"code": null,
"e": 1789,
"s": 1625,
"text": "The teams array is plotted against the X axis and wincount array is plotted against the Y axis. Matplotlib supports RGB or RGBA with float values in the range 0-1."
},
{
"code": null,
"e": 1870,
"s": 1789,
"text": "Now RGB or RGBA values that range between 0-1 determine the color for the chart."
},
{
"code": null,
"e": 2061,
"s": 1870,
"text": "In this example, in-order to create random values ranging between 0 and 1. The red ‘r’, green ‘g’ and blue ‘b’ values obtained are then passed into a tuple color which forms the final color."
},
{
"code": null,
"e": 2131,
"s": 2061,
"text": "This tuple is next assigned to the color attribute of plot() method. "
},
{
"code": null,
"e": 2276,
"s": 2131,
"text": "The X and Y axis are labeled and a title is provided to the chart using the xlabel() , ylabel() and title() method of matplotlib.pyplot library."
},
{
"code": null,
"e": 2297,
"s": 2276,
"text": "Code Implementation:"
},
{
"code": null,
"e": 2305,
"s": 2297,
"text": "Python3"
},
{
"code": "import random as randomimport matplotlib.pyplot as plt teams = ['Kolkata', 'Delhi', 'Mumbai', 'Punjab', 'Hyderabad', 'Bangalore', 'Rajasthan', 'Chennai'] wincount = [2, 0, 6, 0, 1, 0, 1, 4] r = random.random()b = random.random()g = random.random() color = (r, g, b) plt.xlabel(\"Teams\")plt.ylabel(\"Winning Count\")plt.title(\"IPL RECORDS\")plt.plot(teams, wincount, c=color)",
"e": 2689,
"s": 2305,
"text": null
},
{
"code": null,
"e": 2697,
"s": 2689,
"text": "Output:"
},
{
"code": null,
"e": 2713,
"s": 2697,
"text": "Second Approach"
},
{
"code": null,
"e": 3261,
"s": 2713,
"text": "In the second approach, a bar chart is demonstrated. An empty list is declared to hold the color tuples.The X and Y axis are labeled and a title is set for the chart. To append different colors for n records a for loop is executed. The random.choice() method of numpy library is used to create tuples of size 3 with values between 0 and 1. The teams and wincount array are plotted against the X and Y axis.The color attribute of bar() method of matplotlib.pyplot is assigned the list of tuples. Random tuples are chosen from the list for each bar."
},
{
"code": null,
"e": 3366,
"s": 3261,
"text": "In the second approach, a bar chart is demonstrated. An empty list is declared to hold the color tuples."
},
{
"code": null,
"e": 3430,
"s": 3366,
"text": "The X and Y axis are labeled and a title is set for the chart. "
},
{
"code": null,
"e": 3496,
"s": 3430,
"text": "To append different colors for n records a for loop is executed. "
},
{
"code": null,
"e": 3605,
"s": 3496,
"text": "The random.choice() method of numpy library is used to create tuples of size 3 with values between 0 and 1. "
},
{
"code": null,
"e": 3672,
"s": 3605,
"text": "The teams and wincount array are plotted against the X and Y axis."
},
{
"code": null,
"e": 3814,
"s": 3672,
"text": "The color attribute of bar() method of matplotlib.pyplot is assigned the list of tuples. Random tuples are chosen from the list for each bar."
},
{
"code": null,
"e": 3834,
"s": 3814,
"text": "Code Implementation"
},
{
"code": null,
"e": 3842,
"s": 3834,
"text": "Python3"
},
{
"code": "import random as randomimport matplotlib.pyplot as pltimport numpy as np l = []teams = ['Kolkata', 'Delhi', 'Mumbai', 'Punjab', 'Hyderabad', 'Bangalore', 'Rajasthan', 'Chennai'] wincount = [2, 0, 6, 0, 1, 0, 1, 4] plt.xlabel(\"Teams\")plt.ylabel(\"Winning Count\")plt.title(\"IPL RECORDS\") for i in range(0, len(teams)+1): l.append(tuple(np.random.choice(range(0, 2), size=3))) plt.bar(teams, wincount, color=l)",
"e": 4269,
"s": 3842,
"text": null
},
{
"code": null,
"e": 4277,
"s": 4269,
"text": "Output:"
},
{
"code": null,
"e": 4399,
"s": 4277,
"text": "However the disadvantage of using random colors is in case white is chosen, the particular bar or line becomes invisible."
},
{
"code": null,
"e": 4417,
"s": 4399,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4441,
"s": 4417,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4448,
"s": 4441,
"text": "Python"
},
{
"code": null,
"e": 4467,
"s": 4448,
"text": "Technical Scripter"
}
] |
Matplotlib.pyplot.draw() in Python
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The draw() function in pyplot module of matplotlib library is used to redraw the current figure.
Syntax: matplotlib.pyplot.draw()
Below examples illustrate the matplotlib.pyplot.draw() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt def tellme(s): plt.title(s, fontsize = 16) plt.draw()plt.clf()plt.setp(plt.gca(), autoscale_on = False) tellme('matplotlib.pyplot.draw() function Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1)ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 360): ax.view_init(30, angle) plt.draw() plt.pause(.001) ax.set_title('matplotlib.pyplot.draw()\ function Example', fontweight ="bold")
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 247,
"s": 52,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 344,
"s": 247,
"text": "The draw() function in pyplot module of matplotlib library is used to redraw the current figure."
},
{
"code": null,
"e": 377,
"s": 344,
"text": "Syntax: matplotlib.pyplot.draw()"
},
{
"code": null,
"e": 463,
"s": 377,
"text": "Below examples illustrate the matplotlib.pyplot.draw() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 475,
"s": 463,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt def tellme(s): plt.title(s, fontsize = 16) plt.draw()plt.clf()plt.setp(plt.gca(), autoscale_on = False) tellme('matplotlib.pyplot.draw() function Example')plt.show()",
"e": 740,
"s": 475,
"text": null
},
{
"code": null,
"e": 748,
"s": 740,
"text": "Output:"
},
{
"code": null,
"e": 760,
"s": 748,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as plt fig = plt.figure()ax = fig.add_subplot(111, projection ='3d') X, Y, Z = axes3d.get_test_data(0.1)ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5) for angle in range(0, 360): ax.view_init(30, angle) plt.draw() plt.pause(.001) ax.set_title('matplotlib.pyplot.draw()\\ function Example', fontweight =\"bold\")",
"e": 1214,
"s": 760,
"text": null
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "Output:"
},
{
"code": null,
"e": 1240,
"s": 1222,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1247,
"s": 1240,
"text": "Python"
},
{
"code": null,
"e": 1345,
"s": 1247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1377,
"s": 1345,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1404,
"s": 1377,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1435,
"s": 1404,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1456,
"s": 1435,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1479,
"s": 1456,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1535,
"s": 1479,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1577,
"s": 1535,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1619,
"s": 1577,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1658,
"s": 1619,
"text": "Python | Get unique values from a list"
}
] |
Java.util.Arrays.deepEquals() in Java
|
07 Aug, 2017
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension.
Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.
Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return truee1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.e1 == e2e1.equals(e2) would return true.Note that this definition permits null elements at any depth.
e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
e1 == e2
e1.equals(e2) would return true.
Note that this definition permits null elements at any depth.
It is a method of Arrays Class
Syntax:
public static boolean deepEquals(Object[] o1, Object[] o2)
o1 = First Array to test for Equality
o2 = Second Array to test for Equality
Returns true if two array are equal
// Java program to demonstrate working of deepEquals.import java.util.Arrays;public class GFG {public static void main(String[] args) { int a1[][] = { { 10, 20 }, { 40, 50 }, { 60, 70 } }; int a2[][] = { { 30, 20 }, { 10, 0 }, { 60, 80 } }; int a3[][] = { { 10, 20 }, { 40, 50 }, { 60, 70 } }; System.out.println("Check if a1 is equal to a2 : " + Arrays.deepEquals(a1, a2)); System.out.println("Check if a2 is equal to a3 : " + Arrays.deepEquals(a2, a3)); System.out.println("Check if a1 is equal to a3 : " + Arrays.deepEquals(a1, a3)); }}
Output:
Check if a1 is equal to a2 : false
Check if a2 is equal to a3 : false
Check if a1 is equal to a3 : true
We can even use deepEquals() to test the equality of array of Object of the user define class. Refer to the example belowWe should override the equals method to define the equality of the different parameters in a user defined class.
// Java program to demonstrate working of deepEquals// for arrays of user defined obj.import java.util.Arrays;public class GFG {public static class Employee { int Eid; String Ename; public Employee(int Eid, String Ename) { this.Eid = Eid; this.Ename = Ename; } // Overriding the equals() public boolean equals(Object obj) { // type casting obj to Employee Employee s = (Employee)obj; return (this.Eid == s.Eid && this.Ename.equals(s.Ename)); } } public static void main(String args[]) { // Creating an array of objects of user defined class. Employee e1[][] = { { new Employee(10, "Geek1"), new Employee(11, "Geek2") }, { new Employee(12, "Geek3"), new Employee(13, "Geek4") } }; Employee e2[][] = { { new Employee(10, "Geek1"), new Employee(11, "Geek2") }, { new Employee(12, "Geek3"), new Employee(13, "Geek4") } }; Employee e3[][] = { { new Employee(12, "Geek2"), new Employee(25, "Geek4") }, { new Employee(15, "Geek3"), new Employee(30, "Geek1") } }; System.out.println("Check if e1 is equal to e2 : " + Arrays.deepEquals(e1, e2)); System.out.println("Check if e2 is equal to e3 : " + Arrays.deepEquals(e2, e3)); System.out.println("Check if a1 is equal to a3 : " + Arrays.deepEquals(e1, e3)); }}
Output:
Check if e1 is equal to e2 : true
Check if e2 is equal to e3 : false
Check if a1 is equal to a3 : false
Equals() vs deepEquals()
Though Arrays.equals() works correctly on an single dimensional array but it cannot check the equality of a multidimensional arrays.While Arrays.deepEquals() work on all arrays irrespective of the dimension.
Reference :https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#deepEquals-java.lang.Object:A-java.lang.Object:A-
This article is contributed by Sumit Ghosh. 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 - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Aug, 2017"
},
{
"code": null,
"e": 272,
"s": 53,
"text": "Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension."
},
{
"code": null,
"e": 483,
"s": 272,
"text": "Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal."
},
{
"code": null,
"e": 903,
"s": 483,
"text": "Two possibly null elements e1 and e2 are deeply equal if any of the following conditions hold:e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return truee1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.e1 == e2e1.equals(e2) would return true.Note that this definition permits null elements at any depth."
},
{
"code": null,
"e": 1004,
"s": 903,
"text": "e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true"
},
{
"code": null,
"e": 1129,
"s": 1004,
"text": "e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true."
},
{
"code": null,
"e": 1138,
"s": 1129,
"text": "e1 == e2"
},
{
"code": null,
"e": 1171,
"s": 1138,
"text": "e1.equals(e2) would return true."
},
{
"code": null,
"e": 1233,
"s": 1171,
"text": "Note that this definition permits null elements at any depth."
},
{
"code": null,
"e": 1264,
"s": 1233,
"text": "It is a method of Arrays Class"
},
{
"code": null,
"e": 1272,
"s": 1264,
"text": "Syntax:"
},
{
"code": null,
"e": 1447,
"s": 1272,
"text": "public static boolean deepEquals(Object[] o1, Object[] o2)\n\no1 = First Array to test for Equality\no2 = Second Array to test for Equality\n\nReturns true if two array are equal\n"
},
{
"code": "// Java program to demonstrate working of deepEquals.import java.util.Arrays;public class GFG {public static void main(String[] args) { int a1[][] = { { 10, 20 }, { 40, 50 }, { 60, 70 } }; int a2[][] = { { 30, 20 }, { 10, 0 }, { 60, 80 } }; int a3[][] = { { 10, 20 }, { 40, 50 }, { 60, 70 } }; System.out.println(\"Check if a1 is equal to a2 : \" + Arrays.deepEquals(a1, a2)); System.out.println(\"Check if a2 is equal to a3 : \" + Arrays.deepEquals(a2, a3)); System.out.println(\"Check if a1 is equal to a3 : \" + Arrays.deepEquals(a1, a3)); }}",
"e": 2253,
"s": 1447,
"text": null
},
{
"code": null,
"e": 2261,
"s": 2253,
"text": "Output:"
},
{
"code": null,
"e": 2366,
"s": 2261,
"text": "Check if a1 is equal to a2 : false\nCheck if a2 is equal to a3 : false\nCheck if a1 is equal to a3 : true\n"
},
{
"code": null,
"e": 2600,
"s": 2366,
"text": "We can even use deepEquals() to test the equality of array of Object of the user define class. Refer to the example belowWe should override the equals method to define the equality of the different parameters in a user defined class."
},
{
"code": "// Java program to demonstrate working of deepEquals// for arrays of user defined obj.import java.util.Arrays;public class GFG {public static class Employee { int Eid; String Ename; public Employee(int Eid, String Ename) { this.Eid = Eid; this.Ename = Ename; } // Overriding the equals() public boolean equals(Object obj) { // type casting obj to Employee Employee s = (Employee)obj; return (this.Eid == s.Eid && this.Ename.equals(s.Ename)); } } public static void main(String args[]) { // Creating an array of objects of user defined class. Employee e1[][] = { { new Employee(10, \"Geek1\"), new Employee(11, \"Geek2\") }, { new Employee(12, \"Geek3\"), new Employee(13, \"Geek4\") } }; Employee e2[][] = { { new Employee(10, \"Geek1\"), new Employee(11, \"Geek2\") }, { new Employee(12, \"Geek3\"), new Employee(13, \"Geek4\") } }; Employee e3[][] = { { new Employee(12, \"Geek2\"), new Employee(25, \"Geek4\") }, { new Employee(15, \"Geek3\"), new Employee(30, \"Geek1\") } }; System.out.println(\"Check if e1 is equal to e2 : \" + Arrays.deepEquals(e1, e2)); System.out.println(\"Check if e2 is equal to e3 : \" + Arrays.deepEquals(e2, e3)); System.out.println(\"Check if a1 is equal to a3 : \" + Arrays.deepEquals(e1, e3)); }}",
"e": 4321,
"s": 2600,
"text": null
},
{
"code": null,
"e": 4329,
"s": 4321,
"text": "Output:"
},
{
"code": null,
"e": 4434,
"s": 4329,
"text": "Check if e1 is equal to e2 : true\nCheck if e2 is equal to e3 : false\nCheck if a1 is equal to a3 : false\n"
},
{
"code": null,
"e": 4459,
"s": 4434,
"text": "Equals() vs deepEquals()"
},
{
"code": null,
"e": 4667,
"s": 4459,
"text": "Though Arrays.equals() works correctly on an single dimensional array but it cannot check the equality of a multidimensional arrays.While Arrays.deepEquals() work on all arrays irrespective of the dimension."
},
{
"code": null,
"e": 4792,
"s": 4667,
"text": "Reference :https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#deepEquals-java.lang.Object:A-java.lang.Object:A-"
},
{
"code": null,
"e": 5091,
"s": 4792,
"text": "This article is contributed by Sumit Ghosh. 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": 5216,
"s": 5091,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5236,
"s": 5216,
"text": "Java - util package"
},
{
"code": null,
"e": 5241,
"s": 5236,
"text": "Java"
},
{
"code": null,
"e": 5246,
"s": 5241,
"text": "Java"
}
] |
HTML | <input> align Attribute
|
18 Feb, 2022
The HTML <input> align attribute is used with <input type=”image”> to set the horizontal alignment of image. It is not supported by HTML 5.
Syntax:
<input align="left|right|middle|top|bottom">
Attribute Values:
left: It sets the alignment of image to the left. it is a default value.
right: It sets the alignment of image to the right.
middle: It sets the alignment of image to the middle.
top: It sets the alignment of image to the top.
bottom: It sets the alignment of image to the bottom.
Example 1:
<!DOCTYPE html><html> <head> <title> HTML input align Attribute </title></head> <body> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML input align Attribute</h3> <input type="image" src= "https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo" align="right"> </body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title> HTML input align Attribute </title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML input align Attribute</h3> </center> <div> Email_id: <!--Here type="text" align will not work--> <input type="text" alt="mail_id" align="right"> <input type="image" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks" align="right"> </div></body> </html>
Output:Note: Since <input type=”image”> is not supported by the HTML5 so you can use CSS there instead of this attribute. Syntax for CSS <input type=”image” style=”float:right”>.Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 194,
"s": 54,
"text": "The HTML <input> align attribute is used with <input type=”image”> to set the horizontal alignment of image. It is not supported by HTML 5."
},
{
"code": null,
"e": 202,
"s": 194,
"text": "Syntax:"
},
{
"code": null,
"e": 247,
"s": 202,
"text": "<input align=\"left|right|middle|top|bottom\">"
},
{
"code": null,
"e": 265,
"s": 247,
"text": "Attribute Values:"
},
{
"code": null,
"e": 338,
"s": 265,
"text": "left: It sets the alignment of image to the left. it is a default value."
},
{
"code": null,
"e": 390,
"s": 338,
"text": "right: It sets the alignment of image to the right."
},
{
"code": null,
"e": 444,
"s": 390,
"text": "middle: It sets the alignment of image to the middle."
},
{
"code": null,
"e": 492,
"s": 444,
"text": "top: It sets the alignment of image to the top."
},
{
"code": null,
"e": 546,
"s": 492,
"text": "bottom: It sets the alignment of image to the bottom."
},
{
"code": null,
"e": 557,
"s": 546,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML input align Attribute </title></head> <body> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML input align Attribute</h3> <input type=\"image\" src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\" align=\"right\"> </body> </html>",
"e": 921,
"s": 557,
"text": null
},
{
"code": null,
"e": 929,
"s": 921,
"text": "Output:"
},
{
"code": null,
"e": 940,
"s": 929,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML input align Attribute </title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML input align Attribute</h3> </center> <div> Email_id: <!--Here type=\"text\" align will not work--> <input type=\"text\" alt=\"mail_id\" align=\"right\"> <input type=\"image\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks\" align=\"right\"> </div></body> </html>",
"e": 1486,
"s": 940,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1486,
"text": "Output:Note: Since <input type=”image”> is not supported by the HTML5 so you can use CSS there instead of this attribute. Syntax for CSS <input type=”image” style=”float:right”>.Supported Browsers:"
},
{
"code": null,
"e": 1698,
"s": 1684,
"text": "Google Chrome"
},
{
"code": null,
"e": 1716,
"s": 1698,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Firefox"
},
{
"code": null,
"e": 1731,
"s": 1724,
"text": "Safari"
},
{
"code": null,
"e": 1737,
"s": 1731,
"text": "Opera"
},
{
"code": null,
"e": 1751,
"s": 1737,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1767,
"s": 1751,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1772,
"s": 1767,
"text": "HTML"
},
{
"code": null,
"e": 1789,
"s": 1772,
"text": "Web Technologies"
},
{
"code": null,
"e": 1794,
"s": 1789,
"text": "HTML"
}
] |
Plot a Horizontal line in Matplotlib
|
12 Nov, 2020
Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots
Plotting a horizontal line is fairly simple, Using axhline()
The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis.
Syntax: matplotlib.pyplot.axhline(y, color, xmin, xmax, linestyle)
Parameters:
y: Position on Y axis to plot the line, It accepts integers.
xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range
color: color for the line, It accepts a string. eg ‘r’ or ‘b’ .
linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’
Python3
# importing libraryimport matplotlib.pyplot as plt # specifying horizontal line typeplt.axhline(y = 0.5, color = 'r', linestyle = '-') # rendering the plotplt.show()
Output:
To plot multiple horizontal lines, use the axhline() method multiple times.
Python
# importing the moduleimport matplotlib.pyplot as plt # plotting line within the given rangeplt.axhline(y = .5, xmin = 0.25, xmax = 0.9) # line colour is blueplt.axhline(y = 3, color = 'b', linestyle = ':') # line colour is whiteplt.axhline(y = 1, color = 'w', linestyle = '--') # line colour is redplt.axhline(y = 2, color = 'r', linestyle = 'dashed') # adding axis labels plt.xlabel('x - axis')plt.ylabel('y - axis') # displaying the plotplt.show()
Output:
The legend can be added using the legend() function.
Python3
# importing the moduleimport matplotlib.pyplot as plt # plotting line within the given rangeplt.axhline(y = .5, xmin = 0.25, xmax = 0.9) # line colour is blueplt.axhline(y = 3, color = 'b', linestyle = ':', label = "blue line") # line colour is whiteplt.axhline(y = 1, color = 'w', linestyle = '--', label = "white line") # line colour is redplt.axhline(y = 2, color = 'r', linestyle = 'dashed', label = "red line") # adding axis labels plt.xlabel('x - axis')plt.ylabel('y - axis') # plotting the legendplt.legend(bbox_to_anchor = (1.0, 1), loc = 'upper center') # displaying the plotplt.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": "\n12 Nov, 2020"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots"
},
{
"code": null,
"e": 202,
"s": 141,
"text": "Plotting a horizontal line is fairly simple, Using axhline()"
},
{
"code": null,
"e": 314,
"s": 202,
"text": "The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis."
},
{
"code": null,
"e": 381,
"s": 314,
"text": "Syntax: matplotlib.pyplot.axhline(y, color, xmin, xmax, linestyle)"
},
{
"code": null,
"e": 393,
"s": 381,
"text": "Parameters:"
},
{
"code": null,
"e": 455,
"s": 393,
"text": "y: Position on Y axis to plot the line, It accepts integers."
},
{
"code": null,
"e": 540,
"s": 455,
"text": "xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range"
},
{
"code": null,
"e": 605,
"s": 540,
"text": "color: color for the line, It accepts a string. eg ‘r’ or ‘b’ ."
},
{
"code": null,
"e": 744,
"s": 605,
"text": "linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’"
},
{
"code": null,
"e": 752,
"s": 744,
"text": "Python3"
},
{
"code": "# importing libraryimport matplotlib.pyplot as plt # specifying horizontal line typeplt.axhline(y = 0.5, color = 'r', linestyle = '-') # rendering the plotplt.show()",
"e": 920,
"s": 752,
"text": null
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Output:"
},
{
"code": null,
"e": 1004,
"s": 928,
"text": "To plot multiple horizontal lines, use the axhline() method multiple times."
},
{
"code": null,
"e": 1011,
"s": 1004,
"text": "Python"
},
{
"code": "# importing the moduleimport matplotlib.pyplot as plt # plotting line within the given rangeplt.axhline(y = .5, xmin = 0.25, xmax = 0.9) # line colour is blueplt.axhline(y = 3, color = 'b', linestyle = ':') # line colour is whiteplt.axhline(y = 1, color = 'w', linestyle = '--') # line colour is redplt.axhline(y = 2, color = 'r', linestyle = 'dashed') # adding axis labels plt.xlabel('x - axis')plt.ylabel('y - axis') # displaying the plotplt.show()",
"e": 1477,
"s": 1011,
"text": null
},
{
"code": null,
"e": 1485,
"s": 1477,
"text": "Output:"
},
{
"code": null,
"e": 1538,
"s": 1485,
"text": "The legend can be added using the legend() function."
},
{
"code": null,
"e": 1546,
"s": 1538,
"text": "Python3"
},
{
"code": "# importing the moduleimport matplotlib.pyplot as plt # plotting line within the given rangeplt.axhline(y = .5, xmin = 0.25, xmax = 0.9) # line colour is blueplt.axhline(y = 3, color = 'b', linestyle = ':', label = \"blue line\") # line colour is whiteplt.axhline(y = 1, color = 'w', linestyle = '--', label = \"white line\") # line colour is redplt.axhline(y = 2, color = 'r', linestyle = 'dashed', label = \"red line\") # adding axis labels plt.xlabel('x - axis')plt.ylabel('y - axis') # plotting the legendplt.legend(bbox_to_anchor = (1.0, 1), loc = 'upper center') # displaying the plotplt.show()",
"e": 2157,
"s": 1546,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2157,
"text": "Output:"
},
{
"code": null,
"e": 2183,
"s": 2165,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2190,
"s": 2183,
"text": "Python"
}
] |
std::gcd | C++ inbuilt function for finding GCD
|
24 Jun, 2022
In many competitive programming problems, we need to find greatest common divisor also known as gcd. Euclids algorithm to find gcd has been discussed here.C++ has the built-in function for calculating GCD. This function is present in header file. Syntax for C++14 :
Library: 'algorithm'
__gcd(m, n)
Parameter : m, n
Return Value : 0 if both m and n are zero,
else gcd of m and n.
Syntax for C++17 :
Library: 'numeric'
gcd(m, n)
Parameter : m, n
Return Value : 0 if both m and n are zero,
else gcd of m and n.
CPP
// CPP program to illustrate// gcd function of C++ STL#include <iostream>#include <algorithm>// #include<numeric> for C++17 using namespace std; int main(){ cout << "gcd(6, 20) = " << __gcd(6, 20) << endl; // gcd(2.0,8) for C++17}
gcd(6, 20) = 2
Time Complexity: O(logn)
Auxiliary Space: O(1)
Note: If either M or N is not an integer type, or if either is (possibly cv-qualified) bool, the program is ill-formed. Also, If either |m| or |n| is not representable as a value of type std::common_type_t, the behavior is undefined.
CPP
// CPP program to illustrate// undefined behavior of// gcd function of C++ STL#include <iostream>#include <algorithm>// #include<numeric> for C++17 using namespace std; int main(){ cout << "gcd(6, 20) = " << __gcd(2.0, 8) << endl; // gcd(2.0,8) for C++17}
Output: Error, As the data type float is not supported by std::gcd.This article is contributed by Pratik Chhajer. 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.
utkarshanand221
gauravguptaco20b366
CPP-Library
cpp-numerics-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 319,
"s": 53,
"text": "In many competitive programming problems, we need to find greatest common divisor also known as gcd. Euclids algorithm to find gcd has been discussed here.C++ has the built-in function for calculating GCD. This function is present in header file. Syntax for C++14 :"
},
{
"code": null,
"e": 439,
"s": 319,
"text": " Library: 'algorithm'\n __gcd(m, n) \nParameter : m, n\nReturn Value : 0 if both m and n are zero, \nelse gcd of m and n."
},
{
"code": null,
"e": 458,
"s": 439,
"text": "Syntax for C++17 :"
},
{
"code": null,
"e": 570,
"s": 458,
"text": "Library: 'numeric'\ngcd(m, n)\nParameter : m, n\nReturn Value : 0 if both m and n are zero,\nelse gcd of m and n."
},
{
"code": null,
"e": 574,
"s": 570,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// gcd function of C++ STL#include <iostream>#include <algorithm>// #include<numeric> for C++17 using namespace std; int main(){ cout << \"gcd(6, 20) = \" << __gcd(6, 20) << endl; // gcd(2.0,8) for C++17}",
"e": 808,
"s": 574,
"text": null
},
{
"code": null,
"e": 823,
"s": 808,
"text": "gcd(6, 20) = 2"
},
{
"code": null,
"e": 848,
"s": 823,
"text": "Time Complexity: O(logn)"
},
{
"code": null,
"e": 870,
"s": 848,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1106,
"s": 870,
"text": "Note: If either M or N is not an integer type, or if either is (possibly cv-qualified) bool, the program is ill-formed. Also, If either |m| or |n| is not representable as a value of type std::common_type_t, the behavior is undefined. "
},
{
"code": null,
"e": 1110,
"s": 1106,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// undefined behavior of// gcd function of C++ STL#include <iostream>#include <algorithm>// #include<numeric> for C++17 using namespace std; int main(){ cout << \"gcd(6, 20) = \" << __gcd(2.0, 8) << endl; // gcd(2.0,8) for C++17}",
"e": 1369,
"s": 1110,
"text": null
},
{
"code": null,
"e": 1859,
"s": 1369,
"text": "Output: Error, As the data type float is not supported by std::gcd.This article is contributed by Pratik Chhajer. 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": 1875,
"s": 1859,
"text": "utkarshanand221"
},
{
"code": null,
"e": 1895,
"s": 1875,
"text": "gauravguptaco20b366"
},
{
"code": null,
"e": 1907,
"s": 1895,
"text": "CPP-Library"
},
{
"code": null,
"e": 1928,
"s": 1907,
"text": "cpp-numerics-library"
},
{
"code": null,
"e": 1932,
"s": 1928,
"text": "STL"
},
{
"code": null,
"e": 1936,
"s": 1932,
"text": "C++"
},
{
"code": null,
"e": 1940,
"s": 1936,
"text": "STL"
},
{
"code": null,
"e": 1944,
"s": 1940,
"text": "CPP"
}
] |
Puppet - Overview
|
Puppet is a configuration management tool developed by Puppet Labs in order to automate infrastructure management and configuration. Puppet is a very powerful tool which helps in the concept of Infrastructure as code. This tool is written in Ruby DSL language that helps in converting a complete infrastructure in code format, which can be easily managed and configured.
Puppet follows the client-server model, where one machine in any cluster acts as the server, known as puppet master and the other acts as a client known as a slave on nodes. Puppet has the capability to manage any system from scratch, starting from initial configuration till the end-of-life of any particular machine.
Following are the most important features of Puppet.
Puppet supports Idempotency which makes it unique. Similar to Chef, in Puppet, one can safely run the same set of configuration multiple times on the same machine. In this flow, Puppet checks for the current status of the target machine and will only make changes when there is any specific change in the configuration.
Idempotency helps in managing any particular machine throughout its lifecycle starting from the creation of machine, configurational changes in the machine, till the end-of-life. Puppet Idempotency feature is very helpful in keeping the machine updated for years rather than rebuilding the same machine multiple times, when there is any configurational change.
In Puppet, with the help of Resource Abstraction Layer (RAL) which uses Puppet resources, one can target the specified configuration of system without worrying about the implementation details and how the configuration command will work inside the system, which are defined in the underlying configuration file.
Puppet uses the following workflow to apply configuration on the system.
In Puppet, the first thing what the Puppet master does is to collect the details of the target machine. Using the factor which is present on all Puppet nodes (similar to Ohai in Chef) it gets all the machine level configuration details. These details are collected and sent back to the Puppet master.
In Puppet, the first thing what the Puppet master does is to collect the details of the target machine. Using the factor which is present on all Puppet nodes (similar to Ohai in Chef) it gets all the machine level configuration details. These details are collected and sent back to the Puppet master.
Then the puppet master compares the retrieved configuration with defined configuration details, and with the defined configuration it creates a catalog and sends it to the targeted Puppet agents.
Then the puppet master compares the retrieved configuration with defined configuration details, and with the defined configuration it creates a catalog and sends it to the targeted Puppet agents.
The Puppet agent then applies those configurations to get the system into a desired state.
The Puppet agent then applies those configurations to get the system into a desired state.
Finally, once one has the target node in a desired state, it sends a report back to the Puppet master, which helps the Puppet master in understanding where the current state of the system is, as defined in the catalog.
Finally, once one has the target node in a desired state, it sends a report back to the Puppet master, which helps the Puppet master in understanding where the current state of the system is, as defined in the catalog.
Following are the key components of Puppet.
Puppet resources are the key components for modeling any particular machine. These resources have their own implementation model. Puppet uses the same model to get any particular resource in the desired state.
Providers are basically fulfillers of any particular resource used in Puppet. For example, the package type ‘apt-get’ and ‘yum’ both are valid for package management. Sometimes, more than one provider would be available on a particular platform. Though each platform always have a default provider.
Manifest is a collection of resources which are coupled inside the function or classes to configure any target system. They contain a set of Ruby code in order to configure a system.
Module is the key building block of Puppet, which can be defined as a collection of resources, files, templates, etc. They can be easily distributed among different kinds of OS being defined that they are of the same flavor. As they can be easily distributed, one module can be used multiple times with the same configuration.
Templates use Ruby expressions to define the customized content and variable input. They are used to develop custom content. Templates are defined in manifests and are copied to a location on the system. For example, if one wants to define httpd with a customizable port, then it can be done using the following expression.
Listen <% = @httpd_port %>
The httpd_port variable in this case is defined in the manifest that references this template.
Static files can be defined as a general file which are sometimes required to perform specific tasks. They can be simply copied from one location to another using Puppet. All static files are located inside the files directory of any module. Any manipulation of the file in a manifest is done using the file resource.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2544,
"s": 2173,
"text": "Puppet is a configuration management tool developed by Puppet Labs in order to automate infrastructure management and configuration. Puppet is a very powerful tool which helps in the concept of Infrastructure as code. This tool is written in Ruby DSL language that helps in converting a complete infrastructure in code format, which can be easily managed and configured."
},
{
"code": null,
"e": 2863,
"s": 2544,
"text": "Puppet follows the client-server model, where one machine in any cluster acts as the server, known as puppet master and the other acts as a client known as a slave on nodes. Puppet has the capability to manage any system from scratch, starting from initial configuration till the end-of-life of any particular machine."
},
{
"code": null,
"e": 2916,
"s": 2863,
"text": "Following are the most important features of Puppet."
},
{
"code": null,
"e": 3236,
"s": 2916,
"text": "Puppet supports Idempotency which makes it unique. Similar to Chef, in Puppet, one can safely run the same set of configuration multiple times on the same machine. In this flow, Puppet checks for the current status of the target machine and will only make changes when there is any specific change in the configuration."
},
{
"code": null,
"e": 3597,
"s": 3236,
"text": "Idempotency helps in managing any particular machine throughout its lifecycle starting from the creation of machine, configurational changes in the machine, till the end-of-life. Puppet Idempotency feature is very helpful in keeping the machine updated for years rather than rebuilding the same machine multiple times, when there is any configurational change."
},
{
"code": null,
"e": 3909,
"s": 3597,
"text": "In Puppet, with the help of Resource Abstraction Layer (RAL) which uses Puppet resources, one can target the specified configuration of system without worrying about the implementation details and how the configuration command will work inside the system, which are defined in the underlying configuration file."
},
{
"code": null,
"e": 3982,
"s": 3909,
"text": "Puppet uses the following workflow to apply configuration on the system."
},
{
"code": null,
"e": 4283,
"s": 3982,
"text": "In Puppet, the first thing what the Puppet master does is to collect the details of the target machine. Using the factor which is present on all Puppet nodes (similar to Ohai in Chef) it gets all the machine level configuration details. These details are collected and sent back to the Puppet master."
},
{
"code": null,
"e": 4584,
"s": 4283,
"text": "In Puppet, the first thing what the Puppet master does is to collect the details of the target machine. Using the factor which is present on all Puppet nodes (similar to Ohai in Chef) it gets all the machine level configuration details. These details are collected and sent back to the Puppet master."
},
{
"code": null,
"e": 4780,
"s": 4584,
"text": "Then the puppet master compares the retrieved configuration with defined configuration details, and with the defined configuration it creates a catalog and sends it to the targeted Puppet agents."
},
{
"code": null,
"e": 4976,
"s": 4780,
"text": "Then the puppet master compares the retrieved configuration with defined configuration details, and with the defined configuration it creates a catalog and sends it to the targeted Puppet agents."
},
{
"code": null,
"e": 5067,
"s": 4976,
"text": "The Puppet agent then applies those configurations to get the system into a desired state."
},
{
"code": null,
"e": 5158,
"s": 5067,
"text": "The Puppet agent then applies those configurations to get the system into a desired state."
},
{
"code": null,
"e": 5377,
"s": 5158,
"text": "Finally, once one has the target node in a desired state, it sends a report back to the Puppet master, which helps the Puppet master in understanding where the current state of the system is, as defined in the catalog."
},
{
"code": null,
"e": 5596,
"s": 5377,
"text": "Finally, once one has the target node in a desired state, it sends a report back to the Puppet master, which helps the Puppet master in understanding where the current state of the system is, as defined in the catalog."
},
{
"code": null,
"e": 5640,
"s": 5596,
"text": "Following are the key components of Puppet."
},
{
"code": null,
"e": 5850,
"s": 5640,
"text": "Puppet resources are the key components for modeling any particular machine. These resources have their own implementation model. Puppet uses the same model to get any particular resource in the desired state."
},
{
"code": null,
"e": 6149,
"s": 5850,
"text": "Providers are basically fulfillers of any particular resource used in Puppet. For example, the package type ‘apt-get’ and ‘yum’ both are valid for package management. Sometimes, more than one provider would be available on a particular platform. Though each platform always have a default provider."
},
{
"code": null,
"e": 6332,
"s": 6149,
"text": "Manifest is a collection of resources which are coupled inside the function or classes to configure any target system. They contain a set of Ruby code in order to configure a system."
},
{
"code": null,
"e": 6659,
"s": 6332,
"text": "Module is the key building block of Puppet, which can be defined as a collection of resources, files, templates, etc. They can be easily distributed among different kinds of OS being defined that they are of the same flavor. As they can be easily distributed, one module can be used multiple times with the same configuration."
},
{
"code": null,
"e": 6983,
"s": 6659,
"text": "Templates use Ruby expressions to define the customized content and variable input. They are used to develop custom content. Templates are defined in manifests and are copied to a location on the system. For example, if one wants to define httpd with a customizable port, then it can be done using the following expression."
},
{
"code": null,
"e": 7011,
"s": 6983,
"text": "Listen <% = @httpd_port %>\n"
},
{
"code": null,
"e": 7106,
"s": 7011,
"text": "The httpd_port variable in this case is defined in the manifest that references this template."
},
{
"code": null,
"e": 7424,
"s": 7106,
"text": "Static files can be defined as a general file which are sometimes required to perform specific tasks. They can be simply copied from one location to another using Puppet. All static files are located inside the files directory of any module. Any manipulation of the file in a manifest is done using the file resource."
},
{
"code": null,
"e": 7431,
"s": 7424,
"text": " Print"
},
{
"code": null,
"e": 7442,
"s": 7431,
"text": " Add Notes"
}
] |
How to define preformatted text using HTML ? - GeeksforGeeks
|
24 Jun, 2020
In this article, we define a preformatted text in HTML by using the <pre> tag in the document. It is used to define the block of preformatted text that preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the pre tag is displayed in a fixed-width font, but it can be changed using CSS. The pre tag requires a starting and ending tag.
Syntax:
<pre> Contents... </pre>
Example 1:
<html> <head> <title>HTML5: How to define preformatted text?</title> <style> h2 { Text-align:center; }</style> </head> <body> <h2>GeeKsForGeeks</h2> <h2>HTML5: How to define preformatted text</h2> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body> </html>
Output:
Example 2:
<html> <head> <title>HTML5: How to define preformatted text?</title> <style> h2 { Text-align:center; }</style> </head> <body> <h2>GeeKsForGeeks</h2> <h2>HTML5: How to define preformatted text</h2> <pre>this is a pre formatted text</pre> </body> </html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
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.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25428,
"s": 25400,
"text": "\n24 Jun, 2020"
},
{
"code": null,
"e": 25830,
"s": 25428,
"text": "In this article, we define a preformatted text in HTML by using the <pre> tag in the document. It is used to define the block of preformatted text that preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the pre tag is displayed in a fixed-width font, but it can be changed using CSS. The pre tag requires a starting and ending tag."
},
{
"code": null,
"e": 25838,
"s": 25830,
"text": "Syntax:"
},
{
"code": null,
"e": 25863,
"s": 25838,
"text": "<pre> Contents... </pre>"
},
{
"code": null,
"e": 25874,
"s": 25863,
"text": "Example 1:"
},
{
"code": "<html> <head> <title>HTML5: How to define preformatted text?</title> <style> h2 { Text-align:center; }</style> </head> <body> <h2>GeeKsForGeeks</h2> <h2>HTML5: How to define preformatted text</h2> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> </body> </html> ",
"e": 26256,
"s": 25874,
"text": null
},
{
"code": null,
"e": 26264,
"s": 26256,
"text": "Output:"
},
{
"code": null,
"e": 26275,
"s": 26264,
"text": "Example 2:"
},
{
"code": "<html> <head> <title>HTML5: How to define preformatted text?</title> <style> h2 { Text-align:center; }</style> </head> <body> <h2>GeeKsForGeeks</h2> <h2>HTML5: How to define preformatted text</h2> <pre>this is a pre formatted text</pre> </body> </html> ",
"e": 26632,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26640,
"s": 26632,
"text": "Output:"
},
{
"code": null,
"e": 26677,
"s": 26640,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 26691,
"s": 26677,
"text": "Google Chrome"
},
{
"code": null,
"e": 26709,
"s": 26691,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26717,
"s": 26709,
"text": "Firefox"
},
{
"code": null,
"e": 26723,
"s": 26717,
"text": "Opera"
},
{
"code": null,
"e": 26730,
"s": 26723,
"text": "Safari"
},
{
"code": null,
"e": 26867,
"s": 26730,
"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": 26877,
"s": 26867,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26882,
"s": 26877,
"text": "HTML"
},
{
"code": null,
"e": 26899,
"s": 26882,
"text": "Web Technologies"
},
{
"code": null,
"e": 26904,
"s": 26899,
"text": "HTML"
},
{
"code": null,
"e": 27002,
"s": 26904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27050,
"s": 27002,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27100,
"s": 27050,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27124,
"s": 27100,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27174,
"s": 27124,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27216,
"s": 27174,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 27258,
"s": 27216,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27291,
"s": 27258,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27334,
"s": 27291,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27379,
"s": 27334,
"text": "Convert a string to an integer in JavaScript"
}
] |
Python set operation.
|
In mathematics, a set is a collection of distinct objects, considered as an object in its own right. For example, the numbers 2, 4, and 6 are distinct objects when considered separately, but when they are considered collectively they form a single set of size three, written {2,4,6}.
In python, compared to list, the main advantages of using a set are that it has optimized functions for checking whether a specific element is a member of the set or not. This is based on a hash table data structure.
add(x) Method: It adds the item x to a set if it is non-preexisting.
A = {"AA", "BB", "CC"}
A.add("VV")
This will add VV in A set.
union(s) Method: It returns a union of two set.Using the operator ‘|’between 2 existing sets is the same as writing My_Set1.union(My_Set2)..
A = {"AA", "BB", "CC"}
B = {"MM", "NN"}
Z = A.union(B)
OR
Z = A|B
Set population set will have components of both A and B.
intersect(s) Method: It returns an intersection of two givensets. The ‘&’ operator can be used in this operation.
S = A.intersection(B)
Set victims will contain the common elements of A and B.
difference(s) Method: Returns a set containing all the elements which are existing in the first set but not present in the second set. We can use ‘-‘ operator here.
W = A.difference(B)
OR
S = A – B
Set safe will have all the elements that are in A but not in B.
clear() Method: The whole existing set will become empty.
B.clear()
Clears B set
Sets and frozen sets support the following operators -
key in s # containment check
key not in s # non-containment check
s1 == s2 # s1 is equivalent to s2
s1 != s2 # s1 is not equivalent to s2
s1 <= s2 # s1is subset of s2 s1 < s2 # s1 is proper subset of s2 s1 >= s2 # s1is superset of s2
s1 > s2 # s1 is proper superset of s2
s1 | s2 # the union of s1 and s2
s1 & s2 # the intersection of s1 and s2
s1 – s2 # the set of elements in s1 but not s2
s1 ˆ s2 # the set of elements in precisely one of s1 or s2
# Python program to demonstrate working# of
# Set in Python
# creating two sets
My_Set1 = set()
My_Set2 = set()
# Adding elements to My_Set1
for i in range(1, 6):
My_Set1.add(i)
# Adding elements to My_Set2
for i in range(3, 8):
My_Set2.add(i)
print("My_Set1 = ", My_Set1)
print("My_Set2 = ", My_Set2)
print("\n")
# Union of My_Set1 and My_Set2
My_Set3 = My_Set1 | My_Set2# My_Set1.union(My_Set2)
print("Union of My_Set1&My_Set2: My_Set3 = ", My_Set3)
# Intersection of My_Set1 and My_Set2
My_Set4 = My_Set1&My_Set2# My_Set1.intersection(My_Set2)
print("Intersection of My_Set1&My_Set2: My_Set4 = ", My_Set4)
print("\n")
# Checking relation between My_Set3 and My_Set4
if My_Set3>My_Set4: # My_Set3.issuperset(My_Set4)
print("My_Set3 is superset of My_Set4")
elif My_Set3<My_Set4: # My_Set3.issubset(My_Set4)
print("My_Set3 is subset of My_Set4")
else : # My_Set3 == My_Set4
print("My_Set3 is same as My_Set4")
# displaying relation between My_Set4 and My_Set3
if My_Set4<My_Set3: # My_Set4.issubset(My_Set3)
print("My_Set4 is subset of My_Set3")
print("\n")
# difference between My_Set3 and My_Set4
My_Set5 = My_Set3 - My_Set4
print("Elements in My_Set3 and not in My_Set4: My_Set5 = ", My_Set5)
print("\n")
# check if My_Set4 and My_Set5 are disjoint sets
if My_Set4.isdisjoint(My_Set5):
print("My_Set4 and My_Set5 have nothing in common\n")
# Removing all the values of My_Set5
My_Set5.clear()
print("After applying clear on sets My_Set5: ")
print("My_Set5 = ", My_Set5)
My_Set1 = {1, 2, 3, 4, 5}
My_Set2 = {3, 4, 5, 6, 7}
Union of My_Set1&My_Set2: My_Set3 = {1, 2, 3, 4, 5, 6, 7}
Intersection of My_Set1&My_Set2: My_Set4 = {3, 4, 5}
My_Set3 is superset of My_Set4
My_Set4 is subset of My_Set3
Elements in My_Set3 and not in My_Set4: My_Set5 = {1, 2, 6, 7}
My_Set4 and My_Set5 have nothing in common
After applying clear on sets My_Set5:
My_Set5 = set()
|
[
{
"code": null,
"e": 1346,
"s": 1062,
"text": "In mathematics, a set is a collection of distinct objects, considered as an object in its own right. For example, the numbers 2, 4, and 6 are distinct objects when considered separately, but when they are considered collectively they form a single set of size three, written {2,4,6}."
},
{
"code": null,
"e": 1563,
"s": 1346,
"text": "In python, compared to list, the main advantages of using a set are that it has optimized functions for checking whether a specific element is a member of the set or not. This is based on a hash table data structure."
},
{
"code": null,
"e": 1632,
"s": 1563,
"text": "add(x) Method: It adds the item x to a set if it is non-preexisting."
},
{
"code": null,
"e": 1668,
"s": 1632,
"text": "A = {\"AA\", \"BB\", \"CC\"}\nA.add(\"VV\")\n"
},
{
"code": null,
"e": 1695,
"s": 1668,
"text": "This will add VV in A set."
},
{
"code": null,
"e": 1836,
"s": 1695,
"text": "union(s) Method: It returns a union of two set.Using the operator ‘|’between 2 existing sets is the same as writing My_Set1.union(My_Set2).."
},
{
"code": null,
"e": 1903,
"s": 1836,
"text": "A = {\"AA\", \"BB\", \"CC\"}\nB = {\"MM\", \"NN\"}\nZ = A.union(B)\nOR\nZ = A|B\n"
},
{
"code": null,
"e": 1960,
"s": 1903,
"text": "Set population set will have components of both A and B."
},
{
"code": null,
"e": 2074,
"s": 1960,
"text": "intersect(s) Method: It returns an intersection of two givensets. The ‘&’ operator can be used in this operation."
},
{
"code": null,
"e": 2097,
"s": 2074,
"text": "S = A.intersection(B)\n"
},
{
"code": null,
"e": 2154,
"s": 2097,
"text": "Set victims will contain the common elements of A and B."
},
{
"code": null,
"e": 2319,
"s": 2154,
"text": "difference(s) Method: Returns a set containing all the elements which are existing in the first set but not present in the second set. We can use ‘-‘ operator here."
},
{
"code": null,
"e": 2353,
"s": 2319,
"text": "W = A.difference(B)\nOR\nS = A – B\n"
},
{
"code": null,
"e": 2417,
"s": 2353,
"text": "Set safe will have all the elements that are in A but not in B."
},
{
"code": null,
"e": 2475,
"s": 2417,
"text": "clear() Method: The whole existing set will become empty."
},
{
"code": null,
"e": 2486,
"s": 2475,
"text": "B.clear()\n"
},
{
"code": null,
"e": 2499,
"s": 2486,
"text": "Clears B set"
},
{
"code": null,
"e": 2554,
"s": 2499,
"text": "Sets and frozen sets support the following operators -"
},
{
"code": null,
"e": 3079,
"s": 2554,
"text": "key in s # containment check\nkey not in s # non-containment check\ns1 == s2 # s1 is equivalent to s2\ns1 != s2 # s1 is not equivalent to s2\ns1 <= s2 # s1is subset of s2 s1 < s2 # s1 is proper subset of s2 s1 >= s2 # s1is superset of s2\ns1 > s2 # s1 is proper superset of s2\ns1 | s2 # the union of s1 and s2\ns1 & s2 # the intersection of s1 and s2\ns1 – s2 # the set of elements in s1 but not s2\ns1 ˆ s2 # the set of elements in precisely one of s1 or s2\n"
},
{
"code": null,
"e": 4607,
"s": 3079,
"text": "# Python program to demonstrate working# of \n# Set in Python \n# creating two sets \nMy_Set1 = set()\nMy_Set2 = set()\n# Adding elements to My_Set1\nfor i in range(1, 6): \n My_Set1.add(i) \n# Adding elements to My_Set2\nfor i in range(3, 8): \n My_Set2.add(i) \nprint(\"My_Set1 = \", My_Set1) \nprint(\"My_Set2 = \", My_Set2) \nprint(\"\\n\") \n# Union of My_Set1 and My_Set2\nMy_Set3 = My_Set1 | My_Set2# My_Set1.union(My_Set2) \nprint(\"Union of My_Set1&My_Set2: My_Set3 = \", My_Set3) \n# Intersection of My_Set1 and My_Set2\nMy_Set4 = My_Set1&My_Set2# My_Set1.intersection(My_Set2) \nprint(\"Intersection of My_Set1&My_Set2: My_Set4 = \", My_Set4) \nprint(\"\\n\") \n# Checking relation between My_Set3 and My_Set4\nif My_Set3>My_Set4: # My_Set3.issuperset(My_Set4) \n print(\"My_Set3 is superset of My_Set4\") \nelif My_Set3<My_Set4: # My_Set3.issubset(My_Set4) \n print(\"My_Set3 is subset of My_Set4\") \nelse : # My_Set3 == My_Set4\n print(\"My_Set3 is same as My_Set4\") \n# displaying relation between My_Set4 and My_Set3\nif My_Set4<My_Set3: # My_Set4.issubset(My_Set3) \n print(\"My_Set4 is subset of My_Set3\") \n print(\"\\n\") \n# difference between My_Set3 and My_Set4\nMy_Set5 = My_Set3 - My_Set4\nprint(\"Elements in My_Set3 and not in My_Set4: My_Set5 = \", My_Set5) \nprint(\"\\n\") \n# check if My_Set4 and My_Set5 are disjoint sets \nif My_Set4.isdisjoint(My_Set5): \n print(\"My_Set4 and My_Set5 have nothing in common\\n\") \n# Removing all the values of My_Set5\nMy_Set5.clear()\nprint(\"After applying clear on sets My_Set5: \") \nprint(\"My_Set5 = \", My_Set5) "
},
{
"code": null,
"e": 4992,
"s": 4607,
"text": "My_Set1 = {1, 2, 3, 4, 5}\nMy_Set2 = {3, 4, 5, 6, 7}\nUnion of My_Set1&My_Set2: My_Set3 = {1, 2, 3, 4, 5, 6, 7}\nIntersection of My_Set1&My_Set2: My_Set4 = {3, 4, 5}\nMy_Set3 is superset of My_Set4\nMy_Set4 is subset of My_Set3\nElements in My_Set3 and not in My_Set4: My_Set5 = {1, 2, 6, 7}\nMy_Set4 and My_Set5 have nothing in common\nAfter applying clear on sets My_Set5: \nMy_Set5 = set()\n"
}
] |
Count number of Distinct Substring in a String in C++
|
According to the problem we are given a string str, we must count all the substrings in the given string. Substring is a string which is a part of an already existing string whose size may be smaller than or equal to the existing string.
Let's understand the problem and its solution with the help of examples.
Input − str = "wxyz";
Output − count of distinct substring is: 10
Explanation − Distinct substrings counted are −
wxyz, wxy, wx, w, xyz, xy, x, yz, y, z so their count is 10
Input − str = "zzzz"
Output − count of distinct substring is: 4
Explanation − Distinct substrings counted are −
zzzz, zzz, zz, z
Take a string str as an input.
Take a string str as an input.
Declare an empty unordered_set "myset".
Declare an empty unordered_set "myset".
Loop i from 0 move 1 step till i is less than the size of the string.Declare a new string space "" (empty).Loop j starting from i move 1 step at the time till j is less than the size of the string.Concatenate the value of space on each step with str[j]Insert space in myset.
Loop i from 0 move 1 step till i is less than the size of the string.
Declare a new string space "" (empty).
Declare a new string space "" (empty).
Loop j starting from i move 1 step at the time till j is less than the size of the string.
Loop j starting from i move 1 step at the time till j is less than the size of the string.
Concatenate the value of space on each step with str[j]
Concatenate the value of space on each step with str[j]
Insert space in myset.
Insert space in myset.
Print the size of the str as an answer.
Print the size of the str as an answer.
Live Demo
#include<iostream>
#include<unordered_set>
using namespace std;
int main(){
string str = "aaaa";
unordered_set<string> myset;
int i, j;
for (i = 0; i < str.size(); ++i){
string space = "";
for (j = i; j < str.size(); ++j){
space = space + str[j];
myset.insert(space);
}
}
cout <<"count of distinct substring is: " <<str.size();
return 0;
}
If we run the above code we will get the following output −
count of distinct substring is: 4
|
[
{
"code": null,
"e": 1300,
"s": 1062,
"text": "According to the problem we are given a string str, we must count all the substrings in the given string. Substring is a string which is a part of an already existing string whose size may be smaller than or equal to the existing string."
},
{
"code": null,
"e": 1373,
"s": 1300,
"text": "Let's understand the problem and its solution with the help of examples."
},
{
"code": null,
"e": 1395,
"s": 1373,
"text": "Input − str = \"wxyz\";"
},
{
"code": null,
"e": 1439,
"s": 1395,
"text": "Output − count of distinct substring is: 10"
},
{
"code": null,
"e": 1487,
"s": 1439,
"text": "Explanation − Distinct substrings counted are −"
},
{
"code": null,
"e": 1547,
"s": 1487,
"text": "wxyz, wxy, wx, w, xyz, xy, x, yz, y, z so their count is 10"
},
{
"code": null,
"e": 1568,
"s": 1547,
"text": "Input − str = \"zzzz\""
},
{
"code": null,
"e": 1611,
"s": 1568,
"text": "Output − count of distinct substring is: 4"
},
{
"code": null,
"e": 1659,
"s": 1611,
"text": "Explanation − Distinct substrings counted are −"
},
{
"code": null,
"e": 1676,
"s": 1659,
"text": "zzzz, zzz, zz, z"
},
{
"code": null,
"e": 1707,
"s": 1676,
"text": "Take a string str as an input."
},
{
"code": null,
"e": 1738,
"s": 1707,
"text": "Take a string str as an input."
},
{
"code": null,
"e": 1778,
"s": 1738,
"text": "Declare an empty unordered_set \"myset\"."
},
{
"code": null,
"e": 1818,
"s": 1778,
"text": "Declare an empty unordered_set \"myset\"."
},
{
"code": null,
"e": 2093,
"s": 1818,
"text": "Loop i from 0 move 1 step till i is less than the size of the string.Declare a new string space \"\" (empty).Loop j starting from i move 1 step at the time till j is less than the size of the string.Concatenate the value of space on each step with str[j]Insert space in myset."
},
{
"code": null,
"e": 2163,
"s": 2093,
"text": "Loop i from 0 move 1 step till i is less than the size of the string."
},
{
"code": null,
"e": 2202,
"s": 2163,
"text": "Declare a new string space \"\" (empty)."
},
{
"code": null,
"e": 2241,
"s": 2202,
"text": "Declare a new string space \"\" (empty)."
},
{
"code": null,
"e": 2332,
"s": 2241,
"text": "Loop j starting from i move 1 step at the time till j is less than the size of the string."
},
{
"code": null,
"e": 2423,
"s": 2332,
"text": "Loop j starting from i move 1 step at the time till j is less than the size of the string."
},
{
"code": null,
"e": 2479,
"s": 2423,
"text": "Concatenate the value of space on each step with str[j]"
},
{
"code": null,
"e": 2535,
"s": 2479,
"text": "Concatenate the value of space on each step with str[j]"
},
{
"code": null,
"e": 2558,
"s": 2535,
"text": "Insert space in myset."
},
{
"code": null,
"e": 2581,
"s": 2558,
"text": "Insert space in myset."
},
{
"code": null,
"e": 2621,
"s": 2581,
"text": "Print the size of the str as an answer."
},
{
"code": null,
"e": 2661,
"s": 2621,
"text": "Print the size of the str as an answer."
},
{
"code": null,
"e": 2672,
"s": 2661,
"text": " Live Demo"
},
{
"code": null,
"e": 3070,
"s": 2672,
"text": "#include<iostream>\n#include<unordered_set>\nusing namespace std;\nint main(){\n string str = \"aaaa\";\n unordered_set<string> myset;\n int i, j;\n for (i = 0; i < str.size(); ++i){\n string space = \"\";\n for (j = i; j < str.size(); ++j){\n space = space + str[j];\n myset.insert(space);\n }\n }\n cout <<\"count of distinct substring is: \" <<str.size();\n return 0;\n}"
},
{
"code": null,
"e": 3130,
"s": 3070,
"text": "If we run the above code we will get the following output −"
},
{
"code": null,
"e": 3164,
"s": 3130,
"text": "count of distinct substring is: 4"
}
] |
Cheat sheet for Python dataframe ↔ R dataframe syntax conversions | by Shiu-Tang Li | Towards Data Science
|
In this guide, for Python, all the following commands are based on the ‘pandas’ package. For R, the ‘dplyr’ and ‘tidyr’ package are required for certain commands.
Comments / suggestions are welcome.
# Python ⇔ R: object typestype(a) ⇔ class(a) # "class" is better than "typeof"# Python ⇔ R: variable assignmenta=5 ⇔ a<-5 # a=5 also works for R# Python list ⇔ R vector:a = [1,3,5,7] ⇔ a <- c(1,3,5,7)a = [i for i in range(3,9)] ⇔ a <- c(3:9)# Python 'for loop':for val in [1,3,5]: print(val)# R 'for loop':for (val in c(1,3,5)){ print(val)}# Python function:def new_function(a, b=5): return a+b# R function:new_function <- function(a, b=5) { return (a+b)}
# Python ⇔ Rdf.head() ⇔ head(df)df.head(3) ⇔ head(df,3)df.tail(3) ⇔ tail(df,3)df.shape[0] ⇔ nrow(df)df.shape[1] ⇔ ncol(df)df.shape ⇔ dim(df)df.info() ⇔ NO EQUIVALENTdf.describe() ⇔ summary(df) # similar, not exactly the sameNO EQUIVALENT ⇔ str(df)
# Python import pandas as pddf = pd.read_csv("input.csv", sep = ",", header = 0)df.to_csv("output.csv", index = False)# R df <- read.csv("input.csv", header = TRUE, na.strings=c("","NA"), sep = ",")write.csv(df, "output.csv", row.names = FALSE)# na.strings: make sure NAs are not read as empty strings
# Pythonimport pandas as pddf = pd.DataFrame(dict(col_a=['a','b','c'], col_b=[1,2,3]))# Rcol_a <- c('a','b','c')col_b <- c(1,2,3)df <- data.frame(col_a, col_b)
# Python: row filtering df[(df['column_1'] > 3) & (df['column_2'].isnull())]# R: row filtering df[(df$column_1 > 3) & (is.na(df$column_2)), ] ORlibrary(dplyr)df %>% filter((column_1 > 3) & (is.na(column_2)))# Python ⇔ R: column filtering (keep columns) df[['c1', 'c2']] ⇔ df[c('c1', 'c2')] # OR: df[,c('c1', 'c2')]# Python ⇔ R(with dplyr): column filtering (drop columns)df.drop(['c1', 'c2'], axis=1) ⇔ df %>% select(-c('c1', 'c2'))# Python ⇔ R: select columns by positiondf.iloc[:,2:5] ⇔ df[c(3:5)] # Note the indexing# Python: check if a column contains specific valuesdf[df['c1'].isin(['a','b'])]ORdf.query('c1 in ("a", "b")')# R: check if a column contains specific valuesdf[df$c1 %in% c('a', 'b'), ]ORlibrary(dplyr)df %>% filter(c1 %in% c('a', 'b'))
# Python: missing value imputation df['c1'] = df['c1'].fillna(0) ORdf.fillna(value={'c1': 0})# R: missing value imputationdf$c1[is.na(df$c1)] <- 0OR df$c1 = ifelse(is.na(df$c1) == TRUE, 0, df$c1)ORlibrary(dplyr)library(tidyr)df %>% mutate(c1 = replace_na(c1, 0))# Python ⇔ R: number of missing values in a columndf['c1'].isnull().sum() ⇔ sum(is.na(df$c1))
# Python ⇔ R: count value frequency (Similar)df['c1'].value_counts() ⇔ table(df$c1)df['c1'].value_counts(dropna=False) ⇔ table(df$c1, useNA='always')df['c1'].value_counts(ascending=False) ⇔ sort(table(df$c1), decreasing = TRUE)# Python ⇔ R: unique columns (including missing values) df['c1'].unique() ⇔ unique(df$c1)len(df['c1'].unique()) ⇔ length(unique(df$c1))# Python ⇔ R: column max / min / meandf['c1'].max() ⇔ max(df$c1, na.rm = TRUE)df['c1'].min() ⇔ min(df$c1, na.rm = TRUE)df['c1'].mean() ⇔ mean(df$c1, na.rm = TRUE)
# Python: max / min / sum / mean / counttbl = df.groupby('c1').agg({'c2':['max', 'min', 'sum'], 'c3':['mean'], 'c1':['count']}).reset_index()tbl.columns = ['c1', 'c2_max', 'c2_min', 'c2_sum', 'c3_mean', 'count']OR (for chained operations)tbl = df.groupby('c1').agg(c2_max= ('c2', max), c2_min= ('c2', min), c2_sum= ('c2', sum), c3_mean= ('c2', 'mean'), count= ('c1', 'count')).reset_index()# R: max / min / sum / mean / countlibrary(dplyr)df %>% group_by(c1) %>% summarise(c2_max = max(c2, na.rm = T), c2_min = min(c2, na.rm = T), c2_sum = sum(c2, na.rm = T), c3_mean = mean(c3, na.rm = T), count = n()) # Python: count distinctdf.groupby('c1')['c2'].nunique()\ .reset_index()\ .rename(columns={'c2':'c2_cnt_distinct'})# R: count distinctlibrary(dplyr)tbl <- df %>% group_by(c1) %>% summarise(c2_cnt_distinct = n_distinct(c2))
# Python: rename columnsdf.rename(columns={'old_col': 'new_col'}) # R: rename columnslibrary(dplyr)df %>% rename(new_col = old_col)# Python: value mappingdf['Sex'] = df['Sex'].map({'male':0, 'female':1})# R: value mappinglibrary(dplyr)df$Sex <- mapvalues(df$Sex, from=c('male', 'female'), to=c(0,1))# Python ⇔ R: change data typedf['c1'] = df['c1'].astype(str) ⇔ df$c1 <- as.character(df$c1)df['c1'] = df['c1'].astype(int) ⇔ df$c1 <- as.integer(df$c1)df['c1'] = df['c1'].astype(float) ⇔ df$c1 <- as.numeric(df$c1)
# Python ⇔ R: df.loc[df['c1']=='A', 'c2'] = 99 ⇔ df[df$c1=='A', 'c2'] <- 99
# Python: inner join / left joinimport pandas as pdmerged_df1 = pd.merge(df1, df2, on='c1', how='inner')merged_df2 = pd.merge(df1, df2, on='c1', how='left')OR (for chained operations)merged_df1 = df1.merge(df2, on='c1', how='inner')merged_df2 = df1.merge(df2, on='c1', how='left')# R: inner join / left joinmerged_df1 <- merge(x=df1,y=df2,by='c1')merged_df2 <- merge(x=df1,y=df2,by='c1',all.x=TRUE)OR library(dplyr)merged_df1 <- inner_join(x=df1,y=df2,by='c1')merged_df2 <- left_join(x=df1,y=df2,by='c1')# Python: sortingdf.sort_values(by=['c1','c2'], ascending = [True, False])# R: sorting library(dplyr)df %>% arrange(c1, desc(c2))
# Python (import pandas as pd) ⇔ R: concatenationpd.concat([df1, df2, df3]) ⇔ rbind(df1, df2, df3)pd.concat([df1, df2], axis=1) ⇔ cbind(df1, df2)# Python random sampledf.sample(n=3, random_state=42)# R random sampleset.seed(42)sample_n(df, 3)
# Python: chained operations with '.'df.drop('c1', axis=1)\ .sort_values(by='c2', ascending=False)\ .assign(c3 = lambda x: x['c1']*3 + 2)\ .fillna(value={'c2': 0, 'c4':-99})\ .rename(columns={'total': 'TOT'})\ .query('c3 > 10')# R: chained operations with '%>%'library(dplyr)library(tidyr)df %>% select(-c('c1')) %>% arrange(desc(c2)) %>% mutate(c3 = c1*3 + 2) %>% mutate(c2 = replace_na(c2, 0), c4 = replace_na(c4, -99)) %>% rename(TOT = total) %>% filter(c3 > 10)
|
[
{
"code": null,
"e": 334,
"s": 171,
"text": "In this guide, for Python, all the following commands are based on the ‘pandas’ package. For R, the ‘dplyr’ and ‘tidyr’ package are required for certain commands."
},
{
"code": null,
"e": 370,
"s": 334,
"text": "Comments / suggestions are welcome."
},
{
"code": null,
"e": 870,
"s": 370,
"text": "# Python ⇔ R: object typestype(a) ⇔ class(a) # \"class\" is better than \"typeof\"# Python ⇔ R: variable assignmenta=5 ⇔ a<-5 # a=5 also works for R# Python list ⇔ R vector:a = [1,3,5,7] ⇔ a <- c(1,3,5,7)a = [i for i in range(3,9)] ⇔ a <- c(3:9)# Python 'for loop':for val in [1,3,5]: print(val)# R 'for loop':for (val in c(1,3,5)){ print(val)}# Python function:def new_function(a, b=5): return a+b# R function:new_function <- function(a, b=5) { return (a+b)}"
},
{
"code": null,
"e": 1172,
"s": 870,
"text": "# Python ⇔ Rdf.head() ⇔ head(df)df.head(3) ⇔ head(df,3)df.tail(3) ⇔ tail(df,3)df.shape[0] ⇔ nrow(df)df.shape[1] ⇔ ncol(df)df.shape ⇔ dim(df)df.info() ⇔ NO EQUIVALENTdf.describe() ⇔ summary(df) # similar, not exactly the sameNO EQUIVALENT ⇔ str(df)"
},
{
"code": null,
"e": 1557,
"s": 1172,
"text": "# Python import pandas as pddf = pd.read_csv(\"input.csv\", sep = \",\", header = 0)df.to_csv(\"output.csv\", index = False)# R df <- read.csv(\"input.csv\", header = TRUE, na.strings=c(\"\",\"NA\"), sep = \",\")write.csv(df, \"output.csv\", row.names = FALSE)# na.strings: make sure NAs are not read as empty strings"
},
{
"code": null,
"e": 1717,
"s": 1557,
"text": "# Pythonimport pandas as pddf = pd.DataFrame(dict(col_a=['a','b','c'], col_b=[1,2,3]))# Rcol_a <- c('a','b','c')col_b <- c(1,2,3)df <- data.frame(col_a, col_b)"
},
{
"code": null,
"e": 2503,
"s": 1717,
"text": "# Python: row filtering df[(df['column_1'] > 3) & (df['column_2'].isnull())]# R: row filtering df[(df$column_1 > 3) & (is.na(df$column_2)), ] ORlibrary(dplyr)df %>% filter((column_1 > 3) & (is.na(column_2)))# Python ⇔ R: column filtering (keep columns) df[['c1', 'c2']] ⇔ df[c('c1', 'c2')] # OR: df[,c('c1', 'c2')]# Python ⇔ R(with dplyr): column filtering (drop columns)df.drop(['c1', 'c2'], axis=1) ⇔ df %>% select(-c('c1', 'c2'))# Python ⇔ R: select columns by positiondf.iloc[:,2:5] ⇔ df[c(3:5)] # Note the indexing# Python: check if a column contains specific valuesdf[df['c1'].isin(['a','b'])]ORdf.query('c1 in (\"a\", \"b\")')# R: check if a column contains specific valuesdf[df$c1 %in% c('a', 'b'), ]ORlibrary(dplyr)df %>% filter(c1 %in% c('a', 'b'))"
},
{
"code": null,
"e": 2862,
"s": 2503,
"text": "# Python: missing value imputation df['c1'] = df['c1'].fillna(0) ORdf.fillna(value={'c1': 0})# R: missing value imputationdf$c1[is.na(df$c1)] <- 0OR df$c1 = ifelse(is.na(df$c1) == TRUE, 0, df$c1)ORlibrary(dplyr)library(tidyr)df %>% mutate(c1 = replace_na(c1, 0))# Python ⇔ R: number of missing values in a columndf['c1'].isnull().sum() ⇔ sum(is.na(df$c1))"
},
{
"code": null,
"e": 3436,
"s": 2862,
"text": "# Python ⇔ R: count value frequency (Similar)df['c1'].value_counts() ⇔ table(df$c1)df['c1'].value_counts(dropna=False) ⇔ table(df$c1, useNA='always')df['c1'].value_counts(ascending=False) ⇔ sort(table(df$c1), decreasing = TRUE)# Python ⇔ R: unique columns (including missing values) df['c1'].unique() ⇔ unique(df$c1)len(df['c1'].unique()) ⇔ length(unique(df$c1))# Python ⇔ R: column max / min / meandf['c1'].max() ⇔ max(df$c1, na.rm = TRUE)df['c1'].min() ⇔ min(df$c1, na.rm = TRUE)df['c1'].mean() ⇔ mean(df$c1, na.rm = TRUE)"
},
{
"code": null,
"e": 4575,
"s": 3436,
"text": "# Python: max / min / sum / mean / counttbl = df.groupby('c1').agg({'c2':['max', 'min', 'sum'], 'c3':['mean'], 'c1':['count']}).reset_index()tbl.columns = ['c1', 'c2_max', 'c2_min', 'c2_sum', 'c3_mean', 'count']OR (for chained operations)tbl = df.groupby('c1').agg(c2_max= ('c2', max), c2_min= ('c2', min), c2_sum= ('c2', sum), c3_mean= ('c2', 'mean'), count= ('c1', 'count')).reset_index()# R: max / min / sum / mean / countlibrary(dplyr)df %>% group_by(c1) %>% summarise(c2_max = max(c2, na.rm = T), c2_min = min(c2, na.rm = T), c2_sum = sum(c2, na.rm = T), c3_mean = mean(c3, na.rm = T), count = n()) # Python: count distinctdf.groupby('c1')['c2'].nunique()\\ .reset_index()\\ .rename(columns={'c2':'c2_cnt_distinct'})# R: count distinctlibrary(dplyr)tbl <- df %>% group_by(c1) %>% summarise(c2_cnt_distinct = n_distinct(c2))"
},
{
"code": null,
"e": 5127,
"s": 4575,
"text": "# Python: rename columnsdf.rename(columns={'old_col': 'new_col'}) # R: rename columnslibrary(dplyr)df %>% rename(new_col = old_col)# Python: value mappingdf['Sex'] = df['Sex'].map({'male':0, 'female':1})# R: value mappinglibrary(dplyr)df$Sex <- mapvalues(df$Sex, from=c('male', 'female'), to=c(0,1))# Python ⇔ R: change data typedf['c1'] = df['c1'].astype(str) ⇔ df$c1 <- as.character(df$c1)df['c1'] = df['c1'].astype(int) ⇔ df$c1 <- as.integer(df$c1)df['c1'] = df['c1'].astype(float) ⇔ df$c1 <- as.numeric(df$c1)"
},
{
"code": null,
"e": 5205,
"s": 5127,
"text": "# Python ⇔ R: df.loc[df['c1']=='A', 'c2'] = 99 ⇔ df[df$c1=='A', 'c2'] <- 99"
},
{
"code": null,
"e": 5839,
"s": 5205,
"text": "# Python: inner join / left joinimport pandas as pdmerged_df1 = pd.merge(df1, df2, on='c1', how='inner')merged_df2 = pd.merge(df1, df2, on='c1', how='left')OR (for chained operations)merged_df1 = df1.merge(df2, on='c1', how='inner')merged_df2 = df1.merge(df2, on='c1', how='left')# R: inner join / left joinmerged_df1 <- merge(x=df1,y=df2,by='c1')merged_df2 <- merge(x=df1,y=df2,by='c1',all.x=TRUE)OR library(dplyr)merged_df1 <- inner_join(x=df1,y=df2,by='c1')merged_df2 <- left_join(x=df1,y=df2,by='c1')# Python: sortingdf.sort_values(by=['c1','c2'], ascending = [True, False])# R: sorting library(dplyr)df %>% arrange(c1, desc(c2))"
},
{
"code": null,
"e": 6087,
"s": 5839,
"text": "# Python (import pandas as pd) ⇔ R: concatenationpd.concat([df1, df2, df3]) ⇔ rbind(df1, df2, df3)pd.concat([df1, df2], axis=1) ⇔ cbind(df1, df2)# Python random sampledf.sample(n=3, random_state=42)# R random sampleset.seed(42)sample_n(df, 3)"
}
] |
DAX Logical - AND function
|
Checks the two arguments if they are TRUE or FALSE, and returns TRUE only when both are TRUE. Otherwise, returns FALSE.
AND (<logical1>, <logical2>)
TRUE, if both the arguments are TRUE.
FALSE, otherwise.
AND function takes only two arguments. If you have more than two arguments, either nest the AND functions or use the DAX logical operator &&.
= AND([Country] = "USA",[Medal] = "Gold")
This DAX formula returns a calculated column with TRUE for Country – USA and Medal – Gold values, and FALSE otherwise.
USA Gold Medal Count:= SUMX(
Results,IF(AND([Country] = "USA",[Medal] = "Gold") = TRUE(),1,0)
)
This DAX formula returns a calculated field with total number of Gold Medals for USA.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2121,
"s": 2001,
"text": "Checks the two arguments if they are TRUE or FALSE, and returns TRUE only when both are TRUE. Otherwise, returns FALSE."
},
{
"code": null,
"e": 2152,
"s": 2121,
"text": "AND (<logical1>, <logical2>) \n"
},
{
"code": null,
"e": 2190,
"s": 2152,
"text": "TRUE, if both the arguments are TRUE."
},
{
"code": null,
"e": 2208,
"s": 2190,
"text": "FALSE, otherwise."
},
{
"code": null,
"e": 2350,
"s": 2208,
"text": "AND function takes only two arguments. If you have more than two arguments, either nest the AND functions or use the DAX logical operator &&."
},
{
"code": null,
"e": 2393,
"s": 2350,
"text": "= AND([Country] = \"USA\",[Medal] = \"Gold\") "
},
{
"code": null,
"e": 2512,
"s": 2393,
"text": "This DAX formula returns a calculated column with TRUE for Country – USA and Medal – Gold values, and FALSE otherwise."
},
{
"code": null,
"e": 2612,
"s": 2512,
"text": "USA Gold Medal Count:= SUMX(\n Results,IF(AND([Country] = \"USA\",[Medal] = \"Gold\") = TRUE(),1,0)\n) "
},
{
"code": null,
"e": 2698,
"s": 2612,
"text": "This DAX formula returns a calculated field with total number of Gold Medals for USA."
},
{
"code": null,
"e": 2733,
"s": 2698,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2747,
"s": 2733,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2780,
"s": 2747,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2794,
"s": 2780,
"text": " Randy Minder"
},
{
"code": null,
"e": 2829,
"s": 2794,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2843,
"s": 2829,
"text": " Randy Minder"
},
{
"code": null,
"e": 2850,
"s": 2843,
"text": " Print"
},
{
"code": null,
"e": 2861,
"s": 2850,
"text": " Add Notes"
}
] |
Bottom Navigation Bar in Android Jetpack Compose - GeeksforGeeks
|
08 Sep, 2021
We all have seen BottomNavigationBar in so many apps, such as Instagram, Quora. In this article, we will learn how to add bottom navigation in Jetpack Compose. Below is a sample of how it will look.
Why do we need a Bottom Navigation Bar?
It allows the user to switch to different activities/fragments easily.
It makes the user aware of the different screens available in the app.
The user is able to check which screen are they on at the moment.
The following is an anatomy diagram for the Bottom Navigation Bar:
Prerequisites:
Knowledge of Jetpack Compose.
Knowledge of Scaffold in Jetpack compose.
Knowledge of Compose Navigation.
Step 1: Create a New Project (Or use it in the existing Compose project)
To create a new project in the Android Studio Canary version. Refer to this article: How to Create a New Project in Android Studio Canary Version with Jetpack Compose?
Project structure
Step 2: Adding Dependencies
Open build.gradle(app) and add the following dependency.
implementation “androidx.navigation:navigation-compose:2.4.0-alpha07”
Step 3: Creating Screens
Open Screens.kt and create three screens, Home, Search, Profile.
HomeScreen:
Kotlin
@Composablefun HomeScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // Parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Home, contentDescription = "home", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = "Home", color = Color.Black) }}
SearchScreen:
Kotlin
@Composablefun SearchScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Search, contentDescription = "search", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = "Search", color = Color.Black) }}
ProfileScreen:
Kotlin
@Composablefun ProfileScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Person, contentDescription = "Profile", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = "Profile", color = Color.Black) }}
Step 4: Create Bottom nav items
Let’s create a data class to hold data related to bottom nav items like label, icon, route. Open models/BottomNavItem.kt and add the following code.
Kotlin
import androidx.compose.ui.graphics.vector.ImageVector data class BottomNavItem( val label: String, val icon: ImageVector, val route:String,)
And create some bottom nav items, open Utils/Constants.kt, and a list of three nav items.
Kotlin
object Constants { val BottomNavItems = listOf( BottomNavItem( label = "Home", icon = Icons.Filled.Home, route = "home" ), BottomNavItem( label = "Search", icon = Icons.Filled.Search, route = "search" ), BottomNavItem( label = "Profile", icon = Icons.Filled.Person, route = "profile" ) )}
Step 5: Working with the MainActivity and Navigation Components
Create a function with the name NavHostContainer in MainActivity.kt which will contain NavHost and the Composable for navigation. Refer to the comments in the code for a better understanding
Kotlin
@Composablefun NavHostContainer( navController: NavHostController, padding: PaddingValues) { NavHost( navController = navController, // set the start destination as home startDestination = "home", // Set the padding provided by scaffold modifier = Modifier.padding(paddingValues = padding), builder = { // route : Home composable("home") { HomeScreen() } // route : search composable("search") { SearchScreen() } // route : profile composable("profile") { ProfileScreen() } }) }
Step 6: Adding Bottom Navigation
Refer to comments for better understanding.
Kotlin
@Composablefun BottomNavigationBar(navController: NavHostController) { BottomNavigation( // set background color backgroundColor = Color(0xFF0F9D58)) { // observe the backstack val navBackStackEntry by navController.currentBackStackEntryAsState() // observe current route to change the icon // color,label color when navigated val currentRoute = navBackStackEntry?.destination?.route // Bottom nav items we declared Constants.BottomNavItems.forEach { navItem -> // Place the bottom nav items BottomNavigationItem( // it currentRoute is equal then its selected route selected = currentRoute == navItem.route, // navigate on click onClick = { navController.navigate(navItem.route) }, // Icon of navItem icon = { Icon(imageVector = navItem.icon, contentDescription = navItem.label) }, // label label = { Text(text = navItem.label) }, alwaysShowLabel = false ) } }}
Step 7: Putting everything together in Scaffold
Now we need to put everything in the scaffold in setContent on MainActivity class
Kotlin
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BottomNavigationTheme { // remember navController so it does not // get recreated on recomposition val navController = rememberNavController() Surface(color = Color.White) { // Scaffold Component Scaffold( // Bottom navigation bottomBar = { BottomNavigationBar(navController = navController) }, content = { padding -> // Navhost: where screens are placed NavHostContainer(navController = navController, padding = padding) } ) } } } }}
Output:
Project Link: Click Here
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
Android Menus
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 25316,
"s": 25116,
"text": "We all have seen BottomNavigationBar in so many apps, such as Instagram, Quora. In this article, we will learn how to add bottom navigation in Jetpack Compose. Below is a sample of how it will look. "
},
{
"code": null,
"e": 25356,
"s": 25316,
"text": "Why do we need a Bottom Navigation Bar?"
},
{
"code": null,
"e": 25427,
"s": 25356,
"text": "It allows the user to switch to different activities/fragments easily."
},
{
"code": null,
"e": 25498,
"s": 25427,
"text": "It makes the user aware of the different screens available in the app."
},
{
"code": null,
"e": 25564,
"s": 25498,
"text": "The user is able to check which screen are they on at the moment."
},
{
"code": null,
"e": 25631,
"s": 25564,
"text": "The following is an anatomy diagram for the Bottom Navigation Bar:"
},
{
"code": null,
"e": 25646,
"s": 25631,
"text": "Prerequisites:"
},
{
"code": null,
"e": 25676,
"s": 25646,
"text": "Knowledge of Jetpack Compose."
},
{
"code": null,
"e": 25718,
"s": 25676,
"text": "Knowledge of Scaffold in Jetpack compose."
},
{
"code": null,
"e": 25751,
"s": 25718,
"text": "Knowledge of Compose Navigation."
},
{
"code": null,
"e": 25824,
"s": 25751,
"text": "Step 1: Create a New Project (Or use it in the existing Compose project)"
},
{
"code": null,
"e": 25992,
"s": 25824,
"text": "To create a new project in the Android Studio Canary version. Refer to this article: How to Create a New Project in Android Studio Canary Version with Jetpack Compose?"
},
{
"code": null,
"e": 26010,
"s": 25992,
"text": "Project structure"
},
{
"code": null,
"e": 26038,
"s": 26010,
"text": "Step 2: Adding Dependencies"
},
{
"code": null,
"e": 26095,
"s": 26038,
"text": "Open build.gradle(app) and add the following dependency."
},
{
"code": null,
"e": 26170,
"s": 26095,
"text": " implementation “androidx.navigation:navigation-compose:2.4.0-alpha07”"
},
{
"code": null,
"e": 26195,
"s": 26170,
"text": "Step 3: Creating Screens"
},
{
"code": null,
"e": 26260,
"s": 26195,
"text": "Open Screens.kt and create three screens, Home, Search, Profile."
},
{
"code": null,
"e": 26272,
"s": 26260,
"text": "HomeScreen:"
},
{
"code": null,
"e": 26279,
"s": 26272,
"text": "Kotlin"
},
{
"code": "@Composablefun HomeScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // Parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Home, contentDescription = \"home\", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = \"Home\", color = Color.Black) }}",
"e": 26873,
"s": 26279,
"text": null
},
{
"code": null,
"e": 26887,
"s": 26873,
"text": "SearchScreen:"
},
{
"code": null,
"e": 26894,
"s": 26887,
"text": "Kotlin"
},
{
"code": "@Composablefun SearchScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Search, contentDescription = \"search\", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = \"Search\", color = Color.Black) }}",
"e": 27494,
"s": 26894,
"text": null
},
{
"code": null,
"e": 27509,
"s": 27494,
"text": "ProfileScreen:"
},
{
"code": null,
"e": 27516,
"s": 27509,
"text": "Kotlin"
},
{
"code": "@Composablefun ProfileScreen() { // Column Composable, Column( modifier = Modifier .fillMaxSize() .background(Color.White), // parameters set to place the items in center horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Icon Composable Icon( imageVector = Icons.Default.Person, contentDescription = \"Profile\", tint = Color(0xFF0F9D58) ) // Text to Display the current Screen Text(text = \"Profile\", color = Color.Black) }}",
"e": 28119,
"s": 27516,
"text": null
},
{
"code": null,
"e": 28151,
"s": 28119,
"text": "Step 4: Create Bottom nav items"
},
{
"code": null,
"e": 28300,
"s": 28151,
"text": "Let’s create a data class to hold data related to bottom nav items like label, icon, route. Open models/BottomNavItem.kt and add the following code."
},
{
"code": null,
"e": 28307,
"s": 28300,
"text": "Kotlin"
},
{
"code": "import androidx.compose.ui.graphics.vector.ImageVector data class BottomNavItem( val label: String, val icon: ImageVector, val route:String,)",
"e": 28459,
"s": 28307,
"text": null
},
{
"code": null,
"e": 28549,
"s": 28459,
"text": "And create some bottom nav items, open Utils/Constants.kt, and a list of three nav items."
},
{
"code": null,
"e": 28556,
"s": 28549,
"text": "Kotlin"
},
{
"code": "object Constants { val BottomNavItems = listOf( BottomNavItem( label = \"Home\", icon = Icons.Filled.Home, route = \"home\" ), BottomNavItem( label = \"Search\", icon = Icons.Filled.Search, route = \"search\" ), BottomNavItem( label = \"Profile\", icon = Icons.Filled.Person, route = \"profile\" ) )}",
"e": 28992,
"s": 28556,
"text": null
},
{
"code": null,
"e": 29057,
"s": 28992,
"text": "Step 5: Working with the MainActivity and Navigation Components "
},
{
"code": null,
"e": 29248,
"s": 29057,
"text": "Create a function with the name NavHostContainer in MainActivity.kt which will contain NavHost and the Composable for navigation. Refer to the comments in the code for a better understanding"
},
{
"code": null,
"e": 29255,
"s": 29248,
"text": "Kotlin"
},
{
"code": "@Composablefun NavHostContainer( navController: NavHostController, padding: PaddingValues) { NavHost( navController = navController, // set the start destination as home startDestination = \"home\", // Set the padding provided by scaffold modifier = Modifier.padding(paddingValues = padding), builder = { // route : Home composable(\"home\") { HomeScreen() } // route : search composable(\"search\") { SearchScreen() } // route : profile composable(\"profile\") { ProfileScreen() } }) }",
"e": 29968,
"s": 29255,
"text": null
},
{
"code": null,
"e": 30001,
"s": 29968,
"text": "Step 6: Adding Bottom Navigation"
},
{
"code": null,
"e": 30045,
"s": 30001,
"text": "Refer to comments for better understanding."
},
{
"code": null,
"e": 30052,
"s": 30045,
"text": "Kotlin"
},
{
"code": "@Composablefun BottomNavigationBar(navController: NavHostController) { BottomNavigation( // set background color backgroundColor = Color(0xFF0F9D58)) { // observe the backstack val navBackStackEntry by navController.currentBackStackEntryAsState() // observe current route to change the icon // color,label color when navigated val currentRoute = navBackStackEntry?.destination?.route // Bottom nav items we declared Constants.BottomNavItems.forEach { navItem -> // Place the bottom nav items BottomNavigationItem( // it currentRoute is equal then its selected route selected = currentRoute == navItem.route, // navigate on click onClick = { navController.navigate(navItem.route) }, // Icon of navItem icon = { Icon(imageVector = navItem.icon, contentDescription = navItem.label) }, // label label = { Text(text = navItem.label) }, alwaysShowLabel = false ) } }}",
"e": 31335,
"s": 30052,
"text": null
},
{
"code": null,
"e": 31383,
"s": 31335,
"text": "Step 7: Putting everything together in Scaffold"
},
{
"code": null,
"e": 31465,
"s": 31383,
"text": "Now we need to put everything in the scaffold in setContent on MainActivity class"
},
{
"code": null,
"e": 31472,
"s": 31465,
"text": "Kotlin"
},
{
"code": "class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BottomNavigationTheme { // remember navController so it does not // get recreated on recomposition val navController = rememberNavController() Surface(color = Color.White) { // Scaffold Component Scaffold( // Bottom navigation bottomBar = { BottomNavigationBar(navController = navController) }, content = { padding -> // Navhost: where screens are placed NavHostContainer(navController = navController, padding = padding) } ) } } } }}",
"e": 32425,
"s": 31472,
"text": null
},
{
"code": null,
"e": 32433,
"s": 32425,
"text": "Output:"
},
{
"code": null,
"e": 32458,
"s": 32433,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 32474,
"s": 32458,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 32482,
"s": 32474,
"text": "Android"
},
{
"code": null,
"e": 32489,
"s": 32482,
"text": "Kotlin"
},
{
"code": null,
"e": 32497,
"s": 32489,
"text": "Android"
},
{
"code": null,
"e": 32595,
"s": 32497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32604,
"s": 32595,
"text": "Comments"
},
{
"code": null,
"e": 32617,
"s": 32604,
"text": "Old Comments"
},
{
"code": null,
"e": 32656,
"s": 32617,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32698,
"s": 32656,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32731,
"s": 32698,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 32769,
"s": 32731,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32842,
"s": 32769,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 32855,
"s": 32842,
"text": "Kotlin Array"
},
{
"code": null,
"e": 32874,
"s": 32855,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 32916,
"s": 32874,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32930,
"s": 32916,
"text": "Android Menus"
}
] |
Passing a vector to constructor in C++ - GeeksforGeeks
|
31 Jan, 2022
When class member is a vector object (not a reference).We can simply assign in constructor.
CPP
// Passing vector object to a constructor.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) { vec = v; } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}
1 2 3 4 5
We can also initialize using the initializer list.
CPP
// Initializing vector object using initializer// list.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) : vec(v) { } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}
1 2 3 4 5
When class member is a vector a reference. In C++, references must be initialized using initializer list.
CPP
// CPP program to initialize a vector reference.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int>& vec; public: // this is the right way to assign // the reference of stl container MyClass(vector<int>& arr) : vec(arr) { } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}
1 2 3 4 5
chhabradhanvi
cpp-references
cpp-vector
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 23731,
"s": 23703,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 23825,
"s": 23731,
"text": "When class member is a vector object (not a reference).We can simply assign in constructor. "
},
{
"code": null,
"e": 23829,
"s": 23825,
"text": "CPP"
},
{
"code": "// Passing vector object to a constructor.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) { vec = v; } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}",
"e": 24306,
"s": 23829,
"text": null
},
{
"code": null,
"e": 24316,
"s": 24306,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 24370,
"s": 24318,
"text": "We can also initialize using the initializer list. "
},
{
"code": null,
"e": 24374,
"s": 24370,
"text": "CPP"
},
{
"code": "// Initializing vector object using initializer// list.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int> vec; public: MyClass(vector<int> v) : vec(v) { } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}",
"e": 24858,
"s": 24374,
"text": null
},
{
"code": null,
"e": 24868,
"s": 24858,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 24977,
"s": 24870,
"text": "When class member is a vector a reference. In C++, references must be initialized using initializer list. "
},
{
"code": null,
"e": 24981,
"s": 24977,
"text": "CPP"
},
{
"code": "// CPP program to initialize a vector reference.#include <iostream>#include <vector>using namespace std; class MyClass { vector<int>& vec; public: // this is the right way to assign // the reference of stl container MyClass(vector<int>& arr) : vec(arr) { } void print() { /// print the value of vector for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; }}; int main(){ vector<int> vec; for (int i = 1; i <= 5; i++) vec.push_back(i); MyClass obj(vec); obj.print(); return 0;}",
"e": 25546,
"s": 24981,
"text": null
},
{
"code": null,
"e": 25556,
"s": 25546,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 25572,
"s": 25558,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 25587,
"s": 25572,
"text": "cpp-references"
},
{
"code": null,
"e": 25598,
"s": 25587,
"text": "cpp-vector"
},
{
"code": null,
"e": 25602,
"s": 25598,
"text": "C++"
},
{
"code": null,
"e": 25606,
"s": 25602,
"text": "CPP"
},
{
"code": null,
"e": 25704,
"s": 25606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25713,
"s": 25704,
"text": "Comments"
},
{
"code": null,
"e": 25726,
"s": 25713,
"text": "Old Comments"
},
{
"code": null,
"e": 25754,
"s": 25726,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25778,
"s": 25754,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25798,
"s": 25778,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25831,
"s": 25798,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25875,
"s": 25831,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25911,
"s": 25875,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 25962,
"s": 25911,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 25981,
"s": 25962,
"text": "Destructors in C++"
},
{
"code": null,
"e": 26025,
"s": 25981,
"text": "Pair in C++ Standard Template Library (STL)"
}
] |
Groovy - compareTo()
|
The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.
public int compareTo( NumberSubClass referenceName )
referenceName - This could be a Byte, Double, Integer, Float, Long or Short.
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
If the Integer is greater than the argument then 1 is returned.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
Integer x = 5;
//Comparison against a Integer of lower value
System.out.println(x.compareTo(3));
//Comparison against a Integer of equal value
System.out.println(x.compareTo(5));
//Comparison against a Integer of higher value
System.out.println(x.compareTo(8));
}
}
When we run the above program, we will get the following result −
1
0
-1
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2365,
"s": 2238,
"text": "The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers."
},
{
"code": null,
"e": 2420,
"s": 2365,
"text": "public int compareTo( NumberSubClass referenceName ) \n"
},
{
"code": null,
"e": 2497,
"s": 2420,
"text": "referenceName - This could be a Byte, Double, Integer, Float, Long or Short."
},
{
"code": null,
"e": 2557,
"s": 2497,
"text": "If the Integer is equal to the argument then 0 is returned."
},
{
"code": null,
"e": 2619,
"s": 2557,
"text": "If the Integer is less than the argument then -1 is returned."
},
{
"code": null,
"e": 2683,
"s": 2619,
"text": "If the Integer is greater than the argument then 1 is returned."
},
{
"code": null,
"e": 2737,
"s": 2683,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 3119,
"s": 2737,
"text": "class Example { \n static void main(String[] args) { \n Integer x = 5;\n\t\t\n //Comparison against a Integer of lower value \n System.out.println(x.compareTo(3));\n\t\t\n //Comparison against a Integer of equal value \n System.out.println(x.compareTo(5)); \n\t\t\n //Comparison against a Integer of higher value \n System.out.println(x.compareTo(8)); \n } \n} "
},
{
"code": null,
"e": 3185,
"s": 3119,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 3196,
"s": 3185,
"text": "1 \n0 \n-1 \n"
},
{
"code": null,
"e": 3229,
"s": 3196,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3247,
"s": 3229,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3282,
"s": 3247,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3300,
"s": 3282,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3307,
"s": 3300,
"text": " Print"
},
{
"code": null,
"e": 3318,
"s": 3307,
"text": " Add Notes"
}
] |
Android - Localization
|
An android application can run on many devices in many different regions. In order to make your application more interactive, your application should handle text,numbers,files e.t.c in ways appropriate to the locales where your application will be used.
The way of changing string into different languages is called as localization
In this chapter we will explain , how you can localize your application according to different regions e.t.c. We will localize the strings used in the application, and in the same way other things can be localized.
In order to localize the strings used in your application , make a new folder under res with name of values-local where local would be the replaced with the region.
For example, in the case of italy, the values-it folder would be made under res. It is shown in the image below −
Once that folder is made, copy the strings.xmlfrom default folder to the folder you have created. And change its contents. For example, i have changed the value of hello_world string.
<;?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Ciao mondo!</string>
</resources>
<;?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Hola Mundo!</string>
</resources>
<;?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Bonjour le monde !</string>
</resources>
Apart from these languages, the region code of other languages have been given in the table below −
Afrikanns
Code: af. Folder name: values-af
Arabic
Code: ar. Folder name: values-ar
Bengali
Code: bn. Folder name: values-bn
Czech
Code: cs. Folder name: values-cs
Chinese
Code: zh. Folder name: values-zh
German
Code: de. Folder name: values-de
French
Code: fr. Folder name: values-fr
Japanese
Code: ja. Folder name: values-ja
To experiment with this example , you can run this on an actual device or in an emulator.
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="Wifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hindi"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#ff59ff1a"
android:textSize="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/marathi"
android:id="@+id/textView3"
android:textSize="30dp"
android:textColor="#ff67ff1e"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/arabic"
android:id="@+id/textView4"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:textColor="#ff40ff08"
android:textSize="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/chinese"
android:id="@+id/textView5"
android:layout_below="@+id/textView4"
android:layout_alignLeft="@+id/textView3"
android:layout_alignStart="@+id/textView3"
android:layout_marginTop="42dp"
android:textSize="30dp"
android:textColor="#ff56ff12"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="hindi">ట్యుటోరియల్స్ పాయింట్</string>
<string name="marathi">शिकवण्या बिंदू</string>
<string name="arabic">نقطة الدروس7</string>
<string name="chinese">教程点</string>
</resources>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3861,
"s": 3607,
"text": "An android application can run on many devices in many different regions. In order to make your application more interactive, your application should handle text,numbers,files e.t.c in ways appropriate to the locales where your application will be used."
},
{
"code": null,
"e": 3939,
"s": 3861,
"text": "The way of changing string into different languages is called as localization"
},
{
"code": null,
"e": 4154,
"s": 3939,
"text": "In this chapter we will explain , how you can localize your application according to different regions e.t.c. We will localize the strings used in the application, and in the same way other things can be localized."
},
{
"code": null,
"e": 4319,
"s": 4154,
"text": "In order to localize the strings used in your application , make a new folder under res with name of values-local where local would be the replaced with the region."
},
{
"code": null,
"e": 4433,
"s": 4319,
"text": "For example, in the case of italy, the values-it folder would be made under res. It is shown in the image below −"
},
{
"code": null,
"e": 4617,
"s": 4433,
"text": "Once that folder is made, copy the strings.xmlfrom default folder to the folder you have created. And change its contents. For example, i have changed the value of hello_world string."
},
{
"code": null,
"e": 4733,
"s": 4617,
"text": "<;?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"hello_world\">Ciao mondo!</string>\n</resources>"
},
{
"code": null,
"e": 4849,
"s": 4733,
"text": "<;?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"hello_world\">Hola Mundo!</string>\n</resources>"
},
{
"code": null,
"e": 4972,
"s": 4849,
"text": "<;?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"hello_world\">Bonjour le monde !</string>\n</resources>"
},
{
"code": null,
"e": 5072,
"s": 4972,
"text": "Apart from these languages, the region code of other languages have been given in the table below −"
},
{
"code": null,
"e": 5082,
"s": 5072,
"text": "Afrikanns"
},
{
"code": null,
"e": 5115,
"s": 5082,
"text": "Code: af. Folder name: values-af"
},
{
"code": null,
"e": 5122,
"s": 5115,
"text": "Arabic"
},
{
"code": null,
"e": 5155,
"s": 5122,
"text": "Code: ar. Folder name: values-ar"
},
{
"code": null,
"e": 5163,
"s": 5155,
"text": "Bengali"
},
{
"code": null,
"e": 5196,
"s": 5163,
"text": "Code: bn. Folder name: values-bn"
},
{
"code": null,
"e": 5202,
"s": 5196,
"text": "Czech"
},
{
"code": null,
"e": 5235,
"s": 5202,
"text": "Code: cs. Folder name: values-cs"
},
{
"code": null,
"e": 5243,
"s": 5235,
"text": "Chinese"
},
{
"code": null,
"e": 5276,
"s": 5243,
"text": "Code: zh. Folder name: values-zh"
},
{
"code": null,
"e": 5283,
"s": 5276,
"text": "German"
},
{
"code": null,
"e": 5316,
"s": 5283,
"text": "Code: de. Folder name: values-de"
},
{
"code": null,
"e": 5323,
"s": 5316,
"text": "French"
},
{
"code": null,
"e": 5356,
"s": 5323,
"text": "Code: fr. Folder name: values-fr"
},
{
"code": null,
"e": 5365,
"s": 5356,
"text": "Japanese"
},
{
"code": null,
"e": 5398,
"s": 5365,
"text": "Code: ja. Folder name: values-ja"
},
{
"code": null,
"e": 5488,
"s": 5398,
"text": "To experiment with this example , you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 5563,
"s": 5488,
"text": "Following is the modified content of the xml res/layout/activity_main.xml."
},
{
"code": null,
"e": 8298,
"s": 5563,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n 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\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView android:text=\"Wifi\" \n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/hindi\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:textColor=\"#ff59ff1a\"\n android:textSize=\"30dp\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/marathi\"\n android:id=\"@+id/textView3\"\n android:textSize=\"30dp\"\n android:textColor=\"#ff67ff1e\"\n android:layout_centerVertical=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/arabic\"\n android:id=\"@+id/textView4\"\n android:layout_below=\"@+id/textView3\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"42dp\"\n android:textColor=\"#ff40ff08\"\n android:textSize=\"30dp\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/chinese\"\n android:id=\"@+id/textView5\"\n android:layout_below=\"@+id/textView4\"\n android:layout_alignLeft=\"@+id/textView3\"\n android:layout_alignStart=\"@+id/textView3\"\n android:layout_marginTop=\"42dp\"\n android:textSize=\"30dp\"\n android:textColor=\"#ff56ff12\"\n android:layout_alignRight=\"@+id/textView3\"\n android:layout_alignEnd=\"@+id/textView3\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 8353,
"s": 8298,
"text": "Following is the content of the res/values/string.xml."
},
{
"code": null,
"e": 8724,
"s": 8353,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hindi\">ట్యుటోరియల్స్ పాయింట్</string>\n <string name=\"marathi\">शिकवण्या बिंदू</string>\n <string name=\"arabic\">نقطة الدروس7</string>\n <string name=\"chinese\">教程点</string>\n</resources>"
},
{
"code": null,
"e": 9117,
"s": 8724,
"text": "Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 9152,
"s": 9117,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9164,
"s": 9152,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9199,
"s": 9164,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9213,
"s": 9199,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9245,
"s": 9213,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9262,
"s": 9245,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9297,
"s": 9262,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9314,
"s": 9297,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9349,
"s": 9314,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9366,
"s": 9349,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9399,
"s": 9366,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9416,
"s": 9399,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9423,
"s": 9416,
"text": " Print"
},
{
"code": null,
"e": 9434,
"s": 9423,
"text": " Add Notes"
}
] |
Visualizing the Nothing. How to visualize the incompleteness of... | by Thiago Carvalho | Towards Data Science
|
It’s hard to know what to do with null values in our data. Most times, it’s easier to drop them and follow with what’s left.
But they can eventually have meaning and can be investigated. Taking some time to have a good look at them can often bring a better understanding of how the data was collected and even reveal some patterns in it.
In this article, we’ll explore how to visualize all the NULLs in our datasets and get a look at what insights we can extract from doing so.
I’ll run the code in Jupyer Lab, and I’ll use Pandas, Numpy, Missingno, and Matplotlib for this example.
The dataset will be California Jail Profile Survey, which contains monthly county-level data from 1995 to 2018.
import pandas as pdf = 'data/california_jail_county_monthly_1995_2018.csv'df = pd.read_csv(f)
After loading the dataset to Pandas, we can look at one of its convenient methods for dealing with Nulls.
We can use .isnull followed by a .sum and get the number of missing values.
df.isnull().sum()
That’s already useful since it gives us an idea of which fields we can rely on, but there are better ways of visualizing this, let’s try using Missingno.
Missingno is a library for visualizing incompleteness in a dataset, it works on top of Matplotlib and Seaborn and is effortless to use.
import missingno as msno
We’ll start with a simple bar chart. Instead of comparing that extensive list of numbers, we’ll use rectangles and their sizes.
msno.bar(df)
That’s great! In a single method, just passing the data frame, we already have a visual representation of our missing values.
This bar chart represents the number of records in each column. Here we have two scales, one telling the exact amount of values in the field (right) and the other representing the proportion to the total number of rows.
Starting with a bar chart allows us to quickly tell if we’ll need to spend more time analyzing the null values or not.
It isn’t the case with our data, but if you have a blessed dataset without any null values or with an acceptable amount of them, you could stop by now and follow up with your analysis.
Let’s try a different visualization for missing values.
msno.matrix(df)
A matrix tells us exactly where the missing values are, in our example, the data is sorted with the newest records on top.
We can already have some valuable insights by looking at the matrix and knowing how our data is arranged. Here we can see that the data collected changed at some point, where fields such as ‘avg inmates get mental health bed’ on the right of the matrix were discontinued, and others were added.
Pretty cool, the matrix also has a small viz on the right that represents the completeness of the rows — They even mark the max and min amount of missing values.
Now let’s get a look at .heatmap, which will help us understand how the fields relate to each other regarding incompleteness.
msno.heatmap(df)
Okay, things just got complicated — Let’s simplify it.
This plot represents the correlation between the null values by column.
Column A has a value, B also has a value, which means a strong positive correlation or a blue 1 in the chart.
Column A has a value, but B has a null, which means a strong negative correlation, or a red -1 in the chart.
We noticed earlier that there was some change in the way data was collected, and here we can see it again. The new variables have a positive correlation with themselves but a negative correlation to the old fields.
Even though we can visualize that relationship by looking at the matrix, heatmaps make them more evident. It’s not always that we’ll have our rows sorted in a convenient way for us to realize the pattern.
In this dataset, we can see that the fields of the survey are almost grouped.
So, if one question is answered, we’ll very likely have the answers for all items of that group.
Okay, I want to go through one more way of visualizing how the fields relate in matters of nulls.
msno.dendrogram(df)
We saw some group behaviour with the heatmaps, but primarily because of the dataset arrangement.
If the rows are sorted, we can notice some correlation between the fields using the matrix chart, but this would be harder if they’re randomly positioned.
The same thing goes with heatmaps. If the columns are randomly positioned, we would have a more challenging time figuring out the pattern among groups of variables.
The dendrogram uses a hierarchical clustering algorithm to bin the fields by their correlation. *the relationship we saw with the heatmaps.
So it’s like figuring out which fields are highly related to each other in matters of nullity, then testing how those groups of variables relate to themselves and so on.
Again we can notice the discontinued fields, but we can get a more unobstructed view of which variables may be more reliable.
The chart illustrates how the groups connect, where connections farther from zero represent combinations of variables that are less similar in nullity.
Missingno is an excellent tool for quickly visualizing missing values; we only used one line of code for each chart and got a pretty decent result.
The tool has some filtering functions to select and arrange the variables we want to plot. And it allows us to customize some aspects of the chart, all on the same statement.
For whatever you can’t customize directly with the Missingno, you can always go to Matplotlib.
from IPython.core.display import display, HTMLimport matplotlib.pyplot as pltimport numpy as np# define matrix for the 13 columns with most nullsm = msno.matrix(df, figsize=(25, 14), filter='bottom', n=13, color=(0.3, 0.3, 0.5))# get ticks names and positionscols = [i.get_text() for i in m.axes.get_xticklabels()]ticks = np.arange(0,len(cols))# plot new ticksplt.xticks(ticks, labels=ticks+1, rotation=0, ha='center')# title n plotplt.title('Null values matrix\n'.upper(), loc='left', fontsize=22)plt.show()# empty string for the HTML and template for divhtml_table = ''template = '<div style="border-style:solid; display: inline-block; width: 325px; padding-left: 5px; border-width: thin" >{} - {}</div>'table_order = [1, 6, 10, 2, 7, 11, 3, 8, 12, 4, 9, 13, 5]# draw tablefor i in table_order: html_table += template.format(i, cols[i-1])HTML(html_table)
Great, we got a look at the basics of visualizing and analyzing the completeness of a dataset. It’s interesting to see how much we can learn about the data by visualizing their missing values.
Thanks for reading my article. I hope you enjoyed it.
Here you can find more tutorials like this about Python and data visualization.
|
[
{
"code": null,
"e": 296,
"s": 171,
"text": "It’s hard to know what to do with null values in our data. Most times, it’s easier to drop them and follow with what’s left."
},
{
"code": null,
"e": 509,
"s": 296,
"text": "But they can eventually have meaning and can be investigated. Taking some time to have a good look at them can often bring a better understanding of how the data was collected and even reveal some patterns in it."
},
{
"code": null,
"e": 649,
"s": 509,
"text": "In this article, we’ll explore how to visualize all the NULLs in our datasets and get a look at what insights we can extract from doing so."
},
{
"code": null,
"e": 754,
"s": 649,
"text": "I’ll run the code in Jupyer Lab, and I’ll use Pandas, Numpy, Missingno, and Matplotlib for this example."
},
{
"code": null,
"e": 866,
"s": 754,
"text": "The dataset will be California Jail Profile Survey, which contains monthly county-level data from 1995 to 2018."
},
{
"code": null,
"e": 960,
"s": 866,
"text": "import pandas as pdf = 'data/california_jail_county_monthly_1995_2018.csv'df = pd.read_csv(f)"
},
{
"code": null,
"e": 1066,
"s": 960,
"text": "After loading the dataset to Pandas, we can look at one of its convenient methods for dealing with Nulls."
},
{
"code": null,
"e": 1142,
"s": 1066,
"text": "We can use .isnull followed by a .sum and get the number of missing values."
},
{
"code": null,
"e": 1160,
"s": 1142,
"text": "df.isnull().sum()"
},
{
"code": null,
"e": 1314,
"s": 1160,
"text": "That’s already useful since it gives us an idea of which fields we can rely on, but there are better ways of visualizing this, let’s try using Missingno."
},
{
"code": null,
"e": 1450,
"s": 1314,
"text": "Missingno is a library for visualizing incompleteness in a dataset, it works on top of Matplotlib and Seaborn and is effortless to use."
},
{
"code": null,
"e": 1475,
"s": 1450,
"text": "import missingno as msno"
},
{
"code": null,
"e": 1603,
"s": 1475,
"text": "We’ll start with a simple bar chart. Instead of comparing that extensive list of numbers, we’ll use rectangles and their sizes."
},
{
"code": null,
"e": 1616,
"s": 1603,
"text": "msno.bar(df)"
},
{
"code": null,
"e": 1742,
"s": 1616,
"text": "That’s great! In a single method, just passing the data frame, we already have a visual representation of our missing values."
},
{
"code": null,
"e": 1962,
"s": 1742,
"text": "This bar chart represents the number of records in each column. Here we have two scales, one telling the exact amount of values in the field (right) and the other representing the proportion to the total number of rows."
},
{
"code": null,
"e": 2081,
"s": 1962,
"text": "Starting with a bar chart allows us to quickly tell if we’ll need to spend more time analyzing the null values or not."
},
{
"code": null,
"e": 2266,
"s": 2081,
"text": "It isn’t the case with our data, but if you have a blessed dataset without any null values or with an acceptable amount of them, you could stop by now and follow up with your analysis."
},
{
"code": null,
"e": 2322,
"s": 2266,
"text": "Let’s try a different visualization for missing values."
},
{
"code": null,
"e": 2338,
"s": 2322,
"text": "msno.matrix(df)"
},
{
"code": null,
"e": 2461,
"s": 2338,
"text": "A matrix tells us exactly where the missing values are, in our example, the data is sorted with the newest records on top."
},
{
"code": null,
"e": 2756,
"s": 2461,
"text": "We can already have some valuable insights by looking at the matrix and knowing how our data is arranged. Here we can see that the data collected changed at some point, where fields such as ‘avg inmates get mental health bed’ on the right of the matrix were discontinued, and others were added."
},
{
"code": null,
"e": 2918,
"s": 2756,
"text": "Pretty cool, the matrix also has a small viz on the right that represents the completeness of the rows — They even mark the max and min amount of missing values."
},
{
"code": null,
"e": 3044,
"s": 2918,
"text": "Now let’s get a look at .heatmap, which will help us understand how the fields relate to each other regarding incompleteness."
},
{
"code": null,
"e": 3061,
"s": 3044,
"text": "msno.heatmap(df)"
},
{
"code": null,
"e": 3116,
"s": 3061,
"text": "Okay, things just got complicated — Let’s simplify it."
},
{
"code": null,
"e": 3188,
"s": 3116,
"text": "This plot represents the correlation between the null values by column."
},
{
"code": null,
"e": 3298,
"s": 3188,
"text": "Column A has a value, B also has a value, which means a strong positive correlation or a blue 1 in the chart."
},
{
"code": null,
"e": 3407,
"s": 3298,
"text": "Column A has a value, but B has a null, which means a strong negative correlation, or a red -1 in the chart."
},
{
"code": null,
"e": 3622,
"s": 3407,
"text": "We noticed earlier that there was some change in the way data was collected, and here we can see it again. The new variables have a positive correlation with themselves but a negative correlation to the old fields."
},
{
"code": null,
"e": 3827,
"s": 3622,
"text": "Even though we can visualize that relationship by looking at the matrix, heatmaps make them more evident. It’s not always that we’ll have our rows sorted in a convenient way for us to realize the pattern."
},
{
"code": null,
"e": 3905,
"s": 3827,
"text": "In this dataset, we can see that the fields of the survey are almost grouped."
},
{
"code": null,
"e": 4002,
"s": 3905,
"text": "So, if one question is answered, we’ll very likely have the answers for all items of that group."
},
{
"code": null,
"e": 4100,
"s": 4002,
"text": "Okay, I want to go through one more way of visualizing how the fields relate in matters of nulls."
},
{
"code": null,
"e": 4120,
"s": 4100,
"text": "msno.dendrogram(df)"
},
{
"code": null,
"e": 4217,
"s": 4120,
"text": "We saw some group behaviour with the heatmaps, but primarily because of the dataset arrangement."
},
{
"code": null,
"e": 4372,
"s": 4217,
"text": "If the rows are sorted, we can notice some correlation between the fields using the matrix chart, but this would be harder if they’re randomly positioned."
},
{
"code": null,
"e": 4537,
"s": 4372,
"text": "The same thing goes with heatmaps. If the columns are randomly positioned, we would have a more challenging time figuring out the pattern among groups of variables."
},
{
"code": null,
"e": 4677,
"s": 4537,
"text": "The dendrogram uses a hierarchical clustering algorithm to bin the fields by their correlation. *the relationship we saw with the heatmaps."
},
{
"code": null,
"e": 4847,
"s": 4677,
"text": "So it’s like figuring out which fields are highly related to each other in matters of nullity, then testing how those groups of variables relate to themselves and so on."
},
{
"code": null,
"e": 4973,
"s": 4847,
"text": "Again we can notice the discontinued fields, but we can get a more unobstructed view of which variables may be more reliable."
},
{
"code": null,
"e": 5125,
"s": 4973,
"text": "The chart illustrates how the groups connect, where connections farther from zero represent combinations of variables that are less similar in nullity."
},
{
"code": null,
"e": 5273,
"s": 5125,
"text": "Missingno is an excellent tool for quickly visualizing missing values; we only used one line of code for each chart and got a pretty decent result."
},
{
"code": null,
"e": 5448,
"s": 5273,
"text": "The tool has some filtering functions to select and arrange the variables we want to plot. And it allows us to customize some aspects of the chart, all on the same statement."
},
{
"code": null,
"e": 5543,
"s": 5448,
"text": "For whatever you can’t customize directly with the Missingno, you can always go to Matplotlib."
},
{
"code": null,
"e": 6490,
"s": 5543,
"text": "from IPython.core.display import display, HTMLimport matplotlib.pyplot as pltimport numpy as np# define matrix for the 13 columns with most nullsm = msno.matrix(df, figsize=(25, 14), filter='bottom', n=13, color=(0.3, 0.3, 0.5))# get ticks names and positionscols = [i.get_text() for i in m.axes.get_xticklabels()]ticks = np.arange(0,len(cols))# plot new ticksplt.xticks(ticks, labels=ticks+1, rotation=0, ha='center')# title n plotplt.title('Null values matrix\\n'.upper(), loc='left', fontsize=22)plt.show()# empty string for the HTML and template for divhtml_table = ''template = '<div style=\"border-style:solid; display: inline-block; width: 325px; padding-left: 5px; border-width: thin\" >{} - {}</div>'table_order = [1, 6, 10, 2, 7, 11, 3, 8, 12, 4, 9, 13, 5]# draw tablefor i in table_order: html_table += template.format(i, cols[i-1])HTML(html_table)"
},
{
"code": null,
"e": 6683,
"s": 6490,
"text": "Great, we got a look at the basics of visualizing and analyzing the completeness of a dataset. It’s interesting to see how much we can learn about the data by visualizing their missing values."
},
{
"code": null,
"e": 6737,
"s": 6683,
"text": "Thanks for reading my article. I hope you enjoyed it."
}
] |
C# | Reverse the order of the elements in the entire List or in the specified range - GeeksforGeeks
|
10 Oct, 2018
List<T>.Reverse Method is used to reverse the order of the elements in the List<T> or a portion of it. There are two methods in the overload list of List<T>.Reverse Method as follows:
Reverse()
Reverse(Int32, Int32)
This method is used to reverse the order of the elements in the entire List<T>.
Syntax:
public void Reverse ();
Below programs illustrate the use of above discussed method:
Example 1:
// C# Program to reverse the order of// the elements in the entire List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 1; i <= 5; i++) { firstlist.Add(i); } Console.WriteLine("Elements Present in List:"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.WriteLine("After Reversing: "); // using method Reverse() firstlist.Reverse(); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } }}
Output:
Elements Present in List:
1
2
3
4
5
After Reversing:
5
4
3
2
1
Example 2:
// C# Program to reverse the order of// the elements in the entire List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add("Geeks"); firstlist.Add("C#"); firstlist.Add("Java"); firstlist.Add("C++"); Console.WriteLine("Elements Present in List:"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.WriteLine("After Reversing: "); // using method Reverse() firstlist.Reverse(); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}
Output:
Elements Present in List:
Geeks
C#
Java
C++
After Reversing:
C++
Java
C#
Geeks
This method is used to reverse the order of the elements in the specified range.
Syntax:
public void Reverse (int index, int count);
Parameters:
index: It is the zero-based starting index of the range which is to be reversed.
count: It is the number of elements in the range which is to be reversed.
Exceptions:
ArgumentOutOfRangeException: If the index or count is less than zero.
ArgumentException: If the index and count do not denote a valid range of elements in the List<T>.
Below programs illustrate the use of above discussed method:
Example 1:
// C# Program to reverse the order of// sub range in the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add("1st"); firstlist.Add("2nd"); firstlist.Add("3rd"); firstlist.Add("4th"); firstlist.Add("5th"); firstlist.Add("6th"); firstlist.Add("7th"); Console.WriteLine("Elements Present in List:"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.WriteLine("After Reversing: "); // Reversing the sub-range // that starts from index 2 // i.e 3rd element, and // count is 4 elements firstlist.Reverse(2, 4); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}
Output:
Elements Present in List:
1st
2nd
3rd
4th
5th
6th
7th
After Reversing:
1st
2nd
6th
5th
4th
3rd
7th
Example 2:
// C# Program to reverse the order of// sub range in the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add("1st"); firstlist.Add("2nd"); firstlist.Add("3rd"); firstlist.Add("4th"); firstlist.Add("5th"); firstlist.Add("6th"); firstlist.Add("7th"); Console.WriteLine("Elements Present in List:"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.WriteLine("After Reversing: "); // taking negative index will give error firstlist.Reverse(-1, 4); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}
RUntimeError:
Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.reverse?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Introduction to .NET Framework
C# | Constructors
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
C# | Delegates
|
[
{
"code": null,
"e": 25204,
"s": 25176,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 25388,
"s": 25204,
"text": "List<T>.Reverse Method is used to reverse the order of the elements in the List<T> or a portion of it. There are two methods in the overload list of List<T>.Reverse Method as follows:"
},
{
"code": null,
"e": 25398,
"s": 25388,
"text": "Reverse()"
},
{
"code": null,
"e": 25420,
"s": 25398,
"text": "Reverse(Int32, Int32)"
},
{
"code": null,
"e": 25500,
"s": 25420,
"text": "This method is used to reverse the order of the elements in the entire List<T>."
},
{
"code": null,
"e": 25508,
"s": 25500,
"text": "Syntax:"
},
{
"code": null,
"e": 25532,
"s": 25508,
"text": "public void Reverse ();"
},
{
"code": null,
"e": 25593,
"s": 25532,
"text": "Below programs illustrate the use of above discussed method:"
},
{
"code": null,
"e": 25604,
"s": 25593,
"text": "Example 1:"
},
{
"code": "// C# Program to reverse the order of// the elements in the entire List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 1; i <= 5; i++) { firstlist.Add(i); } Console.WriteLine(\"Elements Present in List:\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.WriteLine(\"After Reversing: \"); // using method Reverse() firstlist.Reverse(); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } }}",
"e": 26489,
"s": 25604,
"text": null
},
{
"code": null,
"e": 26497,
"s": 26489,
"text": "Output:"
},
{
"code": null,
"e": 26564,
"s": 26497,
"text": "Elements Present in List:\n1\n2\n3\n4\n5\n \nAfter Reversing: \n5\n4\n3\n2\n1\n"
},
{
"code": null,
"e": 26575,
"s": 26564,
"text": "Example 2:"
},
{
"code": "// C# Program to reverse the order of// the elements in the entire List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add(\"Geeks\"); firstlist.Add(\"C#\"); firstlist.Add(\"Java\"); firstlist.Add(\"C++\"); Console.WriteLine(\"Elements Present in List:\"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.WriteLine(\"After Reversing: \"); // using method Reverse() firstlist.Reverse(); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}",
"e": 27514,
"s": 26575,
"text": null
},
{
"code": null,
"e": 27522,
"s": 27514,
"text": "Output:"
},
{
"code": null,
"e": 27605,
"s": 27522,
"text": "Elements Present in List:\nGeeks\nC#\nJava\nC++\n \nAfter Reversing: \nC++\nJava\nC#\nGeeks\n"
},
{
"code": null,
"e": 27686,
"s": 27605,
"text": "This method is used to reverse the order of the elements in the specified range."
},
{
"code": null,
"e": 27694,
"s": 27686,
"text": "Syntax:"
},
{
"code": null,
"e": 27738,
"s": 27694,
"text": "public void Reverse (int index, int count);"
},
{
"code": null,
"e": 27750,
"s": 27738,
"text": "Parameters:"
},
{
"code": null,
"e": 27831,
"s": 27750,
"text": "index: It is the zero-based starting index of the range which is to be reversed."
},
{
"code": null,
"e": 27905,
"s": 27831,
"text": "count: It is the number of elements in the range which is to be reversed."
},
{
"code": null,
"e": 27917,
"s": 27905,
"text": "Exceptions:"
},
{
"code": null,
"e": 27987,
"s": 27917,
"text": "ArgumentOutOfRangeException: If the index or count is less than zero."
},
{
"code": null,
"e": 28085,
"s": 27987,
"text": "ArgumentException: If the index and count do not denote a valid range of elements in the List<T>."
},
{
"code": null,
"e": 28146,
"s": 28085,
"text": "Below programs illustrate the use of above discussed method:"
},
{
"code": null,
"e": 28157,
"s": 28146,
"text": "Example 1:"
},
{
"code": "// C# Program to reverse the order of// sub range in the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add(\"1st\"); firstlist.Add(\"2nd\"); firstlist.Add(\"3rd\"); firstlist.Add(\"4th\"); firstlist.Add(\"5th\"); firstlist.Add(\"6th\"); firstlist.Add(\"7th\"); Console.WriteLine(\"Elements Present in List:\"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.WriteLine(\"After Reversing: \"); // Reversing the sub-range // that starts from index 2 // i.e 3rd element, and // count is 4 elements firstlist.Reverse(2, 4); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}",
"e": 29272,
"s": 28157,
"text": null
},
{
"code": null,
"e": 29280,
"s": 29272,
"text": "Output:"
},
{
"code": null,
"e": 29383,
"s": 29280,
"text": "Elements Present in List:\n1st\n2nd\n3rd\n4th\n5th\n6th\n7th\n \nAfter Reversing: \n1st\n2nd\n6th\n5th\n4th\n3rd\n7th\n"
},
{
"code": null,
"e": 29394,
"s": 29383,
"text": "Example 2:"
},
{
"code": "// C# Program to reverse the order of// sub range in the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main() { // Creating an List<T> of Integers List<string> firstlist = new List<string>(); // Adding elements to List firstlist.Add(\"1st\"); firstlist.Add(\"2nd\"); firstlist.Add(\"3rd\"); firstlist.Add(\"4th\"); firstlist.Add(\"5th\"); firstlist.Add(\"6th\"); firstlist.Add(\"7th\"); Console.WriteLine(\"Elements Present in List:\"); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.WriteLine(\"After Reversing: \"); // taking negative index will give error firstlist.Reverse(-1, 4); // Displaying the elements of List foreach(string k in firstlist) { Console.WriteLine(k); } }}",
"e": 30428,
"s": 29394,
"text": null
},
{
"code": null,
"e": 30442,
"s": 30428,
"text": "RUntimeError:"
},
{
"code": null,
"e": 30549,
"s": 30442,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Non-negative number required.Parameter name: index"
},
{
"code": null,
"e": 30560,
"s": 30549,
"text": "Reference:"
},
{
"code": null,
"e": 30670,
"s": 30560,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.reverse?view=netframework-4.7.2"
},
{
"code": null,
"e": 30699,
"s": 30670,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 30719,
"s": 30699,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 30744,
"s": 30719,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 30758,
"s": 30744,
"text": "CSharp-method"
},
{
"code": null,
"e": 30761,
"s": 30758,
"text": "C#"
},
{
"code": null,
"e": 30859,
"s": 30761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30868,
"s": 30859,
"text": "Comments"
},
{
"code": null,
"e": 30881,
"s": 30868,
"text": "Old Comments"
},
{
"code": null,
"e": 30909,
"s": 30881,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30932,
"s": 30909,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30954,
"s": 30932,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30985,
"s": 30954,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 31003,
"s": 30985,
"text": "C# | Constructors"
},
{
"code": null,
"e": 31049,
"s": 31003,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 31089,
"s": 31049,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 31111,
"s": 31089,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 31134,
"s": 31111,
"text": "Extension Method in C#"
}
] |
What is the difference between findElement and findElements in Selenium Webdriver?
|
There are differences between findElement and findElements in the Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method
returns a list of matching elements.
The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is thrown by the findElement, however, an empty list is returned by the findElements method.
Good usage of the findElements method usage is counting the total number of images or accessing each of images by iterating with a loop.
Syntax −
WebElement i = driver.findElement(By.id("img-loc"));
List<WebElement> s =
driver.findElements(By.tagName("img"));
Code Implementation
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class FindElementFindElementMthds{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm");
//identify single element
WebElement elm = driver.findElement(By.tagName("h2"));
String s = elm.getText();
System.out.println("Get text on element: " + s);
//identify all elements with tagname
List<WebElement> i = driver.findElements(By.tagName("img"));
//count
int c = i.size();
System.out.println("Number of images: " + c);
//browser close
driver.close();
}
}
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "There are differences between findElement and findElements in the Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method\nreturns a list of matching elements."
},
{
"code": null,
"e": 1562,
"s": 1317,
"text": "The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is thrown by the findElement, however, an empty list is returned by the findElements method."
},
{
"code": null,
"e": 1699,
"s": 1562,
"text": "Good usage of the findElements method usage is counting the total number of images or accessing each of images by iterating with a loop."
},
{
"code": null,
"e": 1708,
"s": 1699,
"text": "Syntax −"
},
{
"code": null,
"e": 1822,
"s": 1708,
"text": "WebElement i = driver.findElement(By.id(\"img-loc\"));\nList<WebElement> s =\ndriver.findElements(By.tagName(\"img\"));"
},
{
"code": null,
"e": 1842,
"s": 1822,
"text": "Code Implementation"
},
{
"code": null,
"e": 2917,
"s": 1842,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class FindElementFindElementMthds{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/upsc_ias_exams.htm\");\n\n //identify single element\n WebElement elm = driver.findElement(By.tagName(\"h2\"));\n String s = elm.getText();\n System.out.println(\"Get text on element: \" + s);\n\n //identify all elements with tagname\n List<WebElement> i = driver.findElements(By.tagName(\"img\"));\n\n //count\n int c = i.size();\n System.out.println(\"Number of images: \" + c);\n\n //browser close\n driver.close();\n }\n}"
}
] |
C# - Structures
|
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure −
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure −
using System;
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure {
public static void Main(string[] args) {
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or C++. The C# structures have the following features −
Structures can have methods, fields, indexers, properties, operator methods, and events.
Structures can have methods, fields, indexers, properties, operator methods, and events.
Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
Unlike classes, structures cannot inherit other structures or classes.
Unlike classes, structures cannot inherit other structures or classes.
Structures cannot be used as a base for other structures or classes.
Structures cannot be used as a base for other structures or classes.
A structure can implement one or more interfaces.
A structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.
If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.
Classes and Structures have the following basic differences −
classes are reference types and structs are value types
structures do not support inheritance
structures cannot have default constructor
In the light of the above discussions, let us rewrite the previous example −
using System;
struct Books {
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id) {
title = t;
author = a;
subject = s;
book_id = id;
}
public void display() {
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure {
public static void Main(string[] args) {
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result −
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2449,
"s": 2270,
"text": "In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure."
},
{
"code": null,
"e": 2618,
"s": 2449,
"text": "Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −"
},
{
"code": null,
"e": 2624,
"s": 2618,
"text": "Title"
},
{
"code": null,
"e": 2631,
"s": 2624,
"text": "Author"
},
{
"code": null,
"e": 2639,
"s": 2631,
"text": "Subject"
},
{
"code": null,
"e": 2647,
"s": 2639,
"text": "Book ID"
},
{
"code": null,
"e": 2795,
"s": 2647,
"text": "To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program."
},
{
"code": null,
"e": 2861,
"s": 2795,
"text": "For example, here is the way you can declare the Book structure −"
},
{
"code": null,
"e": 2979,
"s": 2861,
"text": "struct Books {\n public string title;\n public string author;\n public string subject;\n public int book_id;\n}; "
},
{
"code": null,
"e": 3034,
"s": 2979,
"text": "The following program shows the use of the structure −"
},
{
"code": null,
"e": 4321,
"s": 3034,
"text": "using System;\n\nstruct Books {\n public string title;\n public string author;\n public string subject;\n public int book_id;\n}; \n\npublic class testStructure {\n public static void Main(string[] args) {\n Books Book1; /* Declare Book1 of type Book */\n Books Book2; /* Declare Book2 of type Book */\n\n /* book 1 specification */\n Book1.title = \"C Programming\";\n Book1.author = \"Nuha Ali\"; \n Book1.subject = \"C Programming Tutorial\";\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n Book2.title = \"Telecom Billing\";\n Book2.author = \"Zara Ali\";\n Book2.subject = \"Telecom Billing Tutorial\";\n Book2.book_id = 6495700;\n\n /* print Book1 info */\n Console.WriteLine( \"Book 1 title : {0}\", Book1.title);\n Console.WriteLine(\"Book 1 author : {0}\", Book1.author);\n Console.WriteLine(\"Book 1 subject : {0}\", Book1.subject);\n Console.WriteLine(\"Book 1 book_id :{0}\", Book1.book_id);\n\n /* print Book2 info */\n Console.WriteLine(\"Book 2 title : {0}\", Book2.title);\n Console.WriteLine(\"Book 2 author : {0}\", Book2.author);\n Console.WriteLine(\"Book 2 subject : {0}\", Book2.subject);\n Console.WriteLine(\"Book 2 book_id : {0}\", Book2.book_id); \n\n Console.ReadKey();\n }\n}"
},
{
"code": null,
"e": 4402,
"s": 4321,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4645,
"s": 4402,
"text": "Book 1 title : C Programming\nBook 1 author : Nuha Ali\nBook 1 subject : C Programming Tutorial\nBook 1 book_id : 6495407\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n"
},
{
"code": null,
"e": 4819,
"s": 4645,
"text": "You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or C++. The C# structures have the following features −"
},
{
"code": null,
"e": 4908,
"s": 4819,
"text": "Structures can have methods, fields, indexers, properties, operator methods, and events."
},
{
"code": null,
"e": 4997,
"s": 4908,
"text": "Structures can have methods, fields, indexers, properties, operator methods, and events."
},
{
"code": null,
"e": 5198,
"s": 4997,
"text": "Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed."
},
{
"code": null,
"e": 5399,
"s": 5198,
"text": "Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed."
},
{
"code": null,
"e": 5470,
"s": 5399,
"text": "Unlike classes, structures cannot inherit other structures or classes."
},
{
"code": null,
"e": 5541,
"s": 5470,
"text": "Unlike classes, structures cannot inherit other structures or classes."
},
{
"code": null,
"e": 5610,
"s": 5541,
"text": "Structures cannot be used as a base for other structures or classes."
},
{
"code": null,
"e": 5679,
"s": 5610,
"text": "Structures cannot be used as a base for other structures or classes."
},
{
"code": null,
"e": 5729,
"s": 5679,
"text": "A structure can implement one or more interfaces."
},
{
"code": null,
"e": 5779,
"s": 5729,
"text": "A structure can implement one or more interfaces."
},
{
"code": null,
"e": 5853,
"s": 5779,
"text": "Structure members cannot be specified as abstract, virtual, or protected."
},
{
"code": null,
"e": 5927,
"s": 5853,
"text": "Structure members cannot be specified as abstract, virtual, or protected."
},
{
"code": null,
"e": 6118,
"s": 5927,
"text": "When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator."
},
{
"code": null,
"e": 6309,
"s": 6118,
"text": "When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator."
},
{
"code": null,
"e": 6439,
"s": 6309,
"text": "If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized."
},
{
"code": null,
"e": 6569,
"s": 6439,
"text": "If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized."
},
{
"code": null,
"e": 6631,
"s": 6569,
"text": "Classes and Structures have the following basic differences −"
},
{
"code": null,
"e": 6687,
"s": 6631,
"text": "classes are reference types and structs are value types"
},
{
"code": null,
"e": 6725,
"s": 6687,
"text": "structures do not support inheritance"
},
{
"code": null,
"e": 6768,
"s": 6725,
"text": "structures cannot have default constructor"
},
{
"code": null,
"e": 6845,
"s": 6768,
"text": "In the light of the above discussions, let us rewrite the previous example −"
},
{
"code": null,
"e": 7971,
"s": 6845,
"text": "using System;\n\nstruct Books {\n private string title;\n private string author;\n private string subject;\n private int book_id;\n \n public void getValues(string t, string a, string s, int id) {\n title = t;\n author = a;\n subject = s;\n book_id = id;\n }\n \n public void display() {\n Console.WriteLine(\"Title : {0}\", title);\n Console.WriteLine(\"Author : {0}\", author);\n Console.WriteLine(\"Subject : {0}\", subject);\n Console.WriteLine(\"Book_id :{0}\", book_id);\n }\n}; \n\npublic class testStructure {\n\n public static void Main(string[] args) {\n Books Book1 = new Books(); /* Declare Book1 of type Book */\n Books Book2 = new Books(); /* Declare Book2 of type Book */\n\n /* book 1 specification */\n Book1.getValues(\"C Programming\",\n \"Nuha Ali\", \"C Programming Tutorial\",6495407);\n\n /* book 2 specification */\n Book2.getValues(\"Telecom Billing\",\n \"Zara Ali\", \"Telecom Billing Tutorial\", 6495700);\n\n /* print Book1 info */\n Book1.display();\n\n /* print Book2 info */\n Book2.display(); \n\n Console.ReadKey();\n }\n}"
},
{
"code": null,
"e": 8052,
"s": 7971,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8239,
"s": 8052,
"text": "Title : C Programming\nAuthor : Nuha Ali\nSubject : C Programming Tutorial\nBook_id : 6495407\nTitle : Telecom Billing\nAuthor : Zara Ali\nSubject : Telecom Billing Tutorial\nBook_id : 6495700\n"
},
{
"code": null,
"e": 8276,
"s": 8239,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 8289,
"s": 8276,
"text": " Raja Biswas"
},
{
"code": null,
"e": 8323,
"s": 8289,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8341,
"s": 8323,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 8374,
"s": 8341,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8388,
"s": 8374,
"text": " Peter Jepson"
},
{
"code": null,
"e": 8425,
"s": 8388,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 8440,
"s": 8425,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 8475,
"s": 8440,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 8490,
"s": 8475,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8525,
"s": 8490,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8537,
"s": 8525,
"text": " Eric Frick"
},
{
"code": null,
"e": 8544,
"s": 8537,
"text": " Print"
},
{
"code": null,
"e": 8555,
"s": 8544,
"text": " Add Notes"
}
] |
Java Program to reverse a given String with preserving the position of space.
|
You can reverse the contents of a given String using leaving the spaces using the reverse() method of the StringBuffer class.
public class Test {
public static void main(String args[]) {
String str = "hi welcome to Tutorialspoint";
String strArray[] = str.split(" ");
StringBuffer sb= new StringBuffer(str);
sb.reverse();
for(int i=0 ; i<str.length(); i++){
if(str.charAt(i)== ' '){
sb.insert(i, " ");
}
}
sb.append("");
System.out.println(sb);
}
tn iopslai ro tuT ot emoclew ih
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "You can reverse the contents of a given String using leaving the spaces using the reverse() method of the StringBuffer class."
},
{
"code": null,
"e": 1572,
"s": 1188,
"text": "public class Test {\n public static void main(String args[]) {\n String str = \"hi welcome to Tutorialspoint\";\n String strArray[] = str.split(\" \");\n StringBuffer sb= new StringBuffer(str);\n sb.reverse();\n for(int i=0 ; i<str.length(); i++){\n if(str.charAt(i)== ' '){\n sb.insert(i, \" \");\n }\n }\n sb.append(\"\");\n System.out.println(sb);\n}"
},
{
"code": null,
"e": 1604,
"s": 1572,
"text": "tn iopslai ro tuT ot emoclew ih"
}
] |
Customized Debugging in Sublime Text using C++ for Competitive Programming - GeeksforGeeks
|
13 Jan, 2022
Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest.
Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment
Time is something that is precious and it matters a lot during a coding contest. When writing a code, errors do come and programmers often tend to spend a lot of time debugging it. Often programmers deal with complex data structures during a contest and it is required to debug them in the given time constraint.
This article focuses on how to debug C++ source code efficiently in Sublime Text (IDE) during a contest and save time. First of all, it is required to set up the file structure of our Sublime Text. Below are the steps to set up the file structure of Sublime Text.
Step 1: Open the Sublime Text and follow the below steps:
1. Create three files:
file.cpp: The file to write the code.
inputf.txt: The file where we will be giving the input.
outputf.txt: The file where the output will be displayed.
2. Now, perform the following steps:
Select View > Layout > Columns: 3. This will create three columns in the workspace. Move the three files into three columns.
Select View > Groups > Max Columns : 2 : input.txt and output.txt will get stacked in a single column.
Your Sublime Text would look similar to this:
Sublime Text
Step 2: Create a local function outside the main function. It is used to take input from the input.txt file and display output in the output.txt file. Below is the C++ code snippet for the same.
C++
// Declare this function outside// the main functionvoid local(){ // In case of online judges (like // codechef, codeforces etc) these // lines will be skipped. In other // words these lines would be executed // in Sublime Text only #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); // ONLINE_JUDGE #endif}
Step 3: Call from the main function:
// Call from the main function
local();
By combining the above steps our complete program would be:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Local functionvoid local(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); // ONLINE_JUDGE #endif} // Driver codeint main(){ local(); return 0;}
Step 4: Now the IDE would look similar to this:
Sublime Text
Debugging using print function:
Create a print function in our program whenever we need to print a variable or any data structure like vector, set, map, etc. Below is the C++ program to implement the same approach:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initializing a vector vector<int> vect = {2, 4, 10, 12, 17}; // First operation for (auto& x : vect) { if (x % 2 == 0) x += 10; else x -= 10; } // Second operation for (auto& x : vect) x += 2; // Third operation for (auto& x : vect) x += 20;}
Suppose something went wrong in our logic due to which desired output is not obtained during a contest and hence to check the status of vector after the first operation, one can create a print function outside the main function which accepts a vector.
C++
// print function outside the// main functionvoid print(vector<int>& vect){ cout << "vect " << ' '; cout << '[' << ' '; // Print vector elements for (auto x : vect) { cout << x << ' '; } cout << ']';}
Whenever there is a need to check the vector elements one can call the print() function by passing the vector as an argument to the print function.
// Calling print function from main
print(vect);
Below is the complete C++ program to illustrate how to implement the above concept:
C++
// C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Print function for debuggingvoid print(vector<int>& vect){ cout << "vect " << ' '; cout << '[' << ' '; // Print vector elements for (auto x : vect) { cout << x << ' '; } cout << ']';} // Driver codeint main(){ // Initializing a vector vector<int> vect = {2, 4, 10, 12, 17}; // First operation for (auto& x : vect) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect elements after // applying first operation // Checking the status of vect as // a part of debugging print(vect); // Second operation for (auto& x : vect) x += 2; // Third operation for (auto& x : vect) x += 20; int finalAnswer = 0; for (auto x : vect) finalAnswer += x; // Print the final answer cout << "\nFinal Answer: " << finalAnswer; return 0;}
vect [ 12 14 20 22 7 ]
Final Answer: 185
Disadvantages of this method:
For the same data structure but having different data types there is a need to create multiple print functions. For example, there is a vector of integer type and a vector of string type, then in order to print elements, it is required to create two print functions outside the main function. One print function will accept a vector of integer type and another print function will accept a vector of string type.
Contents of the vector would be printed along with the desired values in the same output.txt file which might be confusing for us.
There is a need to comment statements that are used to call a print function from the main function, before eventually submitting the source code file to the online judge (Codeforces, Spoj, Codechef, etc).
Debugging using template:
In the above method, the data type of vector is hardcoded. The template can be used in C++. A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that there is no need to write the same code (print function) for different data types. Below is the C++ code snippet for the template:
C++
// One print function works for// all data types. This would work// even for user defined types if// operator '>' is overloadedtemplate <typename T> void print(vector<T> vect){ // body}
Below is the complete C++ program to illustrate the above concept:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Using template so that this// function works for all data// typestemplate <typename T> void print( vector<T>& vect){ cout << "vect " << ' '; cout << '[' << ' '; for (auto x : vect) { cout << x << ' '; } cout << ']'; cout << '\n';} // Driver codeint main(){ vector<int> vect1 = {2, 4, 10, 12, 17}; for (auto& x : vect1) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect1 elements print(vect1); // Initializing a vector of // string type vector<string> vect2 = {"Geeks", "for", "Geeks"}; // Printing vect2 elements print(vect2); // Modifying vect2 // push back string "is great" vect2.push_back("is the great"); // Printing vect2 after modification print(vect2); int finalAnswer = 0; for (auto x : vect1) finalAnswer += x; cout << "Final Answer: " << finalAnswer; return 0;}
vect [ 12 14 20 22 7 ]
vect [ Geeks for Geeks ]
vect [ Geeks for Geeks is the great ]
Final Answer: 75
A similar thing can be done with any data structure like a set, multiset, pairs, etc. Below is the implementation using the set:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Using template so that this// function works for all data// typestemplate <typename T> void print( set<T>& set1){ cout << "set " << ' '; cout << '[' << ' '; for (auto x : set1) { cout << x << ' '; } cout << ']'; cout << '\n';} // Driver codeint main(){ // Declaring a set set<int> set1; // Inserting elements in the set for (int i = 0; i < 10; i++) set1.insert(i); // Printing set1 elements print(set1); // Declaring another set of // string type set<string> set2; // Inserting elements in the set set2.insert("GeeksforGeeks"); // Printing set2 elements print(set2); int finalAnswer = 0; for (auto x : set1) finalAnswer += x; cout << "Final Answer: " << finalAnswer; return 0;}
set [ 0 1 2 3 4 5 6 7 8 9 ]
set [ GeeksforGeeks ]
Final Answer: 45
Disadvantages of this method:
The above method is not very efficient as each time before submitting the program there is a need to comment print statements inside the main function.
Elements of the data structure would be printed along with other desired values in the same output.txt file which might be confusing for us.
Debugging using cerr:
The idea is to use the combination of cerr (error stream) and file handling in the program. Create a separate file (error.txt) and use cerr stream instead of cout stream. Finally, with the help of file handling, print the status of data structure in the error.txt file.
Step 1: Firstly add the following snippets outside the main function:
To print a variable we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T> //Function to print the variablevoid print(T x){ // Using error stream to print // the variable cerr << x;}
To print vector elements we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T> // Function to print the elements// of the vectorvoid print(vector<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same to print a variable (Function // Overloading) print(x); cerr << ' '; } cerr << ']';}
To print set elements arranged in non-descending order we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T> // Function to print elements of the// set arranged in non-descending ordervoid print(set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable // (Function Overloading) print(x); cerr << ' '; } cerr << ']';}
To print set elements arranged in non-ascending order we can create a print function with a template definition just above the function:
C++
template <typename T> // Function to print the set elements// arranged in non-ascending ordervoid print(set<T, greater<T> >& a){ cerr << '[' << ' '; for (auto x : a) { // same as printing a variable // (Function Overloading) print(x); cerr << ' '; } cerr << ']';}
To print unordered set elements, we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T> // Function to print unordered// set elementsvoid print(unordered_set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable // Using the concept of function // overloading print(x); cerr << ' '; } cerr << ']';}
To print map elements, we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T, typename V> //Function to print map elements// arranged in non-descending ordervoid print(map<T, V>& a){ cerr << "[ "; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << " "; } cerr << "]";}
To print unordered map elements, we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T, typename V> //Function to print unordered map elementsvoid print(unordered_map<T, V>& a){ cerr << "[ "; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << " "; } cerr << "]";}
To print multiset elements arranged in non-descending order, we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T> //Function to print multiset elements// arranged in non-descending ordervoid print(multiset<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}
To print multiset elements, arranged in non-ascending order we can create a print function with a template definition just above the function:
C++
//Template definitiontemplate <typename T> //Function to print elements of a// multiset arranged in non-ascending ordervoid print(multiset<T, greater<T> >& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}
To print unordered set elements, we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T> // Print function to print unordered// set elementsvoid print(unordered_set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}
To print vector of vectors elements, we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T> // Function to print vector of// vectors elementsvoid print(vector<vector<T> >& a){ cerr << "[ "; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << " "; } cerr << "]";}
To print a pair of elements, we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T, typename V> // Function to print elements of a pairvoid print(pair<T, V> x){ // Sam as printing the variable using // the concept of function overloading print(x.ff); cerr << ':'; // Same as variable using the concept // of function overloading print(x.ss);}
To print a pair of vectors elements, we can create a print function with a template definition just above the function:
C++
// Template definitiontemplate <typename T, typename V> // Function to print vector of// pairs elementsvoid print(vector<pair<T, V> >& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable using // the concept of function overloading print(x.ff); cerr << ":"; // Same as printing a variable using // the concept of function overloading print(x.ss); cerr << ' '; } cerr << ']';}
Step 2: Create one more new file (error.txt) and make sure it is in the same folder.
error.txt file: All the elements of the data structures that we have mentioned in the above snippets would be printed in this text file only without affecting the output.txt file.
Note that we want to write in this file using error stream (cerr). Again help from ifndef and endif preprocessor directives can be taken.
C++
// We want to skip writing on error.txt// file when online judge (Codechef,// Codeforces, etc) is defined#ifndef ONLINE_JUDGE freopen("error.txt", "w", stderr); // ONLINE_JUDGE#endif
After adding the above lines in our local function, the complete function becomes:
C++
// Now local function would look like:void local(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); // ONLINE_JUDGE #endif // It basically means that these // statements (Between ifndef and // endif) would be skipped / ignored // if ONLINE_JUDGE is defined We don't // need to comment "local();" statement // in our function while submitting our // source code file to online judges. // It would be handled automatically #ifndef ONLINE_JUDGE freopen("error.txt", "w", stderr); // ONLINE_JUDGE #endif}
Step 3: Also, we don’t want to comment debug(data_structure) statements while submitting the source code file to online judges. In simple words, there is a need to figure out a way so that debug functions will work for the sublime text (IDE) but they would be skipped/ignored for online judges.Again, this can be achieved by using ifndef and endif preprocessor directives again in the source code.
C++
// If online judge is defined#ifndef ONLINE_JUDGE#define debug(x) cerr << #x << " "; print(x); cerr << '\n'; // If Online Judge is not defined#else#define debug(x)#endif
Now the IDE would look similar to this:
Step 4: Whenever there is a need to check the status of any data structure, the following call can be made:
// Calling from the main function
debug(dataStructure);
Step 5: Below is the implementation of the above method:
Example 1:
C++
/* It is recommended below snippets in your template file of competitive programming */#include <bits/stdc++.h>using namespace std; // Debugging Functions template<class T>void print(T x){ cerr << x;}template<class T, class V> void print(pair<T , V> x){ print(x.ff); cerr << ':'; print(x.ss);}template<class T> void print(vector<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(unordered_set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T, class V> void print(vector<pair<T, V>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x.ff); cerr << ":"; print(x.ss); cerr << ' '; } cerr << ']';}template <class T, class V> void print(map <T, V> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";}template <class T, class V> void print(unordered_map <T, V> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";}template <class T> void print(vector<vector<T>> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";} void local(){ // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen("error.txt", "w", stderr); #endif #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << " "; print(x); cerr << '\n'; #else #define debug(x) #endif} // Driver codeint main(){ local(); // Number of elements in the vector int n; // Taking input from the user // through input.txt file cin >> n; // Declaring a vector of integer // type of size n vector<int> vect1(n); // Initializing the vector for(int i = 0 ; i < n ; i++) cin >> vect1[i]; // Modifying the vector for (auto& x : vect1) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect1 elements // It will be printed in error.txt // file using cerr stream debug(vect1); // Initializing a vector of string type vector<string> vect2 = {"Geeks", "for", "Geeks"}; // Printing vect2 elements // It will be printed in error.txt // file using cerr stream debug(vect2); // Modifying vect2 // push back string "is great" vect2.push_back("is the great"); // Printing vect2 after modification // It will be printed in error.txt // file using cerr stream debug(vect2); // Calculating the answer int finalAnswer = 0; for (auto x : vect1) finalAnswer += x; // Finally, printing answer in output.txt // file using cout stream cout << "Final Answer: " << finalAnswer; return 0;}
file.cpp file:
input.txt file
output.txt file
error.txt file
Example 2:
C++
/* It is recommended below snippets in your template file of competitive programming */ #include <bits/stdc++.h>using namespace std; // Debugging Functionstemplate<class T>void print(T x){ cerr << x;}template<class T , class V> void print(pair<T, V> x){ print(x.ff); cerr << ':'; print(x.ss);}template<class T> void print(vector<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(unordered_set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T, class V> void print(vector<pair<T, V>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x.ff); cerr << ":"; print(x.ss); cerr << ' '; } cerr << ']';}template <class T, class V> void print(map <T, V> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";}template <class T, class V> void print(unordered_map <T, V> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";}template <class T> void print(vector<vector<T>> &a){ cerr << "[ "; for (auto i : a) { print(i); cerr << " "; } cerr << "]";} void local(){ // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen("error.txt", "w", stderr); #endif #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << " "; print(x); cerr << '\n'; #else #define debug(x) #endif} // Driver codeint main(){ local(); // Number of elements in the set int n; // Taking input from the user // through input.txt file cin >> n; // Declaring a set of integers set<int> set1; for(int i = 0 ; i < n ; i++) { int number; // Taking input from the user // through input.txt file cin >> number; //Inserting in the set set1.insert(number); } // Erasing from the set if(!set1.empty()) { // erasing the first element // of the set set1.erase(set1.begin()); } // Printing set1 elements // It will be printed in error.txt // file using cerr stream debug(set1); // Declaring another set set<string> set2; // Inserting in the set set2.insert("GeeksforGeeks"); // Printing set2 elements // It will be printed in error.txt file // using cerr stream debug(set2); // Inserting in set // Insert the string "is great" set2.insert("Geek"); // Printing set2 elements after // inserting into the set, It will // be printed in error.txt file // using cerr stream debug(set2); // Calculating the answer int finalAnswer = 0; for (auto x : set1) finalAnswer += x; // Finally, printing answer in output.txt // file using cout stream cout << "Final Answer: " << finalAnswer; return 0;}
file.cpp file:
input.txt file
output.txt file
error.txt file
Advantage of this method of debugging:
Now there is no need to comment on each of the debug statements in the program before submitting the source code file to online judges.
The data structure or STL elements would be printed in a separate file (error.txt) and desired output values would be printed in the output.txt file, making it more readable.
In a nutshell, this can save a lot of time during a coding contest.
kashishsoda
bhuwanesh
rkbhola5
C++
Competitive Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 25709,
"s": 25479,
"text": "Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest."
},
{
"code": null,
"e": 25791,
"s": 25709,
"text": "Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 26106,
"s": 25791,
"text": "Time is something that is precious and it matters a lot during a coding contest. When writing a code, errors do come and programmers often tend to spend a lot of time debugging it. Often programmers deal with complex data structures during a contest and it is required to debug them in the given time constraint. "
},
{
"code": null,
"e": 26372,
"s": 26106,
"text": "This article focuses on how to debug C++ source code efficiently in Sublime Text (IDE) during a contest and save time. First of all, it is required to set up the file structure of our Sublime Text. Below are the steps to set up the file structure of Sublime Text. "
},
{
"code": null,
"e": 26430,
"s": 26372,
"text": "Step 1: Open the Sublime Text and follow the below steps:"
},
{
"code": null,
"e": 26453,
"s": 26430,
"text": "1. Create three files:"
},
{
"code": null,
"e": 26491,
"s": 26453,
"text": "file.cpp: The file to write the code."
},
{
"code": null,
"e": 26547,
"s": 26491,
"text": "inputf.txt: The file where we will be giving the input."
},
{
"code": null,
"e": 26605,
"s": 26547,
"text": "outputf.txt: The file where the output will be displayed."
},
{
"code": null,
"e": 26642,
"s": 26605,
"text": "2. Now, perform the following steps:"
},
{
"code": null,
"e": 26767,
"s": 26642,
"text": "Select View > Layout > Columns: 3. This will create three columns in the workspace. Move the three files into three columns."
},
{
"code": null,
"e": 26870,
"s": 26767,
"text": "Select View > Groups > Max Columns : 2 : input.txt and output.txt will get stacked in a single column."
},
{
"code": null,
"e": 26916,
"s": 26870,
"text": "Your Sublime Text would look similar to this:"
},
{
"code": null,
"e": 26929,
"s": 26916,
"text": "Sublime Text"
},
{
"code": null,
"e": 27124,
"s": 26929,
"text": "Step 2: Create a local function outside the main function. It is used to take input from the input.txt file and display output in the output.txt file. Below is the C++ code snippet for the same."
},
{
"code": null,
"e": 27128,
"s": 27124,
"text": "C++"
},
{
"code": "// Declare this function outside// the main functionvoid local(){ // In case of online judges (like // codechef, codeforces etc) these // lines will be skipped. In other // words these lines would be executed // in Sublime Text only #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); // ONLINE_JUDGE #endif}",
"e": 27488,
"s": 27128,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27488,
"text": " Step 3: Call from the main function: "
},
{
"code": null,
"e": 27567,
"s": 27527,
"text": "// Call from the main function\nlocal();"
},
{
"code": null,
"e": 27627,
"s": 27567,
"text": "By combining the above steps our complete program would be:"
},
{
"code": null,
"e": 27631,
"s": 27627,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Local functionvoid local(){ #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); // ONLINE_JUDGE #endif} // Driver codeint main(){ local(); return 0;}",
"e": 27944,
"s": 27631,
"text": null
},
{
"code": null,
"e": 27993,
"s": 27944,
"text": " Step 4: Now the IDE would look similar to this:"
},
{
"code": null,
"e": 28006,
"s": 27993,
"text": "Sublime Text"
},
{
"code": null,
"e": 28038,
"s": 28006,
"text": "Debugging using print function:"
},
{
"code": null,
"e": 28221,
"s": 28038,
"text": "Create a print function in our program whenever we need to print a variable or any data structure like vector, set, map, etc. Below is the C++ program to implement the same approach:"
},
{
"code": null,
"e": 28225,
"s": 28221,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // Initializing a vector vector<int> vect = {2, 4, 10, 12, 17}; // First operation for (auto& x : vect) { if (x % 2 == 0) x += 10; else x -= 10; } // Second operation for (auto& x : vect) x += 2; // Third operation for (auto& x : vect) x += 20;}",
"e": 28646,
"s": 28225,
"text": null
},
{
"code": null,
"e": 28901,
"s": 28649,
"text": "Suppose something went wrong in our logic due to which desired output is not obtained during a contest and hence to check the status of vector after the first operation, one can create a print function outside the main function which accepts a vector."
},
{
"code": null,
"e": 28905,
"s": 28901,
"text": "C++"
},
{
"code": "// print function outside the// main functionvoid print(vector<int>& vect){ cout << \"vect \" << ' '; cout << '[' << ' '; // Print vector elements for (auto x : vect) { cout << x << ' '; } cout << ']';}",
"e": 29117,
"s": 28905,
"text": null
},
{
"code": null,
"e": 29266,
"s": 29117,
"text": " Whenever there is a need to check the vector elements one can call the print() function by passing the vector as an argument to the print function."
},
{
"code": null,
"e": 29316,
"s": 29266,
"text": "// Calling print function from main\n\nprint(vect);"
},
{
"code": null,
"e": 29400,
"s": 29316,
"text": "Below is the complete C++ program to illustrate how to implement the above concept:"
},
{
"code": null,
"e": 29404,
"s": 29400,
"text": "C++"
},
{
"code": "// C++ program to implement// the above concept#include <bits/stdc++.h>using namespace std; // Print function for debuggingvoid print(vector<int>& vect){ cout << \"vect \" << ' '; cout << '[' << ' '; // Print vector elements for (auto x : vect) { cout << x << ' '; } cout << ']';} // Driver codeint main(){ // Initializing a vector vector<int> vect = {2, 4, 10, 12, 17}; // First operation for (auto& x : vect) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect elements after // applying first operation // Checking the status of vect as // a part of debugging print(vect); // Second operation for (auto& x : vect) x += 2; // Third operation for (auto& x : vect) x += 20; int finalAnswer = 0; for (auto x : vect) finalAnswer += x; // Print the final answer cout << \"\\nFinal Answer: \" << finalAnswer; return 0;}",
"e": 30317,
"s": 29404,
"text": null
},
{
"code": null,
"e": 30359,
"s": 30317,
"text": "vect [ 12 14 20 22 7 ]\nFinal Answer: 185"
},
{
"code": null,
"e": 30390,
"s": 30359,
"text": "Disadvantages of this method: "
},
{
"code": null,
"e": 30803,
"s": 30390,
"text": "For the same data structure but having different data types there is a need to create multiple print functions. For example, there is a vector of integer type and a vector of string type, then in order to print elements, it is required to create two print functions outside the main function. One print function will accept a vector of integer type and another print function will accept a vector of string type."
},
{
"code": null,
"e": 30934,
"s": 30803,
"text": "Contents of the vector would be printed along with the desired values in the same output.txt file which might be confusing for us."
},
{
"code": null,
"e": 31140,
"s": 30934,
"text": "There is a need to comment statements that are used to call a print function from the main function, before eventually submitting the source code file to the online judge (Codeforces, Spoj, Codechef, etc)."
},
{
"code": null,
"e": 31166,
"s": 31140,
"text": "Debugging using template:"
},
{
"code": null,
"e": 31507,
"s": 31166,
"text": "In the above method, the data type of vector is hardcoded. The template can be used in C++. A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that there is no need to write the same code (print function) for different data types. Below is the C++ code snippet for the template:"
},
{
"code": null,
"e": 31511,
"s": 31507,
"text": "C++"
},
{
"code": "// One print function works for// all data types. This would work// even for user defined types if// operator '>' is overloadedtemplate <typename T> void print(vector<T> vect){ // body}",
"e": 31701,
"s": 31511,
"text": null
},
{
"code": null,
"e": 31769,
"s": 31701,
"text": " Below is the complete C++ program to illustrate the above concept:"
},
{
"code": null,
"e": 31773,
"s": 31769,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Using template so that this// function works for all data// typestemplate <typename T> void print( vector<T>& vect){ cout << \"vect \" << ' '; cout << '[' << ' '; for (auto x : vect) { cout << x << ' '; } cout << ']'; cout << '\\n';} // Driver codeint main(){ vector<int> vect1 = {2, 4, 10, 12, 17}; for (auto& x : vect1) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect1 elements print(vect1); // Initializing a vector of // string type vector<string> vect2 = {\"Geeks\", \"for\", \"Geeks\"}; // Printing vect2 elements print(vect2); // Modifying vect2 // push back string \"is great\" vect2.push_back(\"is the great\"); // Printing vect2 after modification print(vect2); int finalAnswer = 0; for (auto x : vect1) finalAnswer += x; cout << \"Final Answer: \" << finalAnswer; return 0;}",
"e": 32775,
"s": 31773,
"text": null
},
{
"code": null,
"e": 32881,
"s": 32775,
"text": "vect [ 12 14 20 22 7 ]\nvect [ Geeks for Geeks ]\nvect [ Geeks for Geeks is the great ]\nFinal Answer: 75"
},
{
"code": null,
"e": 33012,
"s": 32883,
"text": "A similar thing can be done with any data structure like a set, multiset, pairs, etc. Below is the implementation using the set:"
},
{
"code": null,
"e": 33016,
"s": 33012,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Using template so that this// function works for all data// typestemplate <typename T> void print( set<T>& set1){ cout << \"set \" << ' '; cout << '[' << ' '; for (auto x : set1) { cout << x << ' '; } cout << ']'; cout << '\\n';} // Driver codeint main(){ // Declaring a set set<int> set1; // Inserting elements in the set for (int i = 0; i < 10; i++) set1.insert(i); // Printing set1 elements print(set1); // Declaring another set of // string type set<string> set2; // Inserting elements in the set set2.insert(\"GeeksforGeeks\"); // Printing set2 elements print(set2); int finalAnswer = 0; for (auto x : set1) finalAnswer += x; cout << \"Final Answer: \" << finalAnswer; return 0;}",
"e": 33852,
"s": 33016,
"text": null
},
{
"code": null,
"e": 33921,
"s": 33852,
"text": "set [ 0 1 2 3 4 5 6 7 8 9 ]\nset [ GeeksforGeeks ]\nFinal Answer: 45"
},
{
"code": null,
"e": 33952,
"s": 33921,
"text": "Disadvantages of this method: "
},
{
"code": null,
"e": 34104,
"s": 33952,
"text": "The above method is not very efficient as each time before submitting the program there is a need to comment print statements inside the main function."
},
{
"code": null,
"e": 34245,
"s": 34104,
"text": "Elements of the data structure would be printed along with other desired values in the same output.txt file which might be confusing for us."
},
{
"code": null,
"e": 34267,
"s": 34245,
"text": "Debugging using cerr:"
},
{
"code": null,
"e": 34538,
"s": 34267,
"text": "The idea is to use the combination of cerr (error stream) and file handling in the program. Create a separate file (error.txt) and use cerr stream instead of cout stream. Finally, with the help of file handling, print the status of data structure in the error.txt file."
},
{
"code": null,
"e": 34608,
"s": 34538,
"text": "Step 1: Firstly add the following snippets outside the main function:"
},
{
"code": null,
"e": 34711,
"s": 34608,
"text": "To print a variable we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 34715,
"s": 34711,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T> //Function to print the variablevoid print(T x){ // Using error stream to print // the variable cerr << x;}",
"e": 34869,
"s": 34715,
"text": null
},
{
"code": null,
"e": 34980,
"s": 34872,
"text": "To print vector elements we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 34984,
"s": 34980,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T> // Function to print the elements// of the vectorvoid print(vector<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same to print a variable (Function // Overloading) print(x); cerr << ' '; } cerr << ']';}",
"e": 35254,
"s": 34984,
"text": null
},
{
"code": null,
"e": 35395,
"s": 35257,
"text": "To print set elements arranged in non-descending order we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 35399,
"s": 35395,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T> // Function to print elements of the// set arranged in non-descending ordervoid print(set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable // (Function Overloading) print(x); cerr << ' '; } cerr << ']';}",
"e": 35694,
"s": 35399,
"text": null
},
{
"code": null,
"e": 35834,
"s": 35697,
"text": "To print set elements arranged in non-ascending order we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 35838,
"s": 35834,
"text": "C++"
},
{
"code": "template <typename T> // Function to print the set elements// arranged in non-ascending ordervoid print(set<T, greater<T> >& a){ cerr << '[' << ' '; for (auto x : a) { // same as printing a variable // (Function Overloading) print(x); cerr << ' '; } cerr << ']';}",
"e": 36121,
"s": 35838,
"text": null
},
{
"code": null,
"e": 36240,
"s": 36124,
"text": "To print unordered set elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 36244,
"s": 36240,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T> // Function to print unordered// set elementsvoid print(unordered_set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable // Using the concept of function // overloading print(x); cerr << ' '; } cerr << ']';}",
"e": 36549,
"s": 36244,
"text": null
},
{
"code": null,
"e": 36658,
"s": 36552,
"text": "To print map elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 36662,
"s": 36658,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T, typename V> //Function to print map elements// arranged in non-descending ordervoid print(map<T, V>& a){ cerr << \"[ \"; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << \" \"; } cerr << \"]\";}",
"e": 36966,
"s": 36662,
"text": null
},
{
"code": null,
"e": 37085,
"s": 36969,
"text": "To print unordered map elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 37089,
"s": 37085,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T, typename V> //Function to print unordered map elementsvoid print(unordered_map<T, V>& a){ cerr << \"[ \"; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << \" \"; } cerr << \"]\";}",
"e": 37381,
"s": 37089,
"text": null
},
{
"code": null,
"e": 37528,
"s": 37384,
"text": "To print multiset elements arranged in non-descending order, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 37532,
"s": 37528,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T> //Function to print multiset elements// arranged in non-descending ordervoid print(multiset<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}",
"e": 37837,
"s": 37532,
"text": null
},
{
"code": null,
"e": 37983,
"s": 37840,
"text": "To print multiset elements, arranged in non-ascending order we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 37987,
"s": 37983,
"text": "C++"
},
{
"code": "//Template definitiontemplate <typename T> //Function to print elements of a// multiset arranged in non-ascending ordervoid print(multiset<T, greater<T> >& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}",
"e": 38309,
"s": 37987,
"text": null
},
{
"code": null,
"e": 38428,
"s": 38312,
"text": "To print unordered set elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 38432,
"s": 38428,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T> // Print function to print unordered// set elementsvoid print(unordered_set<T>& a){ cerr << '[' << ' '; for (auto x : a) { // Same as variable using the // concept of function overloading print(x); cerr << ' '; } cerr << ']';}",
"e": 38722,
"s": 38432,
"text": null
},
{
"code": null,
"e": 38845,
"s": 38725,
"text": "To print vector of vectors elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 38849,
"s": 38845,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T> // Function to print vector of// vectors elementsvoid print(vector<vector<T> >& a){ cerr << \"[ \"; for (auto i : a) { // Same as variable using the // concept of function overloading print(i); cerr << \" \"; } cerr << \"]\";}",
"e": 39137,
"s": 38849,
"text": null
},
{
"code": null,
"e": 39252,
"s": 39140,
"text": "To print a pair of elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 39256,
"s": 39252,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T, typename V> // Function to print elements of a pairvoid print(pair<T, V> x){ // Sam as printing the variable using // the concept of function overloading print(x.ff); cerr << ':'; // Same as variable using the concept // of function overloading print(x.ss);}",
"e": 39570,
"s": 39256,
"text": null
},
{
"code": null,
"e": 39690,
"s": 39570,
"text": "To print a pair of vectors elements, we can create a print function with a template definition just above the function:"
},
{
"code": null,
"e": 39694,
"s": 39690,
"text": "C++"
},
{
"code": "// Template definitiontemplate <typename T, typename V> // Function to print vector of// pairs elementsvoid print(vector<pair<T, V> >& a){ cerr << '[' << ' '; for (auto x : a) { // Same as printing a variable using // the concept of function overloading print(x.ff); cerr << \":\"; // Same as printing a variable using // the concept of function overloading print(x.ss); cerr << ' '; } cerr << ']';}",
"e": 40123,
"s": 39694,
"text": null
},
{
"code": null,
"e": 40209,
"s": 40123,
"text": " Step 2: Create one more new file (error.txt) and make sure it is in the same folder."
},
{
"code": null,
"e": 40389,
"s": 40209,
"text": "error.txt file: All the elements of the data structures that we have mentioned in the above snippets would be printed in this text file only without affecting the output.txt file."
},
{
"code": null,
"e": 40527,
"s": 40389,
"text": "Note that we want to write in this file using error stream (cerr). Again help from ifndef and endif preprocessor directives can be taken."
},
{
"code": null,
"e": 40531,
"s": 40527,
"text": "C++"
},
{
"code": "// We want to skip writing on error.txt// file when online judge (Codechef,// Codeforces, etc) is defined#ifndef ONLINE_JUDGE freopen(\"error.txt\", \"w\", stderr); // ONLINE_JUDGE#endif",
"e": 40717,
"s": 40531,
"text": null
},
{
"code": null,
"e": 40800,
"s": 40717,
"text": "After adding the above lines in our local function, the complete function becomes:"
},
{
"code": null,
"e": 40804,
"s": 40800,
"text": "C++"
},
{
"code": "// Now local function would look like:void local(){ #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); // ONLINE_JUDGE #endif // It basically means that these // statements (Between ifndef and // endif) would be skipped / ignored // if ONLINE_JUDGE is defined We don't // need to comment \"local();\" statement // in our function while submitting our // source code file to online judges. // It would be handled automatically #ifndef ONLINE_JUDGE freopen(\"error.txt\", \"w\", stderr); // ONLINE_JUDGE #endif}",
"e": 41373,
"s": 40804,
"text": null
},
{
"code": null,
"e": 41774,
"s": 41376,
"text": "Step 3: Also, we don’t want to comment debug(data_structure) statements while submitting the source code file to online judges. In simple words, there is a need to figure out a way so that debug functions will work for the sublime text (IDE) but they would be skipped/ignored for online judges.Again, this can be achieved by using ifndef and endif preprocessor directives again in the source code."
},
{
"code": null,
"e": 41778,
"s": 41774,
"text": "C++"
},
{
"code": "// If online judge is defined#ifndef ONLINE_JUDGE#define debug(x) cerr << #x << \" \"; print(x); cerr << '\\n'; // If Online Judge is not defined#else#define debug(x)#endif",
"e": 42067,
"s": 41778,
"text": null
},
{
"code": null,
"e": 42108,
"s": 42067,
"text": " Now the IDE would look similar to this:"
},
{
"code": null,
"e": 42216,
"s": 42108,
"text": "Step 4: Whenever there is a need to check the status of any data structure, the following call can be made:"
},
{
"code": null,
"e": 42272,
"s": 42216,
"text": "// Calling from the main function\ndebug(dataStructure);"
},
{
"code": null,
"e": 42329,
"s": 42272,
"text": "Step 5: Below is the implementation of the above method:"
},
{
"code": null,
"e": 42340,
"s": 42329,
"text": "Example 1:"
},
{
"code": null,
"e": 42344,
"s": 42340,
"text": "C++"
},
{
"code": "/* It is recommended below snippets in your template file of competitive programming */#include <bits/stdc++.h>using namespace std; // Debugging Functions template<class T>void print(T x){ cerr << x;}template<class T, class V> void print(pair<T , V> x){ print(x.ff); cerr << ':'; print(x.ss);}template<class T> void print(vector<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(unordered_set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T, class V> void print(vector<pair<T, V>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x.ff); cerr << \":\"; print(x.ss); cerr << ' '; } cerr << ']';}template <class T, class V> void print(map <T, V> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";}template <class T, class V> void print(unordered_map <T, V> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";}template <class T> void print(vector<vector<T>> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";} void local(){ // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); #endif // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen(\"error.txt\", \"w\", stderr); #endif #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << \" \"; print(x); cerr << '\\n'; #else #define debug(x) #endif} // Driver codeint main(){ local(); // Number of elements in the vector int n; // Taking input from the user // through input.txt file cin >> n; // Declaring a vector of integer // type of size n vector<int> vect1(n); // Initializing the vector for(int i = 0 ; i < n ; i++) cin >> vect1[i]; // Modifying the vector for (auto& x : vect1) { if (x % 2 == 0) x += 10; else x -= 10; } // Printing vect1 elements // It will be printed in error.txt // file using cerr stream debug(vect1); // Initializing a vector of string type vector<string> vect2 = {\"Geeks\", \"for\", \"Geeks\"}; // Printing vect2 elements // It will be printed in error.txt // file using cerr stream debug(vect2); // Modifying vect2 // push back string \"is great\" vect2.push_back(\"is the great\"); // Printing vect2 after modification // It will be printed in error.txt // file using cerr stream debug(vect2); // Calculating the answer int finalAnswer = 0; for (auto x : vect1) finalAnswer += x; // Finally, printing answer in output.txt // file using cout stream cout << \"Final Answer: \" << finalAnswer; return 0;}",
"e": 45681,
"s": 42344,
"text": null
},
{
"code": null,
"e": 45696,
"s": 45681,
"text": "file.cpp file:"
},
{
"code": null,
"e": 45711,
"s": 45696,
"text": "input.txt file"
},
{
"code": null,
"e": 45728,
"s": 45711,
"text": "output.txt file "
},
{
"code": null,
"e": 45743,
"s": 45728,
"text": "error.txt file"
},
{
"code": null,
"e": 45754,
"s": 45743,
"text": "Example 2:"
},
{
"code": null,
"e": 45758,
"s": 45754,
"text": "C++"
},
{
"code": "/* It is recommended below snippets in your template file of competitive programming */ #include <bits/stdc++.h>using namespace std; // Debugging Functionstemplate<class T>void print(T x){ cerr << x;}template<class T , class V> void print(pair<T, V> x){ print(x.ff); cerr << ':'; print(x.ss);}template<class T> void print(vector<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(set<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(multiset<T, greater<T>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T> void print(unordered_set<T> &a){ cerr << '[' << ' '; for(auto x : a) { print(x); cerr << ' '; } cerr << ']';}template<class T, class V> void print(vector<pair<T, V>> &a){ cerr << '[' << ' '; for(auto x : a) { print(x.ff); cerr << \":\"; print(x.ss); cerr << ' '; } cerr << ']';}template <class T, class V> void print(map <T, V> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";}template <class T, class V> void print(unordered_map <T, V> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";}template <class T> void print(vector<vector<T>> &a){ cerr << \"[ \"; for (auto i : a) { print(i); cerr << \" \"; } cerr << \"]\";} void local(){ // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen(\"input.txt\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); #endif // ONLINE_JUDGE #ifndef ONLINE_JUDGE freopen(\"error.txt\", \"w\", stderr); #endif #ifndef ONLINE_JUDGE #define debug(x) cerr << #x << \" \"; print(x); cerr << '\\n'; #else #define debug(x) #endif} // Driver codeint main(){ local(); // Number of elements in the set int n; // Taking input from the user // through input.txt file cin >> n; // Declaring a set of integers set<int> set1; for(int i = 0 ; i < n ; i++) { int number; // Taking input from the user // through input.txt file cin >> number; //Inserting in the set set1.insert(number); } // Erasing from the set if(!set1.empty()) { // erasing the first element // of the set set1.erase(set1.begin()); } // Printing set1 elements // It will be printed in error.txt // file using cerr stream debug(set1); // Declaring another set set<string> set2; // Inserting in the set set2.insert(\"GeeksforGeeks\"); // Printing set2 elements // It will be printed in error.txt file // using cerr stream debug(set2); // Inserting in set // Insert the string \"is great\" set2.insert(\"Geek\"); // Printing set2 elements after // inserting into the set, It will // be printed in error.txt file // using cerr stream debug(set2); // Calculating the answer int finalAnswer = 0; for (auto x : set1) finalAnswer += x; // Finally, printing answer in output.txt // file using cout stream cout << \"Final Answer: \" << finalAnswer; return 0;}",
"e": 49212,
"s": 45758,
"text": null
},
{
"code": null,
"e": 49227,
"s": 49212,
"text": "file.cpp file:"
},
{
"code": null,
"e": 49242,
"s": 49227,
"text": "input.txt file"
},
{
"code": null,
"e": 49259,
"s": 49242,
"text": "output.txt file "
},
{
"code": null,
"e": 49274,
"s": 49259,
"text": "error.txt file"
},
{
"code": null,
"e": 49313,
"s": 49274,
"text": "Advantage of this method of debugging:"
},
{
"code": null,
"e": 49449,
"s": 49313,
"text": "Now there is no need to comment on each of the debug statements in the program before submitting the source code file to online judges."
},
{
"code": null,
"e": 49624,
"s": 49449,
"text": "The data structure or STL elements would be printed in a separate file (error.txt) and desired output values would be printed in the output.txt file, making it more readable."
},
{
"code": null,
"e": 49692,
"s": 49624,
"text": "In a nutshell, this can save a lot of time during a coding contest."
},
{
"code": null,
"e": 49704,
"s": 49692,
"text": "kashishsoda"
},
{
"code": null,
"e": 49714,
"s": 49704,
"text": "bhuwanesh"
},
{
"code": null,
"e": 49723,
"s": 49714,
"text": "rkbhola5"
},
{
"code": null,
"e": 49727,
"s": 49723,
"text": "C++"
},
{
"code": null,
"e": 49751,
"s": 49727,
"text": "Competitive Programming"
},
{
"code": null,
"e": 49755,
"s": 49751,
"text": "CPP"
},
{
"code": null,
"e": 49853,
"s": 49755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49881,
"s": 49853,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 49901,
"s": 49881,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 49934,
"s": 49901,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 49958,
"s": 49934,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 49983,
"s": 49958,
"text": "std::string class in C++"
},
{
"code": null,
"e": 50026,
"s": 49983,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 50069,
"s": 50026,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 50110,
"s": 50069,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 50188,
"s": 50110,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Grunt - Getting Started
|
To make use of Grunt, you need to have Node.js installed. The installation of Node.js has been explained in the previous chapter. You can install Grunt and Grunt plugins by using Node.js package manager.
Before setting up Grunt on system, you can update the Node package manager by using the following command −
npm update -g npm
If you are using Mac or Linux, you need to use sudo word at the beginning of the command line to grant administrator access as shown below −
sudo npm update -g npm
CLI stands for Command Line Interface that runs the version of Grunt which has been installed. To get started with Grunt, you need to install Grunt's command line interface (CLI) globally as shown below −
npm install -g grunt-cli
Running the above command will put the grunt command in your system path, which makes it to run from any directory. You cannot install Grunt task runner by installing grunt-cli. It allows a machine to install multiple versions of Grunt simultaneously.
The CLI looks for the installed Grunt on your system by using require() system whenever Grunt is run. Using grunt-cli, you can run Grunt from any directory in your project. If you are using locally installed Grunt, then grunt-cli uses locally installed Grunt library and applies the configuration from the Grunt file.
If you are working with an already configured project that includes package.json and Gruntfile, then follow the simple steps as specified below −
Find the path to the project's root directory.
You can install dependencies using the npm install command.
Run Grunt using the grunt command.
If you are creating a new project, then include the two files package.json and Gruntfile to your project.
package.json − The package.json file is placed in the root directory of the project and it is used to run each listed dependency whenever you run the command npm install in the same folder.
package.json − The package.json file is placed in the root directory of the project and it is used to run each listed dependency whenever you run the command npm install in the same folder.
Gruntfile.js − The Gruntfile.js file is used to write configuration settings for the project.
Gruntfile.js − The Gruntfile.js file is used to write configuration settings for the project.
The package.json file is placed in the root directory of the project, beside the Gruntfile and is used to run each listed dependency whenever you run the command npm install in the same folder.
You can create the package.jsonin different ways as listed below −
You can grunt-init to create package.json file.
You can also create package.json file by using the npm-init command.
You can write specification as shown below −
{
"name": "tutorialspoint",
"version": "0.1.0",
"devDependencies": {
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-nodeunit": "~0.4.1",
"grunt-contrib-uglify": "~0.5.0"
}
}
You can add Grunt and gruntplugins into an existing pacakge.json file by using the following command −
npm install <module> --save-dev
Here, <module> represents the module to be installed locally. The above command will install the specified module and automatically add it to the devDependencies section.
For instance, the following command will install the latest version of Grunt and add it to your devDependencies −
npm install grunt --save-dev
The Gruntfile.js file is a default place where your configuration settings will go for Grunt. The Grunt file includes the following parts −
The wrapper function
Project and task configuration
Loading Grunt plugins and tasks
Custom tasks
The basic Gruntfile.js file is as shown below −
// our wrapper function (required by grunt and its plugins)
// all configuration goes inside this function
module.exports = function(grunt) {
// CONFIGURE GRUNT
grunt.initConfig({
// get the configuration info from package.json file
// this way we can use things like name and version (pkg.name)
pkg: grunt.file.readJSON('package.json'),
// all of our configuration goes here
});
// Load the plugin that provides the "uglify" task
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s)
grunt.registerTask('default', ['uglify']);
};
In the above code, module.exports is a wrapper function where the entire configuration goes inside this function. It is a way of displaying configuration to the rest of application.
module.exports = function(grunt) {
//do grunt-related things here
}
You can configure Grunt tasks, once your Grunt configuration is ready. The project configuration can be written in the grunt.initConfig() section. Inside the grunt.initConfig() function, take the configuration information from package.json file and save it to pkg. You can call your project name using pkg.name and version with pkg.version.
Load the tasks from a specified plugin by using the grunt.loadNpmTasks method. You can install the plugin locally by using npm and it must be relative to the Gruntfile. You can load the plugin with a simple command as shown below −
grunt.task.loadNpmTasks(pluginName)
When you are running Grunt through command line, the Grunt will look for the default task. In the above code, we are using a task called uglify which can be run using gruntcommand. This is same as explicitly running grunt uglify command and you can specify the number of tasks in the array.
grunt.registerTask('default', ['uglify']);
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1919,
"s": 1715,
"text": "To make use of Grunt, you need to have Node.js installed. The installation of Node.js has been explained in the previous chapter. You can install Grunt and Grunt plugins by using Node.js package manager."
},
{
"code": null,
"e": 2027,
"s": 1919,
"text": "Before setting up Grunt on system, you can update the Node package manager by using the following command −"
},
{
"code": null,
"e": 2045,
"s": 2027,
"text": "npm update -g npm"
},
{
"code": null,
"e": 2186,
"s": 2045,
"text": "If you are using Mac or Linux, you need to use sudo word at the beginning of the command line to grant administrator access as shown below −"
},
{
"code": null,
"e": 2209,
"s": 2186,
"text": "sudo npm update -g npm"
},
{
"code": null,
"e": 2414,
"s": 2209,
"text": "CLI stands for Command Line Interface that runs the version of Grunt which has been installed. To get started with Grunt, you need to install Grunt's command line interface (CLI) globally as shown below −"
},
{
"code": null,
"e": 2439,
"s": 2414,
"text": "npm install -g grunt-cli"
},
{
"code": null,
"e": 2691,
"s": 2439,
"text": "Running the above command will put the grunt command in your system path, which makes it to run from any directory. You cannot install Grunt task runner by installing grunt-cli. It allows a machine to install multiple versions of Grunt simultaneously."
},
{
"code": null,
"e": 3009,
"s": 2691,
"text": "The CLI looks for the installed Grunt on your system by using require() system whenever Grunt is run. Using grunt-cli, you can run Grunt from any directory in your project. If you are using locally installed Grunt, then grunt-cli uses locally installed Grunt library and applies the configuration from the Grunt file."
},
{
"code": null,
"e": 3155,
"s": 3009,
"text": "If you are working with an already configured project that includes package.json and Gruntfile, then follow the simple steps as specified below −"
},
{
"code": null,
"e": 3202,
"s": 3155,
"text": "Find the path to the project's root directory."
},
{
"code": null,
"e": 3262,
"s": 3202,
"text": "You can install dependencies using the npm install command."
},
{
"code": null,
"e": 3297,
"s": 3262,
"text": "Run Grunt using the grunt command."
},
{
"code": null,
"e": 3403,
"s": 3297,
"text": "If you are creating a new project, then include the two files package.json and Gruntfile to your project."
},
{
"code": null,
"e": 3593,
"s": 3403,
"text": "package.json − The package.json file is placed in the root directory of the project and it is used to run each listed dependency whenever you run the command npm install in the same folder."
},
{
"code": null,
"e": 3783,
"s": 3593,
"text": "package.json − The package.json file is placed in the root directory of the project and it is used to run each listed dependency whenever you run the command npm install in the same folder."
},
{
"code": null,
"e": 3877,
"s": 3783,
"text": "Gruntfile.js − The Gruntfile.js file is used to write configuration settings for the project."
},
{
"code": null,
"e": 3971,
"s": 3877,
"text": "Gruntfile.js − The Gruntfile.js file is used to write configuration settings for the project."
},
{
"code": null,
"e": 4166,
"s": 3971,
"text": "The package.json file is placed in the root directory of the project, beside the Gruntfile and is used to run each listed dependency whenever you run the command npm install in the same folder. "
},
{
"code": null,
"e": 4233,
"s": 4166,
"text": "You can create the package.jsonin different ways as listed below −"
},
{
"code": null,
"e": 4281,
"s": 4233,
"text": "You can grunt-init to create package.json file."
},
{
"code": null,
"e": 4350,
"s": 4281,
"text": "You can also create package.json file by using the npm-init command."
},
{
"code": null,
"e": 4395,
"s": 4350,
"text": "You can write specification as shown below −"
},
{
"code": null,
"e": 4602,
"s": 4395,
"text": "{\n \"name\": \"tutorialspoint\",\n \"version\": \"0.1.0\",\n \"devDependencies\": {\n \"grunt-contrib-jshint\": \"~0.10.0\",\n \"grunt-contrib-nodeunit\": \"~0.4.1\",\n \"grunt-contrib-uglify\": \"~0.5.0\"\n }\n}"
},
{
"code": null,
"e": 4705,
"s": 4602,
"text": "You can add Grunt and gruntplugins into an existing pacakge.json file by using the following command −"
},
{
"code": null,
"e": 4737,
"s": 4705,
"text": "npm install <module> --save-dev"
},
{
"code": null,
"e": 4908,
"s": 4737,
"text": "Here, <module> represents the module to be installed locally. The above command will install the specified module and automatically add it to the devDependencies section."
},
{
"code": null,
"e": 5022,
"s": 4908,
"text": "For instance, the following command will install the latest version of Grunt and add it to your devDependencies −"
},
{
"code": null,
"e": 5051,
"s": 5022,
"text": "npm install grunt --save-dev"
},
{
"code": null,
"e": 5191,
"s": 5051,
"text": "The Gruntfile.js file is a default place where your configuration settings will go for Grunt. The Grunt file includes the following parts −"
},
{
"code": null,
"e": 5212,
"s": 5191,
"text": "The wrapper function"
},
{
"code": null,
"e": 5243,
"s": 5212,
"text": "Project and task configuration"
},
{
"code": null,
"e": 5275,
"s": 5243,
"text": "Loading Grunt plugins and tasks"
},
{
"code": null,
"e": 5288,
"s": 5275,
"text": "Custom tasks"
},
{
"code": null,
"e": 5336,
"s": 5288,
"text": "The basic Gruntfile.js file is as shown below −"
},
{
"code": null,
"e": 5926,
"s": 5336,
"text": "// our wrapper function (required by grunt and its plugins)\n// all configuration goes inside this function\nmodule.exports = function(grunt) {\n\n // CONFIGURE GRUNT\n grunt.initConfig({\n // get the configuration info from package.json file\n // this way we can use things like name and version (pkg.name)\n pkg: grunt.file.readJSON('package.json'),\n\n // all of our configuration goes here\n\n });\n\n // Load the plugin that provides the \"uglify\" task\n grunt.loadNpmTasks('grunt-contrib-uglify');\n\n // Default task(s)\n grunt.registerTask('default', ['uglify']);\n};"
},
{
"code": null,
"e": 6108,
"s": 5926,
"text": "In the above code, module.exports is a wrapper function where the entire configuration goes inside this function. It is a way of displaying configuration to the rest of application."
},
{
"code": null,
"e": 6179,
"s": 6108,
"text": "module.exports = function(grunt) {\n //do grunt-related things here\n}"
},
{
"code": null,
"e": 6520,
"s": 6179,
"text": "You can configure Grunt tasks, once your Grunt configuration is ready. The project configuration can be written in the grunt.initConfig() section. Inside the grunt.initConfig() function, take the configuration information from package.json file and save it to pkg. You can call your project name using pkg.name and version with pkg.version."
},
{
"code": null,
"e": 6752,
"s": 6520,
"text": "Load the tasks from a specified plugin by using the grunt.loadNpmTasks method. You can install the plugin locally by using npm and it must be relative to the Gruntfile. You can load the plugin with a simple command as shown below −"
},
{
"code": null,
"e": 6788,
"s": 6752,
"text": "grunt.task.loadNpmTasks(pluginName)"
},
{
"code": null,
"e": 7079,
"s": 6788,
"text": "When you are running Grunt through command line, the Grunt will look for the default task. In the above code, we are using a task called uglify which can be run using gruntcommand. This is same as explicitly running grunt uglify command and you can specify the number of tasks in the array."
},
{
"code": null,
"e": 7122,
"s": 7079,
"text": "grunt.registerTask('default', ['uglify']);"
},
{
"code": null,
"e": 7129,
"s": 7122,
"text": " Print"
},
{
"code": null,
"e": 7140,
"s": 7129,
"text": " Add Notes"
}
] |
Redis - Scripting
|
Redis scripting is used to evaluate scripts using the Lua interpreter. It is built into Redis starting from version 2.6.0. The command used for scripting is EVAL command.
Following is the basic syntax of EVAL command.
redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]
Following example explains how Redis scripting works.
redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1
key2 first second
1) "key1"
2) "key2"
3) "first"
4) "second"
Following table lists some basic commands related to Redis Scripting.
Executes a Lua script.
Executes a Lua script.
Checks the existence of scripts in the script cache.
Removes all the scripts from the script cache.
Kills the script currently in execution.
Loads the specified Lua script into the script cache.
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2216,
"s": 2045,
"text": "Redis scripting is used to evaluate scripts using the Lua interpreter. It is built into Redis starting from version 2.6.0. The command used for scripting is EVAL command."
},
{
"code": null,
"e": 2263,
"s": 2216,
"text": "Following is the basic syntax of EVAL command."
},
{
"code": null,
"e": 2334,
"s": 2263,
"text": "redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]\n"
},
{
"code": null,
"e": 2388,
"s": 2334,
"text": "Following example explains how Redis scripting works."
},
{
"code": null,
"e": 2533,
"s": 2388,
"text": "redis 127.0.0.1:6379> EVAL \"return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}\" 2 key1 \nkey2 first second \n1) \"key1\" \n2) \"key2\" \n3) \"first\" \n4) \"second\"\n"
},
{
"code": null,
"e": 2603,
"s": 2533,
"text": "Following table lists some basic commands related to Redis Scripting."
},
{
"code": null,
"e": 2626,
"s": 2603,
"text": "Executes a Lua script."
},
{
"code": null,
"e": 2649,
"s": 2626,
"text": "Executes a Lua script."
},
{
"code": null,
"e": 2702,
"s": 2649,
"text": "Checks the existence of scripts in the script cache."
},
{
"code": null,
"e": 2749,
"s": 2702,
"text": "Removes all the scripts from the script cache."
},
{
"code": null,
"e": 2790,
"s": 2749,
"text": "Kills the script currently in execution."
},
{
"code": null,
"e": 2844,
"s": 2790,
"text": "Loads the specified Lua script into the script cache."
},
{
"code": null,
"e": 2876,
"s": 2844,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2896,
"s": 2876,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2903,
"s": 2896,
"text": " Print"
},
{
"code": null,
"e": 2914,
"s": 2903,
"text": " Add Notes"
}
] |
Python Dictionary update() method - GeeksforGeeks
|
04 Oct, 2021
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Syntax: dict.update([other])
Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters.
Returns: It doesn’t return any value but updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs.
Python3
# Python program to show working# of update() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', }Dictionary2 = {'B': 'Geeks'} # Dictionary before Updationprint("Original Dictionary:")print(Dictionary1) # update the value of key 'B'Dictionary1.update(Dictionary2)print("Dictionary after updation:")print(Dictionary1)
Output:
Original Dictionary:
{'A': 'Geeks', 'B': 'For'}
Dictionary after updation:
{'A': 'Geeks', 'B': 'Geeks'}
Python3
# Python program to show working# of update() method in Dictionary # Dictionary with single itemDictionary1 = {'A': 'Geeks'} # Dictionary before Updationprint("Original Dictionary:")print(Dictionary1) # update the Dictionary with iterableDictionary1.update(B='For', C='Geeks')print("Dictionary after updation:")print(Dictionary1)
Output:
Original Dictionary:
{'A': 'Geeks'}
Dictionary after updation:
{'C': 'Geeks', 'B': 'For', 'A': 'Geeks'}
Python3
def checkKey(dict, key): if key in dict.keys(): print("Key exist, ", end =" ") dict.update({'m':600}) print("value updated =", 600) else: print("Not Exist")dict = {'m': 700, 'n':100, 't':500} key = 'm'checkKey(dict, key)print(dict)
Output:
Key exist, value updated = 600
{'m': 600, 'n': 100, 't': 500}
kumar_satyam
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 22677,
"s": 22649,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 22823,
"s": 22677,
"text": "Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs."
},
{
"code": null,
"e": 22852,
"s": 22823,
"text": "Syntax: dict.update([other])"
},
{
"code": null,
"e": 22977,
"s": 22852,
"text": "Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters."
},
{
"code": null,
"e": 23122,
"s": 22977,
"text": "Returns: It doesn’t return any value but updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs."
},
{
"code": null,
"e": 23130,
"s": 23122,
"text": "Python3"
},
{
"code": "# Python program to show working# of update() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', }Dictionary2 = {'B': 'Geeks'} # Dictionary before Updationprint(\"Original Dictionary:\")print(Dictionary1) # update the value of key 'B'Dictionary1.update(Dictionary2)print(\"Dictionary after updation:\")print(Dictionary1)",
"e": 23487,
"s": 23130,
"text": null
},
{
"code": null,
"e": 23496,
"s": 23487,
"text": "Output: "
},
{
"code": null,
"e": 23601,
"s": 23496,
"text": "Original Dictionary:\n{'A': 'Geeks', 'B': 'For'}\n\nDictionary after updation:\n{'A': 'Geeks', 'B': 'Geeks'}"
},
{
"code": null,
"e": 23609,
"s": 23601,
"text": "Python3"
},
{
"code": "# Python program to show working# of update() method in Dictionary # Dictionary with single itemDictionary1 = {'A': 'Geeks'} # Dictionary before Updationprint(\"Original Dictionary:\")print(Dictionary1) # update the Dictionary with iterableDictionary1.update(B='For', C='Geeks')print(\"Dictionary after updation:\")print(Dictionary1)",
"e": 23939,
"s": 23609,
"text": null
},
{
"code": null,
"e": 23948,
"s": 23939,
"text": "Output: "
},
{
"code": null,
"e": 24053,
"s": 23948,
"text": "Original Dictionary:\n{'A': 'Geeks'}\n\nDictionary after updation:\n{'C': 'Geeks', 'B': 'For', 'A': 'Geeks'}"
},
{
"code": null,
"e": 24061,
"s": 24053,
"text": "Python3"
},
{
"code": "def checkKey(dict, key): if key in dict.keys(): print(\"Key exist, \", end =\" \") dict.update({'m':600}) print(\"value updated =\", 600) else: print(\"Not Exist\")dict = {'m': 700, 'n':100, 't':500} key = 'm'checkKey(dict, key)print(dict)",
"e": 24336,
"s": 24061,
"text": null
},
{
"code": null,
"e": 24344,
"s": 24336,
"text": "Output:"
},
{
"code": null,
"e": 24407,
"s": 24344,
"text": "Key exist, value updated = 600\n{'m': 600, 'n': 100, 't': 500}"
},
{
"code": null,
"e": 24420,
"s": 24407,
"text": "kumar_satyam"
},
{
"code": null,
"e": 24432,
"s": 24420,
"text": "python-dict"
},
{
"code": null,
"e": 24454,
"s": 24432,
"text": "Python-dict-functions"
},
{
"code": null,
"e": 24461,
"s": 24454,
"text": "Python"
},
{
"code": null,
"e": 24473,
"s": 24461,
"text": "python-dict"
},
{
"code": null,
"e": 24571,
"s": 24473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24580,
"s": 24571,
"text": "Comments"
},
{
"code": null,
"e": 24593,
"s": 24580,
"text": "Old Comments"
},
{
"code": null,
"e": 24621,
"s": 24593,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 24671,
"s": 24621,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 24693,
"s": 24671,
"text": "Python map() function"
},
{
"code": null,
"e": 24737,
"s": 24693,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 24755,
"s": 24737,
"text": "Python Dictionary"
},
{
"code": null,
"e": 24778,
"s": 24755,
"text": "Taking input in Python"
},
{
"code": null,
"e": 24813,
"s": 24778,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 24835,
"s": 24813,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 24867,
"s": 24835,
"text": "How to Install PIP on Windows ?"
}
] |
List Methods in Python?
|
Python provides some very useful list methods that we can use to perform list operation very easily.
Below are the list of python built-in methods which we can use on list:
Adds an element at the end of the list
#Append
lst = ['Hello', 'Python']
print(lst)
lst.append('Tutorialspoint')
print(lst)
['Hello', 'Python']
['Hello', 'Python','Tutorialspoint']
Removes all the elements from the list
#clear
lst = ['Hello','Python','Tutorialspoint']
print(lst)
lst.clear()
print(lst)
['Hello', 'Python', 'Tutorialspoint']
[]
Returns a shallow copy of the list.
#COPY()
#Without copy
lst = ['Hello', 'Python', 'Tutorialspoint']
lst1 = lst
lst1.append('Java')
print(lst)
print(lst1)
#With copy
lst = ['Hello', 'Python', 'Tutorialspoint']
lst1 = lst.copy()
lst1.append("Java")
print(lst)
print(lst1)
['Hello', 'Python', 'Tutorialspoint', 'Java']
['Hello', 'Python', 'Tutorialspoint', 'Java']
['Hello', 'Python', 'Tutorialspoint']
['Hello', 'Python', 'Tutorialspoint', 'Java']
Returns the number of elements with the specified value.
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst.count("Python"))
print(lst.count("Tutorialspoint"))
print(lst.count(" "))
2
1
0
Add the elements of a list (or any iterable), to the end of the current list
#extend(iterables)
lst = ['Hello', 'Python']
print(lst)
lst.extend(['Java', 'CSharp'])
print(lst)
['Hello', 'Python']
['Hello', 'Python', 'Java', 'CSharp']
Returns the index of the first element with the specified value
#index()
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst.index('Python'))
print(lst.index("Python", 2))
1
3
Adds an element at the specified position
lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']
print(lst)
lst.insert(0, "CPlusPlus")
print(lst)
lst.insert(3, "Java")
print(lst)
['Hello', 'Python', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
Removes the element at the specified position
#pop()
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
#Without index
lst.pop()
print(lst)
#With Index
lst.pop(3)
print(lst)
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint']
['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint']
Removes the first item with the specified value
#Remove
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
lst.remove('Python')
print(lst)
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['CPlusPlus', 'Hello', 'Java', 'Tutorialspoint', 'Python']
Reverses the order of the list
#reverse()
lst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
print(lst)
lst.reverse()
['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']
['Python', 'Tutorialspoint', 'Java', 'Python', 'Hello', 'CPlusPlus']
Sorts the list
#sort()
lst = [2, 3, 7, 1, 13, 8, 49]
print(lst)
#default
lst.sort()
print(lst)
#reverse = True
lst.sort(reverse = True)
print(lst)
[2, 3, 7, 1, 13, 8, 49]
[1, 2, 3, 7, 8, 13, 49]
[49, 13, 8, 7, 3, 2, 1]
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "Python provides some very useful list methods that we can use to perform list operation very easily."
},
{
"code": null,
"e": 1235,
"s": 1163,
"text": "Below are the list of python built-in methods which we can use on list:"
},
{
"code": null,
"e": 1274,
"s": 1235,
"text": "Adds an element at the end of the list"
},
{
"code": null,
"e": 1359,
"s": 1274,
"text": "#Append\nlst = ['Hello', 'Python']\nprint(lst)\nlst.append('Tutorialspoint')\nprint(lst)"
},
{
"code": null,
"e": 1416,
"s": 1359,
"text": "['Hello', 'Python']\n['Hello', 'Python','Tutorialspoint']"
},
{
"code": null,
"e": 1455,
"s": 1416,
"text": "Removes all the elements from the list"
},
{
"code": null,
"e": 1538,
"s": 1455,
"text": "#clear\nlst = ['Hello','Python','Tutorialspoint']\nprint(lst)\nlst.clear()\nprint(lst)"
},
{
"code": null,
"e": 1579,
"s": 1538,
"text": "['Hello', 'Python', 'Tutorialspoint']\n[]"
},
{
"code": null,
"e": 1615,
"s": 1579,
"text": "Returns a shallow copy of the list."
},
{
"code": null,
"e": 1851,
"s": 1615,
"text": "#COPY()\n#Without copy\nlst = ['Hello', 'Python', 'Tutorialspoint']\nlst1 = lst\nlst1.append('Java')\nprint(lst)\nprint(lst1)\n#With copy\nlst = ['Hello', 'Python', 'Tutorialspoint']\nlst1 = lst.copy()\nlst1.append(\"Java\")\nprint(lst)\nprint(lst1)"
},
{
"code": null,
"e": 2027,
"s": 1851,
"text": "['Hello', 'Python', 'Tutorialspoint', 'Java']\n['Hello', 'Python', 'Tutorialspoint', 'Java']\n['Hello', 'Python', 'Tutorialspoint']\n['Hello', 'Python', 'Tutorialspoint', 'Java']"
},
{
"code": null,
"e": 2084,
"s": 2027,
"text": "Returns the number of elements with the specified value."
},
{
"code": null,
"e": 2222,
"s": 2084,
"text": "lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']\nprint(lst.count(\"Python\"))\nprint(lst.count(\"Tutorialspoint\"))\nprint(lst.count(\" \"))"
},
{
"code": null,
"e": 2228,
"s": 2222,
"text": "2\n1\n0"
},
{
"code": null,
"e": 2305,
"s": 2228,
"text": "Add the elements of a list (or any iterable), to the end of the current list"
},
{
"code": null,
"e": 2403,
"s": 2305,
"text": "#extend(iterables)\nlst = ['Hello', 'Python']\nprint(lst)\nlst.extend(['Java', 'CSharp'])\nprint(lst)"
},
{
"code": null,
"e": 2461,
"s": 2403,
"text": "['Hello', 'Python']\n['Hello', 'Python', 'Java', 'CSharp']"
},
{
"code": null,
"e": 2525,
"s": 2461,
"text": "Returns the index of the first element with the specified value"
},
{
"code": null,
"e": 2645,
"s": 2525,
"text": "#index()\nlst = ['Hello', 'Python', 'Tutorialspoint', 'Python']\nprint(lst.index('Python'))\nprint(lst.index(\"Python\", 2))"
},
{
"code": null,
"e": 2649,
"s": 2645,
"text": "1\n3"
},
{
"code": null,
"e": 2691,
"s": 2649,
"text": "Adds an element at the specified position"
},
{
"code": null,
"e": 2827,
"s": 2691,
"text": "lst = ['Hello', 'Python', 'Tutorialspoint', 'Python']\nprint(lst)\nlst.insert(0, \"CPlusPlus\")\nprint(lst)\nlst.insert(3, \"Java\")\nprint(lst)"
},
{
"code": null,
"e": 3005,
"s": 2827,
"text": "['Hello', 'Python', 'Tutorialspoint', 'Python']\n['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint', 'Python']\n['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']"
},
{
"code": null,
"e": 3051,
"s": 3005,
"text": "Removes the element at the specified position"
},
{
"code": null,
"e": 3214,
"s": 3051,
"text": "#pop()\nlst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\nprint(lst)\n#Without index\nlst.pop()\nprint(lst)\n#With Index\nlst.pop(3)\nprint(lst)"
},
{
"code": null,
"e": 3393,
"s": 3214,
"text": "['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\n['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint']\n['CPlusPlus', 'Hello', 'Python', 'Tutorialspoint']"
},
{
"code": null,
"e": 3441,
"s": 3393,
"text": "Removes the first item with the specified value"
},
{
"code": null,
"e": 3567,
"s": 3441,
"text": "#Remove\nlst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\nprint(lst)\nlst.remove('Python')\nprint(lst)"
},
{
"code": null,
"e": 3695,
"s": 3567,
"text": "['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\n['CPlusPlus', 'Hello', 'Java', 'Tutorialspoint', 'Python']"
},
{
"code": null,
"e": 3726,
"s": 3695,
"text": "Reverses the order of the list"
},
{
"code": null,
"e": 3837,
"s": 3726,
"text": "#reverse()\nlst = ['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\nprint(lst)\nlst.reverse()"
},
{
"code": null,
"e": 3975,
"s": 3837,
"text": "['CPlusPlus', 'Hello', 'Python', 'Java', 'Tutorialspoint', 'Python']\n['Python', 'Tutorialspoint', 'Java', 'Python', 'Hello', 'CPlusPlus']"
},
{
"code": null,
"e": 3990,
"s": 3975,
"text": "Sorts the list"
},
{
"code": null,
"e": 4122,
"s": 3990,
"text": "#sort()\nlst = [2, 3, 7, 1, 13, 8, 49]\nprint(lst)\n#default\nlst.sort()\nprint(lst)\n#reverse = True\nlst.sort(reverse = True)\nprint(lst)"
},
{
"code": null,
"e": 4194,
"s": 4122,
"text": "[2, 3, 7, 1, 13, 8, 49]\n[1, 2, 3, 7, 8, 13, 49]\n[49, 13, 8, 7, 3, 2, 1]"
}
] |
How to Get Saved Contacts in Android Application using Cursor?
|
14 Feb, 2021
Phone Contacts are very important source of data for everyone and hence accessing phone contacts is the main feature for many applications like Truecaller to help their users and provide them a better experience. We all have a default application in our mobile to manage contacts but what happens if we will create our own application that will read all the saved contacts and will show them to the user. We can use that application for backup of our contacts. So, in this article, we are going to learn how to develop an application that will read contacts.
Note: A Cursor is a class that contains the result set for a particular query that was made against a database in Android. This class has an API that provides a facility to read the columns which were returned from the query, as well as helps to iterate over the rows of the result set.
We will be building a simple application in which we will be displaying a Button and when we will click on that button, and it will add all saved contacts (their names and numbers) into ListView of our application. Note that we have to give permission to our application to read our phone contacts. We will use Java language for developing this project.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add Permission
Now, navigate to the app> manifests> AndroidManifest.xml file and add below permission there to read contacts.
<uses-permission android:name=”android.permission.READ_CONTACTS”></uses-permission>
Step 3: Working with the activity_main.xml file
Now it’s time to design the layout of the application. So, navigate to app > res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relative_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Button to perform clicking event to access contacts list inside listView--> <Button android:id="@+id/Button" android:layout_width="150dp" android:layout_height="52dp" android:layout_centerHorizontal="true" android:layout_margin="12dp" android:background="#0F9D58" android:text="Click Here" android:textColor="#FFFFFF" /> <!--ListView to show all saved contacts--> <ListView android:id="@+id/ListView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/Button" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Navigate to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.database.Cursor;import android.os.Bundle;import android.provider.ContactsContract;import android.view.View;import android.widget.Button;import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity;import androidx.cursoradapter.widget.SimpleCursorAdapter; public class MainActivity extends AppCompatActivity { Cursor cursor; ListView listView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // declaring listView using findViewById() listView = findViewById(R.id.ListView); // declaring button using findViewById() button = findViewById(R.id.Button); // set OnClickListener() to the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling of getContacts() getContacts(); } }); } public void getContacts() { // create cursor and query the data cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); startManagingCursor(cursor); // data is a array of String type which is // used to store Number ,Names and id. String[] data = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID}; int[] to = {android.R.id.text1, android.R.id.text2}; // creation of adapter using SimpleCursorAdapter class SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, data, to); // Calling setAdaptor() method to set created adapter listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); }}
Congratulation, now our application is ready so click on the run button. Here is the output video of the application.
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Feb, 2021"
},
{
"code": null,
"e": 613,
"s": 54,
"text": "Phone Contacts are very important source of data for everyone and hence accessing phone contacts is the main feature for many applications like Truecaller to help their users and provide them a better experience. We all have a default application in our mobile to manage contacts but what happens if we will create our own application that will read all the saved contacts and will show them to the user. We can use that application for backup of our contacts. So, in this article, we are going to learn how to develop an application that will read contacts."
},
{
"code": null,
"e": 900,
"s": 613,
"text": "Note: A Cursor is a class that contains the result set for a particular query that was made against a database in Android. This class has an API that provides a facility to read the columns which were returned from the query, as well as helps to iterate over the rows of the result set."
},
{
"code": null,
"e": 1254,
"s": 900,
"text": "We will be building a simple application in which we will be displaying a Button and when we will click on that button, and it will add all saved contacts (their names and numbers) into ListView of our application. Note that we have to give permission to our application to read our phone contacts. We will use Java language for developing this project."
},
{
"code": null,
"e": 1283,
"s": 1254,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1445,
"s": 1283,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1469,
"s": 1445,
"text": "Step 2: Add Permission "
},
{
"code": null,
"e": 1580,
"s": 1469,
"text": "Now, navigate to the app> manifests> AndroidManifest.xml file and add below permission there to read contacts."
},
{
"code": null,
"e": 1664,
"s": 1580,
"text": "<uses-permission android:name=”android.permission.READ_CONTACTS”></uses-permission>"
},
{
"code": null,
"e": 1712,
"s": 1664,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1887,
"s": 1712,
"text": "Now it’s time to design the layout of the application. So, navigate to app > res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file. "
},
{
"code": null,
"e": 1891,
"s": 1887,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/relative_layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Button to perform clicking event to access contacts list inside listView--> <Button android:id=\"@+id/Button\" android:layout_width=\"150dp\" android:layout_height=\"52dp\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"12dp\" android:background=\"#0F9D58\" android:text=\"Click Here\" android:textColor=\"#FFFFFF\" /> <!--ListView to show all saved contacts--> <ListView android:id=\"@+id/ListView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_below=\"@+id/Button\" /> </RelativeLayout>",
"e": 2851,
"s": 1891,
"text": null
},
{
"code": null,
"e": 2899,
"s": 2851,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 3123,
"s": 2899,
"text": "Navigate to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3128,
"s": 3123,
"text": "Java"
},
{
"code": "import android.database.Cursor;import android.os.Bundle;import android.provider.ContactsContract;import android.view.View;import android.widget.Button;import android.widget.ListView; import androidx.appcompat.app.AppCompatActivity;import androidx.cursoradapter.widget.SimpleCursorAdapter; public class MainActivity extends AppCompatActivity { Cursor cursor; ListView listView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // declaring listView using findViewById() listView = findViewById(R.id.ListView); // declaring button using findViewById() button = findViewById(R.id.Button); // set OnClickListener() to the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling of getContacts() getContacts(); } }); } public void getContacts() { // create cursor and query the data cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); startManagingCursor(cursor); // data is a array of String type which is // used to store Number ,Names and id. String[] data = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID}; int[] to = {android.R.id.text1, android.R.id.text2}; // creation of adapter using SimpleCursorAdapter class SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, data, to); // Calling setAdaptor() method to set created adapter listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); }}",
"e": 5074,
"s": 3128,
"text": null
},
{
"code": null,
"e": 5192,
"s": 5074,
"text": "Congratulation, now our application is ready so click on the run button. Here is the output video of the application."
},
{
"code": null,
"e": 5200,
"s": 5192,
"text": "android"
},
{
"code": null,
"e": 5208,
"s": 5200,
"text": "Android"
},
{
"code": null,
"e": 5213,
"s": 5208,
"text": "Java"
},
{
"code": null,
"e": 5218,
"s": 5213,
"text": "Java"
},
{
"code": null,
"e": 5226,
"s": 5218,
"text": "Android"
},
{
"code": null,
"e": 5324,
"s": 5226,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5356,
"s": 5324,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5395,
"s": 5356,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5464,
"s": 5395,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5506,
"s": 5464,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5557,
"s": 5506,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 5572,
"s": 5557,
"text": "Arrays in Java"
},
{
"code": null,
"e": 5616,
"s": 5572,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 5652,
"s": 5616,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5703,
"s": 5652,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Global and Local Variables in Python
|
22 Jun, 2022
Global variables are those which are not defined inside any function and have a global scope whereas local variables are those which are defined inside a function and its scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas the global variables are accessible throughout the program and inside every function. Local variables are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable.
Example: Creating local variables
Python3
def f(): # local variable s = "I love Geeksforgeeks" print(s) # Driver codef()
I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s see what will happen.
Example:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Python3
def f(): # local variable s = "I love Geeksforgeeks" print("Inside Function:", s) # Driver codef()print(s)
Output:
NameError: name 's' is not defined
These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a global variable.
Example: Defining and accessing global variables
Python3
# This function uses global variable sdef f(): print("Inside Function", s) # Global scopes = "I love Geeksforgeeks"f()print("Outside Function", s)
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
The variable s is defined as the global variable and is used both inside the function as well as outside the function.
Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name.
Now, what if there is a variable with the same name initialized inside a function as well as globally. Now the question arises, will the local variable will have some effect on the global variable or vice versa, and what will happen if we change the value of a variable inside of the function f()? Will it affect the globals as well? We test it in the following piece of code:
Python3
# This function has a variable with# name same as s. def f(): s = "Me too." print(s) # Global scopes = "I love Geeksforgeeks"f()print(s)
Me too.
I love Geeksforgeeks
If a variable with the same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value.
The question is, what if we try to change the value of a global variable inside the function. Let’s see it using the below example.
Example:
Python3
# This function uses global variable sdef f(): s += 'GFG' print("Inside Function", s) # Global scopes = "I love Geeksforgeeks"f()
Output:
UnboundLocalError: local variable 's' referenced before assignment
To make the above program work, we need to use the “global” keyword. Let’s see what this global keyword is.
We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for printing and accessing. Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first statement throws the error message. Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example:
Example 1: Using global keyword
Python3
# This function modifies the global variable 's'def f(): global s s += ' GFG' print(s) s = "Look for Geeksforgeeks Python Section" print(s) # Global Scopes = "Python is great!"f()print(s)
Python is great! GFG
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section
Now there is no ambiguity.
Example 2: Using global and local variables
Python3
a = 1 # Uses global because there is no local 'a'def f(): print('Inside f() : ', a) # Variable 'a' is redefined as a localdef g(): a = 2 print('Inside g() : ', a) # Uses global keyword to modify global 'a'def h(): global a a = 3 print('Inside h() : ', a) # Global scopeprint('global : ', a)f()print('global : ', a)g()print('global : ', a)h()print('global : ', a)
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3
https://youtu.be/SH_PDn1FG9I
This article is contributed by Shwetanshu Rohatgi. 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 if you want to share more information about the topic discussed above.
chalapathy
SurajSahoo
vaibhavsinghtanwar
nikhilaggarwal3
surinderdawra388
kushagrathegame1
sheetal18june
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Reverse a string in Java
Arrays in C/C++
Interfaces in Java
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 679,
"s": 52,
"text": "Global variables are those which are not defined inside any function and have a global scope whereas local variables are those which are defined inside a function and its scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas the global variables are accessible throughout the program and inside every function. Local variables are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable."
},
{
"code": null,
"e": 713,
"s": 679,
"text": "Example: Creating local variables"
},
{
"code": null,
"e": 721,
"s": 713,
"text": "Python3"
},
{
"code": "def f(): # local variable s = \"I love Geeksforgeeks\" print(s) # Driver codef()",
"e": 811,
"s": 721,
"text": null
},
{
"code": null,
"e": 832,
"s": 811,
"text": "I love Geeksforgeeks"
},
{
"code": null,
"e": 928,
"s": 832,
"text": "If we will try to use this local variable outside the function then let’s see what will happen."
},
{
"code": null,
"e": 937,
"s": 928,
"text": "Example:"
},
{
"code": null,
"e": 946,
"s": 937,
"text": "Chapters"
},
{
"code": null,
"e": 973,
"s": 946,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1023,
"s": 973,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1046,
"s": 1023,
"text": "captions off, selected"
},
{
"code": null,
"e": 1054,
"s": 1046,
"text": "English"
},
{
"code": null,
"e": 1078,
"s": 1054,
"text": "This is a modal window."
},
{
"code": null,
"e": 1147,
"s": 1078,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1169,
"s": 1147,
"text": "End of dialog window."
},
{
"code": null,
"e": 1177,
"s": 1169,
"text": "Python3"
},
{
"code": "def f(): # local variable s = \"I love Geeksforgeeks\" print(\"Inside Function:\", s) # Driver codef()print(s)",
"e": 1298,
"s": 1177,
"text": null
},
{
"code": null,
"e": 1306,
"s": 1298,
"text": "Output:"
},
{
"code": null,
"e": 1341,
"s": 1306,
"text": "NameError: name 's' is not defined"
},
{
"code": null,
"e": 1532,
"s": 1341,
"text": "These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a global variable."
},
{
"code": null,
"e": 1581,
"s": 1532,
"text": "Example: Defining and accessing global variables"
},
{
"code": null,
"e": 1589,
"s": 1581,
"text": "Python3"
},
{
"code": "# This function uses global variable sdef f(): print(\"Inside Function\", s) # Global scopes = \"I love Geeksforgeeks\"f()print(\"Outside Function\", s)",
"e": 1739,
"s": 1589,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1739,
"text": "Inside Function I love Geeksforgeeks\nOutside Function I love Geeksforgeeks"
},
{
"code": null,
"e": 1933,
"s": 1814,
"text": "The variable s is defined as the global variable and is used both inside the function as well as outside the function."
},
{
"code": null,
"e": 2080,
"s": 1933,
"text": "Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name."
},
{
"code": null,
"e": 2458,
"s": 2080,
"text": "Now, what if there is a variable with the same name initialized inside a function as well as globally. Now the question arises, will the local variable will have some effect on the global variable or vice versa, and what will happen if we change the value of a variable inside of the function f()? Will it affect the globals as well? We test it in the following piece of code: "
},
{
"code": null,
"e": 2466,
"s": 2458,
"text": "Python3"
},
{
"code": "# This function has a variable with# name same as s. def f(): s = \"Me too.\" print(s) # Global scopes = \"I love Geeksforgeeks\"f()print(s)",
"e": 2611,
"s": 2466,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2611,
"text": "Me too.\nI love Geeksforgeeks"
},
{
"code": null,
"e": 2808,
"s": 2640,
"text": "If a variable with the same name is defined inside the scope of function as well then it will print the value given inside the function only and not the global value. "
},
{
"code": null,
"e": 2940,
"s": 2808,
"text": "The question is, what if we try to change the value of a global variable inside the function. Let’s see it using the below example."
},
{
"code": null,
"e": 2950,
"s": 2940,
"text": "Example: "
},
{
"code": null,
"e": 2958,
"s": 2950,
"text": "Python3"
},
{
"code": "# This function uses global variable sdef f(): s += 'GFG' print(\"Inside Function\", s) # Global scopes = \"I love Geeksforgeeks\"f()",
"e": 3095,
"s": 2958,
"text": null
},
{
"code": null,
"e": 3103,
"s": 3095,
"text": "Output:"
},
{
"code": null,
"e": 3170,
"s": 3103,
"text": "UnboundLocalError: local variable 's' referenced before assignment"
},
{
"code": null,
"e": 3278,
"s": 3170,
"text": "To make the above program work, we need to use the “global” keyword. Let’s see what this global keyword is."
},
{
"code": null,
"e": 3834,
"s": 3278,
"text": "We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for printing and accessing. Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first statement throws the error message. Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global”, as can be seen in the following example: "
},
{
"code": null,
"e": 3866,
"s": 3834,
"text": "Example 1: Using global keyword"
},
{
"code": null,
"e": 3874,
"s": 3866,
"text": "Python3"
},
{
"code": "# This function modifies the global variable 's'def f(): global s s += ' GFG' print(s) s = \"Look for Geeksforgeeks Python Section\" print(s) # Global Scopes = \"Python is great!\"f()print(s)",
"e": 4077,
"s": 3874,
"text": null
},
{
"code": null,
"e": 4174,
"s": 4077,
"text": "Python is great! GFG\nLook for Geeksforgeeks Python Section\nLook for Geeksforgeeks Python Section"
},
{
"code": null,
"e": 4202,
"s": 4174,
"text": "Now there is no ambiguity. "
},
{
"code": null,
"e": 4246,
"s": 4202,
"text": "Example 2: Using global and local variables"
},
{
"code": null,
"e": 4254,
"s": 4246,
"text": "Python3"
},
{
"code": "a = 1 # Uses global because there is no local 'a'def f(): print('Inside f() : ', a) # Variable 'a' is redefined as a localdef g(): a = 2 print('Inside g() : ', a) # Uses global keyword to modify global 'a'def h(): global a a = 3 print('Inside h() : ', a) # Global scopeprint('global : ', a)f()print('global : ', a)g()print('global : ', a)h()print('global : ', a)",
"e": 4636,
"s": 4254,
"text": null
},
{
"code": null,
"e": 4732,
"s": 4636,
"text": "global : 1\nInside f() : 1\nglobal : 1\nInside g() : 2\nglobal : 1\nInside h() : 3\nglobal : 3"
},
{
"code": null,
"e": 4761,
"s": 4732,
"text": "https://youtu.be/SH_PDn1FG9I"
},
{
"code": null,
"e": 5190,
"s": 4761,
"text": "This article is contributed by Shwetanshu Rohatgi. 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 if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5201,
"s": 5190,
"text": "chalapathy"
},
{
"code": null,
"e": 5212,
"s": 5201,
"text": "SurajSahoo"
},
{
"code": null,
"e": 5231,
"s": 5212,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 5247,
"s": 5231,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 5264,
"s": 5247,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5281,
"s": 5264,
"text": "kushagrathegame1"
},
{
"code": null,
"e": 5295,
"s": 5281,
"text": "sheetal18june"
},
{
"code": null,
"e": 5302,
"s": 5295,
"text": "Python"
},
{
"code": null,
"e": 5321,
"s": 5302,
"text": "School Programming"
},
{
"code": null,
"e": 5419,
"s": 5321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5447,
"s": 5419,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5497,
"s": 5447,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5519,
"s": 5497,
"text": "Python map() function"
},
{
"code": null,
"e": 5563,
"s": 5519,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 5605,
"s": 5563,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5630,
"s": 5605,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5646,
"s": 5630,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5665,
"s": 5646,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5684,
"s": 5665,
"text": "Inheritance in C++"
}
] |
Protected Keyword in Java with Examples
|
01 May, 2022
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows:
The protected keyword in Java refers to one of its access modifiers. The methods or data members declared as protected can be accessed from
Within the same class.
Subclasses of the same packages.
Different classes of the same packages.
Subclasses of different packages.
There are some certain important points to be remembered as follows:
If one wishes to access a protected modifier outside a package, then inheritance is needed to be applied.Protecting a constructor prevents the users from creating the instance of the class, outside the package.During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only.Outer class and interface cannot be protected.
If one wishes to access a protected modifier outside a package, then inheritance is needed to be applied.
Protecting a constructor prevents the users from creating the instance of the class, outside the package.
During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only.
Outer class and interface cannot be protected.
Implementation: Here we will be creating two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method displayed in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B.
Example 1: Package p1
Java
// Java program to illustrate // protected modifier package p1; // Class A public class A { protected void display() { System.out.println("GeeksforGeeks"); } }
Package p2
Java
// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}
Output:
GeeksforGeeks
Now let us try to analyze different conditions of access:
Calling protected function without extending the parent classAccessing a protected classAccessing display function from the same package but different Accessing display function from a different packageAccessing a protected class by overriding to sub-class within the same package
Calling protected function without extending the parent class
Accessing a protected class
Accessing display function from the same package but different
Accessing display function from a different package
Accessing a protected class by overriding to sub-class within the same package
Here we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method displayed in class A is protected. But the code will not be able to access the function “display” since the child class has not inherited its value from the main class and will throw an exception as shown.
Example 1-A: Package p1
Java
// Java program to illustrate Protected Modifier package p1; // Class Apublic class A { // Method protected void display() { // Print statement System.out.println("GeeksforGeeks"); }}
Example 1-B: Package p2
Java
// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B { public static void main(String args[]) { B obj = new B(); obj.display(); }}
Output:
Exception in thread "main"
java.lang.RuntimeException:
Uncompilable source code -
Erroneous sym type: p2.B.display
at p2.B.main(B.java:16)
Here we are trying to access a protected class A resulting in an error.
Example A:
Java
// Java program to illustrate// protected modifier package p1; // Class Aprotected class A { void display() { System.out.println("GeeksforGeeks"); }}
Example B: Package p2
Java
// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}
Output: This will throw an error
Exception in thread "main"
java.lang.RuntimeException:
Uncompilable source code -
Erroneous sym type: p2.B.display
at p2.B.main(B.java:16)
Implementation: In this example, we have access to access a protected function “display” from the same package but a different class
Example A: Package p1
Java
// Java program to illustrate// protected modifier package p1; // Class Apublic class A { protected void display() { System.out.println("GeeksforGeeks"); }}
Example B: class C
Java
// Java program to illustrate// protected modifier // Class C is a subclass of Apublic class C { public static void main(String args[]) { A obj = new A(); obj.display(); }}
Output:
GeeksforGeeks
Here we have tried to access the protected function display from a different package by inheritance and extending the class.
Example A: Package p1
Java
// Java program to illustrate// protected modifier package p1; // Class Apublic class A { protected void display() { System.out.println("GeeksforGeeks"); }}
Example B: Package p2
Java
// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}
Output:
GeeksforGeeks
Here we have designed two classes A and C, where class C is the overridden one.
Example A: class A
Java
// Java program to illustrate// protected modifierpackage p1; // Class Apublic class A { protected void display() { System.out.println("Class A"); }}
Example B: class C
Java
// Java program to illustrate// protected modifier public class C extends A { // overridden function protected void display() { System.out.println("Class C"); } public static void main(String args[]) { C obj1 = new C(); obj1.display(); }}
Output:
Class C
solankimayank
access modifiers
Java-keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 May, 2022"
},
{
"code": null,
"e": 309,
"s": 52,
"text": "Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows: "
},
{
"code": null,
"e": 449,
"s": 309,
"text": "The protected keyword in Java refers to one of its access modifiers. The methods or data members declared as protected can be accessed from"
},
{
"code": null,
"e": 472,
"s": 449,
"text": "Within the same class."
},
{
"code": null,
"e": 505,
"s": 472,
"text": "Subclasses of the same packages."
},
{
"code": null,
"e": 545,
"s": 505,
"text": "Different classes of the same packages."
},
{
"code": null,
"e": 579,
"s": 545,
"text": "Subclasses of different packages."
},
{
"code": null,
"e": 649,
"s": 579,
"text": "There are some certain important points to be remembered as follows: "
},
{
"code": null,
"e": 1053,
"s": 649,
"text": "If one wishes to access a protected modifier outside a package, then inheritance is needed to be applied.Protecting a constructor prevents the users from creating the instance of the class, outside the package.During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only.Outer class and interface cannot be protected."
},
{
"code": null,
"e": 1159,
"s": 1053,
"text": "If one wishes to access a protected modifier outside a package, then inheritance is needed to be applied."
},
{
"code": null,
"e": 1265,
"s": 1159,
"text": "Protecting a constructor prevents the users from creating the instance of the class, outside the package."
},
{
"code": null,
"e": 1413,
"s": 1265,
"text": "During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only."
},
{
"code": null,
"e": 1460,
"s": 1413,
"text": "Outer class and interface cannot be protected."
},
{
"code": null,
"e": 1735,
"s": 1460,
"text": "Implementation: Here we will be creating two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method displayed in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B."
},
{
"code": null,
"e": 1758,
"s": 1735,
"text": "Example 1: Package p1 "
},
{
"code": null,
"e": 1763,
"s": 1758,
"text": "Java"
},
{
"code": "// Java program to illustrate // protected modifier package p1; // Class A public class A { protected void display() { System.out.println(\"GeeksforGeeks\"); } }",
"e": 1947,
"s": 1763,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1947,
"text": " Package p2 "
},
{
"code": null,
"e": 1965,
"s": 1960,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}",
"e": 2227,
"s": 1965,
"text": null
},
{
"code": null,
"e": 2236,
"s": 2227,
"text": "Output: "
},
{
"code": null,
"e": 2250,
"s": 2236,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 2309,
"s": 2250,
"text": "Now let us try to analyze different conditions of access: "
},
{
"code": null,
"e": 2590,
"s": 2309,
"text": "Calling protected function without extending the parent classAccessing a protected classAccessing display function from the same package but different Accessing display function from a different packageAccessing a protected class by overriding to sub-class within the same package"
},
{
"code": null,
"e": 2652,
"s": 2590,
"text": "Calling protected function without extending the parent class"
},
{
"code": null,
"e": 2680,
"s": 2652,
"text": "Accessing a protected class"
},
{
"code": null,
"e": 2744,
"s": 2680,
"text": "Accessing display function from the same package but different "
},
{
"code": null,
"e": 2796,
"s": 2744,
"text": "Accessing display function from a different package"
},
{
"code": null,
"e": 2875,
"s": 2796,
"text": "Accessing a protected class by overriding to sub-class within the same package"
},
{
"code": null,
"e": 3187,
"s": 2875,
"text": "Here we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method displayed in class A is protected. But the code will not be able to access the function “display” since the child class has not inherited its value from the main class and will throw an exception as shown. "
},
{
"code": null,
"e": 3212,
"s": 3187,
"text": "Example 1-A: Package p1 "
},
{
"code": null,
"e": 3217,
"s": 3212,
"text": "Java"
},
{
"code": "// Java program to illustrate Protected Modifier package p1; // Class Apublic class A { // Method protected void display() { // Print statement System.out.println(\"GeeksforGeeks\"); }}",
"e": 3431,
"s": 3217,
"text": null
},
{
"code": null,
"e": 3456,
"s": 3431,
"text": "Example 1-B: Package p2 "
},
{
"code": null,
"e": 3461,
"s": 3456,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B { public static void main(String args[]) { B obj = new B(); obj.display(); }}",
"e": 3713,
"s": 3461,
"text": null
},
{
"code": null,
"e": 3722,
"s": 3713,
"text": "Output: "
},
{
"code": null,
"e": 3868,
"s": 3722,
"text": "Exception in thread \"main\" \njava.lang.RuntimeException: \nUncompilable source code - \nErroneous sym type: p2.B.display\n at p2.B.main(B.java:16)"
},
{
"code": null,
"e": 3941,
"s": 3868,
"text": "Here we are trying to access a protected class A resulting in an error. "
},
{
"code": null,
"e": 3952,
"s": 3941,
"text": "Example A:"
},
{
"code": null,
"e": 3957,
"s": 3952,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p1; // Class Aprotected class A { void display() { System.out.println(\"GeeksforGeeks\"); }}",
"e": 4125,
"s": 3957,
"text": null
},
{
"code": null,
"e": 4148,
"s": 4125,
"text": "Example B: Package p2 "
},
{
"code": null,
"e": 4153,
"s": 4148,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}",
"e": 4415,
"s": 4153,
"text": null
},
{
"code": null,
"e": 4448,
"s": 4415,
"text": "Output: This will throw an error"
},
{
"code": null,
"e": 4594,
"s": 4448,
"text": "Exception in thread \"main\" \njava.lang.RuntimeException: \nUncompilable source code - \nErroneous sym type: p2.B.display\n at p2.B.main(B.java:16)"
},
{
"code": null,
"e": 4728,
"s": 4594,
"text": "Implementation: In this example, we have access to access a protected function “display” from the same package but a different class "
},
{
"code": null,
"e": 4751,
"s": 4728,
"text": "Example A: Package p1 "
},
{
"code": null,
"e": 4756,
"s": 4751,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p1; // Class Apublic class A { protected void display() { System.out.println(\"GeeksforGeeks\"); }}",
"e": 4931,
"s": 4756,
"text": null
},
{
"code": null,
"e": 4951,
"s": 4931,
"text": "Example B: class C "
},
{
"code": null,
"e": 4956,
"s": 4951,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier // Class C is a subclass of Apublic class C { public static void main(String args[]) { A obj = new A(); obj.display(); }}",
"e": 5153,
"s": 4956,
"text": null
},
{
"code": null,
"e": 5162,
"s": 5153,
"text": "Output: "
},
{
"code": null,
"e": 5176,
"s": 5162,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 5302,
"s": 5176,
"text": "Here we have tried to access the protected function display from a different package by inheritance and extending the class. "
},
{
"code": null,
"e": 5325,
"s": 5302,
"text": "Example A: Package p1 "
},
{
"code": null,
"e": 5330,
"s": 5325,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p1; // Class Apublic class A { protected void display() { System.out.println(\"GeeksforGeeks\"); }}",
"e": 5505,
"s": 5330,
"text": null
},
{
"code": null,
"e": 5528,
"s": 5505,
"text": "Example B: Package p2 "
},
{
"code": null,
"e": 5533,
"s": 5528,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier package p2; // import all classes in package p1import p1.*; // Class B is a subclass of Aclass B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); }}",
"e": 5795,
"s": 5533,
"text": null
},
{
"code": null,
"e": 5804,
"s": 5795,
"text": "Output: "
},
{
"code": null,
"e": 5818,
"s": 5804,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 5899,
"s": 5818,
"text": "Here we have designed two classes A and C, where class C is the overridden one. "
},
{
"code": null,
"e": 5919,
"s": 5899,
"text": "Example A: class A "
},
{
"code": null,
"e": 5924,
"s": 5919,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifierpackage p1; // Class Apublic class A { protected void display() { System.out.println(\"Class A\"); }}",
"e": 6091,
"s": 5924,
"text": null
},
{
"code": null,
"e": 6111,
"s": 6091,
"text": "Example B: class C "
},
{
"code": null,
"e": 6116,
"s": 6111,
"text": "Java"
},
{
"code": "// Java program to illustrate// protected modifier public class C extends A { // overridden function protected void display() { System.out.println(\"Class C\"); } public static void main(String args[]) { C obj1 = new C(); obj1.display(); }}",
"e": 6400,
"s": 6116,
"text": null
},
{
"code": null,
"e": 6409,
"s": 6400,
"text": "Output: "
},
{
"code": null,
"e": 6417,
"s": 6409,
"text": "Class C"
},
{
"code": null,
"e": 6431,
"s": 6417,
"text": "solankimayank"
},
{
"code": null,
"e": 6448,
"s": 6431,
"text": "access modifiers"
},
{
"code": null,
"e": 6461,
"s": 6448,
"text": "Java-keyword"
},
{
"code": null,
"e": 6466,
"s": 6461,
"text": "Java"
},
{
"code": null,
"e": 6471,
"s": 6466,
"text": "Java"
},
{
"code": null,
"e": 6569,
"s": 6471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6588,
"s": 6569,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6603,
"s": 6588,
"text": "Stream In Java"
},
{
"code": null,
"e": 6621,
"s": 6603,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6641,
"s": 6621,
"text": "Collections in Java"
},
{
"code": null,
"e": 6665,
"s": 6641,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6697,
"s": 6665,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6709,
"s": 6697,
"text": "Set in Java"
},
{
"code": null,
"e": 6729,
"s": 6709,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 6757,
"s": 6729,
"text": "Initializing a List in Java"
}
] |
SQLite - DETACH Database
|
SQLite DETACH DATABASE statement is used to detach and dissociate a named database from a database connection which was previously attached using ATTACH statement. If the same database file has been attached with multiple aliases, then DETACH command will disconnect only the given name and rest of the attachment will still continue. You cannot detach the main or temp databases.
If the database is an in-memory or temporary database, the database will be destroyed and the contents will be lost.
Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement.
DETACH DATABASE 'Alias-Name';
Here, 'Alias-Name' is the same alias, which you had used while attaching the database using ATTACH statement.
Consider you have a database, which you created in the previous chapter and attached it with 'test' and 'currentDB' as we can see using .database command.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
3 currentDB /home/sqlite/testDB.db
Let's try to detach 'currentDB' from testDB.db using the following command.
sqlite> DETACH DATABASE 'currentDB';
Now, if you will check the current attachment, you will find that testDB.db is still connected with 'test' and 'main'.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
|
[
{
"code": null,
"e": 3153,
"s": 2772,
"text": "SQLite DETACH DATABASE statement is used to detach and dissociate a named database from a database connection which was previously attached using ATTACH statement. If the same database file has been attached with multiple aliases, then DETACH command will disconnect only the given name and rest of the attachment will still continue. You cannot detach the main or temp databases."
},
{
"code": null,
"e": 3270,
"s": 3153,
"text": "If the database is an in-memory or temporary database, the database will be destroyed and the contents will be lost."
},
{
"code": null,
"e": 3350,
"s": 3270,
"text": "Following is the basic syntax of SQLite DETACH DATABASE 'Alias-Name' statement."
},
{
"code": null,
"e": 3381,
"s": 3350,
"text": "DETACH DATABASE 'Alias-Name';\n"
},
{
"code": null,
"e": 3491,
"s": 3381,
"text": "Here, 'Alias-Name' is the same alias, which you had used while attaching the database using ATTACH statement."
},
{
"code": null,
"e": 3646,
"s": 3491,
"text": "Consider you have a database, which you created in the previous chapter and attached it with 'test' and 'currentDB' as we can see using .database command."
},
{
"code": null,
"e": 3871,
"s": 3646,
"text": "sqlite>.databases\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n2 test /home/sqlite/testDB.db\n3 currentDB /home/sqlite/testDB.db"
},
{
"code": null,
"e": 3948,
"s": 3871,
"text": "Let's try to detach 'currentDB' from testDB.db using the following command."
},
{
"code": null,
"e": 3985,
"s": 3948,
"text": "sqlite> DETACH DATABASE 'currentDB';"
},
{
"code": null,
"e": 4104,
"s": 3985,
"text": "Now, if you will check the current attachment, you will find that testDB.db is still connected with 'test' and 'main'."
}
] |
Multilevel Cache Organisation
|
02 Aug, 2021
Cache is a random access memory used by the CPU to reduce the average time taken to access memory. Multilevel Caches is one of the techniques to improve Cache Performance by reducing the “MISS PENALTY”. Miss Penalty refers to the extra time required to bring the data into cache from the Main memory whenever there is a “miss” in the cache. For clear understanding let us consider an example where the CPU requires 10 Memory References for accessing the desired information and consider this scenario in the following 3 cases of System design :
Case 1 : System Design without Cache Memory
Here the CPU directly communicates with the main memory and no caches are involved. In this case, the CPU needs to access the main memory 10 times to access the desired information.
Case 2 : System Design with Cache Memory
Here the CPU at first checks whether the desired data is present in the Cache Memory or not i.e. whether there is a “hit” in cache or “miss” in the cache. Suppose there is 3 miss in Cache Memory then the Main Memory will be accessed only 3 times. We can see that here the miss penalty is reduced because the Main Memory is accessed a lesser number of times than that in the previous case.
Case 3 : System Design with Multilevel Cache Memory
Here the Cache performance is optimized further by introducing multilevel Caches. As shown in the above figure, we are considering 2 level Cache Design. Suppose there is 3 miss in the L1 Cache Memory and out of these 3 misses there is 2 miss in the L2 Cache Memory then the Main Memory will be accessed only 2 times. It is clear that here the Miss Penalty is reduced considerably than that in the previous case thereby improving the Performance of Cache Memory.
NOTE : We can observe from the above 3 cases that we are trying to decrease the number of Main Memory References and thus decreasing the Miss Penalty in order to improve the overall System Performance. Also, it is important to note that in the Multilevel Cache Design, L1 Cache is attached to the CPU and it is small in size but fast. Although, L2 Cache is attached to the Primary Cache i.e. L1 Cache and it is larger in size and slower but still faster than the Main Memory.
Effective Access Time = Hit rate * Cache access time
+ Miss rate * Lower level access time
Average access Time For Multilevel Cache:(Tavg)
Tavg = H1 * C1 + (1 – H1) * (H2 * C2 +(1 – H2) *M )
where H1 is the Hit rate in the L1 caches. H2 is the Hit rate in the L2 cache. C1 is the Time to access information in the L1 caches. C2 is the Miss penalty to transfer information from the L2 cache to an L1 cache. M is the Miss penalty to transfer information from the main memory to the L2 cache.
Example: Find the Average memory access time for a processor with a 2 ns clock cycle time, a miss rate of 0.04 misses per instruction, a missed penalty of 25 clock cycles, and a cache access time (including hit detection) of 1 clock cycle. Also, assume that the read and write miss penalties are the same and ignore other write stalls.
Solution:
Average Memory access time(AMAT)= Hit Time + Miss Rate * Miss Penalty.
Hit Time = 1 clock cycle (Hit time = Hit rate * access time) but here Hit time is directly given so,
Miss rate = 0.04
Miss Penalty= 25 clock cycle (this is the time taken by the above level of memory after the hit)
so, AMAT= 1 + 0.04 * 25 AMAT= 2 clock cycle
according to question 1 clock cycle = 2 ns
AMAT = 4ns
VaibhavRai3
Pushpender007
Computer Organization & Architecture
GATE CS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Aug, 2021"
},
{
"code": null,
"e": 600,
"s": 54,
"text": "Cache is a random access memory used by the CPU to reduce the average time taken to access memory. Multilevel Caches is one of the techniques to improve Cache Performance by reducing the “MISS PENALTY”. Miss Penalty refers to the extra time required to bring the data into cache from the Main memory whenever there is a “miss” in the cache. For clear understanding let us consider an example where the CPU requires 10 Memory References for accessing the desired information and consider this scenario in the following 3 cases of System design : "
},
{
"code": null,
"e": 645,
"s": 600,
"text": "Case 1 : System Design without Cache Memory "
},
{
"code": null,
"e": 830,
"s": 647,
"text": "Here the CPU directly communicates with the main memory and no caches are involved. In this case, the CPU needs to access the main memory 10 times to access the desired information. "
},
{
"code": null,
"e": 872,
"s": 830,
"text": "Case 2 : System Design with Cache Memory "
},
{
"code": null,
"e": 1264,
"s": 874,
"text": "Here the CPU at first checks whether the desired data is present in the Cache Memory or not i.e. whether there is a “hit” in cache or “miss” in the cache. Suppose there is 3 miss in Cache Memory then the Main Memory will be accessed only 3 times. We can see that here the miss penalty is reduced because the Main Memory is accessed a lesser number of times than that in the previous case. "
},
{
"code": null,
"e": 1317,
"s": 1264,
"text": "Case 3 : System Design with Multilevel Cache Memory "
},
{
"code": null,
"e": 1782,
"s": 1319,
"text": "Here the Cache performance is optimized further by introducing multilevel Caches. As shown in the above figure, we are considering 2 level Cache Design. Suppose there is 3 miss in the L1 Cache Memory and out of these 3 misses there is 2 miss in the L2 Cache Memory then the Main Memory will be accessed only 2 times. It is clear that here the Miss Penalty is reduced considerably than that in the previous case thereby improving the Performance of Cache Memory. "
},
{
"code": null,
"e": 2259,
"s": 1782,
"text": "NOTE : We can observe from the above 3 cases that we are trying to decrease the number of Main Memory References and thus decreasing the Miss Penalty in order to improve the overall System Performance. Also, it is important to note that in the Multilevel Cache Design, L1 Cache is attached to the CPU and it is small in size but fast. Although, L2 Cache is attached to the Primary Cache i.e. L1 Cache and it is larger in size and slower but still faster than the Main Memory. "
},
{
"code": null,
"e": 2377,
"s": 2261,
"text": "Effective Access Time = Hit rate * Cache access time\n + Miss rate * Lower level access time\n\n "
},
{
"code": null,
"e": 2426,
"s": 2377,
"text": "Average access Time For Multilevel Cache:(Tavg) "
},
{
"code": null,
"e": 2479,
"s": 2426,
"text": "Tavg = H1 * C1 + (1 – H1) * (H2 * C2 +(1 – H2) *M ) "
},
{
"code": null,
"e": 2779,
"s": 2479,
"text": "where H1 is the Hit rate in the L1 caches. H2 is the Hit rate in the L2 cache. C1 is the Time to access information in the L1 caches. C2 is the Miss penalty to transfer information from the L2 cache to an L1 cache. M is the Miss penalty to transfer information from the main memory to the L2 cache. "
},
{
"code": null,
"e": 3116,
"s": 2779,
"text": "Example: Find the Average memory access time for a processor with a 2 ns clock cycle time, a miss rate of 0.04 misses per instruction, a missed penalty of 25 clock cycles, and a cache access time (including hit detection) of 1 clock cycle. Also, assume that the read and write miss penalties are the same and ignore other write stalls. "
},
{
"code": null,
"e": 3127,
"s": 3116,
"text": "Solution: "
},
{
"code": null,
"e": 3199,
"s": 3127,
"text": "Average Memory access time(AMAT)= Hit Time + Miss Rate * Miss Penalty. "
},
{
"code": null,
"e": 3301,
"s": 3199,
"text": "Hit Time = 1 clock cycle (Hit time = Hit rate * access time) but here Hit time is directly given so, "
},
{
"code": null,
"e": 3319,
"s": 3301,
"text": "Miss rate = 0.04 "
},
{
"code": null,
"e": 3417,
"s": 3319,
"text": "Miss Penalty= 25 clock cycle (this is the time taken by the above level of memory after the hit) "
},
{
"code": null,
"e": 3462,
"s": 3417,
"text": "so, AMAT= 1 + 0.04 * 25 AMAT= 2 clock cycle "
},
{
"code": null,
"e": 3506,
"s": 3462,
"text": "according to question 1 clock cycle = 2 ns "
},
{
"code": null,
"e": 3518,
"s": 3506,
"text": "AMAT = 4ns "
},
{
"code": null,
"e": 3532,
"s": 3520,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 3546,
"s": 3532,
"text": "Pushpender007"
},
{
"code": null,
"e": 3583,
"s": 3546,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 3591,
"s": 3583,
"text": "GATE CS"
},
{
"code": null,
"e": 3610,
"s": 3591,
"text": "Technical Scripter"
}
] |
How to get client_id and client_secret for Python Reddit API registration ?
|
26 May, 2020
Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them.A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what content the users post. It can be triggered by certain key phrases and also depends on various subreddits regarding their content.In order to implement a Reddit bot, we will use the Python Reddit API Wrapper (PRAW). It allows us to login to the Reddit API to directly interact with the backend of the website. More information about this library can be found here – PRAW – Python Reddit API Wrapper.
reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent', username ='my username', password ='my password')
In order to get the information for these fields:
Create a Reddit account.
The username of the reddit account will go to the username field.
The password of the reddit account will go to the password field.
user_agent is a unique identifier that helps Reddit determine the source of network requests.
client_id and client_secret are needed to access Reddit’s API as a script application. We can find them by:Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret.
Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret.
Login to your Reddit account.
Open the link: https://www.reddit.com/prefs/apps
The following will open up:
Click on “create an app...”. The following fields will be requested:
Give an appropriate name to the application and fill rest of the fields:
Click on “create app”.
The text in the green box is the client_id.
Click on “edit”. The text in the green box is the client_secret.
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 773,
"s": 28,
"text": "Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them.A Reddit bot is something that automatically responds to a user’s post or automatically posts things at certain intervals. This could depend on what content the users post. It can be triggered by certain key phrases and also depends on various subreddits regarding their content.In order to implement a Reddit bot, we will use the Python Reddit API Wrapper (PRAW). It allows us to login to the Reddit API to directly interact with the backend of the website. More information about this library can be found here – PRAW – Python Reddit API Wrapper."
},
{
"code": "reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent', username ='my username', password ='my password') ",
"e": 1020,
"s": 773,
"text": null
},
{
"code": null,
"e": 1070,
"s": 1020,
"text": "In order to get the information for these fields:"
},
{
"code": null,
"e": 1095,
"s": 1070,
"text": "Create a Reddit account."
},
{
"code": null,
"e": 1161,
"s": 1095,
"text": "The username of the reddit account will go to the username field."
},
{
"code": null,
"e": 1227,
"s": 1161,
"text": "The password of the reddit account will go to the password field."
},
{
"code": null,
"e": 1321,
"s": 1227,
"text": "user_agent is a unique identifier that helps Reddit determine the source of network requests."
},
{
"code": null,
"e": 1802,
"s": 1321,
"text": "client_id and client_secret are needed to access Reddit’s API as a script application. We can find them by:Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret."
},
{
"code": null,
"e": 2176,
"s": 1802,
"text": "Login to your Reddit account.Open the link: https://www.reddit.com/prefs/appsThe following will open up:Click on “create an app...”. The following fields will be requested:Give an appropriate name to the application and fill rest of the fields:Click on “create app”.The text in the green box is the client_id.Click on “edit”. The text in the green box is the client_secret."
},
{
"code": null,
"e": 2206,
"s": 2176,
"text": "Login to your Reddit account."
},
{
"code": null,
"e": 2255,
"s": 2206,
"text": "Open the link: https://www.reddit.com/prefs/apps"
},
{
"code": null,
"e": 2283,
"s": 2255,
"text": "The following will open up:"
},
{
"code": null,
"e": 2352,
"s": 2283,
"text": "Click on “create an app...”. The following fields will be requested:"
},
{
"code": null,
"e": 2425,
"s": 2352,
"text": "Give an appropriate name to the application and fill rest of the fields:"
},
{
"code": null,
"e": 2448,
"s": 2425,
"text": "Click on “create app”."
},
{
"code": null,
"e": 2492,
"s": 2448,
"text": "The text in the green box is the client_id."
},
{
"code": null,
"e": 2557,
"s": 2492,
"text": "Click on “edit”. The text in the green box is the client_secret."
},
{
"code": null,
"e": 2564,
"s": 2557,
"text": "Python"
},
{
"code": null,
"e": 2580,
"s": 2564,
"text": "Python Programs"
},
{
"code": null,
"e": 2678,
"s": 2580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2710,
"s": 2678,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2737,
"s": 2710,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2758,
"s": 2737,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2789,
"s": 2758,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2845,
"s": 2789,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2867,
"s": 2845,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2906,
"s": 2867,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2944,
"s": 2906,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2993,
"s": 2944,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Python Property Decorator – @property
|
27 May, 2022
A decorator feature in Python wraps in a function, appends several functionalities to existing code and then returns it. Methods and functions are known to be callable as they can be called. Therefore, a decorator is also a callable that returns callable. This is also known as metaprogramming as at compile time a section of program alters another section of the program. Note: For more information, refer to Decorators in Python
@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters. Now, lets see some examples to illustrate the use of @property decorator in Python: Example 1:
Python
# Python program to illustrate the use of# @property decorator # Defining classclass Portal: # Defining __init__ method def __init__(self): self.__name ='' # Using @property decorator @property # Getter method def name(self): return self.__name # Setter method @name.setter def name(self, val): self.__name = val # Deleter method @name.deleter def name(self): del self.__name # Creating objectp = Portal(); # Setting namep.name = 'GeeksforGeeks' # Prints nameprint (p.name) # Deletes namedel p.name # As name is deleted above this# will throw an errorprint (p.name)
GeeksforGeeks
## An error is thrown
Traceback (most recent call last):
File "main.py", line 42, in
print (p.name)
File "main.py", line 16, in name
return self.__name
AttributeError: 'Portal' object has no attribute '_Portal__name'
Here, the @property decorator is used to define the property name in the class Portal, that has three methods(getter, setter, and deleter) with similar names i.e, name(), but they have different number of parameters. Where, the method name(self) labeled with @property is a getter method, name(self, val) is a setter method as it is used to set the value of the attribute __name and so its labeled with @name.setter. Lastly, the method labeled with @name.deleter is a deleter method which can delete the assigned value by the setter method. However, deleter is invoked with the help of a keyword del. Example 2:
Python
# Python program to illustrate the use of# @property decorator # Creating classclass Celsius: # Defining init method with its parameter def __init__(self, temp = 0): self._temperature = temp # @property decorator @property # Getter method def temp(self): # Prints the assigned temperature value print("The value of the temperature is: ") return self._temperature # Setter method @temp.setter def temp(self, val): # If temperature is less than -273 than a value # error is thrown if val < -273: raise ValueError("It is a value error.") # Prints this if the value of the temperature is set print("The value of the temperature is set.") self._temperature = val # Creating object for the stated classcel = Celsius(); # Setting the temperature valuecel.temp = -270 # Prints the temperature that is setprint(cel.temp) # Setting the temperature value to -300# which is not possible so, an error is# throwncel.temp = -300
The value of the tempereture is set.
The value of the temperature is:
-270
# An error is thrown
Traceback (most recent call last):
File "main.py", line 47, in
cel.temp = -300
File "main.py", line 28, in temp
raise ValueError("It is a value error.")
ValueError: It is a value error.
Here, a value error is thrown as the value of the temperature assigned must be above -273. But here it is -300. Hence, a value error is thrown.
vinayedula
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
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
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 483,
"s": 52,
"text": "A decorator feature in Python wraps in a function, appends several functionalities to existing code and then returns it. Methods and functions are known to be callable as they can be called. Therefore, a decorator is also a callable that returns callable. This is also known as metaprogramming as at compile time a section of program alters another section of the program. Note: For more information, refer to Decorators in Python"
},
{
"code": null,
"e": 865,
"s": 483,
"text": "@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters. Now, lets see some examples to illustrate the use of @property decorator in Python: Example 1: "
},
{
"code": null,
"e": 872,
"s": 865,
"text": "Python"
},
{
"code": "# Python program to illustrate the use of# @property decorator # Defining classclass Portal: # Defining __init__ method def __init__(self): self.__name ='' # Using @property decorator @property # Getter method def name(self): return self.__name # Setter method @name.setter def name(self, val): self.__name = val # Deleter method @name.deleter def name(self): del self.__name # Creating objectp = Portal(); # Setting namep.name = 'GeeksforGeeks' # Prints nameprint (p.name) # Deletes namedel p.name # As name is deleted above this# will throw an errorprint (p.name)",
"e": 1518,
"s": 872,
"text": null
},
{
"code": null,
"e": 1763,
"s": 1518,
"text": "GeeksforGeeks\n\n## An error is thrown\nTraceback (most recent call last):\n File \"main.py\", line 42, in \n print (p.name)\n File \"main.py\", line 16, in name\n return self.__name\nAttributeError: 'Portal' object has no attribute '_Portal__name'"
},
{
"code": null,
"e": 2376,
"s": 1763,
"text": "Here, the @property decorator is used to define the property name in the class Portal, that has three methods(getter, setter, and deleter) with similar names i.e, name(), but they have different number of parameters. Where, the method name(self) labeled with @property is a getter method, name(self, val) is a setter method as it is used to set the value of the attribute __name and so its labeled with @name.setter. Lastly, the method labeled with @name.deleter is a deleter method which can delete the assigned value by the setter method. However, deleter is invoked with the help of a keyword del. Example 2: "
},
{
"code": null,
"e": 2383,
"s": 2376,
"text": "Python"
},
{
"code": "# Python program to illustrate the use of# @property decorator # Creating classclass Celsius: # Defining init method with its parameter def __init__(self, temp = 0): self._temperature = temp # @property decorator @property # Getter method def temp(self): # Prints the assigned temperature value print(\"The value of the temperature is: \") return self._temperature # Setter method @temp.setter def temp(self, val): # If temperature is less than -273 than a value # error is thrown if val < -273: raise ValueError(\"It is a value error.\") # Prints this if the value of the temperature is set print(\"The value of the temperature is set.\") self._temperature = val # Creating object for the stated classcel = Celsius(); # Setting the temperature valuecel.temp = -270 # Prints the temperature that is setprint(cel.temp) # Setting the temperature value to -300# which is not possible so, an error is# throwncel.temp = -300",
"e": 3445,
"s": 2383,
"text": null
},
{
"code": null,
"e": 3741,
"s": 3445,
"text": "The value of the tempereture is set.\nThe value of the temperature is:\n-270\n\n# An error is thrown\nTraceback (most recent call last):\n File \"main.py\", line 47, in \n cel.temp = -300\n File \"main.py\", line 28, in temp\n raise ValueError(\"It is a value error.\")\nValueError: It is a value error."
},
{
"code": null,
"e": 3885,
"s": 3741,
"text": "Here, a value error is thrown as the value of the temperature assigned must be above -273. But here it is -300. Hence, a value error is thrown."
},
{
"code": null,
"e": 3896,
"s": 3885,
"text": "vinayedula"
},
{
"code": null,
"e": 3914,
"s": 3896,
"text": "Python Decorators"
},
{
"code": null,
"e": 3921,
"s": 3914,
"text": "Python"
},
{
"code": null,
"e": 4019,
"s": 3921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4061,
"s": 4019,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4083,
"s": 4061,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4118,
"s": 4083,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4144,
"s": 4118,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4176,
"s": 4144,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4205,
"s": 4176,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4232,
"s": 4205,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4253,
"s": 4232,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4283,
"s": 4253,
"text": "Iterate over a list in Python"
}
] |
PHP | Basics of File Handling
|
08 Nov, 2017
File handling is needed for any application. For some tasks to be done file needs to be processed. File handling in PHP is similar as file handling is done by using any programming language like C. PHP has many functions to work with normal files. Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name of the file which is to be opened and second parameter tells about mode in which file needs to be opened, e.g.,
<?php$file = fopen(“demo.txt”,'w');?>
Files can be opened in any of the following modes :
“w” – Opens a file for write only. If file not exist then new file is created and if file already exists then contents of file is erased.
“r” – File is opened for read only.
“a” – File is opened for write only. File pointer points to end of file. Existing data in file is preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if file already exists then contents of file is erased.
“r+” – File is opened for read/write.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is preserved. If file is not there then new file is created.
“x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes two arguments. One is file pointer and another is file size in bytes, e.g.,
<?php$filename = "demo.txt";$file = fopen( $filename, 'r' );$size = filesize( $filename );$filedata = fread( $file, $size );?>
3) fwrite() – New file can be created or text can be appended to an existing file using fwrite() function. Arguments for fwrite() function are file pointer and text that is to written to file. It can contain optional third argument where length of text to written is specified, e.g.,
<?php$file = fopen("demo.txt", 'w');$text = "Hello world\n";fwrite($file, $text);?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed, e.g.,
<?php$file = fopen("demo.txt", 'r');//some code to be executedfclose($file);?>
Reference –Wikipedia
This article is contributed by Swasthik. 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.
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Nov, 2017"
},
{
"code": null,
"e": 322,
"s": 53,
"text": "File handling is needed for any application. For some tasks to be done file needs to be processed. File handling in PHP is similar as file handling is done by using any programming language like C. PHP has many functions to work with normal files. Those functions are:"
},
{
"code": null,
"e": 533,
"s": 322,
"text": "1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name of the file which is to be opened and second parameter tells about mode in which file needs to be opened, e.g.,"
},
{
"code": "<?php$file = fopen(“demo.txt”,'w');?>",
"e": 571,
"s": 533,
"text": null
},
{
"code": null,
"e": 623,
"s": 571,
"text": "Files can be opened in any of the following modes :"
},
{
"code": null,
"e": 761,
"s": 623,
"text": "“w” – Opens a file for write only. If file not exist then new file is created and if file already exists then contents of file is erased."
},
{
"code": null,
"e": 797,
"s": 761,
"text": "“r” – File is opened for read only."
},
{
"code": null,
"e": 906,
"s": 797,
"text": "“a” – File is opened for write only. File pointer points to end of file. Existing data in file is preserved."
},
{
"code": null,
"e": 1047,
"s": 906,
"text": "“w+” – Opens file for read and write. If file not exist then new file is created and if file already exists then contents of file is erased."
},
{
"code": null,
"e": 1085,
"s": 1047,
"text": "“r+” – File is opened for read/write."
},
{
"code": null,
"e": 1242,
"s": 1085,
"text": "“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is preserved. If file is not there then new file is created."
},
{
"code": null,
"e": 1284,
"s": 1242,
"text": "“x” – New file is created for write only."
},
{
"code": null,
"e": 1463,
"s": 1284,
"text": "2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes two arguments. One is file pointer and another is file size in bytes, e.g.,"
},
{
"code": "<?php$filename = \"demo.txt\";$file = fopen( $filename, 'r' );$size = filesize( $filename );$filedata = fread( $file, $size );?>",
"e": 1590,
"s": 1463,
"text": null
},
{
"code": null,
"e": 1874,
"s": 1590,
"text": "3) fwrite() – New file can be created or text can be appended to an existing file using fwrite() function. Arguments for fwrite() function are file pointer and text that is to written to file. It can contain optional third argument where length of text to written is specified, e.g.,"
},
{
"code": "<?php$file = fopen(\"demo.txt\", 'w');$text = \"Hello world\\n\";fwrite($file, $text);?>",
"e": 1958,
"s": 1874,
"text": null
},
{
"code": null,
"e": 2065,
"s": 1958,
"text": "4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed, e.g.,"
},
{
"code": "<?php$file = fopen(\"demo.txt\", 'r');//some code to be executedfclose($file);?>",
"e": 2144,
"s": 2065,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2144,
"text": "Reference –Wikipedia"
},
{
"code": null,
"e": 2461,
"s": 2165,
"text": "This article is contributed by Swasthik. 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": 2586,
"s": 2461,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2590,
"s": 2586,
"text": "PHP"
},
{
"code": null,
"e": 2607,
"s": 2590,
"text": "Web Technologies"
},
{
"code": null,
"e": 2611,
"s": 2607,
"text": "PHP"
}
] |
LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b}
|
23 Jul, 2021
In this article, we will discuss the LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b} and will see the implementation using LEX code and will understand the approach. Let’s discuss it one by one.
Problem Overview :LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b}.
Example –
Input : abb
Output : Accepted
Input : abababb
Output : Accepted
Input : 23ab
Output : Invalid
Input : ab345
Output : Invalid
Input : bbabaa
Output : Not Accepted
Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define four more states: A, B, C, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at C then display the message “Accepted”. Else if the input string ends at state INITIAL, A, or B then displays the message “Not Accepted”.
Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.
Example –
filename.l
Then after saving the program closes the lex file and then open the terminal and write the following commands as follows.
lex filename.l
cc lex.yy.c
./a.out
Implementation- LEX Code :
%{
%}
%s A B C DEAD
// not accepted state after visiting A
%%
<INITIAL>a BEGIN A;
<INITIAL>b BEGIN INITIAL;
<INITIAL>[^ab\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}
// not accepted state after visiting A and B state
<A>a BEGIN A;
<A>b BEGIN B;
<A>[^ab\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}
// // not accepted state after visiting A and C state
<B>a BEGIN A;
<B>b BEGIN C;
<B>[^ab\n] BEGIN DEAD;
<B>\n BEGIN INITIAL; {printf("Not Accepted\n");}
// Accepted case
<C>a BEGIN A;
<C>b BEGIN INITIAL;
<C>[^ab\n] BEGIN DEAD;
<C>\n BEGIN INITIAL; {printf("Accepted\n");}
// Invalid Case
<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}
%%
// yywrap method
int yywrap()
{
return 1;
}
// main method
int main()
{
printf("Enter String\n");
// called yylex
yylex();
return 0;
}
Output :
DFA
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Decidable and Undecidable problems in Theory of Computation
Halting Problem in Theory of Computation
Post Correspondence Problem
Undecidability and Reducibility in TOC
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Pushdown Automata Acceptance by Final State
Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}
Arden's Theorem in Theory of Computation
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 278,
"s": 52,
"text": "In this article, we will discuss the LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b} and will see the implementation using LEX code and will understand the approach. Let’s discuss it one by one. "
},
{
"code": null,
"e": 375,
"s": 278,
"text": "Problem Overview :LEX Code that accepts the string ending with ‘abb’ over input alphabet {a,b}."
},
{
"code": null,
"e": 385,
"s": 375,
"text": "Example –"
},
{
"code": null,
"e": 556,
"s": 385,
"text": "Input : abb\nOutput : Accepted\n\nInput : abababb\nOutput : Accepted\n\nInput : 23ab\nOutput : Invalid\n\nInput : ab345\nOutput : Invalid\n\nInput : bbabaa\nOutput : Not Accepted"
},
{
"code": null,
"e": 1054,
"s": 556,
"text": "Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define four more states: A, B, C, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at C then display the message “Accepted”. Else if the input string ends at state INITIAL, A, or B then displays the message “Not Accepted”."
},
{
"code": null,
"e": 1203,
"s": 1054,
"text": "Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension."
},
{
"code": null,
"e": 1214,
"s": 1203,
"text": "Example – "
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": "filename.l"
},
{
"code": null,
"e": 1347,
"s": 1225,
"text": "Then after saving the program closes the lex file and then open the terminal and write the following commands as follows."
},
{
"code": null,
"e": 1382,
"s": 1347,
"text": "lex filename.l\ncc lex.yy.c\n./a.out"
},
{
"code": null,
"e": 1409,
"s": 1382,
"text": "Implementation- LEX Code :"
},
{
"code": null,
"e": 2277,
"s": 1409,
"text": "%{\n%}\n \n%s A B C DEAD\n\n// not accepted state after visiting A \n%%\n<INITIAL>a BEGIN A;\n<INITIAL>b BEGIN INITIAL;\n<INITIAL>[^ab\\n] BEGIN DEAD;\n<INITIAL>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");}\n\n// not accepted state after visiting A and B state\n<A>a BEGIN A;\n<A>b BEGIN B;\n<A>[^ab\\n] BEGIN DEAD;\n<A>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");}\n \n// // not accepted state after visiting A and C state \n<B>a BEGIN A;\n<B>b BEGIN C;\n<B>[^ab\\n] BEGIN DEAD;\n<B>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");}\n\n// Accepted case\n<C>a BEGIN A;\n<C>b BEGIN INITIAL;\n<C>[^ab\\n] BEGIN DEAD;\n<C>\\n BEGIN INITIAL; {printf(\"Accepted\\n\");}\n\n// Invalid Case \n<DEAD>[^\\n] BEGIN DEAD;\n<DEAD>\\n BEGIN INITIAL; {printf(\"Invalid\\n\");}\n \n%%\n// yywrap method\nint yywrap()\n{\nreturn 1;\n} \n\n// main method \nint main()\n{\n printf(\"Enter String\\n\");\n // called yylex\n yylex();\nreturn 0;\n}"
},
{
"code": null,
"e": 2286,
"s": 2277,
"text": "Output :"
},
{
"code": null,
"e": 2290,
"s": 2286,
"text": "DFA"
},
{
"code": null,
"e": 2323,
"s": 2290,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 2421,
"s": 2323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2459,
"s": 2421,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 2487,
"s": 2459,
"text": "Variation of Turing Machine"
},
{
"code": null,
"e": 2547,
"s": 2487,
"text": "Decidable and Undecidable problems in Theory of Computation"
},
{
"code": null,
"e": 2588,
"s": 2547,
"text": "Halting Problem in Theory of Computation"
},
{
"code": null,
"e": 2616,
"s": 2588,
"text": "Post Correspondence Problem"
},
{
"code": null,
"e": 2655,
"s": 2616,
"text": "Undecidability and Reducibility in TOC"
},
{
"code": null,
"e": 2710,
"s": 2655,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 2754,
"s": 2710,
"text": "Pushdown Automata Acceptance by Final State"
},
{
"code": null,
"e": 2835,
"s": 2754,
"text": "Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}"
}
] |
Python OOPs Concepts
|
14 Jun, 2022
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data.
Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
OOPs
A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains some attributes and methods.
To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute
Class Definition Syntax:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
class ClassName:
# Statement-1
.
.
.
# Statement-N
Python
# Python3 program to# demonstrate defining# a class class Dog: pass
In the above example, we have created a class named dog using the class keyword.
The object is an entity that has a state and behavior associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve been using objects all along and may not even realize it.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
To understand the state, behavior, and identity let us take the example of the class dog (explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or sleeping.
Python3
obj = Dog()
This will create an object named obj of the class Dog defined above. Before diving deep into objects and class let us understand some basic keywords that will we used while working with objects and classes.
Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides itIf we have a method that takes no arguments, then we still have to have one argument.This is similar to this pointer in C++ and this reference in Java.
Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it
If we have a method that takes no arguments, then we still have to have one argument.
This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
Note: For more information, refer to self in Python class
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
Now let us define a class and create some objects using the self and __init__ method.
Python3
class Dog: # class attribute attr1 = "mammal" # Instance attribute def __init__(self, name): self.name = name # Driver code# Object instantiationRodger = Dog("Rodger")Tommy = Dog("Tommy") # Accessing class attributesprint("Rodger is a {}".format(Rodger.__class__.attr1))print("Tommy is also a {}".format(Tommy.__class__.attr1)) # Accessing instance attributesprint("My name is {}".format(Rodger.name))print("My name is {}".format(Tommy.name))
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Python3
class Dog: # class attribute attr1 = "mammal" # Instance attribute def __init__(self, name): self.name = name def speak(self): print("My name is {}".format(self.name)) # Driver code# Object instantiationRodger = Dog("Rodger")Tommy = Dog("Tommy") # Accessing class methodsRodger.speak()Tommy.speak()
My name is Rodger
My name is Tommy
Note: For more information, refer Python Classes and Objects
Inheritance is the capability of one class to derive or inherit the properties from another class. The class that derives properties is called the derived class or child class and the class from which the properties are being derived is called the base class or parent class. The benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
Single Inheritance:Single-level inheritance enables a derived class to inherit characteristics from a single-parent class.
Multilevel Inheritance:Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class.
Hierarchical Inheritance:Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class.
Multiple Inheritance:Multiple level inheritance enables one derived class to inherit properties from more than one base class.
Python3
# Python code to demonstrate how parent constructors# are called. # parent classclass Person(object): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) def details(self): print("My name is {}".format(self.name)) print("IdNumber: {}".format(self.idnumber)) # child classclass Employee(Person): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) def details(self): print("My name is {}".format(self.name)) print("IdNumber: {}".format(self.idnumber)) print("Post: {}".format(self.post)) # creation of an object variable or an instancea = Employee('Rahul', 886012, 200000, "Intern") # calling a function of the class Person using# its instancea.display()a.details()
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
In the above article, we have created two classes i.e. Person (parent class) and Employee (Child Class). The Employee class inherits from the Person class. We can use the methods of the person class through employee class as seen in the display function in the above code. A child class can also modify the behavior of the parent class as seen through the details() method.
Note: For more information, refer to our Inheritance in Python tutorial.
Polymorphism simply means having many forms. For example, we need to determine if the given species of birds fly or not, using polymorphism we can do this using a single function.
Python3
class Bird: def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") class sparrow(Bird): def flight(self): print("Sparrows can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird = Bird()obj_spr = sparrow()obj_ost = ostrich() obj_bird.intro()obj_bird.flight() obj_spr.intro()obj_spr.flight() obj_ost.intro()obj_ost.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Note: For more information, refer to our Polymorphism in Python Tutorial.
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
Python3
# Python program to# demonstrate private members # Creating a Base classclass Base: def __init__(self): self.a = "GeeksforGeeks" self.__c = "GeeksforGeeks" # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print("Calling private member of base class: ") print(self.__c) # Driver codeobj1 = Base()print(obj1.a) # Uncommenting print(obj1.c) will# raise an AttributeError # Uncommenting obj2 = Derived() will# also raise an AtrributeError as# private member of base class# is called inside derived class
GeeksforGeeks
In the above example, we have created the c variable as the private attribute. We cannot even access this attribute directly and can’t even change its value.
Note: for more information, refer to our Encapsulation in Python Tutorial.
It hides the unnecessary code details from the user. Also, when we do not want to give out sensitive parts of our code implementation and this is where data abstraction came.
Data Abstraction in Python can be achieved through creating abstract classes.
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
https://youtu.be/CiH7lN4
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
tripathipriyanshu1998
nikhilaggarwal3
Kushagra vatsa
raj095907
python-oop-concepts
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
Introduction To PYTHON
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 447,
"s": 52,
"text": "In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data."
},
{
"code": null,
"e": 453,
"s": 447,
"text": "Class"
},
{
"code": null,
"e": 461,
"s": 453,
"text": "Objects"
},
{
"code": null,
"e": 474,
"s": 461,
"text": "Polymorphism"
},
{
"code": null,
"e": 488,
"s": 474,
"text": "Encapsulation"
},
{
"code": null,
"e": 500,
"s": 488,
"text": "Inheritance"
},
{
"code": null,
"e": 517,
"s": 500,
"text": "Data Abstraction"
},
{
"code": null,
"e": 523,
"s": 517,
"text": "OOPs "
},
{
"code": null,
"e": 717,
"s": 523,
"text": "A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains some attributes and methods. "
},
{
"code": null,
"e": 1228,
"s": 717,
"text": "To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes. "
},
{
"code": null,
"e": 1259,
"s": 1228,
"text": "Some points on Python class: "
},
{
"code": null,
"e": 1297,
"s": 1259,
"text": "Classes are created by keyword class."
},
{
"code": null,
"e": 1350,
"s": 1297,
"text": "Attributes are the variables that belong to a class."
},
{
"code": null,
"e": 1452,
"s": 1350,
"text": "Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute"
},
{
"code": null,
"e": 1477,
"s": 1452,
"text": "Class Definition Syntax:"
},
{
"code": null,
"e": 1486,
"s": 1477,
"text": "Chapters"
},
{
"code": null,
"e": 1513,
"s": 1486,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1563,
"s": 1513,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1586,
"s": 1563,
"text": "captions off, selected"
},
{
"code": null,
"e": 1594,
"s": 1586,
"text": "English"
},
{
"code": null,
"e": 1618,
"s": 1594,
"text": "This is a modal window."
},
{
"code": null,
"e": 1687,
"s": 1618,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1709,
"s": 1687,
"text": "End of dialog window."
},
{
"code": null,
"e": 1775,
"s": 1709,
"text": "class ClassName:\n # Statement-1\n .\n .\n .\n # Statement-N"
},
{
"code": null,
"e": 1782,
"s": 1775,
"text": "Python"
},
{
"code": "# Python3 program to# demonstrate defining# a class class Dog: pass",
"e": 1853,
"s": 1782,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1853,
"text": "In the above example, we have created a class named dog using the class keyword."
},
{
"code": null,
"e": 2445,
"s": 1934,
"text": "The object is an entity that has a state and behavior associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve been using objects all along and may not even realize it."
},
{
"code": null,
"e": 2469,
"s": 2445,
"text": "An object consists of :"
},
{
"code": null,
"e": 2572,
"s": 2469,
"text": "State: It is represented by the attributes of an object. It also reflects the properties of an object."
},
{
"code": null,
"e": 2690,
"s": 2572,
"text": "Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects."
},
{
"code": null,
"e": 2791,
"s": 2690,
"text": "Identity: It gives a unique name to an object and enables one object to interact with other objects."
},
{
"code": null,
"e": 2900,
"s": 2791,
"text": "To understand the state, behavior, and identity let us take the example of the class dog (explained above). "
},
{
"code": null,
"e": 2955,
"s": 2900,
"text": "The identity can be considered as the name of the dog."
},
{
"code": null,
"e": 3033,
"s": 2955,
"text": "State or Attributes can be considered as the breed, age, or color of the dog."
},
{
"code": null,
"e": 3109,
"s": 3033,
"text": "The behavior can be considered as to whether the dog is eating or sleeping."
},
{
"code": null,
"e": 3117,
"s": 3109,
"text": "Python3"
},
{
"code": "obj = Dog()",
"e": 3129,
"s": 3117,
"text": null
},
{
"code": null,
"e": 3336,
"s": 3129,
"text": "This will create an object named obj of the class Dog defined above. Before diving deep into objects and class let us understand some basic keywords that will we used while working with objects and classes."
},
{
"code": null,
"e": 3648,
"s": 3336,
"text": "Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides itIf we have a method that takes no arguments, then we still have to have one argument.This is similar to this pointer in C++ and this reference in Java."
},
{
"code": null,
"e": 3809,
"s": 3648,
"text": "Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it"
},
{
"code": null,
"e": 3895,
"s": 3809,
"text": "If we have a method that takes no arguments, then we still have to have one argument."
},
{
"code": null,
"e": 3962,
"s": 3895,
"text": "This is similar to this pointer in C++ and this reference in Java."
},
{
"code": null,
"e": 4156,
"s": 3962,
"text": "When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about."
},
{
"code": null,
"e": 4214,
"s": 4156,
"text": "Note: For more information, refer to self in Python class"
},
{
"code": null,
"e": 4417,
"s": 4214,
"text": "The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. "
},
{
"code": null,
"e": 4503,
"s": 4417,
"text": "Now let us define a class and create some objects using the self and __init__ method."
},
{
"code": null,
"e": 4511,
"s": 4503,
"text": "Python3"
},
{
"code": "class Dog: # class attribute attr1 = \"mammal\" # Instance attribute def __init__(self, name): self.name = name # Driver code# Object instantiationRodger = Dog(\"Rodger\")Tommy = Dog(\"Tommy\") # Accessing class attributesprint(\"Rodger is a {}\".format(Rodger.__class__.attr1))print(\"Tommy is also a {}\".format(Tommy.__class__.attr1)) # Accessing instance attributesprint(\"My name is {}\".format(Rodger.name))print(\"My name is {}\".format(Tommy.name))",
"e": 4975,
"s": 4511,
"text": null
},
{
"code": null,
"e": 5052,
"s": 4975,
"text": "Rodger is a mammal\nTommy is also a mammal\nMy name is Rodger\nMy name is Tommy"
},
{
"code": null,
"e": 5060,
"s": 5052,
"text": "Python3"
},
{
"code": "class Dog: # class attribute attr1 = \"mammal\" # Instance attribute def __init__(self, name): self.name = name def speak(self): print(\"My name is {}\".format(self.name)) # Driver code# Object instantiationRodger = Dog(\"Rodger\")Tommy = Dog(\"Tommy\") # Accessing class methodsRodger.speak()Tommy.speak()",
"e": 5399,
"s": 5060,
"text": null
},
{
"code": null,
"e": 5434,
"s": 5399,
"text": "My name is Rodger\nMy name is Tommy"
},
{
"code": null,
"e": 5495,
"s": 5434,
"text": "Note: For more information, refer Python Classes and Objects"
},
{
"code": null,
"e": 5804,
"s": 5495,
"text": "Inheritance is the capability of one class to derive or inherit the properties from another class. The class that derives properties is called the derived class or child class and the class from which the properties are being derived is called the base class or parent class. The benefits of inheritance are:"
},
{
"code": null,
"e": 5849,
"s": 5804,
"text": "It represents real-world relationships well."
},
{
"code": null,
"e": 6015,
"s": 5849,
"text": "It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it."
},
{
"code": null,
"e": 6173,
"s": 6015,
"text": "It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A."
},
{
"code": null,
"e": 6296,
"s": 6173,
"text": "Single Inheritance:Single-level inheritance enables a derived class to inherit characteristics from a single-parent class."
},
{
"code": null,
"e": 6477,
"s": 6296,
"text": "Multilevel Inheritance:Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class."
},
{
"code": null,
"e": 6612,
"s": 6477,
"text": "Hierarchical Inheritance:Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class."
},
{
"code": null,
"e": 6739,
"s": 6612,
"text": "Multiple Inheritance:Multiple level inheritance enables one derived class to inherit properties from more than one base class."
},
{
"code": null,
"e": 6747,
"s": 6739,
"text": "Python3"
},
{
"code": "# Python code to demonstrate how parent constructors# are called. # parent classclass Person(object): # __init__ is known as the constructor def __init__(self, name, idnumber): self.name = name self.idnumber = idnumber def display(self): print(self.name) print(self.idnumber) def details(self): print(\"My name is {}\".format(self.name)) print(\"IdNumber: {}\".format(self.idnumber)) # child classclass Employee(Person): def __init__(self, name, idnumber, salary, post): self.salary = salary self.post = post # invoking the __init__ of the parent class Person.__init__(self, name, idnumber) def details(self): print(\"My name is {}\".format(self.name)) print(\"IdNumber: {}\".format(self.idnumber)) print(\"Post: {}\".format(self.post)) # creation of an object variable or an instancea = Employee('Rahul', 886012, 200000, \"Intern\") # calling a function of the class Person using# its instancea.display()a.details()",
"e": 7787,
"s": 6747,
"text": null
},
{
"code": null,
"e": 7847,
"s": 7787,
"text": "Rahul\n886012\nMy name is Rahul\nIdNumber: 886012\nPost: Intern"
},
{
"code": null,
"e": 8221,
"s": 7847,
"text": "In the above article, we have created two classes i.e. Person (parent class) and Employee (Child Class). The Employee class inherits from the Person class. We can use the methods of the person class through employee class as seen in the display function in the above code. A child class can also modify the behavior of the parent class as seen through the details() method."
},
{
"code": null,
"e": 8294,
"s": 8221,
"text": "Note: For more information, refer to our Inheritance in Python tutorial."
},
{
"code": null,
"e": 8474,
"s": 8294,
"text": "Polymorphism simply means having many forms. For example, we need to determine if the given species of birds fly or not, using polymorphism we can do this using a single function."
},
{
"code": null,
"e": 8482,
"s": 8474,
"text": "Python3"
},
{
"code": "class Bird: def intro(self): print(\"There are many types of birds.\") def flight(self): print(\"Most of the birds can fly but some cannot.\") class sparrow(Bird): def flight(self): print(\"Sparrows can fly.\") class ostrich(Bird): def flight(self): print(\"Ostriches cannot fly.\") obj_bird = Bird()obj_spr = sparrow()obj_ost = ostrich() obj_bird.intro()obj_bird.flight() obj_spr.intro()obj_spr.flight() obj_ost.intro()obj_ost.flight()",
"e": 8959,
"s": 8482,
"text": null
},
{
"code": null,
"e": 9135,
"s": 8959,
"text": "There are many types of birds.\nMost of the birds can fly but some cannot.\nThere are many types of birds.\nSparrows can fly.\nThere are many types of birds.\nOstriches cannot fly."
},
{
"code": null,
"e": 9209,
"s": 9135,
"text": "Note: For more information, refer to our Polymorphism in Python Tutorial."
},
{
"code": null,
"e": 9657,
"s": 9209,
"text": "Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables."
},
{
"code": null,
"e": 9770,
"s": 9657,
"text": "A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc."
},
{
"code": null,
"e": 9778,
"s": 9770,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate private members # Creating a Base classclass Base: def __init__(self): self.a = \"GeeksforGeeks\" self.__c = \"GeeksforGeeks\" # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print(\"Calling private member of base class: \") print(self.__c) # Driver codeobj1 = Base()print(obj1.a) # Uncommenting print(obj1.c) will# raise an AttributeError # Uncommenting obj2 = Derived() will# also raise an AtrributeError as# private member of base class# is called inside derived class",
"e": 10411,
"s": 9778,
"text": null
},
{
"code": null,
"e": 10425,
"s": 10411,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 10583,
"s": 10425,
"text": "In the above example, we have created the c variable as the private attribute. We cannot even access this attribute directly and can’t even change its value."
},
{
"code": null,
"e": 10658,
"s": 10583,
"text": "Note: for more information, refer to our Encapsulation in Python Tutorial."
},
{
"code": null,
"e": 10834,
"s": 10658,
"text": "It hides the unnecessary code details from the user. Also, when we do not want to give out sensitive parts of our code implementation and this is where data abstraction came."
},
{
"code": null,
"e": 10912,
"s": 10834,
"text": "Data Abstraction in Python can be achieved through creating abstract classes."
},
{
"code": null,
"e": 10992,
"s": 10912,
"text": "Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)"
},
{
"code": null,
"e": 11017,
"s": 10992,
"text": "https://youtu.be/CiH7lN4"
},
{
"code": null,
"e": 11141,
"s": 11017,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 11163,
"s": 11141,
"text": "tripathipriyanshu1998"
},
{
"code": null,
"e": 11179,
"s": 11163,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 11194,
"s": 11179,
"text": "Kushagra vatsa"
},
{
"code": null,
"e": 11204,
"s": 11194,
"text": "raj095907"
},
{
"code": null,
"e": 11224,
"s": 11204,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 11231,
"s": 11224,
"text": "Python"
},
{
"code": null,
"e": 11329,
"s": 11231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11347,
"s": 11329,
"text": "Python Dictionary"
},
{
"code": null,
"e": 11389,
"s": 11347,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 11411,
"s": 11389,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 11446,
"s": 11411,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 11472,
"s": 11446,
"text": "Python String | replace()"
},
{
"code": null,
"e": 11504,
"s": 11472,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 11533,
"s": 11504,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 11560,
"s": 11533,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 11583,
"s": 11560,
"text": "Introduction To PYTHON"
}
] |
Servlets - Exception Handling
|
When a servlet throws an exception, the web container searches the configurations in web.xml that use the exception-type element for a match with the thrown exception type.
You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes.
Consider, you have an ErrorHandler servlet which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml.
<!-- servlet definition -->
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<!-- error-code related error pages -->
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/ErrorHandler</location>
</error-page>
<!-- exception-type related error pages -->
<error-page>
<exception-type>
javax.servlet.ServletException
</exception-type >
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type >
<location>/ErrorHandler</location>
</error-page>
If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception −
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Following are the points to be noted about above web.xml for Exception Handling −
The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.
The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.
If there is any error with status code either 404 (Not Found) or 403 (Forbidden ), then ErrorHandler servlet would be called.
If there is any error with status code either 404 (Not Found) or 403 (Forbidden ), then ErrorHandler servlet would be called.
If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet.
If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet.
You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.
You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept.
Following is the list of request attributes that an error-handling servlet can access to analyze the nature of error/exception.
javax.servlet.error.status_code
This attribute give status code which can be stored and analyzed after storing in a java.lang.Integer data type.
javax.servlet.error.exception_type
This attribute gives information about exception type which can be stored and analysed after storing in a java.lang.Class data type.
javax.servlet.error.message
This attribute gives information exact error message which can be stored and analyzed after storing in a java.lang.String data type.
javax.servlet.error.request_uri
This attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a java.lang.String data type.
javax.servlet.error.exception
This attribute gives information about the exception raised, which can be stored and analysed.
javax.servlet.error.servlet_name
This attribute gives servlet name which can be stored and analyzed after storing in a java.lang.String data type.
This example would give you basic understanding of Exception Handling in Servlet, but you can write more sophisticated filter applications using the same concept −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class ErrorHandler extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer)
request.getAttribute("javax.servlet.error.status_code");
String servletName = (String)
request.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String)
request.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Error/Exception Information";
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");
if (throwable == null && statusCode == null) {
out.println("<h2>Error information is missing</h2>");
out.println("Please return to the <a href=\"" +
response.encodeURL("http://localhost:8080/") +
"\">Home Page</a>.");
} else if (statusCode != null) {
out.println("The status code : " + statusCode);
} else {
out.println("<h2>Error information</h2>");
out.println("Servlet Name : " + servletName + "</br></br>");
out.println("Exception Type : " + throwable.getClass( ).getName( ) + "</br></br>");
out.println("The request URI: " + requestUri + "<br><br>");
out.println("The exception message: " + throwable.getMessage( ));
}
out.println("</body>");
out.println("</html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Compile ErrorHandler.java in usual way and put your class file in /webapps/ROOT/WEB-INF/classes.
Let us add the following configuration in web.xml to handle exceptions −
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it would display the following result −
The status code : 404
The above code may not work with some web browsers. So try with Mozilla and Safari and it should work.
|
[
{
"code": null,
"e": 2492,
"s": 2319,
"text": "When a servlet throws an exception, the web container searches the configurations in web.xml that use the exception-type element for a match with the thrown exception type."
},
{
"code": null,
"e": 2642,
"s": 2492,
"text": "You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain exceptions or HTTP status codes."
},
{
"code": null,
"e": 2806,
"s": 2642,
"text": "Consider, you have an ErrorHandler servlet which would be called whenever there is any defined exception or error. Following would be the entry created in web.xml."
},
{
"code": null,
"e": 3648,
"s": 2806,
"text": "<!-- servlet definition -->\n<servlet>\n <servlet-name>ErrorHandler</servlet-name>\n <servlet-class>ErrorHandler</servlet-class>\n</servlet>\n\n<!-- servlet mappings -->\n<servlet-mapping>\n <servlet-name>ErrorHandler</servlet-name>\n <url-pattern>/ErrorHandler</url-pattern>\n</servlet-mapping>\n\n<!-- error-code related error pages -->\n<error-page>\n <error-code>404</error-code>\n <location>/ErrorHandler</location>\n</error-page>\n\n<error-page>\n <error-code>403</error-code>\n <location>/ErrorHandler</location>\n</error-page>\n\n<!-- exception-type related error pages -->\n<error-page>\n <exception-type>\n javax.servlet.ServletException\n </exception-type >\n <location>/ErrorHandler</location>\n</error-page>\n\n<error-page>\n <exception-type>java.io.IOException</exception-type >\n <location>/ErrorHandler</location>\n</error-page>"
},
{
"code": null,
"e": 3830,
"s": 3648,
"text": "If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of defining separate error-page elements for every exception −"
},
{
"code": null,
"e": 3952,
"s": 3830,
"text": "<error-page>\n <exception-type>java.lang.Throwable</exception-type >\n <location>/ErrorHandler</location>\n</error-page>"
},
{
"code": null,
"e": 4034,
"s": 3952,
"text": "Following are the points to be noted about above web.xml for Exception Handling −"
},
{
"code": null,
"e": 4131,
"s": 4034,
"text": "The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml."
},
{
"code": null,
"e": 4228,
"s": 4131,
"text": "The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml."
},
{
"code": null,
"e": 4354,
"s": 4228,
"text": "If there is any error with status code either 404 (Not Found) or 403 (Forbidden ), then ErrorHandler servlet would be called."
},
{
"code": null,
"e": 4480,
"s": 4354,
"text": "If there is any error with status code either 404 (Not Found) or 403 (Forbidden ), then ErrorHandler servlet would be called."
},
{
"code": null,
"e": 4608,
"s": 4480,
"text": "If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet."
},
{
"code": null,
"e": 4736,
"s": 4608,
"text": "If the web application throws either ServletException or IOException, then the web container invokes the /ErrorHandler servlet."
},
{
"code": null,
"e": 4925,
"s": 4736,
"text": "You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept."
},
{
"code": null,
"e": 5114,
"s": 4925,
"text": "You can define different Error Handlers to handle different type of errors or exceptions. Above example is very much generic and hope it serve the purpose to explain you the basic concept."
},
{
"code": null,
"e": 5242,
"s": 5114,
"text": "Following is the list of request attributes that an error-handling servlet can access to analyze the nature of error/exception."
},
{
"code": null,
"e": 5275,
"s": 5242,
"text": "javax.servlet.error.status_code "
},
{
"code": null,
"e": 5388,
"s": 5275,
"text": "This attribute give status code which can be stored and analyzed after storing in a java.lang.Integer data type."
},
{
"code": null,
"e": 5424,
"s": 5388,
"text": "javax.servlet.error.exception_type "
},
{
"code": null,
"e": 5557,
"s": 5424,
"text": "This attribute gives information about exception type which can be stored and analysed after storing in a java.lang.Class data type."
},
{
"code": null,
"e": 5586,
"s": 5557,
"text": "javax.servlet.error.message "
},
{
"code": null,
"e": 5719,
"s": 5586,
"text": "This attribute gives information exact error message which can be stored and analyzed after storing in a java.lang.String data type."
},
{
"code": null,
"e": 5752,
"s": 5719,
"text": "javax.servlet.error.request_uri "
},
{
"code": null,
"e": 5896,
"s": 5752,
"text": "This attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a java.lang.String data type."
},
{
"code": null,
"e": 5927,
"s": 5896,
"text": "javax.servlet.error.exception "
},
{
"code": null,
"e": 6022,
"s": 5927,
"text": "This attribute gives information about the exception raised, which can be stored and analysed."
},
{
"code": null,
"e": 6056,
"s": 6022,
"text": "javax.servlet.error.servlet_name "
},
{
"code": null,
"e": 6170,
"s": 6056,
"text": "This attribute gives servlet name which can be stored and analyzed after storing in a java.lang.String data type."
},
{
"code": null,
"e": 6334,
"s": 6170,
"text": "This example would give you basic understanding of Exception Handling in Servlet, but you can write more sophisticated filter applications using the same concept −"
},
{
"code": null,
"e": 8812,
"s": 6334,
"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 ErrorHandler extends HttpServlet {\n \n // Method to handle GET method request.\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Analyze the servlet exception \n Throwable throwable = (Throwable)\n request.getAttribute(\"javax.servlet.error.exception\");\n Integer statusCode = (Integer)\n request.getAttribute(\"javax.servlet.error.status_code\");\n String servletName = (String)\n request.getAttribute(\"javax.servlet.error.servlet_name\");\n \n if (servletName == null) {\n servletName = \"Unknown\";\n }\n String requestUri = (String)\n request.getAttribute(\"javax.servlet.error.request_uri\");\n \n if (requestUri == null) {\n requestUri = \"Unknown\";\n }\n\n // Set response content type\n response.setContentType(\"text/html\");\n\n PrintWriter out = response.getWriter();\n String title = \"Error/Exception Information\";\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\n if (throwable == null && statusCode == null) {\n out.println(\"<h2>Error information is missing</h2>\");\n out.println(\"Please return to the <a href=\\\"\" + \n response.encodeURL(\"http://localhost:8080/\") + \n \"\\\">Home Page</a>.\");\n } else if (statusCode != null) {\n out.println(\"The status code : \" + statusCode);\n } else {\n out.println(\"<h2>Error information</h2>\");\n out.println(\"Servlet Name : \" + servletName + \"</br></br>\");\n out.println(\"Exception Type : \" + throwable.getClass( ).getName( ) + \"</br></br>\");\n out.println(\"The request URI: \" + requestUri + \"<br><br>\");\n out.println(\"The exception message: \" + throwable.getMessage( ));\n }\n out.println(\"</body>\");\n out.println(\"</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": 8909,
"s": 8812,
"text": "Compile ErrorHandler.java in usual way and put your class file in /webapps/ROOT/WEB-INF/classes."
},
{
"code": null,
"e": 8982,
"s": 8909,
"text": "Let us add the following configuration in web.xml to handle exceptions −"
},
{
"code": null,
"e": 9469,
"s": 8982,
"text": "<servlet>\n <servlet-name>ErrorHandler</servlet-name>\n <servlet-class>ErrorHandler</servlet-class>\n</servlet>\n\n<!-- servlet mappings -->\n<servlet-mapping>\n <servlet-name>ErrorHandler</servlet-name>\n <url-pattern>/ErrorHandler</url-pattern>\n</servlet-mapping>\n\n<error-page>\n <error-code>404</error-code>\n <location>/ErrorHandler</location>\n</error-page>\n\n<error-page>\n <exception-type>java.lang.Throwable</exception-type >\n <location>/ErrorHandler</location>\n</error-page>"
},
{
"code": null,
"e": 9735,
"s": 9469,
"text": "Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it would display the following result −"
},
{
"code": null,
"e": 9758,
"s": 9735,
"text": "The status code : 404\n"
}
] |
How to work Date query with ISODate in MongoDB?
|
Use $gte operator along with ISODate() to work Date query with ISODate in MongoDB.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.dateDemo.insertOne({"StudentName":"John","StudentAge":26,"AdmissionDate":new ISODate("2013-06-07")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a65799064dcd4a68b70ea")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.dateDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8a65799064dcd4a68b70ea"),
"StudentName" : "John",
"StudentAge" : 26,
"AdmissionDate" : ISODate("2013-06-07T00:00:00Z")
}
Here is the date query with ISODate in MongoDB −
> db.dateDemo.find({"AdmissionDate":{"$gte": ISODate("2013-06-07T00:00:00Z")}}).pretty();
The following is the output −
{
"_id" : ObjectId("5c8a65799064dcd4a68b70ea"),
"StudentName" : "John",
"StudentAge" : 26,
"AdmissionDate" : ISODate("2013-06-07T00:00:00Z")
}
|
[
{
"code": null,
"e": 1270,
"s": 1187,
"text": "Use $gte operator along with ISODate() to work Date query with ISODate in MongoDB."
},
{
"code": null,
"e": 1408,
"s": 1270,
"text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1600,
"s": 1408,
"text": "> db.dateDemo.insertOne({\"StudentName\":\"John\",\"StudentAge\":26,\"AdmissionDate\":new ISODate(\"2013-06-07\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a65799064dcd4a68b70ea\")\n}"
},
{
"code": null,
"e": 1698,
"s": 1600,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 1729,
"s": 1698,
"text": "> db.dateDemo.find().pretty();"
},
{
"code": null,
"e": 1759,
"s": 1729,
"text": "The following is the output −"
},
{
"code": null,
"e": 1914,
"s": 1759,
"text": "{\n \"_id\" : ObjectId(\"5c8a65799064dcd4a68b70ea\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 26,\n \"AdmissionDate\" : ISODate(\"2013-06-07T00:00:00Z\")\n}"
},
{
"code": null,
"e": 1963,
"s": 1914,
"text": "Here is the date query with ISODate in MongoDB −"
},
{
"code": null,
"e": 2053,
"s": 1963,
"text": "> db.dateDemo.find({\"AdmissionDate\":{\"$gte\": ISODate(\"2013-06-07T00:00:00Z\")}}).pretty();"
},
{
"code": null,
"e": 2083,
"s": 2053,
"text": "The following is the output −"
},
{
"code": null,
"e": 2238,
"s": 2083,
"text": "{\n \"_id\" : ObjectId(\"5c8a65799064dcd4a68b70ea\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 26,\n \"AdmissionDate\" : ISODate(\"2013-06-07T00:00:00Z\")\n}"
}
] |
Showing data values on stacked bar chart in ggplot2 in R
|
29 Jun, 2021
In this article, you’ll learn how to show data values on a stacked bar chart in ggplot2 in R Programming Language.
To show the data into the Stacked bar chart you have to use another parameter called geom_text().
Syntax:
geom_text(size, position = position_stack(vjust = value), colour)
Here the size represents the size of the font that will appear on the plot and position_stack() will automatically add values to the plot at their respective positions.
Example 1:
R
# Creating the DataSubject = c(rep(c("Hindi", "English", "Math", "Science", "Computer Science"), times = 4)) Year = c(rep(c("2017-18", "2018-19", "2019-20", "2020-21"), each = 5)) Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,73, 45,76,88,99,77,86,56,77) # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed) # loading the Librarylibrary(ggplot2) # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed, fill = Subject, label = Students_Passed)) +geom_bar(stat = "identity") + geom_text( size = 3, position = position_stack(vjust = 0.5))
Output:
It is also possible to change the color of data values using geom_text() itself. For this just pass the font color to the color attribute.
Example 2:
R
# Creating the DataSubject = c(rep(c("Hindi", "English", "Math", "Science", "Computer Science"), times = 4))Year = c(rep(c("2017-18", "2018-19", "2019-20", "2020-21"), each = 5))Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54, 73,45,76,88,99,77,86,56,77) # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed) # loading the Librarylibrary(ggplot2) # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed, fill = Subject, label = Students_Passed)) +geom_bar(stat = "identity") + geom_text( size = 5, position = position_stack(vjust = 0.5),colour = "white")
Output
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "In this article, you’ll learn how to show data values on a stacked bar chart in ggplot2 in R Programming Language. "
},
{
"code": null,
"e": 242,
"s": 144,
"text": "To show the data into the Stacked bar chart you have to use another parameter called geom_text()."
},
{
"code": null,
"e": 250,
"s": 242,
"text": "Syntax:"
},
{
"code": null,
"e": 317,
"s": 250,
"text": " geom_text(size, position = position_stack(vjust = value), colour)"
},
{
"code": null,
"e": 486,
"s": 317,
"text": "Here the size represents the size of the font that will appear on the plot and position_stack() will automatically add values to the plot at their respective positions."
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Example 1:"
},
{
"code": null,
"e": 499,
"s": 497,
"text": "R"
},
{
"code": "# Creating the DataSubject = c(rep(c(\"Hindi\", \"English\", \"Math\", \"Science\", \"Computer Science\"), times = 4)) Year = c(rep(c(\"2017-18\", \"2018-19\", \"2019-20\", \"2020-21\"), each = 5)) Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54,73, 45,76,88,99,77,86,56,77) # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed) # loading the Librarylibrary(ggplot2) # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed, fill = Subject, label = Students_Passed)) +geom_bar(stat = \"identity\") + geom_text( size = 3, position = position_stack(vjust = 0.5)) ",
"e": 1193,
"s": 499,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Output:"
},
{
"code": null,
"e": 1340,
"s": 1201,
"text": "It is also possible to change the color of data values using geom_text() itself. For this just pass the font color to the color attribute."
},
{
"code": null,
"e": 1351,
"s": 1340,
"text": "Example 2:"
},
{
"code": null,
"e": 1353,
"s": 1351,
"text": "R"
},
{
"code": "# Creating the DataSubject = c(rep(c(\"Hindi\", \"English\", \"Math\", \"Science\", \"Computer Science\"), times = 4))Year = c(rep(c(\"2017-18\", \"2018-19\", \"2019-20\", \"2020-21\"), each = 5))Students_Passed = c(67,34,23,66,76,66,90,43,45,78,54, 73,45,76,88,99,77,86,56,77) # Passing the Data to DataFrameStudents_Data = data.frame(Subject,Year,Students_Passed) # loading the Librarylibrary(ggplot2) # Plotting the Data in ggplot2ggplot(Students_Data, aes(x = Year, y = Students_Passed, fill = Subject, label = Students_Passed)) +geom_bar(stat = \"identity\") + geom_text( size = 5, position = position_stack(vjust = 0.5),colour = \"white\") ",
"e": 2060,
"s": 1353,
"text": null
},
{
"code": null,
"e": 2067,
"s": 2060,
"text": "Output"
},
{
"code": null,
"e": 2074,
"s": 2067,
"text": "Picked"
},
{
"code": null,
"e": 2083,
"s": 2074,
"text": "R-ggplot"
},
{
"code": null,
"e": 2094,
"s": 2083,
"text": "R Language"
},
{
"code": null,
"e": 2192,
"s": 2094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2244,
"s": 2192,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 2296,
"s": 2244,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2354,
"s": 2296,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2386,
"s": 2354,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 2421,
"s": 2386,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2465,
"s": 2421,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 2503,
"s": 2465,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2552,
"s": 2503,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2569,
"s": 2552,
"text": "R - if statement"
}
] |
Print path from a node to root of given Complete Binary Tree
|
11 Jun, 2021
Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form:
The Binary Tree is a Complete Binary Tree up to the level of the Nth node.
The nodes are numbered 1 to N, starting from the root as 1.
The structure of the Tree is as follows:
1
/ \
2 3
/ \ / \
4 5 6 7
................
/ \ ............
N - 1 N ............
Examples:
Input: N = 7Output: 7 3 1Explanation: The path from the node 7 to root is 7 -> 3 -> 1.
Input: N = 11Output: 11 5 2 1Explanation: The path from node 11 to root is 11 -> 5 -> 2 -> 1.
Naive Approach: The simplest approach to solve the problem is to perform DFS from the given node until the root node is encountered and print the path.
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the structure of the given Binary Tree. It can be observed that for every N, its parent node will be N / 2. Therefore, repeatedly print the current value of N and update N to N / 2 until N is equal to 1, i.e. root node is reached.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <iostream>using namespace std; // Function to print the path// from node to rootvoid path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node cout << node << ' '; // Move to parent of // the current node node /= 2; }} // Driver Codeint main(){ int N = 7; path_to_root(N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to print the path// from node to rootstatic void path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node System.out.print(node + " "); // Move to parent of // the current node node /= 2; }} // Driver Codepublic static void main(String[] args){ int N = 7; path_to_root(N);}} // This code is contributed by shivanisinghss2110
# Python3 program for the above approach # Function to print the path# from node to rootdef path_to_root(node): # Iterate until root is reached while (node >= 1): # Print the value of # the current node print(node, end = " ") # Move to parent of # the current node node //= 2 # Driver Codeif __name__ == '__main__': N = 7 path_to_root(N) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to print the path// from node to rootstatic void path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node Console.Write(node + " "); // Move to parent of // the current node node /= 2; }} // Driver Codepublic static void Main(String[] args){ int N = 7; path_to_root(N);}} // This code is contributed by shivanisinghss2110
<script> // Javascript program for the above approach // Function to print the path// from node to rootfunction path_to_root(node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node document.write(node + " "); // Move to parent of // the current node node = parseInt(node / 2, 10); }} // Driver codelet N = 7; path_to_root(N); // This code is contributed by divyeshrabadiya07 </script>
7 3 1
Time Complexity: O(log2(N))Auxiliary Space: O(1)
mohit kumar 29
shivanisinghss2110
nidhi_biet
divyeshrabadiya07
DFS
interview-preparation
Numbers
Greedy
Mathematical
Tree
Greedy
Mathematical
DFS
Numbers
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Operators in C / C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 173,
"s": 54,
"text": "Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form:"
},
{
"code": null,
"e": 248,
"s": 173,
"text": "The Binary Tree is a Complete Binary Tree up to the level of the Nth node."
},
{
"code": null,
"e": 308,
"s": 248,
"text": "The nodes are numbered 1 to N, starting from the root as 1."
},
{
"code": null,
"e": 351,
"s": 308,
"text": "The structure of the Tree is as follows: "
},
{
"code": null,
"e": 527,
"s": 351,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n ................\n / \\ ............\n N - 1 N ............"
},
{
"code": null,
"e": 537,
"s": 527,
"text": "Examples:"
},
{
"code": null,
"e": 624,
"s": 537,
"text": "Input: N = 7Output: 7 3 1Explanation: The path from the node 7 to root is 7 -> 3 -> 1."
},
{
"code": null,
"e": 718,
"s": 624,
"text": "Input: N = 11Output: 11 5 2 1Explanation: The path from node 11 to root is 11 -> 5 -> 2 -> 1."
},
{
"code": null,
"e": 870,
"s": 718,
"text": "Naive Approach: The simplest approach to solve the problem is to perform DFS from the given node until the root node is encountered and print the path."
},
{
"code": null,
"e": 913,
"s": 870,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1210,
"s": 913,
"text": "Efficient Approach: The above approach can be optimized based on the structure of the given Binary Tree. It can be observed that for every N, its parent node will be N / 2. Therefore, repeatedly print the current value of N and update N to N / 2 until N is equal to 1, i.e. root node is reached. "
},
{
"code": null,
"e": 1261,
"s": 1210,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1265,
"s": 1261,
"text": "C++"
},
{
"code": null,
"e": 1270,
"s": 1265,
"text": "Java"
},
{
"code": null,
"e": 1278,
"s": 1270,
"text": "Python3"
},
{
"code": null,
"e": 1281,
"s": 1278,
"text": "C#"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to print the path// from node to rootvoid path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node cout << node << ' '; // Move to parent of // the current node node /= 2; }} // Driver Codeint main(){ int N = 7; path_to_root(N); return 0;}",
"e": 1747,
"s": 1292,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to print the path// from node to rootstatic void path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node System.out.print(node + \" \"); // Move to parent of // the current node node /= 2; }} // Driver Codepublic static void main(String[] args){ int N = 7; path_to_root(N);}} // This code is contributed by shivanisinghss2110",
"e": 2296,
"s": 1747,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to print the path# from node to rootdef path_to_root(node): # Iterate until root is reached while (node >= 1): # Print the value of # the current node print(node, end = \" \") # Move to parent of # the current node node //= 2 # Driver Codeif __name__ == '__main__': N = 7 path_to_root(N) # This code is contributed by mohit kumar 29",
"e": 2742,
"s": 2296,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to print the path// from node to rootstatic void path_to_root(int node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node Console.Write(node + \" \"); // Move to parent of // the current node node /= 2; }} // Driver Codepublic static void Main(String[] args){ int N = 7; path_to_root(N);}} // This code is contributed by shivanisinghss2110",
"e": 3276,
"s": 2742,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to print the path// from node to rootfunction path_to_root(node){ // Iterate until root is reached while (node >= 1) { // Print the value of // the current node document.write(node + \" \"); // Move to parent of // the current node node = parseInt(node / 2, 10); }} // Driver codelet N = 7; path_to_root(N); // This code is contributed by divyeshrabadiya07 </script>",
"e": 3776,
"s": 3276,
"text": null
},
{
"code": null,
"e": 3782,
"s": 3776,
"text": "7 3 1"
},
{
"code": null,
"e": 3833,
"s": 3784,
"text": "Time Complexity: O(log2(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3848,
"s": 3833,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 3867,
"s": 3848,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 3878,
"s": 3867,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3896,
"s": 3878,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 3900,
"s": 3896,
"text": "DFS"
},
{
"code": null,
"e": 3922,
"s": 3900,
"text": "interview-preparation"
},
{
"code": null,
"e": 3930,
"s": 3922,
"text": "Numbers"
},
{
"code": null,
"e": 3937,
"s": 3930,
"text": "Greedy"
},
{
"code": null,
"e": 3950,
"s": 3937,
"text": "Mathematical"
},
{
"code": null,
"e": 3955,
"s": 3950,
"text": "Tree"
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": "Greedy"
},
{
"code": null,
"e": 3975,
"s": 3962,
"text": "Mathematical"
},
{
"code": null,
"e": 3979,
"s": 3975,
"text": "DFS"
},
{
"code": null,
"e": 3987,
"s": 3979,
"text": "Numbers"
},
{
"code": null,
"e": 3992,
"s": 3987,
"text": "Tree"
},
{
"code": null,
"e": 4090,
"s": 3992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4114,
"s": 4090,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 4171,
"s": 4114,
"text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)"
},
{
"code": null,
"e": 4266,
"s": 4171,
"text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements"
},
{
"code": null,
"e": 4354,
"s": 4266,
"text": "Minimize Cash Flow among a given set of friends who have borrowed money from each other"
},
{
"code": null,
"e": 4435,
"s": 4354,
"text": "Minimum time taken by each job to be completed given by a Directed Acyclic Graph"
},
{
"code": null,
"e": 4465,
"s": 4435,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4508,
"s": 4465,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4523,
"s": 4508,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4547,
"s": 4523,
"text": "Merge two sorted arrays"
}
] |
Delete rows and columns of NumPy ndarray
|
21 Apr, 2021
In this article, we will discuss how to delete the specified rows and columns in an n-dimensional array. We are going to delete the rows and columns using numpy.delete() method.
Syntax: numpy.delete(array_name, obj, axis=None)
Let’s discuss with the help of some examples:
Example 1:
Program to create a 2-dimensional array (3 rows and 4 columns) with NumPy and delete the specified row.
Python3
# importing numpy moduleimport numpy as np # create an array with integers# with 3 rows and 4 columnsa = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])print(a) # delete 0 th rowdata = np.delete(a, 0, 0)print("data after 0 th row deleted :", data) # delete 1 st rowdata = np.delete(a, 1, 0)print("data after 1 st row deleted :", data) # delete 2 nd rowdata = np.delete(a, 2, 0)print("data after 2 nd row deleted :", data)
Output:
Example 2:
Program to create a 2-dimensional array (6 rows and 2 columns) with NumPy and delete the specified columns.
Python3
# importing numpy moduleimport numpy as np # create an array with integers with# 6 rows and 2 columnsa = np.array([[1, 2], [5, 6], [9, 10, ], [78, 90], [4, 89], [56, 43]])print(a) # delete 0 th columndata = np.delete(a, 0, 1)print("data after 0 th column deleted :", data) # delete 1 st columndata = np.delete(a, 1, 1)print("data after 1 st column deleted :", data)
Output:
Example 3:
Delete both 1 row and 1 column.
Python3
# importing numpy moduleimport numpy as np # create an array with integers# with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print("Original\n", a) # delete 1 st rowdata = np.delete(a, 0, 0)print("data after 1 st row deleted :\n", data) # delete 1 st columndata = np.delete(a, 0, 1)print("data after 1 st column deleted :\n", data)
Output:
Example 4:
We can delete n number of rows at a time by passing row numbers as a list in the obj argument.
Syntax: numpy.delete(array_name, [row1,row2,.row n], axis=None)
Python3
# importing numpy moduleimport numpy as np # create an array with integers # with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print("Original\n", a) # delete 1 st row and 2 nd # row at a timedata = np.delete(a, [0, 1], 0)print("data after 1 st and 2 ns row deleted :\n", data)
Output:
Example 5:
We can delete n number of columns at a time by passing column numbers as a list in the obj argument.
Syntax: numpy.delete(array_name, [column number1,column number2,.column number n], axis=None)
Python3
# importing numpy moduleimport numpy as np # create an array with integers # with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print("Original\n", a) # delete 1 st column and 3 rd # column at a timedata = np.delete(a, [0, 2], 1)print("data after 1 st and 3 rd column deleted :\n", data)
Output:
Picked
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "In this article, we will discuss how to delete the specified rows and columns in an n-dimensional array. We are going to delete the rows and columns using numpy.delete() method."
},
{
"code": null,
"e": 255,
"s": 206,
"text": "Syntax: numpy.delete(array_name, obj, axis=None)"
},
{
"code": null,
"e": 301,
"s": 255,
"text": "Let’s discuss with the help of some examples:"
},
{
"code": null,
"e": 312,
"s": 301,
"text": "Example 1:"
},
{
"code": null,
"e": 416,
"s": 312,
"text": "Program to create a 2-dimensional array (3 rows and 4 columns) with NumPy and delete the specified row."
},
{
"code": null,
"e": 424,
"s": 416,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with integers# with 3 rows and 4 columnsa = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])print(a) # delete 0 th rowdata = np.delete(a, 0, 0)print(\"data after 0 th row deleted :\", data) # delete 1 st rowdata = np.delete(a, 1, 0)print(\"data after 1 st row deleted :\", data) # delete 2 nd rowdata = np.delete(a, 2, 0)print(\"data after 2 nd row deleted :\", data)",
"e": 890,
"s": 424,
"text": null
},
{
"code": null,
"e": 898,
"s": 890,
"text": "Output:"
},
{
"code": null,
"e": 909,
"s": 898,
"text": "Example 2:"
},
{
"code": null,
"e": 1017,
"s": 909,
"text": "Program to create a 2-dimensional array (6 rows and 2 columns) with NumPy and delete the specified columns."
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with integers with# 6 rows and 2 columnsa = np.array([[1, 2], [5, 6], [9, 10, ], [78, 90], [4, 89], [56, 43]])print(a) # delete 0 th columndata = np.delete(a, 0, 1)print(\"data after 0 th column deleted :\", data) # delete 1 st columndata = np.delete(a, 1, 1)print(\"data after 1 st column deleted :\", data)",
"e": 1413,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1413,
"text": "Output:"
},
{
"code": null,
"e": 1432,
"s": 1421,
"text": "Example 3:"
},
{
"code": null,
"e": 1464,
"s": 1432,
"text": "Delete both 1 row and 1 column."
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with integers# with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print(\"Original\\n\", a) # delete 1 st rowdata = np.delete(a, 0, 0)print(\"data after 1 st row deleted :\\n\", data) # delete 1 st columndata = np.delete(a, 0, 1)print(\"data after 1 st column deleted :\\n\", data)",
"e": 1870,
"s": 1472,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1870,
"text": "Output:"
},
{
"code": null,
"e": 1889,
"s": 1878,
"text": "Example 4:"
},
{
"code": null,
"e": 1984,
"s": 1889,
"text": "We can delete n number of rows at a time by passing row numbers as a list in the obj argument."
},
{
"code": null,
"e": 2048,
"s": 1984,
"text": "Syntax: numpy.delete(array_name, [row1,row2,.row n], axis=None)"
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with integers # with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print(\"Original\\n\", a) # delete 1 st row and 2 nd # row at a timedata = np.delete(a, [0, 1], 0)print(\"data after 1 st and 2 ns row deleted :\\n\", data)",
"e": 2394,
"s": 2056,
"text": null
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Output:"
},
{
"code": null,
"e": 2413,
"s": 2402,
"text": "Example 5:"
},
{
"code": null,
"e": 2514,
"s": 2413,
"text": "We can delete n number of columns at a time by passing column numbers as a list in the obj argument."
},
{
"code": null,
"e": 2608,
"s": 2514,
"text": "Syntax: numpy.delete(array_name, [column number1,column number2,.column number n], axis=None)"
},
{
"code": null,
"e": 2616,
"s": 2608,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # create an array with integers # with 3 rows and 3 columnsa = np.array([[67, 65, 45], [45, 67, 43], [3, 4, 5]])print(\"Original\\n\", a) # delete 1 st column and 3 rd # column at a timedata = np.delete(a, [0, 2], 1)print(\"data after 1 st and 3 rd column deleted :\\n\", data)",
"e": 2964,
"s": 2616,
"text": null
},
{
"code": null,
"e": 2972,
"s": 2964,
"text": "Output:"
},
{
"code": null,
"e": 2979,
"s": 2972,
"text": "Picked"
},
{
"code": null,
"e": 3000,
"s": 2979,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 3013,
"s": 3000,
"text": "Python-numpy"
},
{
"code": null,
"e": 3020,
"s": 3013,
"text": "Python"
},
{
"code": null,
"e": 3118,
"s": 3020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3150,
"s": 3118,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3177,
"s": 3150,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3198,
"s": 3177,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3221,
"s": 3198,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3277,
"s": 3221,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3308,
"s": 3277,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3350,
"s": 3308,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3392,
"s": 3350,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3431,
"s": 3392,
"text": "Python | Get unique values from a list"
}
] |
Inorder Successor of a node in Binary Tree
|
21 Jun, 2022
Given a binary tree and a node, we need to write a program to find inorder successor of this node.Inorder Successor of a node in binary tree is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal.
In the above diagram, inorder successor of node 4 is 2 and node 5 is 1.
We have already discussed how to find the inorder successor of a node in Binary Search Tree. We can not use the same approach to find the inorder successor in general Binary trees.
We need to take care of 3 cases for any node to find its inorder successor as described below:
Right child of node is not NULL. If the right child of the node is not NULL then the inorder successor of this node will be the leftmost node in it’s right subtree.Right Child of the node is NULL. If the right child of node is NULL. Then we keep finding the parent of the given node x, say p such that p->left = x. For example in the above given tree, inorder successor of node 5 will be 1. First parent of 5 is 2 but 2->left != 5. So next parent of 2 is 1, now 1->left = 2. Therefore, inorder successor of 5 is 1. Below is the algorithm for this case: Suppose the given node is x. Start traversing the tree from root node to find x recursively.If root == x, stop recursion otherwise find x recursively for left and right subtrees.Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going upIf node is the rightmost node. If the node is the rightmost node in the given tree. For example, in the above tree node 6 is the right most node. In this case, there will be no inorder successor of this node. i.e. Inorder Successor of the rightmost node in a tree is NULL.
Right child of node is not NULL. If the right child of the node is not NULL then the inorder successor of this node will be the leftmost node in it’s right subtree.
Right Child of the node is NULL. If the right child of node is NULL. Then we keep finding the parent of the given node x, say p such that p->left = x. For example in the above given tree, inorder successor of node 5 will be 1. First parent of 5 is 2 but 2->left != 5. So next parent of 2 is 1, now 1->left = 2. Therefore, inorder successor of 5 is 1. Below is the algorithm for this case: Suppose the given node is x. Start traversing the tree from root node to find x recursively.If root == x, stop recursion otherwise find x recursively for left and right subtrees.Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going up
Suppose the given node is x. Start traversing the tree from root node to find x recursively.
If root == x, stop recursion otherwise find x recursively for left and right subtrees.
Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going up
If node is the rightmost node. If the node is the rightmost node in the given tree. For example, in the above tree node 6 is the right most node. In this case, there will be no inorder successor of this node. i.e. Inorder Successor of the rightmost node in a tree is NULL.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find inorder successor of a node#include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Temporary node for case 2Node* temp = new Node; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to find left most node in a treeNode* leftMostNode(Node* node){ while (node != NULL && node->left != NULL) node = node->left; return node;} // function to find right most node in a treeNode* rightMostNode(Node* node){ while (node != NULL && node->right != NULL) node = node->right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is NULLNode* findInorderRecursive(Node* root, Node* x ){ if (!root) return NULL; if (root==x || (temp = findInorderRecursive(root->left,x)) || (temp = findInorderRecursive(root->right,x))) { if (temp) { if (root->left == temp) { cout << "Inorder Successor of " << x->data; cout << " is "<< root->data << "\n"; return NULL; } } return root; } return NULL;} // function to find inorder successor of// a nodevoid inorderSuccessor(Node* root, Node* x){ // Case1: If right child is not NULL if (x->right != NULL) { Node* inorderSucc = leftMostNode(x->right); cout<<"Inorder Successor of "<<x->data<<" is "; cout<<inorderSucc->data<<"\n"; } // Case2: If right child is NULL if (x->right == NULL) { Node* rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) cout << "No inorder successor! Right most node.\n"; else findInorderRecursive(root, x); }} // Driver program to test above functionsint main(){ // Let's construct the binary tree // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); // Case 1 : When there is a right child // eg: Node(1) has a right child ergo the inorder successor would be leftmost // node of the right subtree ie 6. inorderSuccessor(root, root); // case 2: When the right child is NULL // eg: From the above figure Node(5) satisfies this case inorderSuccessor(root, root->left->left); // case 3: When the node is the rightmost node of the binary tree inorderSuccessor(root, root->right->right); return 0;}
// Java program to find inorder successor of a nodeclass Solution{// A Binary Tree Node static class Node{ int data; Node left, right;} // Temporary node for case 2static Node temp = new Node(); // Utility function to create a new tree nodestatic Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // function to find left most node in a treestatic Node leftMostNode(Node node) { while (node != null && node.left != null) node = node.left; return node;} // function to find right most node in a treestatic Node rightMostNode(Node node) { while (node != null && node.right != null) node = node.right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is nullstatic Node findInorderRecursive(Node root, Node x ) { if (root==null) return null; if (root==x || (temp = findInorderRecursive(root.left,x))!=null || (temp = findInorderRecursive(root.right,x))!=null) { if (temp!=null) { if (root.left == temp) { System.out.print( "Inorder Successor of "+x.data); System.out.print( " is "+ root.data + "\n"); return null; } } return root; } return null;} // function to find inorder successor of// a nodestatic void inorderSuccessor(Node root, Node x) { // Case1: If right child is not null if (x.right != null) { Node inorderSucc = leftMostNode(x.right); System.out.print("Inorder Successor of "+x.data+" is "); System.out.print(inorderSucc.data+"\n"); } // Case2: If right child is null if (x.right == null) { int f = 0; Node rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) System.out.print("No inorder successor! Right most node.\n"); else findInorderRecursive(root, x); }} // Driver program to test above functionspublic static void main(String args[]){ // Let's construct the binary tree // as shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); // Case 1 inorderSuccessor(root, root.right); // case 2 inorderSuccessor(root, root.left.left); // case 3 inorderSuccessor(root, root.right.right); }}//contributed by Arnab Kundu
""" Python3 code for inorder successorand predecessor of tree """ # A Binary Tree Node# Utility function to create a new tree nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function to find left most node in a treedef leftMostNode(node): while (node != None and node.left != None): node = node.left return node # function to find right most node in a treedef rightMostNode(node): while (node != None and node.right != None): node = node.right return node # recursive function to find the Inorder Successor# when the right child of node x is Nonedef findInorderRecursive(root, x ): if (not root): return None if (root == x or (findInorderRecursive(root.left, x)) or (findInorderRecursive(root.right, x))): if findInorderRecursive(root.right, x): temp=findInorderRecursive(root.right, x) else: temp=findInorderRecursive(root.left, x) if (temp): if (root.left == temp): print("Inorder Successor of", x.data, end = "") print(" is", root.data) return None return root return None # function to find inorder successor# of a nodedef inorderSuccessor(root, x): # Case1: If right child is not None if (x.right != None) : inorderSucc = leftMostNode(x.right) print("Inorder Successor of", x.data, "is", end = " ") print(inorderSucc.data) # Case2: If right child is None if (x.right == None): f = 0 rightMost = rightMostNode(root) # case3: If x is the right most node if (rightMost == x): print("No inorder successor!", "Right most node.") else: findInorderRecursive(root, x) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) # Case 1 inorderSuccessor(root, root.right) # case 2 inorderSuccessor(root, root.left.left) # case 3 inorderSuccessor(root, root.right.right) # This code is contributed# by SHUBHAMSINGH10
// C# program to find inorder// successor of a nodeusing System; class GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;} // Temporary node for case 2public static Node temp = new Node(); // Utility function to create// a new tree nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // function to find left most// node in a treepublic static Node leftMostNode(Node node){ while (node != null && node.left != null) { node = node.left; } return node;} // function to find right most// node in a treepublic static Node rightMostNode(Node node){ while (node != null && node.right != null) { node = node.right; } return node;} // recursive function to find the// Inorder Successor when the right// child of node x is nullpublic static Node findInorderRecursive(Node root, Node x){ if (root == null) { return null; } if (root == x || (temp = findInorderRecursive(root.left, x)) != null || (temp = findInorderRecursive(root.right, x)) != null) { if (temp != null) { if (root.left == temp) { Console.Write("Inorder Successor of " + x.data); Console.Write(" is " + root.data + "\n"); return null; } } return root; } return null;} // function to find inorder successor// of a nodepublic static void inorderSuccessor(Node root, Node x){ // Case1: If right child is not null if (x.right != null) { Node inorderSucc = leftMostNode(x.right); Console.Write("Inorder Successor of " + x.data + " is "); Console.Write(inorderSucc.data + "\n"); } // Case2: If right child is null if (x.right == null) { int f = 0; Node rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) { Console.Write("No inorder successor! " + "Right most node.\n"); } else { findInorderRecursive(root, x); } }} // Driver Codepublic static void Main(string[] args){ // Let's construct the binary tree // as shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); // Case 1 inorderSuccessor(root, root.right); // case 2 inorderSuccessor(root, root.left.left); // case 3 inorderSuccessor(root, root.right.right);}} // This code is contributed by Shrikant13
<script>// Javascript program to find inorder successor of a node // A Binary Tree Nodeclass Node{ constructor(data) { this.data=data; this.left=this.right=null; }} // Temporary node for case 2let temp = new Node(); // function to find left most node in a treefunction leftMostNode(node){ while (node != null && node.left != null) node = node.left; return node;} // function to find right most node in a tree function rightMostNode(node){ while (node != null && node.right != null) node = node.right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is nullfunction findInorderRecursive(root,x){ if (root==null) return null; if (root==x || (temp = findInorderRecursive(root.left,x))!=null || (temp = findInorderRecursive(root.right,x))!=null) { if (temp!=null) { if (root.left == temp) { document.write( "Inorder Successor of "+x.data); document.write( " is "+ root.data + "<br>"); return null; } } return root; } return null;} // function to find inorder successor of// a nodefunction inorderSuccessor(root,x){ // Case1: If right child is not null if (x.right != null) { let inorderSucc = leftMostNode(x.right); document.write("Inorder Successor of "+x.data+" is "); document.write(inorderSucc.data+"<br>"); } // Case2: If right child is null if (x.right == null) { let f = 0; let rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) document.write("No inorder successor! Right most node.\n"); else findInorderRecursive(root, x); }} // Driver program to test above functions// Let's construct the binary tree// as shown in above diagram let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); // Case 1inorderSuccessor(root, root.right); // case 2inorderSuccessor(root, root.left.left); // case 3inorderSuccessor(root, root.right.right); // This code is contributed by avanitrachhadiya2155</script>
Output:
Inorder Successor of 1 is 6
Inorder Successor of 4 is 2
No inorder successor! Right most node.
Another approach: We will do a reverse inorder traversal and keep the track of current visited node. Once we found the element, last tracked element would be our answer.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to find inorder successor.#include<bits/stdc++.h>using namespace std; // structure of a Binary Node.struct Node{ int data; Node* left; Node* right;}; // Function to create a new Node.Node* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp;} // function that prints the inorder successor// of a target node. next will point the last// tracked node, which will be the answer.void inorderSuccessor(Node* root, Node* target_node, Node* &next){ // if root is null then return if(!root) return; inorderSuccessor(root->right, target_node, next); // if target node found then enter this condition if(root->data == target_node->data) { // this will be true to the last node // in inorder traversal i.e., rightmost node. if(next == NULL) cout << "inorder successor of " << root->data << " is: null\n"; else cout << "inorder successor of " << root->data << " is: " << next->data << "\n"; } next = root; inorderSuccessor(root->left, target_node, next);} // Driver Codeint main(){ // Let's construct the binary tree // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); // Case 1 Node* next = NULL; inorderSuccessor(root, root, next); // case 2 next = NULL; inorderSuccessor(root, root->left->left, next); // case 3 next = NULL; inorderSuccessor(root, root->right->right, next); return 0;} // This code is contributed by AASTHA VARMA
// Java program to find inorder successor of a node. class Node { int data; Node left, right; Node(int data) { this.data = data; left = null; right = null; }} // class to find inorder successor of// a nodeclass InorderSuccessor { Node root; // to change previous node static class PreviousNode { Node pNode; PreviousNode() { pNode = null; } } // function to find inorder successor of // a node private void inOrderSuccessorOfBinaryTree(Node root, PreviousNode pre, int searchNode) { // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) System.out.println("inorder successor of " + searchNode + " is: " + (pre.pNode != null ? pre.pNode.data : "null")); pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode); } // Driver program to test above functions public static void main(String[] args) { InorderSuccessor tree = new InorderSuccessor(); // Let's construct the binary tree // as shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); // Case 1 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 3); // Case 2 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 4); // Case 3 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 6); }}// This code is contributed by Ashish Goyal.
# Python3 program to find inorder successor. # A Binary Tree Node# Utility function to create a new tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new Node.def newNode(val): temp = Node(0) temp.data = val temp.left = None temp.right = None return temp # function that prints the inorder successor# of a target node. next will point the last# tracked node, which will be the answer.def inorderSuccessor(root, target_node): global next # if root is None then return if(root == None): return inorderSuccessor(root.right, target_node) # if target node found, then # enter this condition if(root.data == target_node.data): # this will be true to the last node # in inorder traversal i.e., rightmost node. if(next == None): print ("inorder successor of", root.data , " is: None") else: print ( "inorder successor of", root.data , "is:", next.data) next = root inorderSuccessor(root.left, target_node) # global variablenext = None # Driver Codeif __name__ == '__main__': # Let's construct the binary tree # as shown in above diagram. root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) # Case 1 next = None inorderSuccessor(root, root.right) # case 2 next = None inorderSuccessor(root, root.left.left) # case 3 next = None inorderSuccessor(root, root.right.right) # This code is contributed by Arnab Kundu
// C# program to find inorder successor of a node.using System; class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; }} // class to find inorder successor of// a nodepublic class InorderSuccessor{ Node root; // to change previous node class PreviousNode { public Node pNode; public PreviousNode() { pNode = null; } } // function to find inorder successor of // a node private void inOrderSuccessorOfBinaryTree(Node root, PreviousNode pre, int searchNode) { // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) { Console.Write("inorder successor of " + searchNode + " is: "); if(pre.pNode != null) Console.WriteLine(pre.pNode.data); else Console.WriteLine("null"); } pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode); } // Driver code public static void Main(String[] args) { InorderSuccessor tree = new InorderSuccessor(); // Let's construct the binary tree // as shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); // Case 1 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 3); // Case 2 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 4); // Case 3 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 6); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find inorder successor of a node. class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // class to find inorder successor of// a nodevar root = null; // to change previous nodeclass PreviousNode{ constructor() { this.pNode = null; }} // function to find inorder successor of// a nodefunction inOrderSuccessorOfBinaryTree(root, pre, searchNode){ // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) { document.write("inorder successor of " + searchNode + " is: "); if(pre.pNode != null) document.write(pre.pNode.data+"<br>"); else document.write("null<br>"); } pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode);} // Driver code // Let's construct the binary tree// as shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); // Case 1inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 3); // Case 2inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 4); // Case 3inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 6); </script>
Output:
inorder successor of 1 is: 6
inorder successor of 4 is: 2
inorder successor of 7 is: null
Time Complexity: O( n ), where n is the number of nodes in the tree.
Space complexity: O(n) for call stack
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.
ashishfk
andrew1234
shrikanth13
princiraj1992
SHUBHAMSINGH10
AASTHA VARMA
rrrtnx
pranav7kaushik
sagartomar9927
avanitrachhadiya2155
simmytarika5
noviced3vq6
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Sorted Array to Balanced BST
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 317,
"s": 52,
"text": "Given a binary tree and a node, we need to write a program to find inorder successor of this node.Inorder Successor of a node in binary tree is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal."
},
{
"code": null,
"e": 389,
"s": 317,
"text": "In the above diagram, inorder successor of node 4 is 2 and node 5 is 1."
},
{
"code": null,
"e": 570,
"s": 389,
"text": "We have already discussed how to find the inorder successor of a node in Binary Search Tree. We can not use the same approach to find the inorder successor in general Binary trees."
},
{
"code": null,
"e": 667,
"s": 570,
"text": "We need to take care of 3 cases for any node to find its inorder successor as described below: "
},
{
"code": null,
"e": 1982,
"s": 667,
"text": "Right child of node is not NULL. If the right child of the node is not NULL then the inorder successor of this node will be the leftmost node in it’s right subtree.Right Child of the node is NULL. If the right child of node is NULL. Then we keep finding the parent of the given node x, say p such that p->left = x. For example in the above given tree, inorder successor of node 5 will be 1. First parent of 5 is 2 but 2->left != 5. So next parent of 2 is 1, now 1->left = 2. Therefore, inorder successor of 5 is 1. Below is the algorithm for this case: Suppose the given node is x. Start traversing the tree from root node to find x recursively.If root == x, stop recursion otherwise find x recursively for left and right subtrees.Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going upIf node is the rightmost node. If the node is the rightmost node in the given tree. For example, in the above tree node 6 is the right most node. In this case, there will be no inorder successor of this node. i.e. Inorder Successor of the rightmost node in a tree is NULL."
},
{
"code": null,
"e": 2147,
"s": 1982,
"text": "Right child of node is not NULL. If the right child of the node is not NULL then the inorder successor of this node will be the leftmost node in it’s right subtree."
},
{
"code": null,
"e": 3026,
"s": 2147,
"text": "Right Child of the node is NULL. If the right child of node is NULL. Then we keep finding the parent of the given node x, say p such that p->left = x. For example in the above given tree, inorder successor of node 5 will be 1. First parent of 5 is 2 but 2->left != 5. So next parent of 2 is 1, now 1->left = 2. Therefore, inorder successor of 5 is 1. Below is the algorithm for this case: Suppose the given node is x. Start traversing the tree from root node to find x recursively.If root == x, stop recursion otherwise find x recursively for left and right subtrees.Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going up"
},
{
"code": null,
"e": 3119,
"s": 3026,
"text": "Suppose the given node is x. Start traversing the tree from root node to find x recursively."
},
{
"code": null,
"e": 3206,
"s": 3119,
"text": "If root == x, stop recursion otherwise find x recursively for left and right subtrees."
},
{
"code": null,
"e": 3518,
"s": 3206,
"text": "Now after finding the node x, recursion will backtrack to the root. Every recursive call will return the node itself to the calling function, we will store this in a temporary node say temp.Now, when it backtracked to its parent which will be root now, check whether root.left = temp, if not , keep going up"
},
{
"code": null,
"e": 3791,
"s": 3518,
"text": "If node is the rightmost node. If the node is the rightmost node in the given tree. For example, in the above tree node 6 is the right most node. In this case, there will be no inorder successor of this node. i.e. Inorder Successor of the rightmost node in a tree is NULL."
},
{
"code": null,
"e": 3840,
"s": 3791,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 3844,
"s": 3840,
"text": "C++"
},
{
"code": null,
"e": 3849,
"s": 3844,
"text": "Java"
},
{
"code": null,
"e": 3857,
"s": 3849,
"text": "Python3"
},
{
"code": null,
"e": 3860,
"s": 3857,
"text": "C#"
},
{
"code": null,
"e": 3871,
"s": 3860,
"text": "Javascript"
},
{
"code": "// CPP program to find inorder successor of a node#include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Temporary node for case 2Node* temp = new Node; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to find left most node in a treeNode* leftMostNode(Node* node){ while (node != NULL && node->left != NULL) node = node->left; return node;} // function to find right most node in a treeNode* rightMostNode(Node* node){ while (node != NULL && node->right != NULL) node = node->right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is NULLNode* findInorderRecursive(Node* root, Node* x ){ if (!root) return NULL; if (root==x || (temp = findInorderRecursive(root->left,x)) || (temp = findInorderRecursive(root->right,x))) { if (temp) { if (root->left == temp) { cout << \"Inorder Successor of \" << x->data; cout << \" is \"<< root->data << \"\\n\"; return NULL; } } return root; } return NULL;} // function to find inorder successor of// a nodevoid inorderSuccessor(Node* root, Node* x){ // Case1: If right child is not NULL if (x->right != NULL) { Node* inorderSucc = leftMostNode(x->right); cout<<\"Inorder Successor of \"<<x->data<<\" is \"; cout<<inorderSucc->data<<\"\\n\"; } // Case2: If right child is NULL if (x->right == NULL) { Node* rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) cout << \"No inorder successor! Right most node.\\n\"; else findInorderRecursive(root, x); }} // Driver program to test above functionsint main(){ // Let's construct the binary tree // 1 // / \\ // 2 3 // / \\ / \\ // 4 5 6 7 Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); // Case 1 : When there is a right child // eg: Node(1) has a right child ergo the inorder successor would be leftmost // node of the right subtree ie 6. inorderSuccessor(root, root); // case 2: When the right child is NULL // eg: From the above figure Node(5) satisfies this case inorderSuccessor(root, root->left->left); // case 3: When the node is the rightmost node of the binary tree inorderSuccessor(root, root->right->right); return 0;}",
"e": 6700,
"s": 3871,
"text": null
},
{
"code": "// Java program to find inorder successor of a nodeclass Solution{// A Binary Tree Node static class Node{ int data; Node left, right;} // Temporary node for case 2static Node temp = new Node(); // Utility function to create a new tree nodestatic Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // function to find left most node in a treestatic Node leftMostNode(Node node) { while (node != null && node.left != null) node = node.left; return node;} // function to find right most node in a treestatic Node rightMostNode(Node node) { while (node != null && node.right != null) node = node.right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is nullstatic Node findInorderRecursive(Node root, Node x ) { if (root==null) return null; if (root==x || (temp = findInorderRecursive(root.left,x))!=null || (temp = findInorderRecursive(root.right,x))!=null) { if (temp!=null) { if (root.left == temp) { System.out.print( \"Inorder Successor of \"+x.data); System.out.print( \" is \"+ root.data + \"\\n\"); return null; } } return root; } return null;} // function to find inorder successor of// a nodestatic void inorderSuccessor(Node root, Node x) { // Case1: If right child is not null if (x.right != null) { Node inorderSucc = leftMostNode(x.right); System.out.print(\"Inorder Successor of \"+x.data+\" is \"); System.out.print(inorderSucc.data+\"\\n\"); } // Case2: If right child is null if (x.right == null) { int f = 0; Node rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) System.out.print(\"No inorder successor! Right most node.\\n\"); else findInorderRecursive(root, x); }} // Driver program to test above functionspublic static void main(String args[]){ // Let's construct the binary tree // as shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); // Case 1 inorderSuccessor(root, root.right); // case 2 inorderSuccessor(root, root.left.left); // case 3 inorderSuccessor(root, root.right.right); }}//contributed by Arnab Kundu",
"e": 9262,
"s": 6700,
"text": null
},
{
"code": "\"\"\" Python3 code for inorder successorand predecessor of tree \"\"\" # A Binary Tree Node# Utility function to create a new tree nodeclass newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function to find left most node in a treedef leftMostNode(node): while (node != None and node.left != None): node = node.left return node # function to find right most node in a treedef rightMostNode(node): while (node != None and node.right != None): node = node.right return node # recursive function to find the Inorder Successor# when the right child of node x is Nonedef findInorderRecursive(root, x ): if (not root): return None if (root == x or (findInorderRecursive(root.left, x)) or (findInorderRecursive(root.right, x))): if findInorderRecursive(root.right, x): temp=findInorderRecursive(root.right, x) else: temp=findInorderRecursive(root.left, x) if (temp): if (root.left == temp): print(\"Inorder Successor of\", x.data, end = \"\") print(\" is\", root.data) return None return root return None # function to find inorder successor# of a nodedef inorderSuccessor(root, x): # Case1: If right child is not None if (x.right != None) : inorderSucc = leftMostNode(x.right) print(\"Inorder Successor of\", x.data, \"is\", end = \" \") print(inorderSucc.data) # Case2: If right child is None if (x.right == None): f = 0 rightMost = rightMostNode(root) # case3: If x is the right most node if (rightMost == x): print(\"No inorder successor!\", \"Right most node.\") else: findInorderRecursive(root, x) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) # Case 1 inorderSuccessor(root, root.right) # case 2 inorderSuccessor(root, root.left.left) # case 3 inorderSuccessor(root, root.right.right) # This code is contributed# by SHUBHAMSINGH10",
"e": 11642,
"s": 9262,
"text": null
},
{
"code": "// C# program to find inorder// successor of a nodeusing System; class GFG{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;} // Temporary node for case 2public static Node temp = new Node(); // Utility function to create// a new tree nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // function to find left most// node in a treepublic static Node leftMostNode(Node node){ while (node != null && node.left != null) { node = node.left; } return node;} // function to find right most// node in a treepublic static Node rightMostNode(Node node){ while (node != null && node.right != null) { node = node.right; } return node;} // recursive function to find the// Inorder Successor when the right// child of node x is nullpublic static Node findInorderRecursive(Node root, Node x){ if (root == null) { return null; } if (root == x || (temp = findInorderRecursive(root.left, x)) != null || (temp = findInorderRecursive(root.right, x)) != null) { if (temp != null) { if (root.left == temp) { Console.Write(\"Inorder Successor of \" + x.data); Console.Write(\" is \" + root.data + \"\\n\"); return null; } } return root; } return null;} // function to find inorder successor// of a nodepublic static void inorderSuccessor(Node root, Node x){ // Case1: If right child is not null if (x.right != null) { Node inorderSucc = leftMostNode(x.right); Console.Write(\"Inorder Successor of \" + x.data + \" is \"); Console.Write(inorderSucc.data + \"\\n\"); } // Case2: If right child is null if (x.right == null) { int f = 0; Node rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) { Console.Write(\"No inorder successor! \" + \"Right most node.\\n\"); } else { findInorderRecursive(root, x); } }} // Driver Codepublic static void Main(string[] args){ // Let's construct the binary tree // as shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); // Case 1 inorderSuccessor(root, root.right); // case 2 inorderSuccessor(root, root.left.left); // case 3 inorderSuccessor(root, root.right.right);}} // This code is contributed by Shrikant13",
"e": 14420,
"s": 11642,
"text": null
},
{
"code": "<script>// Javascript program to find inorder successor of a node // A Binary Tree Nodeclass Node{ constructor(data) { this.data=data; this.left=this.right=null; }} // Temporary node for case 2let temp = new Node(); // function to find left most node in a treefunction leftMostNode(node){ while (node != null && node.left != null) node = node.left; return node;} // function to find right most node in a tree function rightMostNode(node){ while (node != null && node.right != null) node = node.right; return node;} // recursive function to find the Inorder Successor// when the right child of node x is nullfunction findInorderRecursive(root,x){ if (root==null) return null; if (root==x || (temp = findInorderRecursive(root.left,x))!=null || (temp = findInorderRecursive(root.right,x))!=null) { if (temp!=null) { if (root.left == temp) { document.write( \"Inorder Successor of \"+x.data); document.write( \" is \"+ root.data + \"<br>\"); return null; } } return root; } return null;} // function to find inorder successor of// a nodefunction inorderSuccessor(root,x){ // Case1: If right child is not null if (x.right != null) { let inorderSucc = leftMostNode(x.right); document.write(\"Inorder Successor of \"+x.data+\" is \"); document.write(inorderSucc.data+\"<br>\"); } // Case2: If right child is null if (x.right == null) { let f = 0; let rightMost = rightMostNode(root); // case3: If x is the right most node if (rightMost == x) document.write(\"No inorder successor! Right most node.\\n\"); else findInorderRecursive(root, x); }} // Driver program to test above functions// Let's construct the binary tree// as shown in above diagram let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); // Case 1inorderSuccessor(root, root.right); // case 2inorderSuccessor(root, root.left.left); // case 3inorderSuccessor(root, root.right.right); // This code is contributed by avanitrachhadiya2155</script>",
"e": 16737,
"s": 14420,
"text": null
},
{
"code": null,
"e": 16746,
"s": 16737,
"text": "Output: "
},
{
"code": null,
"e": 16841,
"s": 16746,
"text": "Inorder Successor of 1 is 6\nInorder Successor of 4 is 2\nNo inorder successor! Right most node."
},
{
"code": null,
"e": 17011,
"s": 16841,
"text": "Another approach: We will do a reverse inorder traversal and keep the track of current visited node. Once we found the element, last tracked element would be our answer."
},
{
"code": null,
"e": 17059,
"s": 17011,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 17063,
"s": 17059,
"text": "C++"
},
{
"code": null,
"e": 17068,
"s": 17063,
"text": "Java"
},
{
"code": null,
"e": 17076,
"s": 17068,
"text": "Python3"
},
{
"code": null,
"e": 17079,
"s": 17076,
"text": "C#"
},
{
"code": null,
"e": 17090,
"s": 17079,
"text": "Javascript"
},
{
"code": "// C++ Program to find inorder successor.#include<bits/stdc++.h>using namespace std; // structure of a Binary Node.struct Node{ int data; Node* left; Node* right;}; // Function to create a new Node.Node* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp;} // function that prints the inorder successor// of a target node. next will point the last// tracked node, which will be the answer.void inorderSuccessor(Node* root, Node* target_node, Node* &next){ // if root is null then return if(!root) return; inorderSuccessor(root->right, target_node, next); // if target node found then enter this condition if(root->data == target_node->data) { // this will be true to the last node // in inorder traversal i.e., rightmost node. if(next == NULL) cout << \"inorder successor of \" << root->data << \" is: null\\n\"; else cout << \"inorder successor of \" << root->data << \" is: \" << next->data << \"\\n\"; } next = root; inorderSuccessor(root->left, target_node, next);} // Driver Codeint main(){ // Let's construct the binary tree // 1 // / \\ // 2 3 // / \\ / \\ // 4 5 6 7 Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); // Case 1 Node* next = NULL; inorderSuccessor(root, root, next); // case 2 next = NULL; inorderSuccessor(root, root->left->left, next); // case 3 next = NULL; inorderSuccessor(root, root->right->right, next); return 0;} // This code is contributed by AASTHA VARMA",
"e": 19005,
"s": 17090,
"text": null
},
{
"code": "// Java program to find inorder successor of a node. class Node { int data; Node left, right; Node(int data) { this.data = data; left = null; right = null; }} // class to find inorder successor of// a nodeclass InorderSuccessor { Node root; // to change previous node static class PreviousNode { Node pNode; PreviousNode() { pNode = null; } } // function to find inorder successor of // a node private void inOrderSuccessorOfBinaryTree(Node root, PreviousNode pre, int searchNode) { // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) System.out.println(\"inorder successor of \" + searchNode + \" is: \" + (pre.pNode != null ? pre.pNode.data : \"null\")); pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode); } // Driver program to test above functions public static void main(String[] args) { InorderSuccessor tree = new InorderSuccessor(); // Let's construct the binary tree // as shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); // Case 1 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 3); // Case 2 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 4); // Case 3 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 6); }}// This code is contributed by Ashish Goyal.",
"e": 21083,
"s": 19005,
"text": null
},
{
"code": "# Python3 program to find inorder successor. # A Binary Tree Node# Utility function to create a new tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to create a new Node.def newNode(val): temp = Node(0) temp.data = val temp.left = None temp.right = None return temp # function that prints the inorder successor# of a target node. next will point the last# tracked node, which will be the answer.def inorderSuccessor(root, target_node): global next # if root is None then return if(root == None): return inorderSuccessor(root.right, target_node) # if target node found, then # enter this condition if(root.data == target_node.data): # this will be true to the last node # in inorder traversal i.e., rightmost node. if(next == None): print (\"inorder successor of\", root.data , \" is: None\") else: print ( \"inorder successor of\", root.data , \"is:\", next.data) next = root inorderSuccessor(root.left, target_node) # global variablenext = None # Driver Codeif __name__ == '__main__': # Let's construct the binary tree # as shown in above diagram. root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.right = newNode(6) # Case 1 next = None inorderSuccessor(root, root.right) # case 2 next = None inorderSuccessor(root, root.left.left) # case 3 next = None inorderSuccessor(root, root.right.right) # This code is contributed by Arnab Kundu",
"e": 22857,
"s": 21083,
"text": null
},
{
"code": "// C# program to find inorder successor of a node.using System; class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; }} // class to find inorder successor of// a nodepublic class InorderSuccessor{ Node root; // to change previous node class PreviousNode { public Node pNode; public PreviousNode() { pNode = null; } } // function to find inorder successor of // a node private void inOrderSuccessorOfBinaryTree(Node root, PreviousNode pre, int searchNode) { // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) { Console.Write(\"inorder successor of \" + searchNode + \" is: \"); if(pre.pNode != null) Console.WriteLine(pre.pNode.data); else Console.WriteLine(\"null\"); } pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode); } // Driver code public static void Main(String[] args) { InorderSuccessor tree = new InorderSuccessor(); // Let's construct the binary tree // as shown in above diagram tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); // Case 1 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 3); // Case 2 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 4); // Case 3 tree.inOrderSuccessorOfBinaryTree(tree.root, new PreviousNode(), 6); }} // This code is contributed by PrinciRaj1992",
"e": 25137,
"s": 22857,
"text": null
},
{
"code": "<script> // JavaScript program to find inorder successor of a node. class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // class to find inorder successor of// a nodevar root = null; // to change previous nodeclass PreviousNode{ constructor() { this.pNode = null; }} // function to find inorder successor of// a nodefunction inOrderSuccessorOfBinaryTree(root, pre, searchNode){ // Case1: If right child is not NULL if(root.right != null) inOrderSuccessorOfBinaryTree(root.right, pre, searchNode); // Case2: If root data is equal to search node if(root.data == searchNode) { document.write(\"inorder successor of \" + searchNode + \" is: \"); if(pre.pNode != null) document.write(pre.pNode.data+\"<br>\"); else document.write(\"null<br>\"); } pre.pNode = root; if(root.left != null) inOrderSuccessorOfBinaryTree(root.left, pre, searchNode);} // Driver code // Let's construct the binary tree// as shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); // Case 1inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 3); // Case 2inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 4); // Case 3inOrderSuccessorOfBinaryTree(root, new PreviousNode(), 6); </script>",
"e": 26736,
"s": 25137,
"text": null
},
{
"code": null,
"e": 26746,
"s": 26736,
"text": "Output: "
},
{
"code": null,
"e": 26836,
"s": 26746,
"text": "inorder successor of 1 is: 6\ninorder successor of 4 is: 2\ninorder successor of 7 is: null"
},
{
"code": null,
"e": 26906,
"s": 26836,
"text": "Time Complexity: O( n ), where n is the number of nodes in the tree. "
},
{
"code": null,
"e": 26946,
"s": 26906,
"text": "Space complexity: O(n) for call stack "
},
{
"code": null,
"e": 27368,
"s": 26946,
"text": "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": 27377,
"s": 27368,
"text": "ashishfk"
},
{
"code": null,
"e": 27388,
"s": 27377,
"text": "andrew1234"
},
{
"code": null,
"e": 27400,
"s": 27388,
"text": "shrikanth13"
},
{
"code": null,
"e": 27414,
"s": 27400,
"text": "princiraj1992"
},
{
"code": null,
"e": 27429,
"s": 27414,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 27442,
"s": 27429,
"text": "AASTHA VARMA"
},
{
"code": null,
"e": 27449,
"s": 27442,
"text": "rrrtnx"
},
{
"code": null,
"e": 27464,
"s": 27449,
"text": "pranav7kaushik"
},
{
"code": null,
"e": 27479,
"s": 27464,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27500,
"s": 27479,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 27513,
"s": 27500,
"text": "simmytarika5"
},
{
"code": null,
"e": 27525,
"s": 27513,
"text": "noviced3vq6"
},
{
"code": null,
"e": 27537,
"s": 27525,
"text": "Binary Tree"
},
{
"code": null,
"e": 27542,
"s": 27537,
"text": "Tree"
},
{
"code": null,
"e": 27547,
"s": 27542,
"text": "Tree"
},
{
"code": null,
"e": 27645,
"s": 27547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27674,
"s": 27645,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 27706,
"s": 27674,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 27770,
"s": 27706,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 27820,
"s": 27770,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 27834,
"s": 27820,
"text": "Decision Tree"
},
{
"code": null,
"e": 27877,
"s": 27834,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 27919,
"s": 27877,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 27989,
"s": 27919,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 28072,
"s": 27989,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
}
] |
Single Side Band (SSB) Modulation and Demodulation using MATLAB
|
06 Jun, 2022
Single sideband (SSB) modulation might be a sort of modulation used to send data, which includes an audio signal. Amplitude modulation produces an output signal in which the bandwidth is two times the most frequency of the original baseband signal. SSB modulation neglects this bandwidth increase, and also the power wasted on a carrier, at the price of more device complexity and tougher tuning at the receiver side.
Figure: Block Diagram of Modulation
Figure: Spectrum
The Expression for Single Side Band with Upper Side Band : here, m is the cosine wave with time duration of ‘t’, fc is the carrier frequency, t is the time duration and mh s the Hilbert transform of baseband.Example:
MATLAB
% MATLAB code for modulation% carrier frequencyfc = 200; % baseband frequencyfm = 30; % sampling frequencyfs= 4000; % time durationt = (0 : 1 / fs :1 );t = linspace(0, 1, 1000); % cosine wave with time duration of 't'm = cos(2 * pi * fm * t); % Hilbert transform of basebandmh = imag(hilbert(m)); % Single Side Band with Upper Side Bandsb = m .* cos(2 * pi * fc * t) - mh .* sin(2 * pi * fc * t); %Demodulation by Synchronous methodem = sb.*m; %Filtering High Frequemcies[ n,w ] = buttord(2/1000,4/1000, .5, 5);[ a,b ] = butter(n,w,'low');dem = filter(a,b,em); % displaying the modulationfigure;plot(t, sb);title('Single SideBand Modulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the demodulationfigure;plot(t, em);title('Single SideBand Demodulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the filtered signalfigure;plot(t, dem);title('Filtered Signal');xlabel('Time(sec)');ylabel('Amplitude');
Output:
Demodulated Signal
Filtered Signal
roytanupriya1
sumitgumber28
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
ML | Introduction to Data in Machine Learning
Fuzzy Logic | Introduction
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 446,
"s": 28,
"text": "Single sideband (SSB) modulation might be a sort of modulation used to send data, which includes an audio signal. Amplitude modulation produces an output signal in which the bandwidth is two times the most frequency of the original baseband signal. SSB modulation neglects this bandwidth increase, and also the power wasted on a carrier, at the price of more device complexity and tougher tuning at the receiver side."
},
{
"code": null,
"e": 484,
"s": 448,
"text": "Figure: Block Diagram of Modulation"
},
{
"code": null,
"e": 504,
"s": 486,
"text": "Figure: Spectrum "
},
{
"code": null,
"e": 722,
"s": 504,
"text": "The Expression for Single Side Band with Upper Side Band : here, m is the cosine wave with time duration of ‘t’, fc is the carrier frequency, t is the time duration and mh s the Hilbert transform of baseband.Example: "
},
{
"code": null,
"e": 729,
"s": 722,
"text": "MATLAB"
},
{
"code": "% MATLAB code for modulation% carrier frequencyfc = 200; % baseband frequencyfm = 30; % sampling frequencyfs= 4000; % time durationt = (0 : 1 / fs :1 );t = linspace(0, 1, 1000); % cosine wave with time duration of 't'm = cos(2 * pi * fm * t); % Hilbert transform of basebandmh = imag(hilbert(m)); % Single Side Band with Upper Side Bandsb = m .* cos(2 * pi * fc * t) - mh .* sin(2 * pi * fc * t); %Demodulation by Synchronous methodem = sb.*m; %Filtering High Frequemcies[ n,w ] = buttord(2/1000,4/1000, .5, 5);[ a,b ] = butter(n,w,'low');dem = filter(a,b,em); % displaying the modulationfigure;plot(t, sb);title('Single SideBand Modulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the demodulationfigure;plot(t, em);title('Single SideBand Demodulation');xlabel('Time(sec)');ylabel('Amplitude'); % displaying the filtered signalfigure;plot(t, dem);title('Filtered Signal');xlabel('Time(sec)');ylabel('Amplitude');",
"e": 1660,
"s": 729,
"text": null
},
{
"code": null,
"e": 1668,
"s": 1660,
"text": "Output:"
},
{
"code": null,
"e": 1687,
"s": 1668,
"text": "Demodulated Signal"
},
{
"code": null,
"e": 1703,
"s": 1687,
"text": "Filtered Signal"
},
{
"code": null,
"e": 1717,
"s": 1703,
"text": "roytanupriya1"
},
{
"code": null,
"e": 1731,
"s": 1717,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1738,
"s": 1731,
"text": "MATLAB"
},
{
"code": null,
"e": 1764,
"s": 1738,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 1862,
"s": 1764,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1898,
"s": 1862,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 1942,
"s": 1898,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 1978,
"s": 1942,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2002,
"s": 1978,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2037,
"s": 2002,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2078,
"s": 2037,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 2126,
"s": 2078,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 2167,
"s": 2126,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 2213,
"s": 2167,
"text": "ML | Introduction to Data in Machine Learning"
}
] |
Convert CSV to JSON using Python
|
21 Jan, 2021
CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature variable.
On the other hand, JSON (or JavaScript Object Notation) is a dictionary-like notation that can be used by importing the JSON package in Python. Every record (or row) is saved as a separate dictionary, with the column names as Keys of the dictionary. All of these records as dictionaries are saved in a nested dictionary to compose the entire dataset. It is stored with the extension .json, for example, geeksforgeeks.json
Refer to the below articles to understand the basics of JSON and CSV.
Working With JSON Data in Python
Working with CSV file in Python.
We will create a JSON file that will have several dictionaries, each representing a record (row) from the CSV file, with the Key as the column specified.
Sample CSV File used:
Python3
import csvimport json # Function to convert a CSV to JSON# Takes the file paths as argumentsdef make_json(csvFilePath, jsonFilePath): # create a dictionary data = {} # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: # Assuming a column named 'No' to # be the primary key key = rows['No'] data[key] = rows # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) # Driver Code # Decide the two file paths according to your# computer systemcsvFilePath = r'Names.csv'jsonFilePath = r'Names.json' # Call the make_json functionmake_json(csvFilePath, jsonFilePath)
Output:
mezdylan
Python json-programs
python-csv
Python-json
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": 54,
"s": 26,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 413,
"s": 54,
"text": "CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature variable."
},
{
"code": null,
"e": 835,
"s": 413,
"text": "On the other hand, JSON (or JavaScript Object Notation) is a dictionary-like notation that can be used by importing the JSON package in Python. Every record (or row) is saved as a separate dictionary, with the column names as Keys of the dictionary. All of these records as dictionaries are saved in a nested dictionary to compose the entire dataset. It is stored with the extension .json, for example, geeksforgeeks.json"
},
{
"code": null,
"e": 905,
"s": 835,
"text": "Refer to the below articles to understand the basics of JSON and CSV."
},
{
"code": null,
"e": 938,
"s": 905,
"text": "Working With JSON Data in Python"
},
{
"code": null,
"e": 971,
"s": 938,
"text": "Working with CSV file in Python."
},
{
"code": null,
"e": 1126,
"s": 971,
"text": "We will create a JSON file that will have several dictionaries, each representing a record (row) from the CSV file, with the Key as the column specified. "
},
{
"code": null,
"e": 1148,
"s": 1126,
"text": "Sample CSV File used:"
},
{
"code": null,
"e": 1156,
"s": 1148,
"text": "Python3"
},
{
"code": "import csvimport json # Function to convert a CSV to JSON# Takes the file paths as argumentsdef make_json(csvFilePath, jsonFilePath): # create a dictionary data = {} # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: # Assuming a column named 'No' to # be the primary key key = rows['No'] data[key] = rows # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) # Driver Code # Decide the two file paths according to your# computer systemcsvFilePath = r'Names.csv'jsonFilePath = r'Names.json' # Call the make_json functionmake_json(csvFilePath, jsonFilePath)",
"e": 2120,
"s": 1156,
"text": null
},
{
"code": null,
"e": 2131,
"s": 2123,
"text": "Output:"
},
{
"code": null,
"e": 2144,
"s": 2135,
"text": "mezdylan"
},
{
"code": null,
"e": 2165,
"s": 2144,
"text": "Python json-programs"
},
{
"code": null,
"e": 2176,
"s": 2165,
"text": "python-csv"
},
{
"code": null,
"e": 2188,
"s": 2176,
"text": "Python-json"
},
{
"code": null,
"e": 2195,
"s": 2188,
"text": "Python"
},
{
"code": null,
"e": 2293,
"s": 2195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2311,
"s": 2293,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2353,
"s": 2311,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2375,
"s": 2353,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2410,
"s": 2375,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2436,
"s": 2410,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2468,
"s": 2436,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2497,
"s": 2468,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2524,
"s": 2497,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2554,
"s": 2524,
"text": "Iterate over a list in Python"
}
] |
Display MongoDB explain query plan?
|
For information on query plan, use explain() in MongoDB. Let us create a collection with documents −
> db.demo202.insertOne({"StudentFirstName":"Chris","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c3bd103d395bdc21346e8")
}
> db.demo202.insertOne({"StudentFirstName":"David","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c3bd803d395bdc21346e9")
}
> db.demo202.insertOne({"StudentFirstName":"Bob","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c3bde03d395bdc21346ea")
}
Display all documents from a collection with the help of find() method −
> db.demo202.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c3bd103d395bdc21346e8"), "StudentFirstName" : "Chris", "StudentAge" : 21 }
{ "_id" : ObjectId("5e3c3bd803d395bdc21346e9"), "StudentFirstName" : "David", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3c3bde03d395bdc21346ea"), "StudentFirstName" : "Bob", "StudentAge" : 22 }
Following is the query to display explain query plan −
> db.demo202.find({"StudentFirstName":"David"}).explain();
This will produce the following output −
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.demo202",
"indexFilterSet" : false,
"parsedQuery" : {
"StudentFirstName" : {
"$eq" : "David"
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"StudentFirstName" : {
"$eq" : "David"
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "DESKTOP-QN2RB3H",
"port" : 27017,
"version" : "4.0.5",
"gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
},
"ok" : 1
}
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "For information on query plan, use explain() in MongoDB. Let us create a collection with documents −"
},
{
"code": null,
"e": 1626,
"s": 1163,
"text": "> db.demo202.insertOne({\"StudentFirstName\":\"Chris\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3c3bd103d395bdc21346e8\")\n}\n> db.demo202.insertOne({\"StudentFirstName\":\"David\",\"StudentAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3c3bd803d395bdc21346e9\")\n}\n> db.demo202.insertOne({\"StudentFirstName\":\"Bob\",\"StudentAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3c3bde03d395bdc21346ea\")\n}"
},
{
"code": null,
"e": 1699,
"s": 1626,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1720,
"s": 1699,
"text": "> db.demo202.find();"
},
{
"code": null,
"e": 1761,
"s": 1720,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2053,
"s": 1761,
"text": "{ \"_id\" : ObjectId(\"5e3c3bd103d395bdc21346e8\"), \"StudentFirstName\" : \"Chris\", \"StudentAge\" : 21 }\n{ \"_id\" : ObjectId(\"5e3c3bd803d395bdc21346e9\"), \"StudentFirstName\" : \"David\", \"StudentAge\" : 23 }\n{ \"_id\" : ObjectId(\"5e3c3bde03d395bdc21346ea\"), \"StudentFirstName\" : \"Bob\", \"StudentAge\" : 22 }"
},
{
"code": null,
"e": 2108,
"s": 2053,
"text": "Following is the query to display explain query plan −"
},
{
"code": null,
"e": 2167,
"s": 2108,
"text": "> db.demo202.find({\"StudentFirstName\":\"David\"}).explain();"
},
{
"code": null,
"e": 2208,
"s": 2167,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2867,
"s": 2208,
"text": "{\n \"queryPlanner\" : {\n \"plannerVersion\" : 1,\n \"namespace\" : \"test.demo202\",\n \"indexFilterSet\" : false,\n \"parsedQuery\" : {\n \"StudentFirstName\" : {\n \"$eq\" : \"David\"\n }\n },\n \"winningPlan\" : {\n \"stage\" : \"COLLSCAN\",\n \"filter\" : {\n \"StudentFirstName\" : {\n \"$eq\" : \"David\"\n }\n },\n \"direction\" : \"forward\"\n },\n \"rejectedPlans\" : [ ]\n },\n \"serverInfo\" : {\n \"host\" : \"DESKTOP-QN2RB3H\",\n \"port\" : 27017,\n \"version\" : \"4.0.5\",\n \"gitVersion\" : \"3739429dd92b92d1b0ab120911a23d50bf03c412\"\n },\n \"ok\" : 1\n}"
}
] |
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks
|
28 Jun, 2021
Consider a hash table with 100 slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what is the probability that the first 3 slots are unfilled after the first 3 insertions?(A) (97 × 97 × 97)/1003(B) (99 × 98 × 97)/1003(C) (97 × 96 × 95)/1003(D) (97 × 96 × 95)/(3! × 1003)Answer: (A)Explanation: Simple Uniform hashing function is a hypothetical hashing function that evenly distributes items into the slots of a hash table. Moreover, each item to be hashed has an equal probability of being placed into a slot, regardless of the other elements already placed. (Source: https://en.wikipedia.org/wiki/SUHA_%28computer_science%29).
Probability that the first 3 slots are unfilled after the first 3 insertions =
(probability that first item doesn't go in any of the first 3 slots)*
(probability that second item doesn't go in any of the first 3 slots)*
(probability that third item doesn't go in any of the first 3 slots)
= (97/100) * (97/100) * (97/100)
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2001 | Question 48
|
[
{
"code": null,
"e": 24091,
"s": 24063,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24748,
"s": 24091,
"text": "Consider a hash table with 100 slots. Collisions are resolved using chaining. Assuming simple uniform hashing, what is the probability that the first 3 slots are unfilled after the first 3 insertions?(A) (97 × 97 × 97)/1003(B) (99 × 98 × 97)/1003(C) (97 × 96 × 95)/1003(D) (97 × 96 × 95)/(3! × 1003)Answer: (A)Explanation: Simple Uniform hashing function is a hypothetical hashing function that evenly distributes items into the slots of a hash table. Moreover, each item to be hashed has an equal probability of being placed into a slot, regardless of the other elements already placed. (Source: https://en.wikipedia.org/wiki/SUHA_%28computer_science%29)."
},
{
"code": null,
"e": 25138,
"s": 24748,
"text": "Probability that the first 3 slots are unfilled after the first 3 insertions = \n (probability that first item doesn't go in any of the first 3 slots)*\n (probability that second item doesn't go in any of the first 3 slots)*\n (probability that third item doesn't go in any of the first 3 slots)\n\n = (97/100) * (97/100) * (97/100) "
},
{
"code": null,
"e": 25160,
"s": 25138,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25181,
"s": 25160,
"text": "GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 25207,
"s": 25181,
"text": "GATE-GATE-CS-2014-(Set-3)"
},
{
"code": null,
"e": 25212,
"s": 25207,
"text": "GATE"
},
{
"code": null,
"e": 25310,
"s": 25212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25319,
"s": 25310,
"text": "Comments"
},
{
"code": null,
"e": 25332,
"s": 25319,
"text": "Old Comments"
},
{
"code": null,
"e": 25374,
"s": 25332,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25416,
"s": 25374,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25450,
"s": 25416,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 25492,
"s": 25450,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25526,
"s": 25492,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25568,
"s": 25526,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25601,
"s": 25568,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25655,
"s": 25601,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25689,
"s": 25655,
"text": "GATE | GATE CS 2012 | Question 40"
}
] |
Find the Symmetric difference between two arrays - JavaScript
|
In Mathematics, the symmetric difference of two sets, say A and B is represented by A △ B
And it is defined as the set of all those elements which belongs either to A or to B but not to both.
For example −
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
Then the symmetric difference of A and B will be −
const diff = [2, 4, 9]
Following is the code −
const A = [1, 2, 3, 4, 5, 6, 7, 8];
const B = [1, 3, 5, 6, 7, 8, 9];
const symmetricDifference = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
if(arr2.indexOf(arr1[i]) !== -1){
continue;
};
res.push(arr1[i]);
}
for(let i = 0; i < arr2.length; i++){
if(arr1.indexOf(arr2[i]) !== -1){
continue;
};
res.push(arr2[i]);
};
return res;
};
console.log(symmetricDifference(A, B));
This will produce the following output in console −
[2, 4, 9]
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "In Mathematics, the symmetric difference of two sets, say A and B is represented by A △ B"
},
{
"code": null,
"e": 1254,
"s": 1152,
"text": "And it is defined as the set of all those elements which belongs either to A or to B but not to both."
},
{
"code": null,
"e": 1268,
"s": 1254,
"text": "For example −"
},
{
"code": null,
"e": 1337,
"s": 1268,
"text": "const A = [1, 2, 3, 4, 5, 6, 7, 8];\nconst B = [1, 3, 5, 6, 7, 8, 9];"
},
{
"code": null,
"e": 1388,
"s": 1337,
"text": "Then the symmetric difference of A and B will be −"
},
{
"code": null,
"e": 1411,
"s": 1388,
"text": "const diff = [2, 4, 9]"
},
{
"code": null,
"e": 1435,
"s": 1411,
"text": "Following is the code −"
},
{
"code": null,
"e": 1906,
"s": 1435,
"text": "const A = [1, 2, 3, 4, 5, 6, 7, 8];\nconst B = [1, 3, 5, 6, 7, 8, 9];\nconst symmetricDifference = (arr1, arr2) => {\n const res = [];\n for(let i = 0; i < arr1.length; i++){\n if(arr2.indexOf(arr1[i]) !== -1){\n continue;\n };\n res.push(arr1[i]);\n }\n for(let i = 0; i < arr2.length; i++){\n if(arr1.indexOf(arr2[i]) !== -1){\n continue;\n };\n res.push(arr2[i]);\n };\n return res;\n};\nconsole.log(symmetricDifference(A, B));"
},
{
"code": null,
"e": 1958,
"s": 1906,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1968,
"s": 1958,
"text": "[2, 4, 9]"
}
] |
Find square root of number upto given precision using binary search - GeeksforGeeks
|
24 Jun, 2021
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples:
Input : number = 50, precision = 3
Output : 7.071
Input : number = 10, precision = 4
Output : 3.1622
We have discussed how to compute the integral value of square root in Square Root using Binary SearchApproach : 1) As the square root of number lies in range 0 <= squareRoot <= number, therefore, initialize start and end as : start = 0, end = number.2) Compare the square of the mid integer with the given number. If it is equal to the number, the square root is found. Else look for the same in the left or right side depending upon the scenario. 3) Once we are done with finding an integral part, start computing the fractional part. 4) Initialize the increment variable by 0.1 and iteratively compute the fractional part up to P places. For each iteration, the increment changes to 1/10th of its previous value. 5) Finally return the answer computed.Below is the implementation of above approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find// square root of given number// upto given precision using// binary search.#include <bits/stdc++.h>using namespace std; // Function to find square root// of given number upto given// precisionfloat squareRoot(int number, int precision){ int start = 0, end = number; int mid; // variable to store the answer float ans; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision float increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return ans;} // Driver codeint main(){ // Function calling cout << squareRoot(50, 3) << endl; // Function calling cout << squareRoot(10, 4) << endl; return 0;}
// Java implementation to find// square root of given number// upto given precision using// binary search.import java.io.*; class GFG { // Function to find square root // of given number upto given // precision static float squareRoot(int number, int precision) { int start = 0, end = number; int mid; // variable to store the answer double ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision double increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return (float)ans; } // Driver code public static void main(String[] args) { // Function calling System.out.println(squareRoot(50, 3)); // Function calling System.out.println(squareRoot(10, 4)); }} // This code is contributed by vt_m.
# Python3 implementation to find# square root of given number# upto given precision using# binary search. # Function to find square root of# given number upto given precision def squareRoot(number, precision): start = 0 end, ans = number, 1 # For computing integral part # of square root of number while (start <= end): mid = int((start + end) / 2) if (mid * mid == number): ans = mid break # incrementing start if integral # part lies on right side of the mid if (mid * mid < number): start = mid + 1 ans = mid # decrementing end if integral part # lies on the left side of the mid else: end = mid - 1 # For computing the fractional part # of square root upto given precision increment = 0.1 for i in range(0, precision): while (ans * ans <= number): ans += increment # loop terminates when ans * ans > number ans = ans - increment increment = increment / 10 return ans # Driver codeprint(round(squareRoot(50, 3), 4))print(round(squareRoot(10, 4), 4)) # This code is contributed by Smitha Dinesh Semwal.
// C# implementation to find// square root of given number// upto given precision using// binary search.using System;class GFG { // Function to find square root // of given number upto given // precision static float squareRoot(int number, int precision) { int start = 0, end = number; int mid; // variable to store the answer double ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision double increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return (float)ans; } // Driver code public static void Main() { // Function calling Console.WriteLine(squareRoot(50, 3)); // Function calling Console.WriteLine(squareRoot(10, 4)); }} // This code is contributed by Sheharaz Sheikh
<?php// PHP implementation to find// square root of given number// upto given precision using// binary search. // Function to find square root// of given number upto given// precisionfunction squareRoot($number, $precision){ $start=0; $end=$number; $mid; // variable to store // the answer $ans; // for computing integral part // of square root of number while ($start <= $end) { $mid = ($start + $end) / 2; if ($mid * $mid == $number) { $ans = $mid; break; } // incrementing start if integral // part lies on right side of the mid if ($mid * $mid < $number) { $start = $mid + 1; $ans = $mid; } // decrementing end if integral part // lies on the left side of the mid else { $end = $mid - 1; } } // For computing the fractional part // of square root upto given precision $increment = 0.1; for ($i = 0; $i < $precision; $i++) { while ($ans * $ans <= $number) { $ans += $increment; } // loop terminates when // ans * ans > number $ans = $ans - $increment; $increment = $increment / 10; } return $ans;} // Driver code // Function calling echo squareRoot(50, 3),"\n"; // Function calling echo squareRoot(10, 4),"\n"; // This code is contributed by ajit.?>
<script> // JavaScript program implementation to find// square root of given number// upto given precision using// binary search. // Function to find square root // of given number upto given // precision function squareRoot(number, precision) { let start = 0, end = number; let mid; // variable to store the answer let ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision let increment = 0.1; for (let i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return ans; } // Driver code // Function calling document.write(squareRoot(50, 3) + "<br/>"); // Function calling document.write(squareRoot(10, 4) + "<br/>"); </script>
Output:
7.071
3.1622
Time Complexity : The time required to compute the integral part is O(log(number)) and constant i.e, = precision for computing the fractional part. Therefore, overall time complexity is O(log(number) + precision) which is approximately equal to O(log(number)).
jit_t
utkarshpathak1
sheharaz07
sanjoy_62
AmanRanjanVerma
Binary Search
Mathematical
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
The Knight's tour problem | Backtracking-1
Efficient program to print all prime factors of a given number
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Print all possible combinations of r elements in a given array of size n
|
[
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 24393,
"s": 24228,
"text": "Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: "
},
{
"code": null,
"e": 24495,
"s": 24393,
"text": "Input : number = 50, precision = 3\nOutput : 7.071\n\nInput : number = 10, precision = 4\nOutput : 3.1622"
},
{
"code": null,
"e": 25301,
"s": 24497,
"text": "We have discussed how to compute the integral value of square root in Square Root using Binary SearchApproach : 1) As the square root of number lies in range 0 <= squareRoot <= number, therefore, initialize start and end as : start = 0, end = number.2) Compare the square of the mid integer with the given number. If it is equal to the number, the square root is found. Else look for the same in the left or right side depending upon the scenario. 3) Once we are done with finding an integral part, start computing the fractional part. 4) Initialize the increment variable by 0.1 and iteratively compute the fractional part up to P places. For each iteration, the increment changes to 1/10th of its previous value. 5) Finally return the answer computed.Below is the implementation of above approach : "
},
{
"code": null,
"e": 25305,
"s": 25301,
"text": "C++"
},
{
"code": null,
"e": 25310,
"s": 25305,
"text": "Java"
},
{
"code": null,
"e": 25318,
"s": 25310,
"text": "Python3"
},
{
"code": null,
"e": 25321,
"s": 25318,
"text": "C#"
},
{
"code": null,
"e": 25325,
"s": 25321,
"text": "PHP"
},
{
"code": null,
"e": 25336,
"s": 25325,
"text": "Javascript"
},
{
"code": "// C++ implementation to find// square root of given number// upto given precision using// binary search.#include <bits/stdc++.h>using namespace std; // Function to find square root// of given number upto given// precisionfloat squareRoot(int number, int precision){ int start = 0, end = number; int mid; // variable to store the answer float ans; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision float increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return ans;} // Driver codeint main(){ // Function calling cout << squareRoot(50, 3) << endl; // Function calling cout << squareRoot(10, 4) << endl; return 0;}",
"e": 26751,
"s": 25336,
"text": null
},
{
"code": "// Java implementation to find// square root of given number// upto given precision using// binary search.import java.io.*; class GFG { // Function to find square root // of given number upto given // precision static float squareRoot(int number, int precision) { int start = 0, end = number; int mid; // variable to store the answer double ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision double increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return (float)ans; } // Driver code public static void main(String[] args) { // Function calling System.out.println(squareRoot(50, 3)); // Function calling System.out.println(squareRoot(10, 4)); }} // This code is contributed by vt_m.",
"e": 28435,
"s": 26751,
"text": null
},
{
"code": "# Python3 implementation to find# square root of given number# upto given precision using# binary search. # Function to find square root of# given number upto given precision def squareRoot(number, precision): start = 0 end, ans = number, 1 # For computing integral part # of square root of number while (start <= end): mid = int((start + end) / 2) if (mid * mid == number): ans = mid break # incrementing start if integral # part lies on right side of the mid if (mid * mid < number): start = mid + 1 ans = mid # decrementing end if integral part # lies on the left side of the mid else: end = mid - 1 # For computing the fractional part # of square root upto given precision increment = 0.1 for i in range(0, precision): while (ans * ans <= number): ans += increment # loop terminates when ans * ans > number ans = ans - increment increment = increment / 10 return ans # Driver codeprint(round(squareRoot(50, 3), 4))print(round(squareRoot(10, 4), 4)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 29630,
"s": 28435,
"text": null
},
{
"code": "// C# implementation to find// square root of given number// upto given precision using// binary search.using System;class GFG { // Function to find square root // of given number upto given // precision static float squareRoot(int number, int precision) { int start = 0, end = number; int mid; // variable to store the answer double ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision double increment = 0.1; for (int i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return (float)ans; } // Driver code public static void Main() { // Function calling Console.WriteLine(squareRoot(50, 3)); // Function calling Console.WriteLine(squareRoot(10, 4)); }} // This code is contributed by Sheharaz Sheikh",
"e": 31302,
"s": 29630,
"text": null
},
{
"code": "<?php// PHP implementation to find// square root of given number// upto given precision using// binary search. // Function to find square root// of given number upto given// precisionfunction squareRoot($number, $precision){ $start=0; $end=$number; $mid; // variable to store // the answer $ans; // for computing integral part // of square root of number while ($start <= $end) { $mid = ($start + $end) / 2; if ($mid * $mid == $number) { $ans = $mid; break; } // incrementing start if integral // part lies on right side of the mid if ($mid * $mid < $number) { $start = $mid + 1; $ans = $mid; } // decrementing end if integral part // lies on the left side of the mid else { $end = $mid - 1; } } // For computing the fractional part // of square root upto given precision $increment = 0.1; for ($i = 0; $i < $precision; $i++) { while ($ans * $ans <= $number) { $ans += $increment; } // loop terminates when // ans * ans > number $ans = $ans - $increment; $increment = $increment / 10; } return $ans;} // Driver code // Function calling echo squareRoot(50, 3),\"\\n\"; // Function calling echo squareRoot(10, 4),\"\\n\"; // This code is contributed by ajit.?>",
"e": 32745,
"s": 31302,
"text": null
},
{
"code": "<script> // JavaScript program implementation to find// square root of given number// upto given precision using// binary search. // Function to find square root // of given number upto given // precision function squareRoot(number, precision) { let start = 0, end = number; let mid; // variable to store the answer let ans = 0.0; // for computing integral part // of square root of number while (start <= end) { mid = (start + end) / 2; if (mid * mid == number) { ans = mid; break; } // incrementing start if integral // part lies on right side of the mid if (mid * mid < number) { start = mid + 1; ans = mid; } // decrementing end if integral part // lies on the left side of the mid else { end = mid - 1; } } // For computing the fractional part // of square root upto given precision let increment = 0.1; for (let i = 0; i < precision; i++) { while (ans * ans <= number) { ans += increment; } // loop terminates when ans * ans > number ans = ans - increment; increment = increment / 10; } return ans; } // Driver code // Function calling document.write(squareRoot(50, 3) + \"<br/>\"); // Function calling document.write(squareRoot(10, 4) + \"<br/>\"); </script>",
"e": 34405,
"s": 32745,
"text": null
},
{
"code": null,
"e": 34414,
"s": 34405,
"text": "Output: "
},
{
"code": null,
"e": 34427,
"s": 34414,
"text": "7.071\n3.1622"
},
{
"code": null,
"e": 34689,
"s": 34427,
"text": "Time Complexity : The time required to compute the integral part is O(log(number)) and constant i.e, = precision for computing the fractional part. Therefore, overall time complexity is O(log(number) + precision) which is approximately equal to O(log(number)). "
},
{
"code": null,
"e": 34695,
"s": 34689,
"text": "jit_t"
},
{
"code": null,
"e": 34710,
"s": 34695,
"text": "utkarshpathak1"
},
{
"code": null,
"e": 34721,
"s": 34710,
"text": "sheharaz07"
},
{
"code": null,
"e": 34731,
"s": 34721,
"text": "sanjoy_62"
},
{
"code": null,
"e": 34747,
"s": 34731,
"text": "AmanRanjanVerma"
},
{
"code": null,
"e": 34761,
"s": 34747,
"text": "Binary Search"
},
{
"code": null,
"e": 34774,
"s": 34761,
"text": "Mathematical"
},
{
"code": null,
"e": 34787,
"s": 34774,
"text": "Mathematical"
},
{
"code": null,
"e": 34801,
"s": 34787,
"text": "Binary Search"
},
{
"code": null,
"e": 34899,
"s": 34801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34942,
"s": 34899,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34991,
"s": 34942,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 35025,
"s": 34991,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 35046,
"s": 35025,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 35088,
"s": 35046,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 35131,
"s": 35088,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 35194,
"s": 35131,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 35247,
"s": 35194,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 35284,
"s": 35247,
"text": "Minimum number of jumps to reach end"
}
] |
How to Convert HTML Table into Excel Spreadsheet using jQuery ? - GeeksforGeeks
|
03 Aug, 2021
Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this.
Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet.Syntax:$("#table-id").table2excel({
filename: "excel_sheet-name.xls"
});Example:<table id="studtable"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <script> $(document).ready(function () { $("#studtable").table2excel({ filename: "Students.xls" }); }); </script>Output:
ID Name Age Address
101 Alex 15 Maldives
102 Chris 14 Canada
103 Jay 15 TorontoThe above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is.About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class.Syntax for noExport:$(document).ready(function() {
$("#table-id").table2excel({
exclude: ".noExport",
filename: "name-of-the-file",
});
});Example code for excluding some specified cells:<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script> <button>Export</button><table> <thead> <tr> <td class="noExport"> This cell will not be exported. </td> <td> This cell will get exported. </td> </tr> </thead> <tbody> <tr> <td>Alex</td> <td class="noExport">Maldives</td> </tr> <tr> <td>Chris</td> <td>Canada</td> </tr> </tbody></table>Note:In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
Syntax:
$("#table-id").table2excel({
filename: "excel_sheet-name.xls"
});
Example:
<table id="studtable"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <script> $(document).ready(function () { $("#studtable").table2excel({ filename: "Students.xls" }); }); </script>
Output:
ID Name Age Address
101 Alex 15 Maldives
102 Chris 14 Canada
103 Jay 15 Toronto
The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is.
About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class.
Syntax for noExport:
$(document).ready(function() {
$("#table-id").table2excel({
exclude: ".noExport",
filename: "name-of-the-file",
});
});
Example code for excluding some specified cells:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script> <button>Export</button><table> <thead> <tr> <td class="noExport"> This cell will not be exported. </td> <td> This cell will get exported. </td> </tr> </thead> <tbody> <tr> <td>Alex</td> <td class="noExport">Maldives</td> </tr> <tr> <td>Chris</td> <td>Canada</td> </tr> </tbody></table>
Note:In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet.Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE.<!DOCTYPE html><html> <head> <title> HTML Table To Excel spreadsheet using HTML only </title></head> <body> <table id="studtable"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <button onclick="tableToExcel( 'studtable', 'Students')"> Click to Export </button></body> </html>Output:
Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE.
<!DOCTYPE html><html> <head> <title> HTML Table To Excel spreadsheet using HTML only </title></head> <body> <table id="studtable"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <button onclick="tableToExcel( 'studtable', 'Students')"> Click to Export </button></body> </html>
Output:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
How to set div width to fit content using CSS ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25078,
"s": 25050,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25308,
"s": 25078,
"text": "Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this."
},
{
"code": null,
"e": 27624,
"s": 25308,
"text": "Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet.Syntax:$(\"#table-id\").table2excel({\n filename: \"excel_sheet-name.xls\"\n});Example:<table id=\"studtable\"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <script> $(document).ready(function () { $(\"#studtable\").table2excel({ filename: \"Students.xls\" }); }); </script>Output: \nID Name Age Address\n101 Alex 15 Maldives\n102 Chris 14 Canada\n103 Jay 15 TorontoThe above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is.About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class.Syntax for noExport:$(document).ready(function() {\n $(\"#table-id\").table2excel({\n exclude: \".noExport\",\n filename: \"name-of-the-file\",\n });\n});Example code for excluding some specified cells:<script src=\"//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script><script src=\"//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js\"></script> <button>Export</button><table> <thead> <tr> <td class=\"noExport\"> This cell will not be exported. </td> <td> This cell will get exported. </td> </tr> </thead> <tbody> <tr> <td>Alex</td> <td class=\"noExport\">Maldives</td> </tr> <tr> <td>Chris</td> <td>Canada</td> </tr> </tbody></table>Note:In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data."
},
{
"code": null,
"e": 27632,
"s": 27624,
"text": "Syntax:"
},
{
"code": null,
"e": 27702,
"s": 27632,
"text": "$(\"#table-id\").table2excel({\n filename: \"excel_sheet-name.xls\"\n});"
},
{
"code": null,
"e": 27711,
"s": 27702,
"text": "Example:"
},
{
"code": "<table id=\"studtable\"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <script> $(document).ready(function () { $(\"#studtable\").table2excel({ filename: \"Students.xls\" }); }); </script>",
"e": 28285,
"s": 27711,
"text": null
},
{
"code": null,
"e": 28293,
"s": 28285,
"text": "Output:"
},
{
"code": null,
"e": 28411,
"s": 28293,
"text": " \nID Name Age Address\n101 Alex 15 Maldives\n102 Chris 14 Canada\n103 Jay 15 Toronto"
},
{
"code": null,
"e": 28513,
"s": 28411,
"text": "The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is."
},
{
"code": null,
"e": 28735,
"s": 28513,
"text": "About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class."
},
{
"code": null,
"e": 28756,
"s": 28735,
"text": "Syntax for noExport:"
},
{
"code": null,
"e": 28900,
"s": 28756,
"text": "$(document).ready(function() {\n $(\"#table-id\").table2excel({\n exclude: \".noExport\",\n filename: \"name-of-the-file\",\n });\n});"
},
{
"code": null,
"e": 28949,
"s": 28900,
"text": "Example code for excluding some specified cells:"
},
{
"code": "<script src=\"//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js\"></script><script src=\"//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js\"></script> <button>Export</button><table> <thead> <tr> <td class=\"noExport\"> This cell will not be exported. </td> <td> This cell will get exported. </td> </tr> </thead> <tbody> <tr> <td>Alex</td> <td class=\"noExport\">Maldives</td> </tr> <tr> <td>Chris</td> <td>Canada</td> </tr> </tbody></table>",
"e": 29596,
"s": 28949,
"text": null
},
{
"code": null,
"e": 29823,
"s": 29596,
"text": "Note:In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data."
},
{
"code": null,
"e": 31046,
"s": 29823,
"text": "Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet.Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE.<!DOCTYPE html><html> <head> <title> HTML Table To Excel spreadsheet using HTML only </title></head> <body> <table id=\"studtable\"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <button onclick=\"tableToExcel( 'studtable', 'Students')\"> Click to Export </button></body> </html>Output:"
},
{
"code": null,
"e": 31262,
"s": 31046,
"text": "Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE."
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML Table To Excel spreadsheet using HTML only </title></head> <body> <table id=\"studtable\"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Address</th> </tr> <tr> <td>101</td> <td>Alex</td> <td>15</td> <td>Maldives</td> </tr> <tr> <td>102</td> <td>Chris</td> <td>14</td> <td>Canada</td> </tr> <tr> <td>103</td> <td>Jay</td> <td>15</td> <td>Toronto</td> </tr> </table> <button onclick=\"tableToExcel( 'studtable', 'Students')\"> Click to Export </button></body> </html>",
"e": 32060,
"s": 31262,
"text": null
},
{
"code": null,
"e": 32068,
"s": 32060,
"text": "Output:"
},
{
"code": null,
"e": 32262,
"s": 32068,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 32448,
"s": 32262,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 32716,
"s": 32448,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 32853,
"s": 32716,
"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": 32862,
"s": 32853,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32872,
"s": 32862,
"text": "HTML-Misc"
},
{
"code": null,
"e": 32884,
"s": 32872,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 32891,
"s": 32884,
"text": "Picked"
},
{
"code": null,
"e": 32895,
"s": 32891,
"text": "CSS"
},
{
"code": null,
"e": 32900,
"s": 32895,
"text": "HTML"
},
{
"code": null,
"e": 32907,
"s": 32900,
"text": "JQuery"
},
{
"code": null,
"e": 32924,
"s": 32907,
"text": "Web Technologies"
},
{
"code": null,
"e": 32951,
"s": 32924,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32956,
"s": 32951,
"text": "HTML"
},
{
"code": null,
"e": 33054,
"s": 32956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33063,
"s": 33054,
"text": "Comments"
},
{
"code": null,
"e": 33076,
"s": 33063,
"text": "Old Comments"
},
{
"code": null,
"e": 33117,
"s": 33076,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 33154,
"s": 33117,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33218,
"s": 33154,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 33279,
"s": 33218,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 33327,
"s": 33279,
"text": "How to set div width to fit content using CSS ?"
},
{
"code": null,
"e": 33387,
"s": 33327,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33448,
"s": 33387,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 33501,
"s": 33448,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 33551,
"s": 33501,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Decimal to any base conversion | Practice | GeeksforGeeks
|
Given a decimal number N and the base B to which it should be converted. Convert the given number to the given base.
Example 1:
Input:
B = 2
N = 12
Output:
1100
Explanation:
If the number 12 is converted to a
number with base 2 we get the binary
representation of 12 = 1100.
Example 2:
Input:
B = 16
N = 282
Output:
11A
Explanation:
If the number 282 is converted to a
number with base 16 we get the hexadecimal
representation of 282 = 11A.
Your Task:
You don't need to read input or print anything. Your task is to complete the function getNumber() which takes two integer B and N representing the base and the decimal number and returns the number in the given base.
Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)
Constraints:
2 <= B <= 16
1 <= N <= 999999999
0
kollinagavenkatapavan20001 month ago
Can anyone tell me why is it showing output difference , even though expected output and my code's output both were same .
And it is not showing output difference when I run this test case alone in custom input .
Thank You .
0
Aman Nigam9 months ago
Aman Nigam
Very Easy C++ Solution
https://uploads.disquscdn.c...
0
insane_banda1 year ago
insane_banda
Very irritating that java testcase is broken. I've observed that you guys don't pay much importance to java testcases. Faced same issue many times. Same logic gets accepted in c++ but throws error in java due to some input/output errors.
0
Shreyansh Kumar Singh1 year ago
Shreyansh Kumar Singh
Java SolutionOne Liner > return Integer.toString(N, B).toUpperCase();Another approach https://uploads.disquscdn.c...
0
Shreyansh Kumar Singh
This comment was deleted.
0
Shreyansh Kumar Singh
This comment was deleted.
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": 355,
"s": 238,
"text": "Given a decimal number N and the base B to which it should be converted. Convert the given number to the given base."
},
{
"code": null,
"e": 366,
"s": 355,
"text": "Example 1:"
},
{
"code": null,
"e": 518,
"s": 366,
"text": "Input:\nB = 2\nN = 12 \n\nOutput:\n1100\n\nExplanation:\nIf the number 12 is converted to a \nnumber with base 2 we get the binary \nrepresentation of 12 = 1100."
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Example 2:"
},
{
"code": null,
"e": 689,
"s": 529,
"text": "Input:\nB = 16\nN = 282\n\nOutput:\n11A\n\nExplanation:\nIf the number 282 is converted to a \nnumber with base 16 we get the hexadecimal \nrepresentation of 282 = 11A.\n"
},
{
"code": null,
"e": 919,
"s": 689,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function getNumber() which takes two integer B and N representing the base and the decimal number and returns the number in the given base."
},
{
"code": null,
"e": 984,
"s": 919,
"text": "Expected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1030,
"s": 984,
"text": "Constraints:\n2 <= B <= 16\n1 <= N <= 999999999"
},
{
"code": null,
"e": 1032,
"s": 1030,
"text": "0"
},
{
"code": null,
"e": 1069,
"s": 1032,
"text": "kollinagavenkatapavan20001 month ago"
},
{
"code": null,
"e": 1195,
"s": 1069,
"text": " Can anyone tell me why is it showing output difference , even though expected output and my code's output both were same . "
},
{
"code": null,
"e": 1288,
"s": 1197,
"text": "And it is not showing output difference when I run this test case alone in custom input . "
},
{
"code": null,
"e": 1303,
"s": 1290,
"text": "Thank You . "
},
{
"code": null,
"e": 1305,
"s": 1303,
"text": "0"
},
{
"code": null,
"e": 1328,
"s": 1305,
"text": "Aman Nigam9 months ago"
},
{
"code": null,
"e": 1339,
"s": 1328,
"text": "Aman Nigam"
},
{
"code": null,
"e": 1362,
"s": 1339,
"text": "Very Easy C++ Solution"
},
{
"code": null,
"e": 1393,
"s": 1362,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1395,
"s": 1393,
"text": "0"
},
{
"code": null,
"e": 1418,
"s": 1395,
"text": "insane_banda1 year ago"
},
{
"code": null,
"e": 1431,
"s": 1418,
"text": "insane_banda"
},
{
"code": null,
"e": 1669,
"s": 1431,
"text": "Very irritating that java testcase is broken. I've observed that you guys don't pay much importance to java testcases. Faced same issue many times. Same logic gets accepted in c++ but throws error in java due to some input/output errors."
},
{
"code": null,
"e": 1671,
"s": 1669,
"text": "0"
},
{
"code": null,
"e": 1703,
"s": 1671,
"text": "Shreyansh Kumar Singh1 year ago"
},
{
"code": null,
"e": 1725,
"s": 1703,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 1842,
"s": 1725,
"text": "Java SolutionOne Liner > return Integer.toString(N, B).toUpperCase();Another approach https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1844,
"s": 1842,
"text": "0"
},
{
"code": null,
"e": 1866,
"s": 1844,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 1892,
"s": 1866,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1894,
"s": 1892,
"text": "0"
},
{
"code": null,
"e": 1916,
"s": 1894,
"text": "Shreyansh Kumar Singh"
},
{
"code": null,
"e": 1942,
"s": 1916,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2088,
"s": 1942,
"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": 2124,
"s": 2088,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2134,
"s": 2124,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2144,
"s": 2134,
"text": "\nContest\n"
},
{
"code": null,
"e": 2207,
"s": 2144,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2355,
"s": 2207,
"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": 2563,
"s": 2355,
"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": 2669,
"s": 2563,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Draw a circle using Arcade in Python3 - GeeksforGeeks
|
22 Jul, 2021
The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions.
Arcade inbuilt functions to draw circle :-
1. arcade.draw_circle_outline( ) : This function is used to draw the outline of a circle.
Syntax: arcade.draw_circle_outline(center_x, center_y, radius, color, border_width, num_segments)
Parameters:
center_x – x position that is the center of the circle.
center_y – y position that is the center of the circle.
radius – width of the circle.
color – color which with outline will be drawn.
border_width – Width of the circle outline in pixels.
num_segments – Higher is the number of segments, higher is the quality, but slower render time. The default value is -1 which means arcade will try to calculate a reasonable amount of segments based on the size of the circle.
Let’s take an example-
Python3
#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, "Draw an arc for GfG ") #set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() #function to draw a circlearcade.draw_circle_outline(300, 285, 88, arcade.color.GREEN, 9,-1) #finish drawingarcade.finish_render() #to display everythingarcade.run()
Output:
Since, now you know how to draw a simple outline of a circle. Let’s draw the Olympic flag using this arcade.draw_circle_outline( ).
Python3
#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, "Draw an arc for GfG ") # set background colorarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # function for designing olympic flagarcade.draw_circle_outline(100, 285, 88, arcade.color.BLUE, 9, -1)arcade.draw_circle_outline(300, 285, 88, arcade.color.BLACK, 9, -1)arcade.draw_circle_outline(500, 285, 88, arcade.color.RED, 9, -1)arcade.draw_circle_outline(200, 185, 88, arcade.color.YELLOW, 9, -1)arcade.draw_circle_outline(400, 185, 88, arcade.color.GREEN, 9, -1) # finished drawingarcade.finish_render() # to display everythingarcade.run()
Output:
2. arcade.draw_circle_filled( ) : This function is used to draw color filled circle .
Syntax: arcade.draw_circle_outline(center_x, center_y, radius, color, num_segments)
Parameters:
center_x – x position that is the center of the circle.
center_y – y position that is the center of the circle.
radius – width of the circle.
color – color which with outline will be drawn.
num_segments – Higher is the number of segments, higher is the quality, but slower render time. The default value is -1 which means arcade will try to calculate a reasonable amount of segments based on the size of the circle.
Let’s take an example-
Python3
#import moduleimport arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, "Draw a circle for GfG ") # set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # draw circlearcade.draw_circle_filled(300, 450, 78, arcade.color.PINK, 0) # finish drawingarcade.finish_render() # to display everythingarcade.run()
Output:
Since, now you know how to draw a simple outline of a circle. Let’s draw a snowman using this arcade.draw_circle_filled( ).
Python3
#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, "Draw a circle for GfG ") # set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # snowman upper partarcade.draw_circle_filled(300, 450, 68, arcade.color.SKY_BLUE, 0) # snowman eyesarcade.draw_circle_filled(289, 475, 8, arcade.color.BLACK, 0)arcade.draw_circle_filled(329, 475, 8, arcade.color.BLACK, 0) # snowman lower partarcade.draw_circle_filled(300, 350, 88, arcade.color.BLUE, 0)arcade.draw_circle_filled(300, 250, 108, arcade.color.SKY_BLUE, 0) # finish drawingarcade.finish_render() # to display everythingarcade.run()
Output:
gabaa406
rajeev0719singh
Python-Arcade
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
|
[
{
"code": null,
"e": 24589,
"s": 24561,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 24800,
"s": 24589,
"text": "The arcade library is a high-tech Python Package with advanced set of tools for making 2D games with gripping graphics and sound. It is Object-oriented and is especially built for Python 3.6 and above versions."
},
{
"code": null,
"e": 24843,
"s": 24800,
"text": "Arcade inbuilt functions to draw circle :-"
},
{
"code": null,
"e": 24936,
"s": 24843,
"text": "1. arcade.draw_circle_outline( ) : This function is used to draw the outline of a circle. "
},
{
"code": null,
"e": 25034,
"s": 24936,
"text": "Syntax: arcade.draw_circle_outline(center_x, center_y, radius, color, border_width, num_segments)"
},
{
"code": null,
"e": 25046,
"s": 25034,
"text": "Parameters:"
},
{
"code": null,
"e": 25103,
"s": 25046,
"text": "center_x – x position that is the center of the circle."
},
{
"code": null,
"e": 25160,
"s": 25103,
"text": "center_y – y position that is the center of the circle."
},
{
"code": null,
"e": 25191,
"s": 25160,
"text": "radius – width of the circle."
},
{
"code": null,
"e": 25239,
"s": 25191,
"text": "color – color which with outline will be drawn."
},
{
"code": null,
"e": 25293,
"s": 25239,
"text": "border_width – Width of the circle outline in pixels."
},
{
"code": null,
"e": 25519,
"s": 25293,
"text": "num_segments – Higher is the number of segments, higher is the quality, but slower render time. The default value is -1 which means arcade will try to calculate a reasonable amount of segments based on the size of the circle."
},
{
"code": null,
"e": 25542,
"s": 25519,
"text": "Let’s take an example-"
},
{
"code": null,
"e": 25550,
"s": 25542,
"text": "Python3"
},
{
"code": "#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, \"Draw an arc for GfG \") #set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() #function to draw a circlearcade.draw_circle_outline(300, 285, 88, arcade.color.GREEN, 9,-1) #finish drawingarcade.finish_render() #to display everythingarcade.run()",
"e": 25985,
"s": 25550,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25988,
"text": "Output:"
},
{
"code": null,
"e": 26132,
"s": 26000,
"text": "Since, now you know how to draw a simple outline of a circle. Let’s draw the Olympic flag using this arcade.draw_circle_outline( )."
},
{
"code": null,
"e": 26142,
"s": 26134,
"text": "Python3"
},
{
"code": "#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, \"Draw an arc for GfG \") # set background colorarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # function for designing olympic flagarcade.draw_circle_outline(100, 285, 88, arcade.color.BLUE, 9, -1)arcade.draw_circle_outline(300, 285, 88, arcade.color.BLACK, 9, -1)arcade.draw_circle_outline(500, 285, 88, arcade.color.RED, 9, -1)arcade.draw_circle_outline(200, 185, 88, arcade.color.YELLOW, 9, -1)arcade.draw_circle_outline(400, 185, 88, arcade.color.GREEN, 9, -1) # finished drawingarcade.finish_render() # to display everythingarcade.run()",
"e": 26866,
"s": 26142,
"text": null
},
{
"code": null,
"e": 26874,
"s": 26866,
"text": "Output:"
},
{
"code": null,
"e": 26961,
"s": 26874,
"text": "2. arcade.draw_circle_filled( ) : This function is used to draw color filled circle . "
},
{
"code": null,
"e": 27045,
"s": 26961,
"text": "Syntax: arcade.draw_circle_outline(center_x, center_y, radius, color, num_segments)"
},
{
"code": null,
"e": 27057,
"s": 27045,
"text": "Parameters:"
},
{
"code": null,
"e": 27114,
"s": 27057,
"text": "center_x – x position that is the center of the circle."
},
{
"code": null,
"e": 27171,
"s": 27114,
"text": "center_y – y position that is the center of the circle."
},
{
"code": null,
"e": 27202,
"s": 27171,
"text": "radius – width of the circle."
},
{
"code": null,
"e": 27250,
"s": 27202,
"text": "color – color which with outline will be drawn."
},
{
"code": null,
"e": 27476,
"s": 27250,
"text": "num_segments – Higher is the number of segments, higher is the quality, but slower render time. The default value is -1 which means arcade will try to calculate a reasonable amount of segments based on the size of the circle."
},
{
"code": null,
"e": 27499,
"s": 27476,
"text": "Let’s take an example-"
},
{
"code": null,
"e": 27507,
"s": 27499,
"text": "Python3"
},
{
"code": "#import moduleimport arcade # Open the window. Set the window title and dimensions (width and height)arcade.open_window(600, 600, \"Draw a circle for GfG \") # set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # draw circlearcade.draw_circle_filled(300, 450, 78, arcade.color.PINK, 0) # finish drawingarcade.finish_render() # to display everythingarcade.run()",
"e": 27929,
"s": 27507,
"text": null
},
{
"code": null,
"e": 27937,
"s": 27929,
"text": "Output:"
},
{
"code": null,
"e": 28061,
"s": 27937,
"text": "Since, now you know how to draw a simple outline of a circle. Let’s draw a snowman using this arcade.draw_circle_filled( )."
},
{
"code": null,
"e": 28069,
"s": 28061,
"text": "Python3"
},
{
"code": "#import moduleimport arcade # Open the window. Set the window title and# dimensions (width and height)arcade.open_window(600, 600, \"Draw a circle for GfG \") # set backgroundarcade.set_background_color(arcade.color.WHITE) # Start the render process.arcade.start_render() # snowman upper partarcade.draw_circle_filled(300, 450, 68, arcade.color.SKY_BLUE, 0) # snowman eyesarcade.draw_circle_filled(289, 475, 8, arcade.color.BLACK, 0)arcade.draw_circle_filled(329, 475, 8, arcade.color.BLACK, 0) # snowman lower partarcade.draw_circle_filled(300, 350, 88, arcade.color.BLUE, 0)arcade.draw_circle_filled(300, 250, 108, arcade.color.SKY_BLUE, 0) # finish drawingarcade.finish_render() # to display everythingarcade.run()",
"e": 28787,
"s": 28069,
"text": null
},
{
"code": null,
"e": 28795,
"s": 28787,
"text": "Output:"
},
{
"code": null,
"e": 28804,
"s": 28795,
"text": "gabaa406"
},
{
"code": null,
"e": 28820,
"s": 28804,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 28834,
"s": 28820,
"text": "Python-Arcade"
},
{
"code": null,
"e": 28841,
"s": 28834,
"text": "Python"
},
{
"code": null,
"e": 28939,
"s": 28841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28948,
"s": 28939,
"text": "Comments"
},
{
"code": null,
"e": 28961,
"s": 28948,
"text": "Old Comments"
},
{
"code": null,
"e": 28979,
"s": 28961,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29001,
"s": 28979,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29036,
"s": 29001,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29058,
"s": 29036,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29100,
"s": 29058,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29125,
"s": 29100,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29155,
"s": 29125,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29187,
"s": 29155,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29203,
"s": 29187,
"text": "Deque in Python"
}
] |
SQLAlchemy Core - Using Textual SQL
|
SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged.
It constructs a new TextClause, representing a textual SQL string directly as shown in the below code −
from sqlalchemy import text
t = text("SELECT * FROM students")
result = connection.execute(t)
The advantages text() provides over a plain string are −
backend-neutral support for bind parameters
per-statement execution options
result-column typing behaviour
The text()function requires Bound parameters in the named colon format. They are consistent regardless of database backend. To send values in for the parameters, we pass them into the execute() method as additional arguments.
The following example uses bound parameters in textual SQL −
from sqlalchemy.sql import text
s = text("select students.name, students.lastname from students where students.name between :x and :y")
conn.execute(s, x = 'A', y = 'L').fetchall()
The text() function constructs SQL expression as follows −
select students.name, students.lastname from students where students.name between ? and ?
The values of x = ’A’ and y = ’L’ are passed as parameters. Result is a list of rows with names between ‘A’ and ‘L’ −
[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]
The text() construct supports pre-established bound values using the TextClause.bindparams() method. The parameters can also be explicitly typed as follows −
stmt = text("SELECT * FROM students WHERE students.name BETWEEN :x AND :y")
stmt = stmt.bindparams(
bindparam("x", type_= String),
bindparam("y", type_= String)
)
result = conn.execute(stmt, {"x": "A", "y": "L"})
The text() function also be produces fragments of SQL within a select() object that
accepts text() objects as an arguments. The “geometry” of the statement is provided by
select() construct , and the textual content by text() construct. We can build a statement
without the need to refer to any pre-established Table metadata.
from sqlalchemy.sql import select
s = select([text("students.name, students.lastname from students")]).where(text("students.name between :x and :y"))
conn.execute(s, x = 'A', y = 'L').fetchall()
You can also use and_() function to combine multiple conditions in WHERE clause created with the help of text() function.
from sqlalchemy import and_
from sqlalchemy.sql import select
s = select([text("* from students")]) \
.where(
and_(
text("students.name between :x and :y"),
text("students.id>2")
)
)
conn.execute(s, x = 'A', y = 'L').fetchall()
Above code fetches rows with names between “A” and “L” with id greater than 2. The output of the code is given below −
[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]
21 Lectures
1.5 hours
Jack Chan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2610,
"s": 2340,
"text": "SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn’t a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged."
},
{
"code": null,
"e": 2714,
"s": 2610,
"text": "It constructs a new TextClause, representing a textual SQL string directly as shown in the below code −"
},
{
"code": null,
"e": 2808,
"s": 2714,
"text": "from sqlalchemy import text\nt = text(\"SELECT * FROM students\")\nresult = connection.execute(t)"
},
{
"code": null,
"e": 2865,
"s": 2808,
"text": "The advantages text() provides over a plain string are −"
},
{
"code": null,
"e": 2909,
"s": 2865,
"text": "backend-neutral support for bind parameters"
},
{
"code": null,
"e": 2941,
"s": 2909,
"text": "per-statement execution options"
},
{
"code": null,
"e": 2972,
"s": 2941,
"text": "result-column typing behaviour"
},
{
"code": null,
"e": 3198,
"s": 2972,
"text": "The text()function requires Bound parameters in the named colon format. They are consistent regardless of database backend. To send values in for the parameters, we pass them into the execute() method as additional arguments."
},
{
"code": null,
"e": 3259,
"s": 3198,
"text": "The following example uses bound parameters in textual SQL −"
},
{
"code": null,
"e": 3440,
"s": 3259,
"text": "from sqlalchemy.sql import text\ns = text(\"select students.name, students.lastname from students where students.name between :x and :y\")\nconn.execute(s, x = 'A', y = 'L').fetchall()"
},
{
"code": null,
"e": 3499,
"s": 3440,
"text": "The text() function constructs SQL expression as follows −"
},
{
"code": null,
"e": 3589,
"s": 3499,
"text": "select students.name, students.lastname from students where students.name between ? and ?"
},
{
"code": null,
"e": 3707,
"s": 3589,
"text": "The values of x = ’A’ and y = ’L’ are passed as parameters. Result is a list of rows with names between ‘A’ and ‘L’ −"
},
{
"code": null,
"e": 3752,
"s": 3707,
"text": "[('Komal', 'Bhandari'), ('Abdul', 'Sattar')]"
},
{
"code": null,
"e": 3910,
"s": 3752,
"text": "The text() construct supports pre-established bound values using the TextClause.bindparams() method. The parameters can also be explicitly typed as follows −"
},
{
"code": null,
"e": 4660,
"s": 3910,
"text": "stmt = text(\"SELECT * FROM students WHERE students.name BETWEEN :x AND :y\")\n\nstmt = stmt.bindparams(\n bindparam(\"x\", type_= String), \n bindparam(\"y\", type_= String)\n)\n\nresult = conn.execute(stmt, {\"x\": \"A\", \"y\": \"L\"})\n\nThe text() function also be produces fragments of SQL within a select() object that \naccepts text() objects as an arguments. The “geometry” of the statement is provided by \nselect() construct , and the textual content by text() construct. We can build a statement \nwithout the need to refer to any pre-established Table metadata. \n\nfrom sqlalchemy.sql import select\ns = select([text(\"students.name, students.lastname from students\")]).where(text(\"students.name between :x and :y\"))\nconn.execute(s, x = 'A', y = 'L').fetchall()"
},
{
"code": null,
"e": 4782,
"s": 4660,
"text": "You can also use and_() function to combine multiple conditions in WHERE clause created with the help of text() function."
},
{
"code": null,
"e": 5028,
"s": 4782,
"text": "from sqlalchemy import and_\nfrom sqlalchemy.sql import select\ns = select([text(\"* from students\")]) \\\n.where(\n and_(\n text(\"students.name between :x and :y\"),\n text(\"students.id>2\")\n )\n)\nconn.execute(s, x = 'A', y = 'L').fetchall()"
},
{
"code": null,
"e": 5147,
"s": 5028,
"text": "Above code fetches rows with names between “A” and “L” with id greater than 2. The output of the code is given below −"
},
{
"code": null,
"e": 5199,
"s": 5147,
"text": "[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar')]\n"
},
{
"code": null,
"e": 5234,
"s": 5199,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5245,
"s": 5234,
"text": " Jack Chan"
},
{
"code": null,
"e": 5252,
"s": 5245,
"text": " Print"
},
{
"code": null,
"e": 5263,
"s": 5252,
"text": " Add Notes"
}
] |
Calculate the area of an image using Matplotlib - GeeksforGeeks
|
31 Jul, 2021
Let us see how to calculate the area of an image in Python using Matplotlib.
Algorithm:
Import the matplotlib.pyplot module.Import an image using the imread() method.Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.Calculate the area as, area = height * width.Display the area.
Import the matplotlib.pyplot module.
Import an image using the imread() method.
Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.
Calculate the area as, area = height * width.
Display the area.
Example 1: Consider the following image :
“GFG.jpg”
Python3
# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread("GFG.jpg") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint("Area of the image is : ", area)
Output :
Area of the image is : 50244
Example 2: Consider the following image :
“image.jpg”
Python3
# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread("image.jpg") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint("Area of the image is : ", area)
Output :
Area of the image is : 213200
gulshankumarar231
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 30302,
"s": 30274,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 30380,
"s": 30302,
"text": "Let us see how to calculate the area of an image in Python using Matplotlib. "
},
{
"code": null,
"e": 30392,
"s": 30380,
"text": "Algorithm: "
},
{
"code": null,
"e": 30659,
"s": 30392,
"text": "Import the matplotlib.pyplot module.Import an image using the imread() method.Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image.Calculate the area as, area = height * width.Display the area."
},
{
"code": null,
"e": 30696,
"s": 30659,
"text": "Import the matplotlib.pyplot module."
},
{
"code": null,
"e": 30739,
"s": 30696,
"text": "Import an image using the imread() method."
},
{
"code": null,
"e": 30866,
"s": 30739,
"text": "Use the shape attribute of the image to get the height and width of the image. It fetches the number of channels in the image."
},
{
"code": null,
"e": 30912,
"s": 30866,
"text": "Calculate the area as, area = height * width."
},
{
"code": null,
"e": 30930,
"s": 30912,
"text": "Display the area."
},
{
"code": null,
"e": 30974,
"s": 30930,
"text": "Example 1: Consider the following image : "
},
{
"code": null,
"e": 30984,
"s": 30974,
"text": "“GFG.jpg”"
},
{
"code": null,
"e": 30992,
"s": 30984,
"text": "Python3"
},
{
"code": "# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread(\"GFG.jpg\") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint(\"Area of the image is : \", area)",
"e": 31269,
"s": 30992,
"text": null
},
{
"code": null,
"e": 31279,
"s": 31269,
"text": "Output : "
},
{
"code": null,
"e": 31308,
"s": 31279,
"text": "Area of the image is : 50244"
},
{
"code": null,
"e": 31351,
"s": 31308,
"text": "Example 2: Consider the following image : "
},
{
"code": null,
"e": 31363,
"s": 31351,
"text": "“image.jpg”"
},
{
"code": null,
"e": 31371,
"s": 31363,
"text": "Python3"
},
{
"code": "# import necessary libraryimport matplotlib.pyplot as plt # read an imageimg = plt.imread(\"image.jpg\") # fetch the height and widthheight, width, _ = img.shape # area is calculated as “height x width”area = height * width # display the areaprint(\"Area of the image is : \", area)",
"e": 31650,
"s": 31371,
"text": null
},
{
"code": null,
"e": 31660,
"s": 31650,
"text": "Output : "
},
{
"code": null,
"e": 31690,
"s": 31660,
"text": "Area of the image is : 213200"
},
{
"code": null,
"e": 31710,
"s": 31692,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 31728,
"s": 31710,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 31735,
"s": 31728,
"text": "Python"
},
{
"code": null,
"e": 31833,
"s": 31735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31861,
"s": 31833,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 31911,
"s": 31861,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 31933,
"s": 31911,
"text": "Python map() function"
},
{
"code": null,
"e": 31977,
"s": 31933,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 31995,
"s": 31977,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32018,
"s": 31995,
"text": "Taking input in Python"
},
{
"code": null,
"e": 32053,
"s": 32018,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 32075,
"s": 32053,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 32107,
"s": 32075,
"text": "How to Install PIP on Windows ?"
}
] |
Implementing Gauss Seidel Method in Java - GeeksforGeeks
|
28 Jul, 2021
Gauss-Seidel (also known as successive displacement method) is a mathematical computational method mainly used to find the solution of a System of Linear Algebra. Ever heard of the Jacobi Method? Well, the Gauss-Seidel is nothing but a better version of the Jacobi.
Example :
Input:
Enter the number of variables in the equation:
2
Enter the augmented matrix:
1 2 3
6 5 4
Output:
6.0 5.0 4.0
1.0 2.0 3.0
X0 = {0.6666666666666666 1.1666666666666667 }
X1 = {-0.30555555555555564 1.652777777777778 }
X2 = {-0.7106481481481481 1.855324074074074 }
X3 = {-0.8794367283950617 1.9397183641975309 }
X4 = {-0.9497653034979425 1.9748826517489713 }
X5 = {-0.9790688764574759 1.9895344382287379 }
X6 = {-0.9912786985239483 1.9956393492619742 }
X7 = {-0.9963661243849785 1.9981830621924892 }
X8 = {-0.9984858851604077 1.9992429425802039 }
X9 = {-0.9993691188168363 1.999684559408418 }
X10 = {-0.9997371328403484 1.999868566420174 }
X11 = {-0.9998904720168117 1.9999452360084058 }
X12 = {-0.999954363340338 1.999977181670169 }
X13 = {-0.9999809847251406 1.9999904923625702 }
X14 = {-0.9999920769688085 1.9999960384844042 }
X15 = {-0.9999966987370034 1.9999983493685016 }
X16 = {-0.9999986244737512 1.9999993122368755 }
X17 = {-0.9999994268640631 1.9999997134320315 }
X18 = {-0.9999997611933598 1.9999998805966799 }
X19 = {-0.9999999004972331 1.9999999502486165 }
X20 = {-0.9999999585405137 1.9999999792702567 }
X21 = {-0.999999982725214 1.999999991362607 }
X22 = {-0.9999999928021724 1.9999999964010862 }
X23 = {-0.999999997000905 1.9999999985004524 }
X24 = {-0.999999998750377 1.9999999993751885 }
X25 = {-0.9999999994793237 1.9999999997396618 }
X26 = {-0.9999999997830514 1.9999999998915257 }
X27 = {-0.9999999999096048 1.9999999999548024 }
X28 = {-0.9999999999623352 1.9999999999811675 }
X29 = {-0.9999999999843061 1.999999999992153 }
X30 = {-0.9999999999934606 1.9999999999967302 }
X31 = {-0.9999999999972751 1.9999999999986375 }
X32 = {-0.9999999999988646 1.9999999999994322 }
X33 = {-0.9999999999995268 1.9999999999997633 }
X34 = {-0.9999999999998028 1.9999999999999014 }
X35 = {-0.9999999999999176 1.9999999999999587 }
X36 = {-0.9999999999999656 1.9999999999999827 }
X37 = {-0.9999999999999855 1.9999999999999927 }
X38 = {-0.9999999999999938 1.999999999999997 }
X39 = {-0.9999999999999973 1.9999999999999987 }
X40 = {-0.9999999999999988 1.9999999999999993 }
X41 = {-0.9999999999999993 1.9999999999999996 }
A basic mathematical algorithm for the Gauss Seidel:
Given a set of n equations and n unknowns:
a11x1+a12x2+a13x3+......+a1nxn=c1
a21x1+a22x2+a23x3+......+a2nxn=c2
. .
. .
. .
a1nx1+a2nx2+a3nx3+......+annxn=cn
If the diagonal elements are non-zero, each equation is rewritten for the corresponding unknown, that is, the first equation is rewritten with x1 on the left hand side, the second equation is rewritten with x2 on the left hand side and so on as follows:
x1=(c1-a12x2-a13x3-....-a1nxn)/a11
x2=(c2-a21x1-a23x3-....-a2nxn)/a22
.
.
.
xn=(cn-an1x1-an2x2-....-an.n-1xn-1)/ann
.These equations can be re-written in the form as:
x1=(c1-nj=1,j!=1∑a1jxj)/a11
x2=(c2-nj=1,j!=2∑a2jxj)/a22
.
.
.
x2=(cn-nj=1,j!=n∑anjxj)/ann
Hence, for any row i ;
xi=(ci- nj=i,j!=i∑aijxj)/aii , i=1,2,..,n
Note: Gauss-Seidel is applicable to strictly diagonally dominant or symmetric positive definite.
In short, for a linear system of equations, say:
Ax=b
Deduced formula:
xi(k)=(bi-∑j<i a i j x j(k)-∑j>i a i j x j(k-1))/aii
In terms of matrices, the definition of Gauss-Seidel:
x(k)=(D-L)-1(Ux(k-1)+b)
Here, D represents the diagonal part of the matrix A, -L strictly lower triangle part of A, U strictly upper triangle part of A.
Programming algorithm:
Take the number of variables in the equation and the values of the augmented matrix (formed by appending the columns of the two given matrices) as the input.Checking if the given augmented matrix is diagonally dominant.Attempting to transform the given augmented matrix into diagonally dominant. If proved otherwise, then an appropriate message returned to the user.Computing and printing the final result as well as the iterations.
Take the number of variables in the equation and the values of the augmented matrix (formed by appending the columns of the two given matrices) as the input.
Checking if the given augmented matrix is diagonally dominant.
Attempting to transform the given augmented matrix into diagonally dominant. If proved otherwise, then an appropriate message returned to the user.
Computing and printing the final result as well as the iterations.
Implementation in Java:
Java
// Implementing Gauss Seidel Method in Javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Arrays;import java.util.StringTokenizer; class GFG { // we set a max number of iterations to // prevent an infinite loop public static final int MAX_ITERATIONS = 100; private double[][] M; public GFG(double[][] matrix) { M = matrix; } public void print() // printing { int n = M.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n + 1; j++) System.out.print(M[i][j] + " "); System.out.println(); } } // attempting to change a matrix to dominant // if proved that it is not public boolean transformToDominant(int r, boolean[] V, int[] R) { int n = M.length; if (r == M.length) { double[][] T = new double[n][n + 1]; for (int i = 0; i < R.length; i++) { for (int j = 0; j < n + 1; j++) T[i][j] = M[R[i]][j]; } M = T; return true; } for (int i = 0; i < n; i++) { if (V[i]) continue; double sum = 0; for (int j = 0; j < n; j++) sum += Math.abs(M[i][j]); if (2 * Math.abs(M[i][r]) > sum) { // diagonally dominant? V[i] = true; R[r] = i; if (transformToDominant(r + 1, V, R)) return true; V[i] = false; } } return false; } // method to check whether matrix is // diagonally dominant or not public boolean makeDominant() { boolean[] visited = new boolean[M.length]; int[] rows = new int[M.length]; Arrays.fill(visited, false); return transformToDominant(0, visited, rows); } // method to find the solution of the matrix // after all conditions are satisfied public void solve() { int iterations = 0; int n = M.length; double epsilon = 1e-15; double[] X = new double[n]; // Approximations double[] P = new double[n]; // Prev Arrays.fill(X, 0); while (true) { for (int i = 0; i < n; i++) { double sum = M[i][n]; // b_n for (int j = 0; j < n; j++) if (j != i) sum -= M[i][j] * X[j]; // Update xi to use in the next // row calculation X[i] = 1 / M[i][i] * sum; } System.out.print("X" + iterations + " = {"); for (int i = 0; i < n; i++) System.out.print(X[i] + " "); System.out.println("}"); iterations++; if (iterations == 1) continue; boolean stop = true; for (int i = 0; i < n && stop; i++) if (Math.abs(X[i] - P[i]) > epsilon) stop = false; if (stop || iterations == MAX_ITERATIONS) break; P = (double[])X.clone(); } } public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(System.out, true); int n = 2, k = 1; double[][] M = new double[n][n + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n + 1; j++) M[i][j] = k++; } GFG gausSeidel = new GFG(M); if (!gausSeidel.makeDominant()) { // if it is found that a matrix cannot be // changed into diagonally dominant then we // return the message to the user writer.println( "The system isn't diagonally dominant: " + "The method cannot guarantee convergence."); } writer.println(); gausSeidel.print(); gausSeidel.solve(); }}
The system isn't diagonally dominant: The method cannot guarantee convergence.
1.0 2.0 3.0
4.0 5.0 6.0
X0 = {3.0 -1.2000000000000002 }
X1 = {5.4 -3.1200000000000006 }
X2 = {9.240000000000002 -6.192000000000002 }
X3 = {15.384000000000004 -11.107200000000004 }
X4 = {25.21440000000001 -18.97152000000001 }
X5 = {40.94304000000002 -31.554432000000016 }
X6 = {66.10886400000004 -51.68709120000003 }
X7 = {106.37418240000007 -83.89934592000006 }
X8 = {170.79869184000012 -135.4389534720001 }
X9 = {273.8779069440002 -217.90232555520015 }
X10 = {438.8046511104003 -349.84372088832026 }
X11 = {702.6874417766405 -560.9499534213124 }
X12 = {1124.899906842625 -898.7199254740999 }
X13 = {1800.4398509481998 -1439.1518807585599 }
X14 = {2881.3037615171197 -2303.843009213696 }
X15 = {4610.686018427392 -3687.348814741914 }
X16 = {7377.697629483828 -5900.958103587062 }
X17 = {11804.916207174125 -9442.7329657393 }
X18 = {18888.4659314786 -15109.57274518288 }
X19 = {30222.14549036576 -24176.51639229261 }
X20 = {48356.03278458522 -38683.62622766818 }
X21 = {77370.25245533636 -61895.00196426909 }
X22 = {123793.00392853818 -99033.20314283055 }
X23 = {198069.4062856611 -158454.3250285289 }
X24 = {316911.6500570578 -253528.12004564624 }
X25 = {507059.2400912925 -405646.192073034 }
X26 = {811295.384146068 -649035.1073168544 }
X27 = {1298073.2146337088 -1038457.3717069671 }
X28 = {2076917.7434139343 -1661532.9947311475 }
X29 = {3323068.989462295 -2658453.991569836 }
X30 = {5316910.983139672 -4253527.586511738 }
X31 = {8507058.173023475 -6805645.338418781 }
X32 = {1.3611293676837562E7 -1.088903374147005E7 }
X33 = {2.17780704829401E7 -1.742245518635208E7 }
X34 = {3.484491337270416E7 -2.787592949816333E7 }
X35 = {5.575186199632666E7 -4.460148839706133E7 }
X36 = {8.920297979412267E7 -7.136238263529813E7 }
X37 = {1.4272476827059627E8 -1.1417981341647702E8 }
X38 = {2.2835962983295405E8 -1.8268770266636324E8 }
X39 = {3.653754083327265E8 -2.923003254661812E8 }
X40 = {5.846006539323624E8 -4.6768052194588995E8 }
X41 = {9.353610468917799E8 -7.48288836313424E8 }
X42 = {1.496577675626848E9 -1.1972621393014784E9 }
X43 = {2.394524281602957E9 -1.9156194240823655E9 }
X44 = {3.831238851164731E9 -3.064991079731785E9 }
X45 = {6.12998216246357E9 -4.903985728770856E9 }
X46 = {9.807971460541712E9 -7.84637716723337E9 }
X47 = {1.569275433746674E10 -1.2554203468773392E10 }
X48 = {2.5108406940546783E10 -2.0086725551237427E10 }
X49 = {4.017345110547485E10 -3.2138760883179886E10 }
X50 = {6.427752176935977E10 -5.142201741428782E10 }
X51 = {1.0284403483157564E11 -8.227522786406052E10 }
X52 = {1.6455045573112103E11 -1.3164036458369684E11 }
X53 = {2.6328072917039368E11 -2.1062458333511496E11 }
X54 = {4.212491666732299E11 -3.36999333337384E11 }
X55 = {6.73998666677768E11 -5.391989333410144E11 }
X56 = {1.0783978666850288E12 -8.627182933468231E11 }
X57 = {1.7254365866966462E12 -1.3803492693561172E12 }
X58 = {2.7606985387152344E12 -2.208558830970988E12 }
X59 = {4.417117661944976E12 -3.533694129554781E12 }
X60 = {7.067388259112562E12 -5.65391060728885E12 }
X61 = {1.13078212145807E13 -9.04625697166336E12 }
X62 = {1.809251394332972E13 -1.4474011154662576E13 }
X63 = {2.8948022309328152E13 -2.3158417847461324E13 }
X64 = {4.631683569492565E13 -3.705346855593932E13 }
X65 = {7.410693711188164E13 -5.928554968950412E13 }
X66 = {1.1857109937901123E14 -9.48568795032078E13 }
X67 = {1.897137590064186E14 -1.517710072051337E14 }
X68 = {3.035420144102704E14 -2.4283361152821512E14 }
X69 = {4.8566722305643325E14 -3.8853377844514544E14 }
X70 = {7.770675568902939E14 -6.216540455122339E14 }
X71 = {1.2433080910244708E15 -9.946464728195755E14 }
X72 = {1.989292945639154E15 -1.591434356511322E15 }
X73 = {3.182868713022647E15 -2.5462949704181165E15 }
X74 = {5.092589940836236E15 -4.0740719526689875E15 }
X75 = {8.148143905337978E15 -6.518515124270381E15 }
X76 = {1.3037030248540764E16 -1.042962419883261E16 }
X77 = {2.0859248397665224E16 -1.668739871813218E16 }
X78 = {3.3374797436264364E16 -2.6699837949011492E16 }
X79 = {5.3399675898022984E16 -4.2719740718418392E16 }
X80 = {8.5439481436836784E16 -6.8351585149469432E16 }
X81 = {1.36703170298938864E17 -1.09362536239151104E17 }
X82 = {2.18725072478302208E17 -1.74980057982641792E17 }
X83 = {3.4996011596528358E17 -2.7996809277222688E17 }
X84 = {5.5993618554445376E17 -4.4794894843556301E17 }
X85 = {8.9589789687112602E17 -7.1671831749690086E17 }
X86 = {1.43343663499380173E18 -1.14674930799504141E18 }
X87 = {2.29349861599008282E18 -1.8347988927920663E18 }
X88 = {3.6695977855841326E18 -2.9356782284673065E18 }
X89 = {5.871356456934613E18 -4.697085165547691E18 }
X90 = {9.394170331095382E18 -7.5153362648763064E18 }
X91 = {1.5030672529752613E19 -1.2024538023802092E19 }
X92 = {2.4049076047604183E19 -1.9239260838083346E19 }
X93 = {3.847852167616669E19 -3.0782817340933358E19 }
X94 = {6.1565634681866715E19 -4.925250774549338E19 }
X95 = {9.850501549098675E19 -7.880401239278941E19 }
X96 = {1.5760802478557882E20 -1.2608641982846306E20 }
X97 = {2.5217283965692612E20 -2.017382717255409E20 }
X98 = {4.034765434510818E20 -3.227812347608655E20 }
X99 = {6.45562469521731E20 -5.164499756173848E20 }
Time Complexity: O(N2)
AshokJaiswal
simmytarika5
anikakapoor
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file 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": 25347,
"s": 25319,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25615,
"s": 25347,
"text": "Gauss-Seidel (also known as successive displacement method) is a mathematical computational method mainly used to find the solution of a System of Linear Algebra. Ever heard of the Jacobi Method? Well, the Gauss-Seidel is nothing but a better version of the Jacobi. "
},
{
"code": null,
"e": 25625,
"s": 25615,
"text": "Example :"
},
{
"code": null,
"e": 27752,
"s": 25625,
"text": "Input:\nEnter the number of variables in the equation:\n2\nEnter the augmented matrix:\n1 2 3\n6 5 4\n \nOutput: \n6.0 5.0 4.0 \n1.0 2.0 3.0 \nX0 = {0.6666666666666666 1.1666666666666667 }\nX1 = {-0.30555555555555564 1.652777777777778 }\nX2 = {-0.7106481481481481 1.855324074074074 }\nX3 = {-0.8794367283950617 1.9397183641975309 }\nX4 = {-0.9497653034979425 1.9748826517489713 }\nX5 = {-0.9790688764574759 1.9895344382287379 }\nX6 = {-0.9912786985239483 1.9956393492619742 }\nX7 = {-0.9963661243849785 1.9981830621924892 }\nX8 = {-0.9984858851604077 1.9992429425802039 }\nX9 = {-0.9993691188168363 1.999684559408418 }\nX10 = {-0.9997371328403484 1.999868566420174 }\nX11 = {-0.9998904720168117 1.9999452360084058 }\nX12 = {-0.999954363340338 1.999977181670169 }\nX13 = {-0.9999809847251406 1.9999904923625702 }\nX14 = {-0.9999920769688085 1.9999960384844042 }\nX15 = {-0.9999966987370034 1.9999983493685016 }\nX16 = {-0.9999986244737512 1.9999993122368755 }\nX17 = {-0.9999994268640631 1.9999997134320315 }\nX18 = {-0.9999997611933598 1.9999998805966799 }\nX19 = {-0.9999999004972331 1.9999999502486165 }\nX20 = {-0.9999999585405137 1.9999999792702567 }\nX21 = {-0.999999982725214 1.999999991362607 }\nX22 = {-0.9999999928021724 1.9999999964010862 }\nX23 = {-0.999999997000905 1.9999999985004524 }\nX24 = {-0.999999998750377 1.9999999993751885 }\nX25 = {-0.9999999994793237 1.9999999997396618 }\nX26 = {-0.9999999997830514 1.9999999998915257 }\nX27 = {-0.9999999999096048 1.9999999999548024 }\nX28 = {-0.9999999999623352 1.9999999999811675 }\nX29 = {-0.9999999999843061 1.999999999992153 }\nX30 = {-0.9999999999934606 1.9999999999967302 }\nX31 = {-0.9999999999972751 1.9999999999986375 }\nX32 = {-0.9999999999988646 1.9999999999994322 }\nX33 = {-0.9999999999995268 1.9999999999997633 }\nX34 = {-0.9999999999998028 1.9999999999999014 }\nX35 = {-0.9999999999999176 1.9999999999999587 }\nX36 = {-0.9999999999999656 1.9999999999999827 }\nX37 = {-0.9999999999999855 1.9999999999999927 }\nX38 = {-0.9999999999999938 1.999999999999997 }\nX39 = {-0.9999999999999973 1.9999999999999987 }\nX40 = {-0.9999999999999988 1.9999999999999993 }\nX41 = {-0.9999999999999993 1.9999999999999996 }"
},
{
"code": null,
"e": 27805,
"s": 27752,
"text": "A basic mathematical algorithm for the Gauss Seidel:"
},
{
"code": null,
"e": 27848,
"s": 27805,
"text": "Given a set of n equations and n unknowns:"
},
{
"code": null,
"e": 28032,
"s": 27848,
"text": "a11x1+a12x2+a13x3+......+a1nxn=c1\n\na21x1+a22x2+a23x3+......+a2nxn=c2\n. .\n. .\n. .\na1nx1+a2nx2+a3nx3+......+annxn=cn"
},
{
"code": null,
"e": 28286,
"s": 28032,
"text": "If the diagonal elements are non-zero, each equation is rewritten for the corresponding unknown, that is, the first equation is rewritten with x1 on the left hand side, the second equation is rewritten with x2 on the left hand side and so on as follows:"
},
{
"code": null,
"e": 28402,
"s": 28286,
"text": "x1=(c1-a12x2-a13x3-....-a1nxn)/a11\nx2=(c2-a21x1-a23x3-....-a2nxn)/a22\n.\n.\n.\nxn=(cn-an1x1-an2x2-....-an.n-1xn-1)/ann"
},
{
"code": null,
"e": 28453,
"s": 28402,
"text": ".These equations can be re-written in the form as:"
},
{
"code": null,
"e": 28543,
"s": 28453,
"text": "x1=(c1-nj=1,j!=1∑a1jxj)/a11\nx2=(c2-nj=1,j!=2∑a2jxj)/a22\n.\n.\n.\nx2=(cn-nj=1,j!=n∑anjxj)/ann"
},
{
"code": null,
"e": 28566,
"s": 28543,
"text": "Hence, for any row i ;"
},
{
"code": null,
"e": 28608,
"s": 28566,
"text": "xi=(ci- nj=i,j!=i∑aijxj)/aii , i=1,2,..,n"
},
{
"code": null,
"e": 28705,
"s": 28608,
"text": "Note: Gauss-Seidel is applicable to strictly diagonally dominant or symmetric positive definite."
},
{
"code": null,
"e": 28755,
"s": 28705,
"text": "In short, for a linear system of equations, say: "
},
{
"code": null,
"e": 28760,
"s": 28755,
"text": "Ax=b"
},
{
"code": null,
"e": 28777,
"s": 28760,
"text": "Deduced formula:"
},
{
"code": null,
"e": 28830,
"s": 28777,
"text": "xi(k)=(bi-∑j<i a i j x j(k)-∑j>i a i j x j(k-1))/aii"
},
{
"code": null,
"e": 28884,
"s": 28830,
"text": "In terms of matrices, the definition of Gauss-Seidel:"
},
{
"code": null,
"e": 28908,
"s": 28884,
"text": "x(k)=(D-L)-1(Ux(k-1)+b)"
},
{
"code": null,
"e": 29037,
"s": 28908,
"text": "Here, D represents the diagonal part of the matrix A, -L strictly lower triangle part of A, U strictly upper triangle part of A."
},
{
"code": null,
"e": 29060,
"s": 29037,
"text": "Programming algorithm:"
},
{
"code": null,
"e": 29495,
"s": 29060,
"text": "Take the number of variables in the equation and the values of the augmented matrix (formed by appending the columns of the two given matrices) as the input.Checking if the given augmented matrix is diagonally dominant.Attempting to transform the given augmented matrix into diagonally dominant. If proved otherwise, then an appropriate message returned to the user.Computing and printing the final result as well as the iterations. "
},
{
"code": null,
"e": 29654,
"s": 29495,
"text": "Take the number of variables in the equation and the values of the augmented matrix (formed by appending the columns of the two given matrices) as the input."
},
{
"code": null,
"e": 29717,
"s": 29654,
"text": "Checking if the given augmented matrix is diagonally dominant."
},
{
"code": null,
"e": 29865,
"s": 29717,
"text": "Attempting to transform the given augmented matrix into diagonally dominant. If proved otherwise, then an appropriate message returned to the user."
},
{
"code": null,
"e": 29933,
"s": 29865,
"text": "Computing and printing the final result as well as the iterations. "
},
{
"code": null,
"e": 29958,
"s": 29933,
"text": "Implementation in Java: "
},
{
"code": null,
"e": 29963,
"s": 29958,
"text": "Java"
},
{
"code": "// Implementing Gauss Seidel Method in Javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Arrays;import java.util.StringTokenizer; class GFG { // we set a max number of iterations to // prevent an infinite loop public static final int MAX_ITERATIONS = 100; private double[][] M; public GFG(double[][] matrix) { M = matrix; } public void print() // printing { int n = M.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n + 1; j++) System.out.print(M[i][j] + \" \"); System.out.println(); } } // attempting to change a matrix to dominant // if proved that it is not public boolean transformToDominant(int r, boolean[] V, int[] R) { int n = M.length; if (r == M.length) { double[][] T = new double[n][n + 1]; for (int i = 0; i < R.length; i++) { for (int j = 0; j < n + 1; j++) T[i][j] = M[R[i]][j]; } M = T; return true; } for (int i = 0; i < n; i++) { if (V[i]) continue; double sum = 0; for (int j = 0; j < n; j++) sum += Math.abs(M[i][j]); if (2 * Math.abs(M[i][r]) > sum) { // diagonally dominant? V[i] = true; R[r] = i; if (transformToDominant(r + 1, V, R)) return true; V[i] = false; } } return false; } // method to check whether matrix is // diagonally dominant or not public boolean makeDominant() { boolean[] visited = new boolean[M.length]; int[] rows = new int[M.length]; Arrays.fill(visited, false); return transformToDominant(0, visited, rows); } // method to find the solution of the matrix // after all conditions are satisfied public void solve() { int iterations = 0; int n = M.length; double epsilon = 1e-15; double[] X = new double[n]; // Approximations double[] P = new double[n]; // Prev Arrays.fill(X, 0); while (true) { for (int i = 0; i < n; i++) { double sum = M[i][n]; // b_n for (int j = 0; j < n; j++) if (j != i) sum -= M[i][j] * X[j]; // Update xi to use in the next // row calculation X[i] = 1 / M[i][i] * sum; } System.out.print(\"X\" + iterations + \" = {\"); for (int i = 0; i < n; i++) System.out.print(X[i] + \" \"); System.out.println(\"}\"); iterations++; if (iterations == 1) continue; boolean stop = true; for (int i = 0; i < n && stop; i++) if (Math.abs(X[i] - P[i]) > epsilon) stop = false; if (stop || iterations == MAX_ITERATIONS) break; P = (double[])X.clone(); } } public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(System.out, true); int n = 2, k = 1; double[][] M = new double[n][n + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n + 1; j++) M[i][j] = k++; } GFG gausSeidel = new GFG(M); if (!gausSeidel.makeDominant()) { // if it is found that a matrix cannot be // changed into diagonally dominant then we // return the message to the user writer.println( \"The system isn't diagonally dominant: \" + \"The method cannot guarantee convergence.\"); } writer.println(); gausSeidel.print(); gausSeidel.solve(); }}",
"e": 33944,
"s": 29963,
"text": null
},
{
"code": null,
"e": 39068,
"s": 33947,
"text": "The system isn't diagonally dominant: The method cannot guarantee convergence.\n\n1.0 2.0 3.0 \n4.0 5.0 6.0 \nX0 = {3.0 -1.2000000000000002 }\nX1 = {5.4 -3.1200000000000006 }\nX2 = {9.240000000000002 -6.192000000000002 }\nX3 = {15.384000000000004 -11.107200000000004 }\nX4 = {25.21440000000001 -18.97152000000001 }\nX5 = {40.94304000000002 -31.554432000000016 }\nX6 = {66.10886400000004 -51.68709120000003 }\nX7 = {106.37418240000007 -83.89934592000006 }\nX8 = {170.79869184000012 -135.4389534720001 }\nX9 = {273.8779069440002 -217.90232555520015 }\nX10 = {438.8046511104003 -349.84372088832026 }\nX11 = {702.6874417766405 -560.9499534213124 }\nX12 = {1124.899906842625 -898.7199254740999 }\nX13 = {1800.4398509481998 -1439.1518807585599 }\nX14 = {2881.3037615171197 -2303.843009213696 }\nX15 = {4610.686018427392 -3687.348814741914 }\nX16 = {7377.697629483828 -5900.958103587062 }\nX17 = {11804.916207174125 -9442.7329657393 }\nX18 = {18888.4659314786 -15109.57274518288 }\nX19 = {30222.14549036576 -24176.51639229261 }\nX20 = {48356.03278458522 -38683.62622766818 }\nX21 = {77370.25245533636 -61895.00196426909 }\nX22 = {123793.00392853818 -99033.20314283055 }\nX23 = {198069.4062856611 -158454.3250285289 }\nX24 = {316911.6500570578 -253528.12004564624 }\nX25 = {507059.2400912925 -405646.192073034 }\nX26 = {811295.384146068 -649035.1073168544 }\nX27 = {1298073.2146337088 -1038457.3717069671 }\nX28 = {2076917.7434139343 -1661532.9947311475 }\nX29 = {3323068.989462295 -2658453.991569836 }\nX30 = {5316910.983139672 -4253527.586511738 }\nX31 = {8507058.173023475 -6805645.338418781 }\nX32 = {1.3611293676837562E7 -1.088903374147005E7 }\nX33 = {2.17780704829401E7 -1.742245518635208E7 }\nX34 = {3.484491337270416E7 -2.787592949816333E7 }\nX35 = {5.575186199632666E7 -4.460148839706133E7 }\nX36 = {8.920297979412267E7 -7.136238263529813E7 }\nX37 = {1.4272476827059627E8 -1.1417981341647702E8 }\nX38 = {2.2835962983295405E8 -1.8268770266636324E8 }\nX39 = {3.653754083327265E8 -2.923003254661812E8 }\nX40 = {5.846006539323624E8 -4.6768052194588995E8 }\nX41 = {9.353610468917799E8 -7.48288836313424E8 }\nX42 = {1.496577675626848E9 -1.1972621393014784E9 }\nX43 = {2.394524281602957E9 -1.9156194240823655E9 }\nX44 = {3.831238851164731E9 -3.064991079731785E9 }\nX45 = {6.12998216246357E9 -4.903985728770856E9 }\nX46 = {9.807971460541712E9 -7.84637716723337E9 }\nX47 = {1.569275433746674E10 -1.2554203468773392E10 }\nX48 = {2.5108406940546783E10 -2.0086725551237427E10 }\nX49 = {4.017345110547485E10 -3.2138760883179886E10 }\nX50 = {6.427752176935977E10 -5.142201741428782E10 }\nX51 = {1.0284403483157564E11 -8.227522786406052E10 }\nX52 = {1.6455045573112103E11 -1.3164036458369684E11 }\nX53 = {2.6328072917039368E11 -2.1062458333511496E11 }\nX54 = {4.212491666732299E11 -3.36999333337384E11 }\nX55 = {6.73998666677768E11 -5.391989333410144E11 }\nX56 = {1.0783978666850288E12 -8.627182933468231E11 }\nX57 = {1.7254365866966462E12 -1.3803492693561172E12 }\nX58 = {2.7606985387152344E12 -2.208558830970988E12 }\nX59 = {4.417117661944976E12 -3.533694129554781E12 }\nX60 = {7.067388259112562E12 -5.65391060728885E12 }\nX61 = {1.13078212145807E13 -9.04625697166336E12 }\nX62 = {1.809251394332972E13 -1.4474011154662576E13 }\nX63 = {2.8948022309328152E13 -2.3158417847461324E13 }\nX64 = {4.631683569492565E13 -3.705346855593932E13 }\nX65 = {7.410693711188164E13 -5.928554968950412E13 }\nX66 = {1.1857109937901123E14 -9.48568795032078E13 }\nX67 = {1.897137590064186E14 -1.517710072051337E14 }\nX68 = {3.035420144102704E14 -2.4283361152821512E14 }\nX69 = {4.8566722305643325E14 -3.8853377844514544E14 }\nX70 = {7.770675568902939E14 -6.216540455122339E14 }\nX71 = {1.2433080910244708E15 -9.946464728195755E14 }\nX72 = {1.989292945639154E15 -1.591434356511322E15 }\nX73 = {3.182868713022647E15 -2.5462949704181165E15 }\nX74 = {5.092589940836236E15 -4.0740719526689875E15 }\nX75 = {8.148143905337978E15 -6.518515124270381E15 }\nX76 = {1.3037030248540764E16 -1.042962419883261E16 }\nX77 = {2.0859248397665224E16 -1.668739871813218E16 }\nX78 = {3.3374797436264364E16 -2.6699837949011492E16 }\nX79 = {5.3399675898022984E16 -4.2719740718418392E16 }\nX80 = {8.5439481436836784E16 -6.8351585149469432E16 }\nX81 = {1.36703170298938864E17 -1.09362536239151104E17 }\nX82 = {2.18725072478302208E17 -1.74980057982641792E17 }\nX83 = {3.4996011596528358E17 -2.7996809277222688E17 }\nX84 = {5.5993618554445376E17 -4.4794894843556301E17 }\nX85 = {8.9589789687112602E17 -7.1671831749690086E17 }\nX86 = {1.43343663499380173E18 -1.14674930799504141E18 }\nX87 = {2.29349861599008282E18 -1.8347988927920663E18 }\nX88 = {3.6695977855841326E18 -2.9356782284673065E18 }\nX89 = {5.871356456934613E18 -4.697085165547691E18 }\nX90 = {9.394170331095382E18 -7.5153362648763064E18 }\nX91 = {1.5030672529752613E19 -1.2024538023802092E19 }\nX92 = {2.4049076047604183E19 -1.9239260838083346E19 }\nX93 = {3.847852167616669E19 -3.0782817340933358E19 }\nX94 = {6.1565634681866715E19 -4.925250774549338E19 }\nX95 = {9.850501549098675E19 -7.880401239278941E19 }\nX96 = {1.5760802478557882E20 -1.2608641982846306E20 }\nX97 = {2.5217283965692612E20 -2.017382717255409E20 }\nX98 = {4.034765434510818E20 -3.227812347608655E20 }\nX99 = {6.45562469521731E20 -5.164499756173848E20 }"
},
{
"code": null,
"e": 39093,
"s": 39070,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 39108,
"s": 39095,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 39121,
"s": 39108,
"text": "simmytarika5"
},
{
"code": null,
"e": 39133,
"s": 39121,
"text": "anikakapoor"
},
{
"code": null,
"e": 39140,
"s": 39133,
"text": "Picked"
},
{
"code": null,
"e": 39164,
"s": 39140,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 39169,
"s": 39164,
"text": "Java"
},
{
"code": null,
"e": 39183,
"s": 39169,
"text": "Java Programs"
},
{
"code": null,
"e": 39202,
"s": 39183,
"text": "Technical Scripter"
},
{
"code": null,
"e": 39207,
"s": 39202,
"text": "Java"
},
{
"code": null,
"e": 39305,
"s": 39207,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39320,
"s": 39305,
"text": "Stream In Java"
},
{
"code": null,
"e": 39339,
"s": 39320,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 39360,
"s": 39339,
"text": "Constructors in Java"
},
{
"code": null,
"e": 39390,
"s": 39360,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 39436,
"s": 39390,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 39462,
"s": 39436,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 39496,
"s": 39462,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 39543,
"s": 39496,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 39575,
"s": 39543,
"text": "How to Iterate HashMap in Java?"
}
] |
Character.hashCode() in Java with examples - GeeksforGeeks
|
06 Dec, 2018
Java.lang.Character.hashCode() is a built-in method in Java which returns a hash code for this Character. The returned hash code is equal to the result of invoking charValue().
Syntax:
public int hashCode()
This function does not accepts any parameter.
Return Value: This method returns a hash code value for this Character.
Below programs illustrate the Java.lang.Character.hashCode() function:
Program 1:
// Java program to demonstrate the// function when the value passed in the parameter// is a character import java.lang.*; public class Gfg { public static void main(String[] args) { // parameter ch char ch = 'B'; // assigns character values Character c = Character.valueOf(ch); // assign hashcodes of c1, c2 to i1, i2 int i = c.hashCode(); // prints the character values System.out.println("Hashcode of " + ch + " is " + i); }}
Hashcode of B is 66
Program 2:
// Java program to demonstrate the// function when the value passed in the parameter// is a number import java.lang.*; public class Gfg { public static void main(String[] args) { // parameter ch char ch = '6'; // assigns character values Character c = Character.valueOf(ch); // assign hashcodes of ch int i = c.hashCode(); // prints the character values System.out.println("Hashcode of " + ch + " is " + i); }}
Hashcode of 6 is 54
Java-Character
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
|
[
{
"code": null,
"e": 24312,
"s": 24284,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24489,
"s": 24312,
"text": "Java.lang.Character.hashCode() is a built-in method in Java which returns a hash code for this Character. The returned hash code is equal to the result of invoking charValue()."
},
{
"code": null,
"e": 24497,
"s": 24489,
"text": "Syntax:"
},
{
"code": null,
"e": 24567,
"s": 24497,
"text": "public int hashCode()\n\nThis function does not accepts any parameter.\n"
},
{
"code": null,
"e": 24639,
"s": 24567,
"text": "Return Value: This method returns a hash code value for this Character."
},
{
"code": null,
"e": 24710,
"s": 24639,
"text": "Below programs illustrate the Java.lang.Character.hashCode() function:"
},
{
"code": null,
"e": 24721,
"s": 24710,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate the// function when the value passed in the parameter// is a character import java.lang.*; public class Gfg { public static void main(String[] args) { // parameter ch char ch = 'B'; // assigns character values Character c = Character.valueOf(ch); // assign hashcodes of c1, c2 to i1, i2 int i = c.hashCode(); // prints the character values System.out.println(\"Hashcode of \" + ch + \" is \" + i); }}",
"e": 25242,
"s": 24721,
"text": null
},
{
"code": null,
"e": 25263,
"s": 25242,
"text": "Hashcode of B is 66\n"
},
{
"code": null,
"e": 25274,
"s": 25263,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate the// function when the value passed in the parameter// is a number import java.lang.*; public class Gfg { public static void main(String[] args) { // parameter ch char ch = '6'; // assigns character values Character c = Character.valueOf(ch); // assign hashcodes of ch int i = c.hashCode(); // prints the character values System.out.println(\"Hashcode of \" + ch + \" is \" + i); }}",
"e": 25779,
"s": 25274,
"text": null
},
{
"code": null,
"e": 25800,
"s": 25779,
"text": "Hashcode of 6 is 54\n"
},
{
"code": null,
"e": 25815,
"s": 25800,
"text": "Java-Character"
},
{
"code": null,
"e": 25830,
"s": 25815,
"text": "Java-Functions"
},
{
"code": null,
"e": 25848,
"s": 25830,
"text": "Java-lang package"
},
{
"code": null,
"e": 25853,
"s": 25848,
"text": "Java"
},
{
"code": null,
"e": 25858,
"s": 25853,
"text": "Java"
},
{
"code": null,
"e": 25956,
"s": 25858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25965,
"s": 25956,
"text": "Comments"
},
{
"code": null,
"e": 25978,
"s": 25965,
"text": "Old Comments"
},
{
"code": null,
"e": 26010,
"s": 25978,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26040,
"s": 26010,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26059,
"s": 26040,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26090,
"s": 26059,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26108,
"s": 26090,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26159,
"s": 26108,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26191,
"s": 26159,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26211,
"s": 26191,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26230,
"s": 26211,
"text": "LinkedList in Java"
}
] |
Print Bracket Number - GeeksforGeeks
|
21 May, 2021
Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed.Examples :
Input : (a+(b*c))+(d/e)
Output : 1 2 2 1 3 3
The highlighted brackets in the given expression
(a+(b*c))+(d/e) has been assigned the numbers as:
1 2 2 1 3 3.
Input : ((())(()))
Output : 1 2 3 3 2 4 5 5 4 1
Source: Flipkart Interview Experience | Set 49.
Approach :
Define a variable left_bnum = 1.Create a stack right_bnum.Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
Define a variable left_bnum = 1.
Create a stack right_bnum.
Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.
Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to print the bracket number#include <bits/stdc++.h> using namespace std; // function to print the bracket numbervoid printBracketNumber(string exp, int n){ // used to print the bracket number // for the left bracket int left_bnum = 1; // used to obtain the bracket number // for the right bracket stack<int> right_bnum; // traverse the given expression 'exp' for (int i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', cout << left_bnum << " "; // push 'left_bum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number cout << right_bnum.top() << " "; // pop the top element from the stack right_bnum.pop(); } }} // Driver program to test aboveint main(){ string exp = "(a+(b*c))+(d/e)"; int n = exp.size(); printBracketNumber(exp, n); return 0;}
// Java implementation to// print the bracket numberimport java.io.*;import java.util.*; class GFG{ // function to print // the bracket number static void printBracketNumber(String exp, int n) { // used to print the // bracket number for // the left bracket int left_bnum = 1; // used to obtain the // bracket number for // the right bracket Stack<Integer> right_bnum = new Stack<Integer>(); // traverse the given // expression 'exp' for (int i = 0; i < n; i++) { // if current character // is a left bracket if (exp.charAt(i) == '(') { // print 'left_bnum', System.out.print( left_bnum + " "); // push 'left_bum' on to // the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character // is a right bracket else if(exp.charAt(i) == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number System.out.print( right_bnum.peek() + " "); // pop the top element // from the stack right_bnum.pop(); } } } // Driver Code public static void main(String args[]) { String exp = "(a+(b*c))+(d/e)"; int n = exp.length(); printBracketNumber(exp, n); }} // This code is contributed// by Manish Shaw(manishshaw1)
# Python3 implementation to print the bracket number # function to print the bracket numberdef printBracketNumber(exp, n): # used to print the bracket number # for the left bracket left_bnum = 1 # used to obtain the bracket number # for the right bracket right_bnum = list() # traverse the given expression 'exp' for i in range(n): # if current character is a left bracket if exp[i] == '(': # print 'left_bnum', print(left_bnum, end = " ") # push 'left_bum' on to the stack 'right_bnum' right_bnum.append(left_bnum) # increment 'left_bnum' by 1 left_bnum += 1 # else if current character is a right bracket elif exp[i] == ')': # print the top element of stack 'right_bnum' # it will be the right bracket number print(right_bnum[-1], end = " ") # pop the top element from the stack right_bnum.pop() # Driver Codeif __name__ == "__main__": exp = "(a+(b*c))+(d/e)" n = len(exp) printBracketNumber(exp, n) # This code is contributed by# sanjeev2552
// C# implementation to// print the bracket numberusing System;using System.Collections.Generic; class GFG{ // function to print // the bracket number static void printBracketNumber(string exp, int n) { // used to print the bracket // number for the left bracket int left_bnum = 1; // used to obtain the bracket // number for the right bracket Stack<int> right_bnum = new Stack<int>(); // traverse the given // expression 'exp' for (int i = 0; i < n; i++) { // if current character // is a left bracket if (exp[i] == '(') { // print 'left_bnum', Console.Write(left_bnum + " "); // Push 'left_bum' on to // the stack 'right_bnum' right_bnum.Push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character // is a right bracket else if(exp[i] == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number Console.Write(right_bnum.Peek() + " "); // Pop the top element // from the stack right_bnum.Pop(); } } } // Driver Code static void Main() { string exp = "(a+(b*c))+(d/e)"; int n = exp.Length; printBracketNumber(exp, n); }} // This code is contributed// by Manish Shaw(manishshaw1)
<?php// PHP implementation to// print the bracket number // function to print// the bracket numberfunction printBracketNumber($exp, $n){ // used to print the // bracket number for // the left bracket $left_bnum = 1; // used to obtain the // bracket number for // the right bracket $right_bnum = array(); $t = 0; // traverse the given // expression 'exp' for ($i = 0; $i < $n; $i++) { // if current character // is a left bracket if ($exp[$i] == '(') { // print 'left_bnum', echo $left_bnum . " "; // push 'left_bum' on to // the stack 'right_bnum' $right_bnum[$t++] = $left_bnum; // increment 'left_bnum' by 1 $left_bnum++; } // else if current character // is a right bracket else if($exp[$i] == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number echo $right_bnum[$t - 1] . " "; // pop the top element // from the stack $right_bnum[$t - 1] = 1; $t--; } }} // Driver Code$exp = "(a+(b*c))+(d/e)";$n = strlen($exp); printBracketNumber($exp, $n); // This code is contributed// by mits?>
<script> // Javascript implementation to print the bracket number // function to print the bracket numberfunction printBracketNumber(exp, n){ // used to print the bracket number // for the left bracket var left_bnum = 1; // used to obtain the bracket number // for the right bracket var right_bnum = []; // traverse the given expression 'exp' for (var i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', document.write( left_bnum + " "); // push 'left_bum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number document.write( right_bnum[right_bnum.length-1] + " "); // pop the top element from the stack right_bnum.pop(); } }} // Driver program to test abovevar exp = "(a+(b*c))+(d/e)";var n = exp.length; printBracketNumber(exp, n); </script>
1 2 2 1 3 3
Time Complexity : O(n). Auxiliary Space : O(n).
YouTubeGeeksforGeeks500K subscribersPrint Bracket Number | 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 / 5:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hOO5pvZeH4s" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
manishshaw1
Mithun Kumar
sanjeev2552
rrrtnx
expression-evaluation
Flipkart
Mathematical
Stack
Strings
Flipkart
Strings
Mathematical
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Operators in C / C++
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Program for Tower of Hanoi
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 25064,
"s": 25036,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 25219,
"s": 25064,
"text": "Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed.Examples : "
},
{
"code": null,
"e": 25426,
"s": 25219,
"text": "Input : (a+(b*c))+(d/e)\nOutput : 1 2 2 1 3 3\nThe highlighted brackets in the given expression\n(a+(b*c))+(d/e) has been assigned the numbers as:\n1 2 2 1 3 3.\n\nInput : ((())(()))\nOutput : 1 2 3 3 2 4 5 5 4 1 "
},
{
"code": null,
"e": 25474,
"s": 25426,
"text": "Source: Flipkart Interview Experience | Set 49."
},
{
"code": null,
"e": 25489,
"s": 25476,
"text": "Approach : "
},
{
"code": null,
"e": 25807,
"s": 25489,
"text": "Define a variable left_bnum = 1.Create a stack right_bnum.Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack."
},
{
"code": null,
"e": 25840,
"s": 25807,
"text": "Define a variable left_bnum = 1."
},
{
"code": null,
"e": 25867,
"s": 25840,
"text": "Create a stack right_bnum."
},
{
"code": null,
"e": 26127,
"s": 25867,
"text": "Now, for i = 0 to n-1.If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack."
},
{
"code": null,
"e": 26365,
"s": 26127,
"text": "If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack."
},
{
"code": null,
"e": 26485,
"s": 26365,
"text": "If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1."
},
{
"code": null,
"e": 26604,
"s": 26485,
"text": "Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack."
},
{
"code": null,
"e": 26610,
"s": 26606,
"text": "C++"
},
{
"code": null,
"e": 26615,
"s": 26610,
"text": "Java"
},
{
"code": null,
"e": 26623,
"s": 26615,
"text": "Python3"
},
{
"code": null,
"e": 26626,
"s": 26623,
"text": "C#"
},
{
"code": null,
"e": 26630,
"s": 26626,
"text": "PHP"
},
{
"code": null,
"e": 26641,
"s": 26630,
"text": "Javascript"
},
{
"code": "// C++ implementation to print the bracket number#include <bits/stdc++.h> using namespace std; // function to print the bracket numbervoid printBracketNumber(string exp, int n){ // used to print the bracket number // for the left bracket int left_bnum = 1; // used to obtain the bracket number // for the right bracket stack<int> right_bnum; // traverse the given expression 'exp' for (int i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', cout << left_bnum << \" \"; // push 'left_bum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number cout << right_bnum.top() << \" \"; // pop the top element from the stack right_bnum.pop(); } }} // Driver program to test aboveint main(){ string exp = \"(a+(b*c))+(d/e)\"; int n = exp.size(); printBracketNumber(exp, n); return 0;}",
"e": 27951,
"s": 26641,
"text": null
},
{
"code": "// Java implementation to// print the bracket numberimport java.io.*;import java.util.*; class GFG{ // function to print // the bracket number static void printBracketNumber(String exp, int n) { // used to print the // bracket number for // the left bracket int left_bnum = 1; // used to obtain the // bracket number for // the right bracket Stack<Integer> right_bnum = new Stack<Integer>(); // traverse the given // expression 'exp' for (int i = 0; i < n; i++) { // if current character // is a left bracket if (exp.charAt(i) == '(') { // print 'left_bnum', System.out.print( left_bnum + \" \"); // push 'left_bum' on to // the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character // is a right bracket else if(exp.charAt(i) == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number System.out.print( right_bnum.peek() + \" \"); // pop the top element // from the stack right_bnum.pop(); } } } // Driver Code public static void main(String args[]) { String exp = \"(a+(b*c))+(d/e)\"; int n = exp.length(); printBracketNumber(exp, n); }} // This code is contributed// by Manish Shaw(manishshaw1)",
"e": 29854,
"s": 27951,
"text": null
},
{
"code": "# Python3 implementation to print the bracket number # function to print the bracket numberdef printBracketNumber(exp, n): # used to print the bracket number # for the left bracket left_bnum = 1 # used to obtain the bracket number # for the right bracket right_bnum = list() # traverse the given expression 'exp' for i in range(n): # if current character is a left bracket if exp[i] == '(': # print 'left_bnum', print(left_bnum, end = \" \") # push 'left_bum' on to the stack 'right_bnum' right_bnum.append(left_bnum) # increment 'left_bnum' by 1 left_bnum += 1 # else if current character is a right bracket elif exp[i] == ')': # print the top element of stack 'right_bnum' # it will be the right bracket number print(right_bnum[-1], end = \" \") # pop the top element from the stack right_bnum.pop() # Driver Codeif __name__ == \"__main__\": exp = \"(a+(b*c))+(d/e)\" n = len(exp) printBracketNumber(exp, n) # This code is contributed by# sanjeev2552",
"e": 30992,
"s": 29854,
"text": null
},
{
"code": "// C# implementation to// print the bracket numberusing System;using System.Collections.Generic; class GFG{ // function to print // the bracket number static void printBracketNumber(string exp, int n) { // used to print the bracket // number for the left bracket int left_bnum = 1; // used to obtain the bracket // number for the right bracket Stack<int> right_bnum = new Stack<int>(); // traverse the given // expression 'exp' for (int i = 0; i < n; i++) { // if current character // is a left bracket if (exp[i] == '(') { // print 'left_bnum', Console.Write(left_bnum + \" \"); // Push 'left_bum' on to // the stack 'right_bnum' right_bnum.Push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character // is a right bracket else if(exp[i] == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number Console.Write(right_bnum.Peek() + \" \"); // Pop the top element // from the stack right_bnum.Pop(); } } } // Driver Code static void Main() { string exp = \"(a+(b*c))+(d/e)\"; int n = exp.Length; printBracketNumber(exp, n); }} // This code is contributed// by Manish Shaw(manishshaw1)",
"e": 32770,
"s": 30992,
"text": null
},
{
"code": "<?php// PHP implementation to// print the bracket number // function to print// the bracket numberfunction printBracketNumber($exp, $n){ // used to print the // bracket number for // the left bracket $left_bnum = 1; // used to obtain the // bracket number for // the right bracket $right_bnum = array(); $t = 0; // traverse the given // expression 'exp' for ($i = 0; $i < $n; $i++) { // if current character // is a left bracket if ($exp[$i] == '(') { // print 'left_bnum', echo $left_bnum . \" \"; // push 'left_bum' on to // the stack 'right_bnum' $right_bnum[$t++] = $left_bnum; // increment 'left_bnum' by 1 $left_bnum++; } // else if current character // is a right bracket else if($exp[$i] == ')') { // print the top element // of stack 'right_bnum' // it will be the right // bracket number echo $right_bnum[$t - 1] . \" \"; // pop the top element // from the stack $right_bnum[$t - 1] = 1; $t--; } }} // Driver Code$exp = \"(a+(b*c))+(d/e)\";$n = strlen($exp); printBracketNumber($exp, $n); // This code is contributed// by mits?>",
"e": 34176,
"s": 32770,
"text": null
},
{
"code": "<script> // Javascript implementation to print the bracket number // function to print the bracket numberfunction printBracketNumber(exp, n){ // used to print the bracket number // for the left bracket var left_bnum = 1; // used to obtain the bracket number // for the right bracket var right_bnum = []; // traverse the given expression 'exp' for (var i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', document.write( left_bnum + \" \"); // push 'left_bum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number document.write( right_bnum[right_bnum.length-1] + \" \"); // pop the top element from the stack right_bnum.pop(); } }} // Driver program to test abovevar exp = \"(a+(b*c))+(d/e)\";var n = exp.length; printBracketNumber(exp, n); </script>",
"e": 35440,
"s": 34176,
"text": null
},
{
"code": null,
"e": 35452,
"s": 35440,
"text": "1 2 2 1 3 3"
},
{
"code": null,
"e": 35504,
"s": 35454,
"text": "Time Complexity : O(n). Auxiliary Space : O(n). "
},
{
"code": null,
"e": 36323,
"s": 35504,
"text": "YouTubeGeeksforGeeks500K subscribersPrint Bracket Number | 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 / 5:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hOO5pvZeH4s\" 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": 36337,
"s": 36325,
"text": "manishshaw1"
},
{
"code": null,
"e": 36350,
"s": 36337,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 36362,
"s": 36350,
"text": "sanjeev2552"
},
{
"code": null,
"e": 36369,
"s": 36362,
"text": "rrrtnx"
},
{
"code": null,
"e": 36391,
"s": 36369,
"text": "expression-evaluation"
},
{
"code": null,
"e": 36400,
"s": 36391,
"text": "Flipkart"
},
{
"code": null,
"e": 36413,
"s": 36400,
"text": "Mathematical"
},
{
"code": null,
"e": 36419,
"s": 36413,
"text": "Stack"
},
{
"code": null,
"e": 36427,
"s": 36419,
"text": "Strings"
},
{
"code": null,
"e": 36436,
"s": 36427,
"text": "Flipkart"
},
{
"code": null,
"e": 36444,
"s": 36436,
"text": "Strings"
},
{
"code": null,
"e": 36457,
"s": 36444,
"text": "Mathematical"
},
{
"code": null,
"e": 36463,
"s": 36457,
"text": "Stack"
},
{
"code": null,
"e": 36561,
"s": 36463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36570,
"s": 36561,
"text": "Comments"
},
{
"code": null,
"e": 36583,
"s": 36570,
"text": "Old Comments"
},
{
"code": null,
"e": 36626,
"s": 36583,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36650,
"s": 36626,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36664,
"s": 36650,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36713,
"s": 36664,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36734,
"s": 36713,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 36782,
"s": 36734,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36798,
"s": 36782,
"text": "Stack in Python"
},
{
"code": null,
"e": 36818,
"s": 36798,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 36845,
"s": 36818,
"text": "Program for Tower of Hanoi"
}
] |
MySQL Tryit Editor v1.0
|
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 105,
"s": 42,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 165,
"s": 105,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 233,
"s": 165,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 271,
"s": 233,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 356,
"s": 271,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 530,
"s": 356,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 581,
"s": 530,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 649,
"s": 581,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 820,
"s": 649,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 920,
"s": 820,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 970,
"s": 920,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
How to create a folder if it does not exist in C#?
|
For creating a directory, we must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories.
It is always recommended to check if the Directory exist before doing any file operation in C# because the complier will throw exception if the folder does not exist.
using System;
using System.IO;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string folderName = @"D:\Demo Folder";
// If directory does not exist, create it
if (!Directory.Exists(folderName)) {
Directory.CreateDirectory(folderName);
}
Console.ReadLine();
}
}
}
The above code will create a Demo Folder in the D: directory.
Directory.CreateDirectory can also be used to create subfolders.
using System;
using System.IO;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string folderName = @"D:\Demo Folder\Sub Folder";
// If directory does not exist, create it
if (!Directory.Exists(folderName)) {
Directory.CreateDirectory(folderName);
}
Console.ReadLine();
}
}
}
The above code will create a Demo Folder with a Sub Folder in the D: directory.
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "For creating a directory, we must first import the System.IO namespace in C#. The namespace is a library that allows you to access static methods for creating, copying, moving, and deleting directories."
},
{
"code": null,
"e": 1432,
"s": 1265,
"text": "It is always recommended to check if the Directory exist before doing any file operation in C# because the complier will throw exception if the folder does not exist."
},
{
"code": null,
"e": 1801,
"s": 1432,
"text": "using System;\nusing System.IO;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n string folderName = @\"D:\\Demo Folder\";\n // If directory does not exist, create it\n if (!Directory.Exists(folderName)) {\n Directory.CreateDirectory(folderName);\n }\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1863,
"s": 1801,
"text": "The above code will create a Demo Folder in the D: directory."
},
{
"code": null,
"e": 1928,
"s": 1863,
"text": "Directory.CreateDirectory can also be used to create subfolders."
},
{
"code": null,
"e": 2308,
"s": 1928,
"text": "using System;\nusing System.IO;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n string folderName = @\"D:\\Demo Folder\\Sub Folder\";\n // If directory does not exist, create it\n if (!Directory.Exists(folderName)) {\n Directory.CreateDirectory(folderName);\n }\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2388,
"s": 2308,
"text": "The above code will create a Demo Folder with a Sub Folder in the D: directory."
}
] |
Optimize Streamlit Deployment | Towards Data Science
|
What happens when you deploy a data app without coding for memory optimization? In my case, at least, the app crashed and I spent days painfully refactoring code. If you are luckier or smarter (or both), then you have nothing to worry about. Otherwise, consider lessons from my mistakes and some helpful resources to avoid your own special headaches.
How to avoid my optimization mistakes to deploy your app for the win.
I have always acknowledged the importance of writing optimized code but I did not fully appreciate what it meant until deploying a Web app. On my laptop, even the most poorly written code will likely run, albeit slowly. However, the consequences on the Web are far more severe — memory leaks and inefficient code can cripple the experience. If you don’t like waiting on an app to load, neither does the user.
towardsdatascience.com
In a previous article (linked above), I share a few issues that I encountered when deploying my app. Although I successfully got the app up and running, it started crashing after adding a larger dataset. As a result, in this article, I share some post-deployment problems and solutions.
App unavailable because it has gone over its resource limitsApp crashes a few hours after deployment and continues crashing after repeated reboots
App unavailable because it has gone over its resource limits
App crashes a few hours after deployment and continues crashing after repeated reboots
DataFrame size too large at over 270 megabytes (MB)! By comparison, 100 MB is probably already way too large. Although there is not a perfect size, for a table of 1 million rows, I eventually got the file down to about 50 MB — still hefty but manageable.
Lesson 1: Exhaust all possible options to reduce the DataFrame’s size.
towardsdatascience.com
App holds DataFrame in memory. There is a tradeoff here — hold data in memory for fast access, but hold too much and everything breaks. Without thinking about it, coded the app to hold the entire DataFrame (the one that was way too large to begin with) in memory — this turned out to be a disaster.
Lesson 2: Be intentional about what is stored in memory.
Function Caching. After I started searching for advice on a crashing Web app, I discovered that Streamlit has a handy @st.cache function decorator. Then, after implementing caching in correctly, I learned about TTL. To save you some time think about caching and TTL from the start. Consider, for any function that you touch multiple times and that is expensive to run, caching might help by holding the result of the function in memory. Caching can be useful for generating Plotly graphs once and retrieving them from the cache later.
Lesson 3: Cache functions with @st.cache and don’t forget TTL parameters.
discuss.streamlit.io
DataFrame data hogs. In a Pandas DataFrame, each column’s size can be reduced by half or more when transforming from an object dtype to categorical dtype or integer dtype. Early on, I transformed most but missed a few columns — this oversight ended up eating my lunch.
Lesson 4: Apply least precision as necessary in DataFrame; avoid ‘object’ dtypes like the plague.
towardsdatascience.com
Junk Imports. This is a catch-all issue with program design. As one example, at the top of each Python file, I had necessary import statements for libraries and packages for data cleaning but not required for the Web app. Although these junk imports did not take up a great amount of memory, they still consumed bits of time and memory that I could not afford to give.
Lesson 5: Import only what you need, get rid of the junk.
Let’s start with a rough snapshot of the dumpster fire that is the original architecture in my program. In Figure 2, Streamlit calls app.py which, in turn reads in data as DataFrames and calls all the program’s other functions. At first, this works just fine with a small dataset on my laptop. Unfortunately, things go off the rails after deploying the app with a full dataset. By the end of the day, my tiny app exceeded its resource limits and shut down.
Now, consider a better architecture in Figure 3. Instead of calling in a massive table and bloating the app, everything is slimmed down. The app only calls a small file that is needed for context menus and calls other data via functions when needed. To be sure, this is not perfect, but it is a vast improvement from the original.
There are two important scenarios with caching, (1) caching with ttl and (2) caching with hashed dictionaries.
First, consider a typical Streamlit call to plot a graph from some other code (stat_charts.py) that makes the actual plot with some function (graph1()). In this case, the program generates the graph anew each time. In some cases, this can cause your app to crash or use up allotted resources.
# Streamlit with Plotly, no cachingimport streamlit as stfrom figs.stat_charts.py import Achartst.plotly_chart(Achart().graph1())
According to the docs, you might try to use the @st.cache decorator with a function wrapper. However, after a few hours of repeated calls, memory problems will accumulate and crash the app as described in this blog post.
# with basic caching, eventually crash app@st.cache()def make_fig(): some_fig = Achart().graph1() return some_figdef show_objects(): st.plotly_chart(make_fig())
Instead, make sure to include parameters for max_entries and ttl to manage the cache size. For my part, I am going forward with these parameters as a default unless there is reason not to.
# with basic cache controls@st.cache(max_entries=10, ttl=3600)def make_fig(): some_fig = Achart().graph1() return some_figdef show_objects(): st.plotly_chart(make_fig())
Second, depending on your functions, you may run into a CachedObjectMutationWarning which basically means something inside the function is changing every time. According to the documentation, mutating a cached function is generally undesirable but there is a workaround from this blog post.
CachedObjectMutationWarning: Return value of overview_data() was mutated between runs.By default, Streamlit's cache should be treated as immutable, or it may behave in unexpected ways. You received this warning because Streamlit detected that an object returned by overview_data() was mutated outside of overview_data().
A solution from the Streamlit blog, which is quite clever, returns the plot into the cache as a hashed dictionary key-value pair. Afterwards, subsequent calls are to the dictionary. This is super cool!
# cache plots in hashed dictionary@st.cache(hash_funcs={dict: lambda _: None})def make_fig(): some_fig = Achart().graph1() cached_dict = {'f1': some_fig} return cached_dictdef show_objects(): charts = make_fig() st.plotly_chart(charts['f1'])
For Pandas optimization, there are a two layers to consider. First, the data types (dtypes) of each column. Second, the overall size and format of the source file and DataFrame. Since both optimization topics are covered well by other TDS articles (see resources), I will provide one example within the context of this Streamlit deployment.
In an example of a column that should be boolean (True/False), I mistakenly turned it into text at some point. As a result, the column takes up huge amounts of space with two, non-boolean values (‘nan’ and 1.). In this case, the ‘nan’ is a literal string nan instead of the numpy.nan type.
Don’t let ‘nan’ strings take up valuable memory.
# correcting a mistake for a boolean column# a DataFrame with about 1 million rowsprint(df['flag_col'].unique())# >>> [nan 1.] should be boolean!print(df['flag_col'].memory_usage())# >>> 15,274,640 ouch, way too much memory!
To patch this specific case, map a dictionary with new values and apply a new dtype. Notice the memory savings when a boolean column is property typed as boolean.
# correct a Pandas Column that should be boolean# make column into booldf['flag_col'] = df['flag_col'].astype('boolean')print(df['flag_col'].memory_usage())# >>> 8,591,985 huge savings in memory!
A checklist of other optimization considerations (apply as appropriate):
Use least precision as required for analysis for floating point numbers and integers, i.e. float16 instead of float64
Use category dtype instead of object
Intentionally read specific columns, i.e. df = df[[col1, col2, col3]]
Compress large files but pickle smaller files (think about a tradeoff in terms of space and decompression time for large files and speed for smaller files) as described in Resources.
Updates on 11 and 13 January 2021:
For Plotly charts in Streamlit, create smaller slices of uncompressed pickle files instead of reading from a large, compressed file. Each file should contain only the columns and data you need for a chart. While working this article, despite optimization and compression, I found that displaying charts will still run too slowly if reading from a single, large table.
Changed example for bools transformation from ‘bool’ to ‘boolean’ — this is a major issue! For more, read about it here:
towardsdatascience.com
Sometimes resource sections are an afterthought; however, I wanted to highlight and share some informative articles about a subject I never thought to research before.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
In this article, I share some post-deployment optimization pitfalls for a simple data dashboard app with Streamlit and Python. Previously, I shared some gotchas in pre-deployment but afterwards, discovered a number of additional issues with memory and optimization. The issues were not clear at first, but after the app kept crashing, I realized I had serious design flaws. Thanks to a ton of great advice from the Web, I resolved and patched most issues.
The lessons boil down to leveraging caching on the Web app, reducing the data file size as much as possible, leveraging least precision in Pandas DataFrame dtypes, and simplifying the program’s architecture. As for next steps, I’m considering how to leverage libraries such as Modin and and Spark for when I run out of tricks and need more performance.
My project is available here and via GitHub and implements all the concepts described in this article. Thanks for reading, I wish you the best in your next project!
|
[
{
"code": null,
"e": 397,
"s": 46,
"text": "What happens when you deploy a data app without coding for memory optimization? In my case, at least, the app crashed and I spent days painfully refactoring code. If you are luckier or smarter (or both), then you have nothing to worry about. Otherwise, consider lessons from my mistakes and some helpful resources to avoid your own special headaches."
},
{
"code": null,
"e": 467,
"s": 397,
"text": "How to avoid my optimization mistakes to deploy your app for the win."
},
{
"code": null,
"e": 876,
"s": 467,
"text": "I have always acknowledged the importance of writing optimized code but I did not fully appreciate what it meant until deploying a Web app. On my laptop, even the most poorly written code will likely run, albeit slowly. However, the consequences on the Web are far more severe — memory leaks and inefficient code can cripple the experience. If you don’t like waiting on an app to load, neither does the user."
},
{
"code": null,
"e": 899,
"s": 876,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1186,
"s": 899,
"text": "In a previous article (linked above), I share a few issues that I encountered when deploying my app. Although I successfully got the app up and running, it started crashing after adding a larger dataset. As a result, in this article, I share some post-deployment problems and solutions."
},
{
"code": null,
"e": 1333,
"s": 1186,
"text": "App unavailable because it has gone over its resource limitsApp crashes a few hours after deployment and continues crashing after repeated reboots"
},
{
"code": null,
"e": 1394,
"s": 1333,
"text": "App unavailable because it has gone over its resource limits"
},
{
"code": null,
"e": 1481,
"s": 1394,
"text": "App crashes a few hours after deployment and continues crashing after repeated reboots"
},
{
"code": null,
"e": 1736,
"s": 1481,
"text": "DataFrame size too large at over 270 megabytes (MB)! By comparison, 100 MB is probably already way too large. Although there is not a perfect size, for a table of 1 million rows, I eventually got the file down to about 50 MB — still hefty but manageable."
},
{
"code": null,
"e": 1807,
"s": 1736,
"text": "Lesson 1: Exhaust all possible options to reduce the DataFrame’s size."
},
{
"code": null,
"e": 1830,
"s": 1807,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2129,
"s": 1830,
"text": "App holds DataFrame in memory. There is a tradeoff here — hold data in memory for fast access, but hold too much and everything breaks. Without thinking about it, coded the app to hold the entire DataFrame (the one that was way too large to begin with) in memory — this turned out to be a disaster."
},
{
"code": null,
"e": 2186,
"s": 2129,
"text": "Lesson 2: Be intentional about what is stored in memory."
},
{
"code": null,
"e": 2721,
"s": 2186,
"text": "Function Caching. After I started searching for advice on a crashing Web app, I discovered that Streamlit has a handy @st.cache function decorator. Then, after implementing caching in correctly, I learned about TTL. To save you some time think about caching and TTL from the start. Consider, for any function that you touch multiple times and that is expensive to run, caching might help by holding the result of the function in memory. Caching can be useful for generating Plotly graphs once and retrieving them from the cache later."
},
{
"code": null,
"e": 2795,
"s": 2721,
"text": "Lesson 3: Cache functions with @st.cache and don’t forget TTL parameters."
},
{
"code": null,
"e": 2816,
"s": 2795,
"text": "discuss.streamlit.io"
},
{
"code": null,
"e": 3085,
"s": 2816,
"text": "DataFrame data hogs. In a Pandas DataFrame, each column’s size can be reduced by half or more when transforming from an object dtype to categorical dtype or integer dtype. Early on, I transformed most but missed a few columns — this oversight ended up eating my lunch."
},
{
"code": null,
"e": 3183,
"s": 3085,
"text": "Lesson 4: Apply least precision as necessary in DataFrame; avoid ‘object’ dtypes like the plague."
},
{
"code": null,
"e": 3206,
"s": 3183,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3575,
"s": 3206,
"text": "Junk Imports. This is a catch-all issue with program design. As one example, at the top of each Python file, I had necessary import statements for libraries and packages for data cleaning but not required for the Web app. Although these junk imports did not take up a great amount of memory, they still consumed bits of time and memory that I could not afford to give."
},
{
"code": null,
"e": 3633,
"s": 3575,
"text": "Lesson 5: Import only what you need, get rid of the junk."
},
{
"code": null,
"e": 4090,
"s": 3633,
"text": "Let’s start with a rough snapshot of the dumpster fire that is the original architecture in my program. In Figure 2, Streamlit calls app.py which, in turn reads in data as DataFrames and calls all the program’s other functions. At first, this works just fine with a small dataset on my laptop. Unfortunately, things go off the rails after deploying the app with a full dataset. By the end of the day, my tiny app exceeded its resource limits and shut down."
},
{
"code": null,
"e": 4421,
"s": 4090,
"text": "Now, consider a better architecture in Figure 3. Instead of calling in a massive table and bloating the app, everything is slimmed down. The app only calls a small file that is needed for context menus and calls other data via functions when needed. To be sure, this is not perfect, but it is a vast improvement from the original."
},
{
"code": null,
"e": 4532,
"s": 4421,
"text": "There are two important scenarios with caching, (1) caching with ttl and (2) caching with hashed dictionaries."
},
{
"code": null,
"e": 4825,
"s": 4532,
"text": "First, consider a typical Streamlit call to plot a graph from some other code (stat_charts.py) that makes the actual plot with some function (graph1()). In this case, the program generates the graph anew each time. In some cases, this can cause your app to crash or use up allotted resources."
},
{
"code": null,
"e": 4955,
"s": 4825,
"text": "# Streamlit with Plotly, no cachingimport streamlit as stfrom figs.stat_charts.py import Achartst.plotly_chart(Achart().graph1())"
},
{
"code": null,
"e": 5176,
"s": 4955,
"text": "According to the docs, you might try to use the @st.cache decorator with a function wrapper. However, after a few hours of repeated calls, memory problems will accumulate and crash the app as described in this blog post."
},
{
"code": null,
"e": 5346,
"s": 5176,
"text": "# with basic caching, eventually crash app@st.cache()def make_fig(): some_fig = Achart().graph1() return some_figdef show_objects(): st.plotly_chart(make_fig())"
},
{
"code": null,
"e": 5535,
"s": 5346,
"text": "Instead, make sure to include parameters for max_entries and ttl to manage the cache size. For my part, I am going forward with these parameters as a default unless there is reason not to."
},
{
"code": null,
"e": 5714,
"s": 5535,
"text": "# with basic cache controls@st.cache(max_entries=10, ttl=3600)def make_fig(): some_fig = Achart().graph1() return some_figdef show_objects(): st.plotly_chart(make_fig())"
},
{
"code": null,
"e": 6005,
"s": 5714,
"text": "Second, depending on your functions, you may run into a CachedObjectMutationWarning which basically means something inside the function is changing every time. According to the documentation, mutating a cached function is generally undesirable but there is a workaround from this blog post."
},
{
"code": null,
"e": 6326,
"s": 6005,
"text": "CachedObjectMutationWarning: Return value of overview_data() was mutated between runs.By default, Streamlit's cache should be treated as immutable, or it may behave in unexpected ways. You received this warning because Streamlit detected that an object returned by overview_data() was mutated outside of overview_data()."
},
{
"code": null,
"e": 6528,
"s": 6326,
"text": "A solution from the Streamlit blog, which is quite clever, returns the plot into the cache as a hashed dictionary key-value pair. Afterwards, subsequent calls are to the dictionary. This is super cool!"
},
{
"code": null,
"e": 6789,
"s": 6528,
"text": "# cache plots in hashed dictionary@st.cache(hash_funcs={dict: lambda _: None})def make_fig(): some_fig = Achart().graph1() cached_dict = {'f1': some_fig} return cached_dictdef show_objects(): charts = make_fig() st.plotly_chart(charts['f1'])"
},
{
"code": null,
"e": 7130,
"s": 6789,
"text": "For Pandas optimization, there are a two layers to consider. First, the data types (dtypes) of each column. Second, the overall size and format of the source file and DataFrame. Since both optimization topics are covered well by other TDS articles (see resources), I will provide one example within the context of this Streamlit deployment."
},
{
"code": null,
"e": 7420,
"s": 7130,
"text": "In an example of a column that should be boolean (True/False), I mistakenly turned it into text at some point. As a result, the column takes up huge amounts of space with two, non-boolean values (‘nan’ and 1.). In this case, the ‘nan’ is a literal string nan instead of the numpy.nan type."
},
{
"code": null,
"e": 7469,
"s": 7420,
"text": "Don’t let ‘nan’ strings take up valuable memory."
},
{
"code": null,
"e": 7695,
"s": 7469,
"text": "# correcting a mistake for a boolean column# a DataFrame with about 1 million rowsprint(df['flag_col'].unique())# >>> [nan 1.] should be boolean!print(df['flag_col'].memory_usage())# >>> 15,274,640 ouch, way too much memory!"
},
{
"code": null,
"e": 7858,
"s": 7695,
"text": "To patch this specific case, map a dictionary with new values and apply a new dtype. Notice the memory savings when a boolean column is property typed as boolean."
},
{
"code": null,
"e": 8054,
"s": 7858,
"text": "# correct a Pandas Column that should be boolean# make column into booldf['flag_col'] = df['flag_col'].astype('boolean')print(df['flag_col'].memory_usage())# >>> 8,591,985 huge savings in memory!"
},
{
"code": null,
"e": 8127,
"s": 8054,
"text": "A checklist of other optimization considerations (apply as appropriate):"
},
{
"code": null,
"e": 8245,
"s": 8127,
"text": "Use least precision as required for analysis for floating point numbers and integers, i.e. float16 instead of float64"
},
{
"code": null,
"e": 8282,
"s": 8245,
"text": "Use category dtype instead of object"
},
{
"code": null,
"e": 8352,
"s": 8282,
"text": "Intentionally read specific columns, i.e. df = df[[col1, col2, col3]]"
},
{
"code": null,
"e": 8535,
"s": 8352,
"text": "Compress large files but pickle smaller files (think about a tradeoff in terms of space and decompression time for large files and speed for smaller files) as described in Resources."
},
{
"code": null,
"e": 8570,
"s": 8535,
"text": "Updates on 11 and 13 January 2021:"
},
{
"code": null,
"e": 8938,
"s": 8570,
"text": "For Plotly charts in Streamlit, create smaller slices of uncompressed pickle files instead of reading from a large, compressed file. Each file should contain only the columns and data you need for a chart. While working this article, despite optimization and compression, I found that displaying charts will still run too slowly if reading from a single, large table."
},
{
"code": null,
"e": 9059,
"s": 8938,
"text": "Changed example for bools transformation from ‘bool’ to ‘boolean’ — this is a major issue! For more, read about it here:"
},
{
"code": null,
"e": 9082,
"s": 9059,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9250,
"s": 9082,
"text": "Sometimes resource sections are an afterthought; however, I wanted to highlight and share some informative articles about a subject I never thought to research before."
},
{
"code": null,
"e": 9273,
"s": 9250,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9296,
"s": 9273,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9319,
"s": 9296,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9342,
"s": 9319,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9365,
"s": 9342,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9821,
"s": 9365,
"text": "In this article, I share some post-deployment optimization pitfalls for a simple data dashboard app with Streamlit and Python. Previously, I shared some gotchas in pre-deployment but afterwards, discovered a number of additional issues with memory and optimization. The issues were not clear at first, but after the app kept crashing, I realized I had serious design flaws. Thanks to a ton of great advice from the Web, I resolved and patched most issues."
},
{
"code": null,
"e": 10174,
"s": 9821,
"text": "The lessons boil down to leveraging caching on the Web app, reducing the data file size as much as possible, leveraging least precision in Pandas DataFrame dtypes, and simplifying the program’s architecture. As for next steps, I’m considering how to leverage libraries such as Modin and and Spark for when I run out of tricks and need more performance."
}
] |
11 Dplyr Functions to Start Using Right Now in R | by Amanda West | Towards Data Science
|
As a freshman in college, when my life goal was still to become a hot-shot diplomat or United Nations ambassador, I took an Uber back to my university with a techie guy wearing our school colors that happened to live a few blocks from my dorm. Trying to make small talk the best I could, I asked him about his life and found out that he was a recent engineering grad turned data scientist at Domino’s.
“Oh, that’s cool...what, uh, packages do you use the most?” I said, proud of myself just for remembering what “packages” were in code-speak.
“Mostly Dplyr.”
“Sounds...interesting.” I said, nodding and looking down at my hands. I tried to think of something to ask him about pizza after that, like if he got free pizza for life and if he believed it was possible to be addicted to cheese, but instead just looked out the window and continued played with my hands for thirty minutes. In the end, I gave him my number so he could Venmo request my half for the ride, but just like the deafening silence of that rideshare, I never got a follow-up text from him again (let’s hope he doesn’t read TDS at work, lol).
So now here I am, still cringing from a car ride I took with a nameless stranger four years ago. But maybe, just maybe, if you get stuck in a car with a stranger who knows Dplyr, you can use the contents of this article to have a conversation. And then you, my dear reader, will not spend four years of your life wondering what Dplyr is, realize your old dreams are no longer, teach yourself how to code, graduate in a global pandemic, explore an entirely new field in graduate school, and eventually become a data scientist yourself and revisit that initial awkward conversation in the form of a TDS article.
OK, but in all seriousness, Dplyr is pretty dang cool (another grand invention by the one and only Hadley Wickham). In terms of scope, Dplyr is to R what Pandas is to Python, but both of these languages also contain very strong similarities to SQL as well. If you find yourself relying on base R a lot, there are a number of everyday data wrangling tasks that Dplyr’s %>% can probably solve more efficiently and intuitively for you.
Before I jump into the top functions that you need to start implementing right now, there’s an elephant in the room that we should first discuss...
Alternative name for this article: What the $@&% is the %>% operator?
The %>% (read: “pipe”) is an operator in R that feeds what is before it into what comes after. This is important, because the pipe operator can be used sequentially to chain together many layers of commands. Because of this, one always starts with the dataset they wish to modify, followed by another pipe, and then the modifier. There can be an unlimited number of modifiers added but they must be broken up by a pipe between each to work. For me, I like to think of the %>% in Dplyr working similarly to how a . is utilized in Pandas. Alternatively, if x represents the base dataset, then one %>% is like putting x into the function f(x), two layers is g(f(x)), three layers is h(g(f(x))), so on and so forth.
Below is an example Pandas vs. Dplyr to rename two columns. In my humble opinion, Dplyr actually comes out a little ahead in terms of readability:
# pandasdf.rename(columns={'old_name1': 'new_name1', 'old_name2': 'new_name2'}, inplace=True)--------------------------------------------------------------------# dplyr df %>% rename(new_name1 = old_name1, new_name2 = old_name2)
And here are some examples of chaining together multiple pipes, which can be done an unlimited number of times:
# in order to follow along, run these: library(tidyverse) library(gapminder)# one pipe gapminder %>% select(country, continent, year, pop)# two pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop)# three pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop) %>% filter(year > 1985)# four pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop) %>% filter(year > 1985) %>% arrange(desc(population)) # for the last, notice that we say "arrange(desc(population))" because in step two it was renamed from "pop".
Now that we’ve gotten that out of the way we can begin to dive into the functions themselves!
glimpse(): Returns 1) # rows, 2) # cols, 3) datatype of each column, and 4) the first ~10 or so entries (depending on what the space on your screen). The corresponding Pandas function I would equate this to is df.describe().
library(tidyverse) library(gapminder)gapminder %>% glimpse()
arrange(): Having a set of eyes on the data can sometimes be incredibly beneficial, so we use arrange() to shuffle various columns in ascending or descending order. This is most similar to the ORDER BY clause in SQL or df.sort_values() in Pandas.
# sort ascending (default)gapminder %>% arrange(lifeExp)# sort descending gapminder %>% arrange(desc(lifeExp))# sort on multiple columnsgapminder %>% arrange(lifeExp, pop, country)
select(), transmute(): The select() function takes a snapshot of the original dataset with only the columns that you specify. Similarly, transmute() works in the same way with the additional ability to create new columns simultaneously. Both of these functions work extremely similarly to the SELECT clause in SQL.
If you are simply wishing to pull untouched columns from the dataframe, I’d stick with select, while if you are going to be making transformations, transmute is the way to go. In the example below, we have the variables gdpPercap and pop and we are making a new gdp column.
gapminder %>% select(country, continent, year, pop)gapminder %>% transmute(country, continent, gdp = gdpPercap * pop)
There are also some more advanced options with select to help you get exactly the columns you want, including a string of connected columns or all columns that contain, start, or end with certain characters:
# advanced select() tools# 1. rename variables with select() gapminder %>% select(country, continent, population = pop)# 2. Include a string of columns at once with ':'gapminder %>% select(country, year, lifeExp:gdpPercap)# 3. Include any column with a given string gapminder %>% select(country, year, contains("gdp"))# 4. Include any column starting with a given string gapminder %>% select(country, year, starts_with("co"))# 5. Include any column ending with a given stringgapminder %>% select(country, year, ends_with("Exp"))# Keep the last column, by any namegapminder %>% select(country, year, last_col())
rename(), mutate(): These functions modify one or more columns and saves them back to the file. As the name suggests, rename() is for renaming while mutate() creates a new function entirely from a transformation.
With both rename() and mutate(), we can use a comma to denote multiple modifications at once. Renaming in Dplyr is similar to using df.rename() and mutating is similar to df[new_col] = df[old_col1] * df[old_col2] used in Python.
# rename a column to be called something elsegapminder %>% rename(population = pop, #ex. 'pop' turns into 'population' countries = country, life_expectancy = lifeExp)# add a new calculated fieldgapminder %>% mutate(gdp = gdpPercap * pop) #ex. 'gdp' is created as a new var
filter(): Similar to the WHERE clause in SQL or a conditional expression in Python (df[df['country'] == 'France']). Akin to other Dplyr functions, one can specify multiple filters by breaking up each argument with a ,, &, or | sign. For strings, using %in% is suggested over using == .
# filter for Francegapminder %>% filter(country %in% "France")# filter for a subset of countries (c stands for 'concat')gapminder %>% select(pop, country, year) %>% filter(country %in% c('France','Spain','Portugal'))# "or" operator functiongapminder %>% select(pop, country, year) %>% filter(pop > 50000 | pop < 100000)# "and" operator function 1 gapminder %>% select(pop, country, year) %>% filter(pop > 50000, pop < 100000)# "and" operator function 2gapminder %>% select(pop, country, year) %>% filter(pop > 50000 & pop < 100000)
count(), summarize(), and top_n(k, )
The count() function goes through the dataset and counts the number of times a value appears in a given column/columns. I most often use it to look at one column at a time, such as for understanding how many countries are in each continent that I’m looking at or how many people in a city take a car, bike, or bus to work.
gapminder %>% count(continent)
With summarize we can look at aggregate functions such as the sum, median, mean, standard deviation, variance, min, and max of a column and give it a name. When mixed with functions like group_by() , these functions can become incredibly useful in understanding subpopulations in the dataset.
# summarize # sum(), mean(), median(), min(), max(), sd(), var()gapminder %>% summarize(total_gdp = sum(gdpPercap))gapminder %>% summarize(avg_gdp = mean(gdpPercap))gapminder %>% summarize(gdp_standard_dev = sd(gdpPercap))gapminder %>% summarize(gdp_variance = var(gdpPercap))# we can also create many columns at oncegapminder %>% summarize(max_gdp = max(gdpPercap), total_pop = sum(pop), min_lifeExp = min(lifeExp))# I use __ = __ in order to give a name to the new summary columns, # but it is not required.
Finally, we can use the top_n(k, ) to only keep the top k values in a dataframe or group. For example, we can look at the country in each continent with the highest GDP per capita below. If we had not included the group_by() function first, then result would be the single country in the world with the highest GDP per capita, i.e. Kuwait. Similarly, if we had specified k=4 then it would have shown us the top four countries with highest life expectancies in each continent.
# top_n(k, )gapminder %>% group_by(continent) %>% top_n(1, gdpPercap)
group_by() & ungroup(): As with all programming languages, where would we be without a good group by function? Used in combination with the other functions listed, we can draw out interesting conclusions about the subpopulations present in the dataset. This function works the same as in Pandas df.group_by() or SQL’s GROUP BY, with the exception being that these groups will stay put until you manually uncouple them with ungroup() again.
# Using group_bygapminder %>% group_by(year) %>% mutate(year_total = sum(pop))# Grouping and then ungrouping again with ungroup()gapminder %>% group_by(year) %>% mutate(year_total = sum(pop)) %>% ungroup() %>% mutate(fraction = pop / year_total)
All in all, I hope that this introduction gets across to you that Dplyr has strong similarities to both SQL and Pandas. If something about a data transformation is tripping you up, Dplyr is strong on efficiency and readability — and there’s plenty of cheat sheets and tutorials floating around for it on the interwebs!
If you liked this article on data wrangling with Dplyr please let me know with a clap or comment— if there’s enough interest then I will do a part 2 where I go over the more complex commands lying within Dplyr, and perhaps find more awkward stories of my past to expose in the process. 🙃
And to Hadley Wickham, the maker of all things R....seriously, when do we just make him our supreme overlord already?
**Edit: Base R is getting a pipe, after all! Link: https://www.youtube.com/watch?v=wmvjxb6Gdm8
|
[
{
"code": null,
"e": 574,
"s": 172,
"text": "As a freshman in college, when my life goal was still to become a hot-shot diplomat or United Nations ambassador, I took an Uber back to my university with a techie guy wearing our school colors that happened to live a few blocks from my dorm. Trying to make small talk the best I could, I asked him about his life and found out that he was a recent engineering grad turned data scientist at Domino’s."
},
{
"code": null,
"e": 715,
"s": 574,
"text": "“Oh, that’s cool...what, uh, packages do you use the most?” I said, proud of myself just for remembering what “packages” were in code-speak."
},
{
"code": null,
"e": 731,
"s": 715,
"text": "“Mostly Dplyr.”"
},
{
"code": null,
"e": 1283,
"s": 731,
"text": "“Sounds...interesting.” I said, nodding and looking down at my hands. I tried to think of something to ask him about pizza after that, like if he got free pizza for life and if he believed it was possible to be addicted to cheese, but instead just looked out the window and continued played with my hands for thirty minutes. In the end, I gave him my number so he could Venmo request my half for the ride, but just like the deafening silence of that rideshare, I never got a follow-up text from him again (let’s hope he doesn’t read TDS at work, lol)."
},
{
"code": null,
"e": 1893,
"s": 1283,
"text": "So now here I am, still cringing from a car ride I took with a nameless stranger four years ago. But maybe, just maybe, if you get stuck in a car with a stranger who knows Dplyr, you can use the contents of this article to have a conversation. And then you, my dear reader, will not spend four years of your life wondering what Dplyr is, realize your old dreams are no longer, teach yourself how to code, graduate in a global pandemic, explore an entirely new field in graduate school, and eventually become a data scientist yourself and revisit that initial awkward conversation in the form of a TDS article."
},
{
"code": null,
"e": 2326,
"s": 1893,
"text": "OK, but in all seriousness, Dplyr is pretty dang cool (another grand invention by the one and only Hadley Wickham). In terms of scope, Dplyr is to R what Pandas is to Python, but both of these languages also contain very strong similarities to SQL as well. If you find yourself relying on base R a lot, there are a number of everyday data wrangling tasks that Dplyr’s %>% can probably solve more efficiently and intuitively for you."
},
{
"code": null,
"e": 2474,
"s": 2326,
"text": "Before I jump into the top functions that you need to start implementing right now, there’s an elephant in the room that we should first discuss..."
},
{
"code": null,
"e": 2544,
"s": 2474,
"text": "Alternative name for this article: What the $@&% is the %>% operator?"
},
{
"code": null,
"e": 3256,
"s": 2544,
"text": "The %>% (read: “pipe”) is an operator in R that feeds what is before it into what comes after. This is important, because the pipe operator can be used sequentially to chain together many layers of commands. Because of this, one always starts with the dataset they wish to modify, followed by another pipe, and then the modifier. There can be an unlimited number of modifiers added but they must be broken up by a pipe between each to work. For me, I like to think of the %>% in Dplyr working similarly to how a . is utilized in Pandas. Alternatively, if x represents the base dataset, then one %>% is like putting x into the function f(x), two layers is g(f(x)), three layers is h(g(f(x))), so on and so forth."
},
{
"code": null,
"e": 3403,
"s": 3256,
"text": "Below is an example Pandas vs. Dplyr to rename two columns. In my humble opinion, Dplyr actually comes out a little ahead in terms of readability:"
},
{
"code": null,
"e": 3661,
"s": 3403,
"text": "# pandasdf.rename(columns={'old_name1': 'new_name1', 'old_name2': 'new_name2'}, inplace=True)--------------------------------------------------------------------# dplyr df %>% rename(new_name1 = old_name1, new_name2 = old_name2)"
},
{
"code": null,
"e": 3773,
"s": 3661,
"text": "And here are some examples of chaining together multiple pipes, which can be done an unlimited number of times:"
},
{
"code": null,
"e": 4387,
"s": 3773,
"text": "# in order to follow along, run these: library(tidyverse) library(gapminder)# one pipe gapminder %>% select(country, continent, year, pop)# two pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop)# three pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop) %>% filter(year > 1985)# four pipesgapminder %>% select(country, continent, year, pop) %>% rename(population = pop) %>% filter(year > 1985) %>% arrange(desc(population)) # for the last, notice that we say \"arrange(desc(population))\" because in step two it was renamed from \"pop\". "
},
{
"code": null,
"e": 4481,
"s": 4387,
"text": "Now that we’ve gotten that out of the way we can begin to dive into the functions themselves!"
},
{
"code": null,
"e": 4706,
"s": 4481,
"text": "glimpse(): Returns 1) # rows, 2) # cols, 3) datatype of each column, and 4) the first ~10 or so entries (depending on what the space on your screen). The corresponding Pandas function I would equate this to is df.describe()."
},
{
"code": null,
"e": 4768,
"s": 4706,
"text": "library(tidyverse) library(gapminder)gapminder %>% glimpse()"
},
{
"code": null,
"e": 5015,
"s": 4768,
"text": "arrange(): Having a set of eyes on the data can sometimes be incredibly beneficial, so we use arrange() to shuffle various columns in ascending or descending order. This is most similar to the ORDER BY clause in SQL or df.sort_values() in Pandas."
},
{
"code": null,
"e": 5202,
"s": 5015,
"text": "# sort ascending (default)gapminder %>% arrange(lifeExp)# sort descending gapminder %>% arrange(desc(lifeExp))# sort on multiple columnsgapminder %>% arrange(lifeExp, pop, country)"
},
{
"code": null,
"e": 5517,
"s": 5202,
"text": "select(), transmute(): The select() function takes a snapshot of the original dataset with only the columns that you specify. Similarly, transmute() works in the same way with the additional ability to create new columns simultaneously. Both of these functions work extremely similarly to the SELECT clause in SQL."
},
{
"code": null,
"e": 5791,
"s": 5517,
"text": "If you are simply wishing to pull untouched columns from the dataframe, I’d stick with select, while if you are going to be making transformations, transmute is the way to go. In the example below, we have the variables gdpPercap and pop and we are making a new gdp column."
},
{
"code": null,
"e": 5911,
"s": 5791,
"text": "gapminder %>% select(country, continent, year, pop)gapminder %>% transmute(country, continent, gdp = gdpPercap * pop)"
},
{
"code": null,
"e": 6119,
"s": 5911,
"text": "There are also some more advanced options with select to help you get exactly the columns you want, including a string of connected columns or all columns that contain, start, or end with certain characters:"
},
{
"code": null,
"e": 6736,
"s": 6119,
"text": "# advanced select() tools# 1. rename variables with select() gapminder %>% select(country, continent, population = pop)# 2. Include a string of columns at once with ':'gapminder %>% select(country, year, lifeExp:gdpPercap)# 3. Include any column with a given string gapminder %>% select(country, year, contains(\"gdp\"))# 4. Include any column starting with a given string gapminder %>% select(country, year, starts_with(\"co\"))# 5. Include any column ending with a given stringgapminder %>% select(country, year, ends_with(\"Exp\"))# Keep the last column, by any namegapminder %>% select(country, year, last_col())"
},
{
"code": null,
"e": 6949,
"s": 6736,
"text": "rename(), mutate(): These functions modify one or more columns and saves them back to the file. As the name suggests, rename() is for renaming while mutate() creates a new function entirely from a transformation."
},
{
"code": null,
"e": 7178,
"s": 6949,
"text": "With both rename() and mutate(), we can use a comma to denote multiple modifications at once. Renaming in Dplyr is similar to using df.rename() and mutating is similar to df[new_col] = df[old_col1] * df[old_col2] used in Python."
},
{
"code": null,
"e": 7478,
"s": 7178,
"text": "# rename a column to be called something elsegapminder %>% rename(population = pop, #ex. 'pop' turns into 'population' countries = country, life_expectancy = lifeExp)# add a new calculated fieldgapminder %>% mutate(gdp = gdpPercap * pop) #ex. 'gdp' is created as a new var"
},
{
"code": null,
"e": 7764,
"s": 7478,
"text": "filter(): Similar to the WHERE clause in SQL or a conditional expression in Python (df[df['country'] == 'France']). Akin to other Dplyr functions, one can specify multiple filters by breaking up each argument with a ,, &, or | sign. For strings, using %in% is suggested over using == ."
},
{
"code": null,
"e": 8340,
"s": 7764,
"text": "# filter for Francegapminder %>% filter(country %in% \"France\")# filter for a subset of countries (c stands for 'concat')gapminder %>% select(pop, country, year) %>% filter(country %in% c('France','Spain','Portugal'))# \"or\" operator functiongapminder %>% select(pop, country, year) %>% filter(pop > 50000 | pop < 100000)# \"and\" operator function 1 gapminder %>% select(pop, country, year) %>% filter(pop > 50000, pop < 100000)# \"and\" operator function 2gapminder %>% select(pop, country, year) %>% filter(pop > 50000 & pop < 100000)"
},
{
"code": null,
"e": 8377,
"s": 8340,
"text": "count(), summarize(), and top_n(k, )"
},
{
"code": null,
"e": 8700,
"s": 8377,
"text": "The count() function goes through the dataset and counts the number of times a value appears in a given column/columns. I most often use it to look at one column at a time, such as for understanding how many countries are in each continent that I’m looking at or how many people in a city take a car, bike, or bus to work."
},
{
"code": null,
"e": 8732,
"s": 8700,
"text": "gapminder %>% count(continent)"
},
{
"code": null,
"e": 9025,
"s": 8732,
"text": "With summarize we can look at aggregate functions such as the sum, median, mean, standard deviation, variance, min, and max of a column and give it a name. When mixed with functions like group_by() , these functions can become incredibly useful in understanding subpopulations in the dataset."
},
{
"code": null,
"e": 9563,
"s": 9025,
"text": "# summarize # sum(), mean(), median(), min(), max(), sd(), var()gapminder %>% summarize(total_gdp = sum(gdpPercap))gapminder %>% summarize(avg_gdp = mean(gdpPercap))gapminder %>% summarize(gdp_standard_dev = sd(gdpPercap))gapminder %>% summarize(gdp_variance = var(gdpPercap))# we can also create many columns at oncegapminder %>% summarize(max_gdp = max(gdpPercap), total_pop = sum(pop), min_lifeExp = min(lifeExp))# I use __ = __ in order to give a name to the new summary columns, # but it is not required."
},
{
"code": null,
"e": 10039,
"s": 9563,
"text": "Finally, we can use the top_n(k, ) to only keep the top k values in a dataframe or group. For example, we can look at the country in each continent with the highest GDP per capita below. If we had not included the group_by() function first, then result would be the single country in the world with the highest GDP per capita, i.e. Kuwait. Similarly, if we had specified k=4 then it would have shown us the top four countries with highest life expectancies in each continent."
},
{
"code": null,
"e": 10113,
"s": 10039,
"text": "# top_n(k, )gapminder %>% group_by(continent) %>% top_n(1, gdpPercap)"
},
{
"code": null,
"e": 10553,
"s": 10113,
"text": "group_by() & ungroup(): As with all programming languages, where would we be without a good group by function? Used in combination with the other functions listed, we can draw out interesting conclusions about the subpopulations present in the dataset. This function works the same as in Pandas df.group_by() or SQL’s GROUP BY, with the exception being that these groups will stay put until you manually uncouple them with ungroup() again."
},
{
"code": null,
"e": 10889,
"s": 10553,
"text": "# Using group_bygapminder %>% group_by(year) %>% mutate(year_total = sum(pop))# Grouping and then ungrouping again with ungroup()gapminder %>% group_by(year) %>% mutate(year_total = sum(pop)) %>% ungroup() %>% mutate(fraction = pop / year_total)"
},
{
"code": null,
"e": 11208,
"s": 10889,
"text": "All in all, I hope that this introduction gets across to you that Dplyr has strong similarities to both SQL and Pandas. If something about a data transformation is tripping you up, Dplyr is strong on efficiency and readability — and there’s plenty of cheat sheets and tutorials floating around for it on the interwebs!"
},
{
"code": null,
"e": 11496,
"s": 11208,
"text": "If you liked this article on data wrangling with Dplyr please let me know with a clap or comment— if there’s enough interest then I will do a part 2 where I go over the more complex commands lying within Dplyr, and perhaps find more awkward stories of my past to expose in the process. 🙃"
},
{
"code": null,
"e": 11614,
"s": 11496,
"text": "And to Hadley Wickham, the maker of all things R....seriously, when do we just make him our supreme overlord already?"
}
] |
The ElementTree XML API in Python
|
The Extensible Markup Language (XML) is a markup language much like HTML. It is a portable and it is useful for handling small to medium amounts of data without using any SQL database.
Python's standard library contains xml package. This package has ElementTree module. This is a simple and lightweight XML processor API.
XML is a tree like hierarchical data format. The 'ElementTree' in this module treats the whole XML document as a tree. the 'Element' class represents a single node in this tree. Reading and writing operations on XML files are done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.
The tree is a hierarchical structure of elements starting with root followed by other elements. Each element is created by using Element() function of this module.
import xml.etree.ElementTree as et
e=et.Element('name')
Each element is characterized by a tag and attrib attribute which is a dict object. For tree's starting element, attrib is an empty dictionary
>>> root=xml.Element('employees')
>>> root.tag
'emploees'
>>> root.attrib
{}
You may now set up one or more child elements to be added under root element. Each child may have one or more subelements. Add them using Subelement() function and define it's text attribute.
child=xml.Element("employee")
nm = xml.SubElement(child, "name")
nm.text = student.get('name')
age = xml.SubElement(child, "salary")
age.text = str(student.get('salary'))
Each child is added to root by append() function as
root.append(child)
After adding required number of child elements, construct a tree object by elementTree() function
tree = et.ElementTree(root)
The entire tree structure is written to a binary file by tree object's write() function
f = open('employees.xml', "wb")
tree.write(f)
In following example tree is constructed out of list of dictionary items. Each dictionary item holds key-value pairs describing a student data structure. The tree so constructed is written to 'myfile.xml'
import xml.etree.ElementTree as et
employees=[{'name':'aaa','age':21,'sal':5000},{'name':xyz,'age':22,'sal':6000}]
root = et.Element("employees")
for employee in employees:
child=xml.Element("employee")
root.append(child)
nm = xml.SubElement(child, "name")
nm.text = student.get('name')
age = xml.SubElement(child, "age")
age.text = str(student.get('age'))
sal=xml.SubElement(child, "sal")
sal.text=str(student.get('sal'))
tree = et.ElementTree(root)
with open('employees.xml', "wb") as fh:
tree.write(fh)
The 'myfile.xml' is stored in current working directory.
<employees><employee><name>aaa</name><age>21</age><sal>5000</sal></employee><employee><name>xyz</name><age>22</age><sal>60</sal></employee></employee>
Let us now read back the 'myfile.xml' created in above example. For this purpose following functions in ElementTree module will be used
ElementTree() This function is overloaded to read the hierarchical structure of elements to a tree objects.
tree = et.ElementTree(file='students.xml')
getroot() This function returns root element of the tree
root = tree.getroot()
getchildren() This function returns the list of sub-elements one level below of an element.
children = root.getchildren()
In following example, elements and sub-elements of the 'myfile.xml' are parsed into a list of dictionary items.
import xml.etree.ElementTree as et
tree = et.ElementTree(file='employees.xml')
root = tree.getroot()
students = []
children = root.getchildren()
for child in children:
employee={}
pairs = child.getchildren()
for pair in pairs:
employee[pair.tag]=pair.text
employees.append(student)
print (employees)
[{'name': 'aaa', 'age': '21', 'sal': '5000'}, {'name': 'xyz', 'age': '22', 'sal': '6000'}]
We shall use iter() function of Element. It creates a tree iterator for given tag with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order.
Let us build iterator for all 'marks' subelements and increment text of each sal tag by 100.
import xml.etree.ElementTree as et
tree = et.ElementTree(file='students.xml')
root = tree.getroot()
for x in root.iter('sal'):
s = int (x.text)
s = s+100
x.text=str(s)
with open("employees.xml", "wb") as fh:
tree.write(fh)
Our 'employees.xml' will now be modified accordingly.
We can also use set() to update value of a certain key.
x.set(marks, str(mark))
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "The Extensible Markup Language (XML) is a markup language much like HTML. It is a portable and it is useful for handling small to medium amounts of data without using any SQL database."
},
{
"code": null,
"e": 1384,
"s": 1247,
"text": "Python's standard library contains xml package. This package has ElementTree module. This is a simple and lightweight XML processor API."
},
{
"code": null,
"e": 1732,
"s": 1384,
"text": "XML is a tree like hierarchical data format. The 'ElementTree' in this module treats the whole XML document as a tree. the 'Element' class represents a single node in this tree. Reading and writing operations on XML files are done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level."
},
{
"code": null,
"e": 1896,
"s": 1732,
"text": "The tree is a hierarchical structure of elements starting with root followed by other elements. Each element is created by using Element() function of this module."
},
{
"code": null,
"e": 1952,
"s": 1896,
"text": "import xml.etree.ElementTree as et\ne=et.Element('name')"
},
{
"code": null,
"e": 2095,
"s": 1952,
"text": "Each element is characterized by a tag and attrib attribute which is a dict object. For tree's starting element, attrib is an empty dictionary"
},
{
"code": null,
"e": 2172,
"s": 2095,
"text": ">>> root=xml.Element('employees')\n>>> root.tag\n'emploees'\n>>> root.attrib\n{}"
},
{
"code": null,
"e": 2364,
"s": 2172,
"text": "You may now set up one or more child elements to be added under root element. Each child may have one or more subelements. Add them using Subelement() function and define it's text attribute."
},
{
"code": null,
"e": 2535,
"s": 2364,
"text": "child=xml.Element(\"employee\")\nnm = xml.SubElement(child, \"name\")\nnm.text = student.get('name')\nage = xml.SubElement(child, \"salary\")\nage.text = str(student.get('salary'))"
},
{
"code": null,
"e": 2587,
"s": 2535,
"text": "Each child is added to root by append() function as"
},
{
"code": null,
"e": 2606,
"s": 2587,
"text": "root.append(child)"
},
{
"code": null,
"e": 2704,
"s": 2606,
"text": "After adding required number of child elements, construct a tree object by elementTree() function"
},
{
"code": null,
"e": 2732,
"s": 2704,
"text": "tree = et.ElementTree(root)"
},
{
"code": null,
"e": 2820,
"s": 2732,
"text": "The entire tree structure is written to a binary file by tree object's write() function"
},
{
"code": null,
"e": 2866,
"s": 2820,
"text": "f = open('employees.xml', \"wb\")\ntree.write(f)"
},
{
"code": null,
"e": 3071,
"s": 2866,
"text": "In following example tree is constructed out of list of dictionary items. Each dictionary item holds key-value pairs describing a student data structure. The tree so constructed is written to 'myfile.xml'"
},
{
"code": null,
"e": 3578,
"s": 3071,
"text": "import xml.etree.ElementTree as et\nemployees=[{'name':'aaa','age':21,'sal':5000},{'name':xyz,'age':22,'sal':6000}]\nroot = et.Element(\"employees\")\nfor employee in employees:\nchild=xml.Element(\"employee\")\nroot.append(child)\nnm = xml.SubElement(child, \"name\")\nnm.text = student.get('name')\nage = xml.SubElement(child, \"age\")\nage.text = str(student.get('age'))\nsal=xml.SubElement(child, \"sal\")\nsal.text=str(student.get('sal'))\n\ntree = et.ElementTree(root)\nwith open('employees.xml', \"wb\") as fh:\ntree.write(fh)"
},
{
"code": null,
"e": 3635,
"s": 3578,
"text": "The 'myfile.xml' is stored in current working directory."
},
{
"code": null,
"e": 3786,
"s": 3635,
"text": "<employees><employee><name>aaa</name><age>21</age><sal>5000</sal></employee><employee><name>xyz</name><age>22</age><sal>60</sal></employee></employee>"
},
{
"code": null,
"e": 3922,
"s": 3786,
"text": "Let us now read back the 'myfile.xml' created in above example. For this purpose following functions in ElementTree module will be used"
},
{
"code": null,
"e": 4030,
"s": 3922,
"text": "ElementTree() This function is overloaded to read the hierarchical structure of elements to a tree objects."
},
{
"code": null,
"e": 4073,
"s": 4030,
"text": "tree = et.ElementTree(file='students.xml')"
},
{
"code": null,
"e": 4130,
"s": 4073,
"text": "getroot() This function returns root element of the tree"
},
{
"code": null,
"e": 4152,
"s": 4130,
"text": "root = tree.getroot()"
},
{
"code": null,
"e": 4244,
"s": 4152,
"text": "getchildren() This function returns the list of sub-elements one level below of an element."
},
{
"code": null,
"e": 4274,
"s": 4244,
"text": "children = root.getchildren()"
},
{
"code": null,
"e": 4386,
"s": 4274,
"text": "In following example, elements and sub-elements of the 'myfile.xml' are parsed into a list of dictionary items."
},
{
"code": null,
"e": 4686,
"s": 4386,
"text": "import xml.etree.ElementTree as et\ntree = et.ElementTree(file='employees.xml')\nroot = tree.getroot()\nstudents = []\nchildren = root.getchildren()\nfor child in children:\nemployee={}\npairs = child.getchildren()\nfor pair in pairs:\nemployee[pair.tag]=pair.text\nemployees.append(student)\nprint (employees)"
},
{
"code": null,
"e": 4777,
"s": 4686,
"text": "[{'name': 'aaa', 'age': '21', 'sal': '5000'}, {'name': 'xyz', 'age': '22', 'sal': '6000'}]"
},
{
"code": null,
"e": 4997,
"s": 4777,
"text": "We shall use iter() function of Element. It creates a tree iterator for given tag with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order."
},
{
"code": null,
"e": 5090,
"s": 4997,
"text": "Let us build iterator for all 'marks' subelements and increment text of each sal tag by 100."
},
{
"code": null,
"e": 5313,
"s": 5090,
"text": "import xml.etree.ElementTree as et\ntree = et.ElementTree(file='students.xml')\nroot = tree.getroot()\nfor x in root.iter('sal'):\ns = int (x.text)\ns = s+100\nx.text=str(s)\nwith open(\"employees.xml\", \"wb\") as fh:\ntree.write(fh)"
},
{
"code": null,
"e": 5367,
"s": 5313,
"text": "Our 'employees.xml' will now be modified accordingly."
},
{
"code": null,
"e": 5423,
"s": 5367,
"text": "We can also use set() to update value of a certain key."
},
{
"code": null,
"e": 5447,
"s": 5423,
"text": "x.set(marks, str(mark))"
}
] |
Find the element that appears once in sorted array - JavaScript
|
Suppose, we have a sorted array of literals like this −
const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false.
For this array, the output should be 6
Following is the code −
const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
const firstNonDuplicate = arr => {
let appeared = false;
for(let i = 0; i < arr.length; i++){
if(appeared){
if(arr[i+1] !== arr[i]){
appeared = false;
};
}else{
if(arr[i+1] === arr[i]){
appeared = true;
continue;
};
return arr[i];
};
};
return false;
};
console.log(firstNonDuplicate(arr));
Following is the output in the console −
6
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "Suppose, we have a sorted array of literals like this −"
},
{
"code": null,
"e": 1165,
"s": 1118,
"text": "const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];"
},
{
"code": null,
"e": 1372,
"s": 1165,
"text": "We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false."
},
{
"code": null,
"e": 1411,
"s": 1372,
"text": "For this array, the output should be 6"
},
{
"code": null,
"e": 1435,
"s": 1411,
"text": "Following is the code −"
},
{
"code": null,
"e": 1884,
"s": 1435,
"text": "const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];\nconst firstNonDuplicate = arr => {\n let appeared = false;\n for(let i = 0; i < arr.length; i++){\n if(appeared){\n if(arr[i+1] !== arr[i]){\n appeared = false;\n };\n }else{\n if(arr[i+1] === arr[i]){\n appeared = true;\n continue;\n };\n return arr[i];\n };\n };\n return false;\n};\nconsole.log(firstNonDuplicate(arr));"
},
{
"code": null,
"e": 1925,
"s": 1884,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1927,
"s": 1925,
"text": "6"
}
] |
Kotlin - Extensions
|
Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class.
The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions.
Similarly, we can also define extension properties for an existing Kotlin class.
A kotlin extension function is a member function of a class, which is defined outside the class. The created extension functions are used as a regular function inside that class.
Following is the syntax to define an extension function. Here, the extension function is declared with using the class name and also with using method name.
fun <class_name>.<method_name>(){
....
function body
}
In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level.
class Alien {
var skills : String = "null"
fun printMySkills() {
print(skills)
}
}
fun main(args: Array<String>) {
var a1 = Alien()
a1.skills = "JAVA"
//a1.printMySkills()
var a2 = Alien()
a2.skills = "SQL"
//a2.printMySkills()
var a3 = Alien()
a3.skills = a1.addMySkills(a2)
a3.printMySkills()
}
fun Alien.addMySkills(a:Alien):String{
var a4 = Alien()
a4.skills = this.skills + " " +a.skills
return a4.skills
}
In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension.
When you run the above Kotlin program, it will generate the following output:
JAVA SQL
Kotlin allows to extend the standard library classes as well as user-defined classes. For example, if you need a specialised function for standard Kotlin String class which will return the number of vowels available in the string, such method is not already available in String class but you can use an extension function to accomplish this task.
fun main(args: Array<String>) {
val str = "Good morning Kotlin"
val result = str.countVowels()
println("Number of vowels: $result")
}
fun String.countVowels(): Int{
var vowels = 0
for (i in 0.. this.length - 1) {
val ch = this[i]
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels
}
}
return vowels;
}
When you run the above Kotlin program, it will generate the following output:
Number of vowels: 6
Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the companion object which is declared inside a class and marked with the companion keyword. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name.
In the following example, we will create a “companion object”.
fun main(args: Array<String>) {
println("Heyyy!!!"+A.show())
}
class A {
companion object {
fun show():String {
return("You are learning Kotlin from TutorialsPoint.com")
}
}
}
When you run the above Kotlin program, it will generate the following output:
Heyyy!!! You are learning Kotlin from TutorialsPoint.com
The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions.
Kotlin allows to define Extension Functions with a nullable class type. These extension function can be called on a nullable object variable.
To define an extension for Nullable receiver, we just need to add a check for null receiver inside the extension function, and the appropriate value is returned.
fun main(args: Array<String>) {
var str1 = "Good morning Kotlin"
var str2 : String? = null
var result = str1.countVowels()
println("Number of vowels in str1 : $result")
result = str2.countVowels()
println("Number of vowels in str2 : $result")
}
fun String?.countVowels(): Any{
if (this == null) return "null"
var vowels = 0
for (i in 0.. this.length - 1) {
val ch = this[i]
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels
}
}
return vowels;
}
When you run the above Kotlin program, it will generate the following output:
Number of vowels in str1 : 6
Number of vowels in str2 : null
Kotlin allows to define extension properties in very similar way like we defined extension function. Extension properties are also defined outside of the class. Since extensions do not actually insert members into classes, there is no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties.
We can add getter and setter along with the property which are nothing but the extension functions.
class Temperature(var celsius: Float)
fun main(args: Array<String>) {
val t = Temperature(40f)
println(t.fahrenheit)
t.fahrenheit = 85f
println(t.celsius)
}
var Temperature.fahrenheit: Float
get() = (celsius * 9 / 5) + 32
set(value) {
celsius = (value - 32) * 5 / 9
}
When you run the above Kotlin program, it will generate the following output:
104.0
29.444445
Q 1 - Which one is true about kotlin extension function :
A - They are defined outside the class without impacting existing functionality
B - We can inherit Kotlin class and add a new function inside the class
C - Latest version of Kotlin does not allow to define extension function
D - All are incorrect about extension function
Kotlin extension functions are defined outside the class without impacting existing functionality.
Q 2 - Which one is true about Kotlin extension properties
A - They are defined outside the class without impacting existing functionality
B - Initializers are not allowed for extension properties.
C - We can define getter and setter functions to manage the extension properties
D - All are incorrect about extension properties
All the statements are correct about extension properties.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2703,
"s": 2425,
"text": "Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class."
},
{
"code": null,
"e": 3007,
"s": 2703,
"text": "The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions."
},
{
"code": null,
"e": 3088,
"s": 3007,
"text": "Similarly, we can also define extension properties for an existing Kotlin class."
},
{
"code": null,
"e": 3267,
"s": 3088,
"text": "A kotlin extension function is a member function of a class, which is defined outside the class. The created extension functions are used as a regular function inside that class."
},
{
"code": null,
"e": 3424,
"s": 3267,
"text": "Following is the syntax to define an extension function. Here, the extension function is declared with using the class name and also with using method name."
},
{
"code": null,
"e": 3482,
"s": 3424,
"text": "fun <class_name>.<method_name>(){\n ....\n function body\n}\n"
},
{
"code": null,
"e": 3661,
"s": 3482,
"text": "In function extension, Kotlin allows to define a method outside of the main class. In the following example, we will see how the extension is implemented at the functional level."
},
{
"code": null,
"e": 4136,
"s": 3661,
"text": "class Alien {\n var skills : String = \"null\"\n\t\n fun printMySkills() {\n print(skills)\n }\t\t\n}\nfun main(args: Array<String>) {\n var a1 = Alien()\n a1.skills = \"JAVA\"\n //a1.printMySkills()\n\t\n var a2 = Alien()\n a2.skills = \"SQL\"\n //a2.printMySkills()\n\t\n var a3 = Alien()\n a3.skills = a1.addMySkills(a2)\n a3.printMySkills()\n}\nfun Alien.addMySkills(a:Alien):String{\n var a4 = Alien()\n a4.skills = this.skills + \" \" +a.skills\n return a4.skills\n}\n"
},
{
"code": null,
"e": 4350,
"s": 4136,
"text": "In the above example, we don’t have any method inside “Alien” class named as “addMySkills()”, however, we still are implementing the same method somewhere else outside of the class, This is the magic of extension."
},
{
"code": null,
"e": 4428,
"s": 4350,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4438,
"s": 4428,
"text": "JAVA SQL\n"
},
{
"code": null,
"e": 4785,
"s": 4438,
"text": "Kotlin allows to extend the standard library classes as well as user-defined classes. For example, if you need a specialised function for standard Kotlin String class which will return the number of vowels available in the string, such method is not already available in String class but you can use an extension function to accomplish this task."
},
{
"code": null,
"e": 5168,
"s": 4785,
"text": "fun main(args: Array<String>) {\n val str = \"Good morning Kotlin\"\n \n val result = str.countVowels()\n println(\"Number of vowels: $result\")\n}\nfun String.countVowels(): Int{\n var vowels = 0\n for (i in 0.. this.length - 1) {\n val ch = this[i]\n if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {\n ++vowels\n }\n }\n return vowels; \n}\n"
},
{
"code": null,
"e": 5246,
"s": 5168,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5267,
"s": 5246,
"text": "Number of vowels: 6\n"
},
{
"code": null,
"e": 5623,
"s": 5267,
"text": "Kotlin provides another mechanism to implement static functionality of Java. This can be achieved using the companion object which is declared inside a class and marked with the companion keyword. Using this mechanism, we can create an object of a class inside a factory method and later we can just call that method using the reference of the class name."
},
{
"code": null,
"e": 5687,
"s": 5623,
"text": "In the following example, we will create a “companion object”."
},
{
"code": null,
"e": 5894,
"s": 5687,
"text": "fun main(args: Array<String>) {\n println(\"Heyyy!!!\"+A.show())\n}\nclass A {\n companion object {\n fun show():String {\n return(\"You are learning Kotlin from TutorialsPoint.com\")\n }\n }\n}\n"
},
{
"code": null,
"e": 5972,
"s": 5894,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6030,
"s": 5972,
"text": "Heyyy!!! You are learning Kotlin from TutorialsPoint.com\n"
},
{
"code": null,
"e": 6371,
"s": 6030,
"text": "The above example seems like static in Java, however, in real-time we are creating an object as a member variable of that same class. This is why it is also included under extension property and can be alternatively called as an object extension. You are basically extending the object of the same class to use some of the member functions."
},
{
"code": null,
"e": 6513,
"s": 6371,
"text": "Kotlin allows to define Extension Functions with a nullable class type. These extension function can be called on a nullable object variable."
},
{
"code": null,
"e": 6675,
"s": 6513,
"text": "To define an extension for Nullable receiver, we just need to add a check for null receiver inside the extension function, and the appropriate value is returned."
},
{
"code": null,
"e": 7222,
"s": 6675,
"text": "fun main(args: Array<String>) {\n var str1 = \"Good morning Kotlin\"\n var str2 : String? = null\n \n var result = str1.countVowels()\n println(\"Number of vowels in str1 : $result\")\n \n result = str2.countVowels()\n println(\"Number of vowels in str2 : $result\")\n}\nfun String?.countVowels(): Any{\n if (this == null) return \"null\"\n \n var vowels = 0\n for (i in 0.. this.length - 1) {\n val ch = this[i]\n if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {\n ++vowels\n }\n }\n return vowels; \n}\n"
},
{
"code": null,
"e": 7300,
"s": 7222,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7362,
"s": 7300,
"text": "Number of vowels in str1 : 6\nNumber of vowels in str2 : null\n"
},
{
"code": null,
"e": 7730,
"s": 7362,
"text": "Kotlin allows to define extension properties in very similar way like we defined extension function. Extension properties are also defined outside of the class. Since extensions do not actually insert members into classes, there is no efficient way for an extension property to have a backing field. This is why initializers are not allowed for extension properties. "
},
{
"code": null,
"e": 7830,
"s": 7730,
"text": "We can add getter and setter along with the property which are nothing but the extension functions."
},
{
"code": null,
"e": 8133,
"s": 7830,
"text": "class Temperature(var celsius: Float)\n\nfun main(args: Array<String>) {\n val t = Temperature(40f)\n println(t.fahrenheit)\n\n t.fahrenheit = 85f\n println(t.celsius)\n}\nvar Temperature.fahrenheit: Float\n get() = (celsius * 9 / 5) + 32\n set(value) {\n celsius = (value - 32) * 5 / 9\n }\n"
},
{
"code": null,
"e": 8211,
"s": 8133,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 8228,
"s": 8211,
"text": "104.0\n29.444445\n"
},
{
"code": null,
"e": 8286,
"s": 8228,
"text": "Q 1 - Which one is true about kotlin extension function :"
},
{
"code": null,
"e": 8366,
"s": 8286,
"text": "A - They are defined outside the class without impacting existing functionality"
},
{
"code": null,
"e": 8438,
"s": 8366,
"text": "B - We can inherit Kotlin class and add a new function inside the class"
},
{
"code": null,
"e": 8511,
"s": 8438,
"text": "C - Latest version of Kotlin does not allow to define extension function"
},
{
"code": null,
"e": 8558,
"s": 8511,
"text": "D - All are incorrect about extension function"
},
{
"code": null,
"e": 8657,
"s": 8558,
"text": "Kotlin extension functions are defined outside the class without impacting existing functionality."
},
{
"code": null,
"e": 8716,
"s": 8657,
"text": "Q 2 - Which one is true about Kotlin extension properties "
},
{
"code": null,
"e": 8796,
"s": 8716,
"text": "A - They are defined outside the class without impacting existing functionality"
},
{
"code": null,
"e": 8855,
"s": 8796,
"text": "B - Initializers are not allowed for extension properties."
},
{
"code": null,
"e": 8936,
"s": 8855,
"text": "C - We can define getter and setter functions to manage the extension properties"
},
{
"code": null,
"e": 8985,
"s": 8936,
"text": "D - All are incorrect about extension properties"
},
{
"code": null,
"e": 9044,
"s": 8985,
"text": "All the statements are correct about extension properties."
},
{
"code": null,
"e": 9079,
"s": 9044,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9098,
"s": 9079,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9133,
"s": 9098,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9150,
"s": 9133,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9185,
"s": 9150,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9202,
"s": 9185,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 9235,
"s": 9202,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9251,
"s": 9235,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 9286,
"s": 9251,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9306,
"s": 9286,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 9339,
"s": 9306,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9356,
"s": 9339,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 9363,
"s": 9356,
"text": " Print"
},
{
"code": null,
"e": 9374,
"s": 9363,
"text": " Add Notes"
}
] |
A Complete Exploratory Data Analysis and Visualization for Text Data | by Susan Li | Towards Data Science
|
Visually representing the content of a text document is one of the most important tasks in the field of text mining. As a data scientist or NLP specialist, not only we explore the content of documents from different aspects and at different levels of details, but also we summarize a single document, show the words and topics, detect events, and create storylines.
However, there are some gaps between visualizing unstructured (text) data and structured data. For example, many text visualizations do not represent the text directly, they represent an output of a language model(word count, character length, word sequences, etc.).
In this post, we will use Womens Clothing E-Commerce Reviews data set, and try to explore and visualize as much as we can, using Plotly’s Python graphing library and Bokeh visualization library. Not only we are going to explore text data, but also we will visualize numeric and categorical features. Let’s get started!
df = pd.read_csv('Womens Clothing E-Commerce Reviews.csv')
After a brief inspection of the data, we found there are a series of data pre-processing we have to conduct.
Remove the “Title” feature.
Remove the rows where “Review Text” were missing.
Clean “Review Text” column.
Using TextBlob to calculate sentiment polarity which lies in the range of [-1,1] where 1 means positive sentiment and -1 means a negative sentiment.
Create new feature for the length of the review.
Create new feature for the word count of the review.
To preview whether the sentiment polarity score works, we randomly select 5 reviews with the highest sentiment polarity score (1):
print('5 random reviews with the highest positive sentiment polarity: \n')cl = df.loc[df.polarity == 1, ['Review Text']].sample(5).valuesfor c in cl: print(c[0])
Then randomly select 5 reviews with the most neutral sentiment polarity score (zero):
print('5 random reviews with the most neutral sentiment(zero) polarity: \n')cl = df.loc[df.polarity == 0, ['Review Text']].sample(5).valuesfor c in cl: print(c[0])
There were only 2 reviews with the most negative sentiment polarity score:
print('2 reviews with the most negative polarity: \n')cl = df.loc[df.polarity == -0.97500000000000009, ['Review Text']].sample(2).valuesfor c in cl: print(c[0])
It worked!
Single-variable or univariate visualization is the simplest type of visualization which consists of observations on only a single characteristic or attribute. Univariate visualization includes histogram, bar plots and line charts.
df['polarity'].iplot( kind='hist', bins=50, xTitle='polarity', linecolor='black', yTitle='count', title='Sentiment Polarity Distribution')
Vast majority of the sentiment polarity scores are greater than zero, means most of them are pretty positive.
df['Rating'].iplot( kind='hist', xTitle='rating', linecolor='black', yTitle='count', title='Review Rating Distribution')
The ratings are in align with the polarity score, that is, most of the ratings are pretty high at 4 or 5 ranges.
df['Age'].iplot( kind='hist', bins=50, xTitle='age', linecolor='black', yTitle='count', title='Reviewers Age Distribution')
Most reviewers are in their 30s to 40s.
df['review_len'].iplot( kind='hist', bins=100, xTitle='review length', linecolor='black', yTitle='count', title='Review Text Length Distribution')
df['word_count'].iplot( kind='hist', bins=100, xTitle='word count', linecolor='black', yTitle='count', title='Review Text Word Count Distribution')
There were quite number of people like to leave long reviews.
For categorical features, we simply use bar chart to present the frequency.
df.groupby('Division Name').count()['Clothing ID'].iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Division Name', xTitle='Division Name')
General division has the most number of reviews, and Initmates division has the least number of reviews.
df.groupby('Department Name').count()['Clothing ID'].sort_values(ascending=False).iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Department Name', xTitle='Department Name')
When comes to department, Tops department has the most reviews and Trend department has the least number of reviews.
df.groupby('Class Name').count()['Clothing ID'].sort_values(ascending=False).iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Class Name', xTitle='Class Name')
Now we come to “Review Text” feature, before explore this feature, we need to extract N-Gram features. N-grams are used to describe the number of words used as observation points, e.g., unigram means singly-worded, bigram means 2-worded phrase, and trigram means 3-worded phrase. In order to do this, we use scikit-learn’s CountVectorizer function.
First, it would be interesting to compare unigrams before and after removing stop words.
Second, we want to compare bigrams before and after removing stop words.
Last, we compare trigrams before and after removing stop words.
Part-Of-Speech Tagging (POS) is a process of assigning parts of speech to each word, such as noun, verb, adjective, etc
We use a simple TextBlob API to dive into POS of our “Review Text” feature in our data set, and visualize these tags.
Box plot is used to compare the sentiment polarity score, rating, review text lengths of each department or division of the e-commerce store.
The highest sentiment polarity score was achieved by all of the six departments except Trend department, and the lowest sentiment polarity score was collected by Tops department. And the Trend department has the lowest median polarity score. If you remember, the Trend department has the least number of reviews. This explains why it does not have as wide variety of score distribution as the other departments.
Except Trend department, all the other departments’ median rating were 5. Overall, the ratings are high and sentiment are positive in this review data set.
The median review length of Tops & Intimate departments are relative lower than those of the other departments.
Bivariate visualization is a type of visualization that consists two features at a time. It describes association or relationship between two features.
It is obvious that reviews have higher polarity score are more likely to be recommended.
Recommended reviews have higher ratings than those of not recommended ones.
Recommended reviews tend to be lengthier than those of not recommended reviews.
There were few people are very positive or very negative. People who give neutral to positive reviews are more likely to be in their 30s. Probably people at these age are likely to be more active.
Sometimes we want to analyzes words used by different categories and outputs some notable term associations. We will use scattertext and spaCy libraries to accomplish these.
First, we need to turn the data frame into a Scattertext Corpus. To look for differences in department name, set the category_colparameter to 'Department Names', and use the review present in the Review Text column, to analyze by setting the text col parameter. Finally, pass a spaCy model in to the nlp argument and call build() to construct the corpus.
Following are the terms that differentiate the review text from a general English corpus.
corpus = st.CorpusFromPandas(df, category_col='Department Name', text_col='Review Text', nlp=nlp).build()print(list(corpus.get_scaled_f_scores_vs_background().index[:10]))
Following are the terms in review text that are most associated with the Tops department:
term_freq_df = corpus.get_term_freq_df()term_freq_df['Tops Score'] = corpus.get_scaled_f_scores('Tops')pprint(list(term_freq_df.sort_values(by='Tops Score', ascending=False).index[:10]))
Following are the terms that are most associated with the Dresses department:
term_freq_df['Dresses Score'] = corpus.get_scaled_f_scores('Dresses')pprint(list(term_freq_df.sort_values(by='Dresses Score', ascending=False).index[:10]))
Finally, we want to explore topic modeling algorithm to this data set, to see whether it would provide any benefit, and fit with what we are doing for our review text feature.
We will experiment with Latent Semantic Analysis (LSA) technique in topic modeling.
Generating our document-term matrix from review text to a matrix of TF-IDF features.
LSA model replaces raw counts in the document-term matrix with a TF-IDF score.
Perform dimensionality reduction on the document-term matrix using truncated SVD.
Because the number of department is 6, we set n_topics=6.
Taking the argmax of each review text in this topic matrix will give the predicted topics of each review text in the data. We can then sort these into counts of each topic.
To better understand each topic, we will find the most frequent three words in each topic.
top_3_words = get_top_n_words(3, lsa_keys, document_term_matrix, tfidf_vectorizer)labels = ['Topic {}: \n'.format(i) + top_3_words[i] for i in lsa_categories]fig, ax = plt.subplots(figsize=(16,8))ax.bar(lsa_categories, lsa_counts);ax.set_xticks(lsa_categories);ax.set_xticklabels(labels);ax.set_ylabel('Number of review text');ax.set_title('LSA topic counts');plt.show();
By looking at the most frequent words in each topic, we have a sense that we may not reach any degree of separation across the topic categories. In another word, we could not separate review text by departments using topic modeling techniques.
Topic modeling techniques have a number of important limitations. To begin, the term “topic” is somewhat ambigious, and by now it is perhaps clear that topic models will not produce highly nuanced classification of texts for our data.
In addition, we can observe that the vast majority of the review text are categorized to the first topic (Topic 0). The t-SNE visualization of LSA topic modeling won’t be pretty.
All the code can be found on the Jupyter notebook. And code plus the interactive visualizations can be viewed on nbviewer.
|
[
{
"code": null,
"e": 538,
"s": 172,
"text": "Visually representing the content of a text document is one of the most important tasks in the field of text mining. As a data scientist or NLP specialist, not only we explore the content of documents from different aspects and at different levels of details, but also we summarize a single document, show the words and topics, detect events, and create storylines."
},
{
"code": null,
"e": 805,
"s": 538,
"text": "However, there are some gaps between visualizing unstructured (text) data and structured data. For example, many text visualizations do not represent the text directly, they represent an output of a language model(word count, character length, word sequences, etc.)."
},
{
"code": null,
"e": 1124,
"s": 805,
"text": "In this post, we will use Womens Clothing E-Commerce Reviews data set, and try to explore and visualize as much as we can, using Plotly’s Python graphing library and Bokeh visualization library. Not only we are going to explore text data, but also we will visualize numeric and categorical features. Let’s get started!"
},
{
"code": null,
"e": 1183,
"s": 1124,
"text": "df = pd.read_csv('Womens Clothing E-Commerce Reviews.csv')"
},
{
"code": null,
"e": 1292,
"s": 1183,
"text": "After a brief inspection of the data, we found there are a series of data pre-processing we have to conduct."
},
{
"code": null,
"e": 1320,
"s": 1292,
"text": "Remove the “Title” feature."
},
{
"code": null,
"e": 1370,
"s": 1320,
"text": "Remove the rows where “Review Text” were missing."
},
{
"code": null,
"e": 1398,
"s": 1370,
"text": "Clean “Review Text” column."
},
{
"code": null,
"e": 1547,
"s": 1398,
"text": "Using TextBlob to calculate sentiment polarity which lies in the range of [-1,1] where 1 means positive sentiment and -1 means a negative sentiment."
},
{
"code": null,
"e": 1596,
"s": 1547,
"text": "Create new feature for the length of the review."
},
{
"code": null,
"e": 1649,
"s": 1596,
"text": "Create new feature for the word count of the review."
},
{
"code": null,
"e": 1780,
"s": 1649,
"text": "To preview whether the sentiment polarity score works, we randomly select 5 reviews with the highest sentiment polarity score (1):"
},
{
"code": null,
"e": 1945,
"s": 1780,
"text": "print('5 random reviews with the highest positive sentiment polarity: \\n')cl = df.loc[df.polarity == 1, ['Review Text']].sample(5).valuesfor c in cl: print(c[0])"
},
{
"code": null,
"e": 2031,
"s": 1945,
"text": "Then randomly select 5 reviews with the most neutral sentiment polarity score (zero):"
},
{
"code": null,
"e": 2198,
"s": 2031,
"text": "print('5 random reviews with the most neutral sentiment(zero) polarity: \\n')cl = df.loc[df.polarity == 0, ['Review Text']].sample(5).valuesfor c in cl: print(c[0])"
},
{
"code": null,
"e": 2273,
"s": 2198,
"text": "There were only 2 reviews with the most negative sentiment polarity score:"
},
{
"code": null,
"e": 2437,
"s": 2273,
"text": "print('2 reviews with the most negative polarity: \\n')cl = df.loc[df.polarity == -0.97500000000000009, ['Review Text']].sample(2).valuesfor c in cl: print(c[0])"
},
{
"code": null,
"e": 2448,
"s": 2437,
"text": "It worked!"
},
{
"code": null,
"e": 2679,
"s": 2448,
"text": "Single-variable or univariate visualization is the simplest type of visualization which consists of observations on only a single characteristic or attribute. Univariate visualization includes histogram, bar plots and line charts."
},
{
"code": null,
"e": 2836,
"s": 2679,
"text": "df['polarity'].iplot( kind='hist', bins=50, xTitle='polarity', linecolor='black', yTitle='count', title='Sentiment Polarity Distribution')"
},
{
"code": null,
"e": 2946,
"s": 2836,
"text": "Vast majority of the sentiment polarity scores are greater than zero, means most of them are pretty positive."
},
{
"code": null,
"e": 3082,
"s": 2946,
"text": "df['Rating'].iplot( kind='hist', xTitle='rating', linecolor='black', yTitle='count', title='Review Rating Distribution')"
},
{
"code": null,
"e": 3195,
"s": 3082,
"text": "The ratings are in align with the polarity score, that is, most of the ratings are pretty high at 4 or 5 ranges."
},
{
"code": null,
"e": 3337,
"s": 3195,
"text": "df['Age'].iplot( kind='hist', bins=50, xTitle='age', linecolor='black', yTitle='count', title='Reviewers Age Distribution')"
},
{
"code": null,
"e": 3377,
"s": 3337,
"text": "Most reviewers are in their 30s to 40s."
},
{
"code": null,
"e": 3542,
"s": 3377,
"text": "df['review_len'].iplot( kind='hist', bins=100, xTitle='review length', linecolor='black', yTitle='count', title='Review Text Length Distribution')"
},
{
"code": null,
"e": 3708,
"s": 3542,
"text": "df['word_count'].iplot( kind='hist', bins=100, xTitle='word count', linecolor='black', yTitle='count', title='Review Text Word Count Distribution')"
},
{
"code": null,
"e": 3770,
"s": 3708,
"text": "There were quite number of people like to leave long reviews."
},
{
"code": null,
"e": 3846,
"s": 3770,
"text": "For categorical features, we simply use bar chart to present the frequency."
},
{
"code": null,
"e": 4081,
"s": 3846,
"text": "df.groupby('Division Name').count()['Clothing ID'].iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Division Name', xTitle='Division Name')"
},
{
"code": null,
"e": 4186,
"s": 4081,
"text": "General division has the most number of reviews, and Initmates division has the least number of reviews."
},
{
"code": null,
"e": 4456,
"s": 4186,
"text": "df.groupby('Department Name').count()['Clothing ID'].sort_values(ascending=False).iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Department Name', xTitle='Department Name')"
},
{
"code": null,
"e": 4573,
"s": 4456,
"text": "When comes to department, Tops department has the most reviews and Trend department has the least number of reviews."
},
{
"code": null,
"e": 4828,
"s": 4573,
"text": "df.groupby('Class Name').count()['Clothing ID'].sort_values(ascending=False).iplot(kind='bar', yTitle='Count', linecolor='black', opacity=0.8, title='Bar chart of Class Name', xTitle='Class Name')"
},
{
"code": null,
"e": 5177,
"s": 4828,
"text": "Now we come to “Review Text” feature, before explore this feature, we need to extract N-Gram features. N-grams are used to describe the number of words used as observation points, e.g., unigram means singly-worded, bigram means 2-worded phrase, and trigram means 3-worded phrase. In order to do this, we use scikit-learn’s CountVectorizer function."
},
{
"code": null,
"e": 5266,
"s": 5177,
"text": "First, it would be interesting to compare unigrams before and after removing stop words."
},
{
"code": null,
"e": 5339,
"s": 5266,
"text": "Second, we want to compare bigrams before and after removing stop words."
},
{
"code": null,
"e": 5403,
"s": 5339,
"text": "Last, we compare trigrams before and after removing stop words."
},
{
"code": null,
"e": 5523,
"s": 5403,
"text": "Part-Of-Speech Tagging (POS) is a process of assigning parts of speech to each word, such as noun, verb, adjective, etc"
},
{
"code": null,
"e": 5641,
"s": 5523,
"text": "We use a simple TextBlob API to dive into POS of our “Review Text” feature in our data set, and visualize these tags."
},
{
"code": null,
"e": 5783,
"s": 5641,
"text": "Box plot is used to compare the sentiment polarity score, rating, review text lengths of each department or division of the e-commerce store."
},
{
"code": null,
"e": 6195,
"s": 5783,
"text": "The highest sentiment polarity score was achieved by all of the six departments except Trend department, and the lowest sentiment polarity score was collected by Tops department. And the Trend department has the lowest median polarity score. If you remember, the Trend department has the least number of reviews. This explains why it does not have as wide variety of score distribution as the other departments."
},
{
"code": null,
"e": 6351,
"s": 6195,
"text": "Except Trend department, all the other departments’ median rating were 5. Overall, the ratings are high and sentiment are positive in this review data set."
},
{
"code": null,
"e": 6463,
"s": 6351,
"text": "The median review length of Tops & Intimate departments are relative lower than those of the other departments."
},
{
"code": null,
"e": 6615,
"s": 6463,
"text": "Bivariate visualization is a type of visualization that consists two features at a time. It describes association or relationship between two features."
},
{
"code": null,
"e": 6704,
"s": 6615,
"text": "It is obvious that reviews have higher polarity score are more likely to be recommended."
},
{
"code": null,
"e": 6780,
"s": 6704,
"text": "Recommended reviews have higher ratings than those of not recommended ones."
},
{
"code": null,
"e": 6860,
"s": 6780,
"text": "Recommended reviews tend to be lengthier than those of not recommended reviews."
},
{
"code": null,
"e": 7057,
"s": 6860,
"text": "There were few people are very positive or very negative. People who give neutral to positive reviews are more likely to be in their 30s. Probably people at these age are likely to be more active."
},
{
"code": null,
"e": 7231,
"s": 7057,
"text": "Sometimes we want to analyzes words used by different categories and outputs some notable term associations. We will use scattertext and spaCy libraries to accomplish these."
},
{
"code": null,
"e": 7586,
"s": 7231,
"text": "First, we need to turn the data frame into a Scattertext Corpus. To look for differences in department name, set the category_colparameter to 'Department Names', and use the review present in the Review Text column, to analyze by setting the text col parameter. Finally, pass a spaCy model in to the nlp argument and call build() to construct the corpus."
},
{
"code": null,
"e": 7676,
"s": 7586,
"text": "Following are the terms that differentiate the review text from a general English corpus."
},
{
"code": null,
"e": 7848,
"s": 7676,
"text": "corpus = st.CorpusFromPandas(df, category_col='Department Name', text_col='Review Text', nlp=nlp).build()print(list(corpus.get_scaled_f_scores_vs_background().index[:10]))"
},
{
"code": null,
"e": 7938,
"s": 7848,
"text": "Following are the terms in review text that are most associated with the Tops department:"
},
{
"code": null,
"e": 8125,
"s": 7938,
"text": "term_freq_df = corpus.get_term_freq_df()term_freq_df['Tops Score'] = corpus.get_scaled_f_scores('Tops')pprint(list(term_freq_df.sort_values(by='Tops Score', ascending=False).index[:10]))"
},
{
"code": null,
"e": 8203,
"s": 8125,
"text": "Following are the terms that are most associated with the Dresses department:"
},
{
"code": null,
"e": 8359,
"s": 8203,
"text": "term_freq_df['Dresses Score'] = corpus.get_scaled_f_scores('Dresses')pprint(list(term_freq_df.sort_values(by='Dresses Score', ascending=False).index[:10]))"
},
{
"code": null,
"e": 8535,
"s": 8359,
"text": "Finally, we want to explore topic modeling algorithm to this data set, to see whether it would provide any benefit, and fit with what we are doing for our review text feature."
},
{
"code": null,
"e": 8619,
"s": 8535,
"text": "We will experiment with Latent Semantic Analysis (LSA) technique in topic modeling."
},
{
"code": null,
"e": 8704,
"s": 8619,
"text": "Generating our document-term matrix from review text to a matrix of TF-IDF features."
},
{
"code": null,
"e": 8783,
"s": 8704,
"text": "LSA model replaces raw counts in the document-term matrix with a TF-IDF score."
},
{
"code": null,
"e": 8865,
"s": 8783,
"text": "Perform dimensionality reduction on the document-term matrix using truncated SVD."
},
{
"code": null,
"e": 8923,
"s": 8865,
"text": "Because the number of department is 6, we set n_topics=6."
},
{
"code": null,
"e": 9096,
"s": 8923,
"text": "Taking the argmax of each review text in this topic matrix will give the predicted topics of each review text in the data. We can then sort these into counts of each topic."
},
{
"code": null,
"e": 9187,
"s": 9096,
"text": "To better understand each topic, we will find the most frequent three words in each topic."
},
{
"code": null,
"e": 9559,
"s": 9187,
"text": "top_3_words = get_top_n_words(3, lsa_keys, document_term_matrix, tfidf_vectorizer)labels = ['Topic {}: \\n'.format(i) + top_3_words[i] for i in lsa_categories]fig, ax = plt.subplots(figsize=(16,8))ax.bar(lsa_categories, lsa_counts);ax.set_xticks(lsa_categories);ax.set_xticklabels(labels);ax.set_ylabel('Number of review text');ax.set_title('LSA topic counts');plt.show();"
},
{
"code": null,
"e": 9803,
"s": 9559,
"text": "By looking at the most frequent words in each topic, we have a sense that we may not reach any degree of separation across the topic categories. In another word, we could not separate review text by departments using topic modeling techniques."
},
{
"code": null,
"e": 10038,
"s": 9803,
"text": "Topic modeling techniques have a number of important limitations. To begin, the term “topic” is somewhat ambigious, and by now it is perhaps clear that topic models will not produce highly nuanced classification of texts for our data."
},
{
"code": null,
"e": 10217,
"s": 10038,
"text": "In addition, we can observe that the vast majority of the review text are categorized to the first topic (Topic 0). The t-SNE visualization of LSA topic modeling won’t be pretty."
}
] |
Tryit Editor v3.7
|
HTML Web Storage
Tryit: HTML count the clicks
|
[
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Web Storage"
}
] |
How to create a scroll pane using JavaFX?
|
A scroll pane holds a UI element and provides a scrollable view of it. In JavaFX, you can create a scroll pane by instantiating the javafx.scene.control.ScrollPane class. You can set content to the scroll pane using the setContent() method.
To add a scroll pane to a node −
To add a scroll pane to a node −
Instantiate the ScrollPane class.
Instantiate the ScrollPane class.
Create the desired node.
Create the desired node.
Set the node to the scroll pane using the setContent() method.
Set the node to the scroll pane using the setContent() method.
Set the dimensions of the scroll pane using the setter methods.
Set the dimensions of the scroll pane using the setter methods.
Add the scroll pane to the layout pane or group.
Add the scroll pane to the layout pane or group.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ScrollPaneActionExample extends Application {
public void start(Stage stage) throws FileNotFoundException {
//creating the image object
InputStream stream = new FileInputStream("D:\\images\\elephant.jpg");
Image image = new Image(stream);
//Creating the image view
ImageView imageView = new ImageView();
//Setting image to the image view
imageView.setImage(image);
//Setting the image view parameters
imageView.setX(5);
imageView.setY(0);
imageView.setFitWidth(595);
imageView.setPreserveRatio(true);
//Creating the scroll pane
ScrollPane scroll = new ScrollPane();
scroll.setPrefSize(595, 200);
//Setting content to the scroll pane
scroll.setContent(imageView);
//Setting the stage
Group root = new Group();
root.getChildren().addAll(scroll);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Scroll Pane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1303,
"s": 1062,
"text": "A scroll pane holds a UI element and provides a scrollable view of it. In JavaFX, you can create a scroll pane by instantiating the javafx.scene.control.ScrollPane class. You can set content to the scroll pane using the setContent() method."
},
{
"code": null,
"e": 1336,
"s": 1303,
"text": "To add a scroll pane to a node −"
},
{
"code": null,
"e": 1369,
"s": 1336,
"text": "To add a scroll pane to a node −"
},
{
"code": null,
"e": 1403,
"s": 1369,
"text": "Instantiate the ScrollPane class."
},
{
"code": null,
"e": 1437,
"s": 1403,
"text": "Instantiate the ScrollPane class."
},
{
"code": null,
"e": 1462,
"s": 1437,
"text": "Create the desired node."
},
{
"code": null,
"e": 1487,
"s": 1462,
"text": "Create the desired node."
},
{
"code": null,
"e": 1550,
"s": 1487,
"text": "Set the node to the scroll pane using the setContent() method."
},
{
"code": null,
"e": 1613,
"s": 1550,
"text": "Set the node to the scroll pane using the setContent() method."
},
{
"code": null,
"e": 1677,
"s": 1613,
"text": "Set the dimensions of the scroll pane using the setter methods."
},
{
"code": null,
"e": 1741,
"s": 1677,
"text": "Set the dimensions of the scroll pane using the setter methods."
},
{
"code": null,
"e": 1790,
"s": 1741,
"text": "Add the scroll pane to the layout pane or group."
},
{
"code": null,
"e": 1839,
"s": 1790,
"text": "Add the scroll pane to the layout pane or group."
},
{
"code": null,
"e": 3309,
"s": 1839,
"text": "import java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ScrollPaneActionExample extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //creating the image object\n InputStream stream = new FileInputStream(\"D:\\\\images\\\\elephant.jpg\");\n Image image = new Image(stream);\n //Creating the image view\n ImageView imageView = new ImageView();\n //Setting image to the image view\n imageView.setImage(image);\n //Setting the image view parameters\n imageView.setX(5);\n imageView.setY(0);\n imageView.setFitWidth(595);\n imageView.setPreserveRatio(true);\n //Creating the scroll pane\n ScrollPane scroll = new ScrollPane();\n scroll.setPrefSize(595, 200);\n //Setting content to the scroll pane\n scroll.setContent(imageView);\n //Setting the stage\n Group root = new Group();\n root.getChildren().addAll(scroll);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Scroll Pane Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Convert Image to Data URI with JavaScript
|
To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.
This will return the base64 encoded data URI of the image. For example,
if you have an image with id my-image, you can use the following −
function getDataUrl(img) {
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set width and height
canvas.width = img.width;
canvas.height = img.height;
// Draw the image
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
const dataUrl = getDataUrl(event.currentTarget);
console.log(dataUrl);
});
This will give the output −
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it."
},
{
"code": null,
"e": 1434,
"s": 1295,
"text": "This will return the base64 encoded data URI of the image. For example,\nif you have an image with id my-image, you can use the following −"
},
{
"code": null,
"e": 1952,
"s": 1434,
"text": "function getDataUrl(img) {\n // Create canvas\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n // Set width and height\n canvas.width = img.width;\n canvas.height = img.height;\n // Draw the image\n ctx.drawImage(img, 0, 0);\n return canvas.toDataURL('image/jpeg');\n}\n// Select the image\nconst img = document.querySelector('#my-image');\nimg.addEventListener('load', function (event) {\n const dataUrl = getDataUrl(event.currentTarget);\n console.log(dataUrl);\n});"
},
{
"code": null,
"e": 1980,
"s": 1952,
"text": "This will give the output −"
},
{
"code": null,
"e": 2054,
"s": 1980,
"text": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB"
}
] |
PHPUnit assertSame() Function - GeeksforGeeks
|
07 Aug, 2020
The assertSame() function is a builtin function in PHPUnit and is used to assert whether the actually obtained value is the same as the expected value or not. This assertion will return true in the case if the expected value is the same as the actual value else returns false. In case of true the asserted test case got passed else test case got failed.
Syntax:
assertSame(mixed $expected, mixed $actual[, string $message = ''])
Parameters: This function accepts three parameters as mentioned above and described below:
$expected: This parameter is of any type which represents the expected data.
$actual: This parameter is of any type which represents the actual data.
$message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message.
Below examples illustrate the assertSame() function in PHPUnit:
Examples 1:
PHP
<?php use PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testNegativeForassertSame() { $expected = "(108) banana"; $actual = "(108) mango"; // Assert function to test whether expected // value is same as actual value or not $this->assertSame( $expected, $actual, "actual value is not same as expected value" ); } } ?>
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 90 ms, Memory: 10.00 MB
There was 1 failure:
1) GeeksPhpunitTestCase::testNegativeForassertSame
actual value is not same as expected value
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
-'(108) banana'
+'(108) mango'
/home/lovely/Documents/php/test.php:17
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
Example 2:
PHP
<?php use PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testPositiveForassertSame() { $expected = "(108) mango"; $actual = "(108) mango"; // Assert function to test whether expected // value is same as actual value or not $this->assertSame( $expected, $actual, "actual value is not same as expected value" ); } } ?>
Output:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 89 ms, Memory: 10.00 MB
OK (1 test, 1 assertion)
Reference: https://phpunit.readthedocs.io/en/9.2/assertions.html#assertsame
PHP-PHPUnit
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
How to fetch data from localserver database and display on HTML table using PHP ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24162,
"s": 24134,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 24516,
"s": 24162,
"text": "The assertSame() function is a builtin function in PHPUnit and is used to assert whether the actually obtained value is the same as the expected value or not. This assertion will return true in the case if the expected value is the same as the actual value else returns false. In case of true the asserted test case got passed else test case got failed."
},
{
"code": null,
"e": 24524,
"s": 24516,
"text": "Syntax:"
},
{
"code": null,
"e": 24592,
"s": 24524,
"text": "assertSame(mixed $expected, mixed $actual[, string $message = ''])\n"
},
{
"code": null,
"e": 24683,
"s": 24592,
"text": "Parameters: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 24760,
"s": 24683,
"text": "$expected: This parameter is of any type which represents the expected data."
},
{
"code": null,
"e": 24833,
"s": 24760,
"text": "$actual: This parameter is of any type which represents the actual data."
},
{
"code": null,
"e": 24965,
"s": 24833,
"text": "$message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message."
},
{
"code": null,
"e": 25029,
"s": 24965,
"text": "Below examples illustrate the assertSame() function in PHPUnit:"
},
{
"code": null,
"e": 25041,
"s": 25029,
"text": "Examples 1:"
},
{
"code": null,
"e": 25045,
"s": 25041,
"text": "PHP"
},
{
"code": "<?php use PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testNegativeForassertSame() { $expected = \"(108) banana\"; $actual = \"(108) mango\"; // Assert function to test whether expected // value is same as actual value or not $this->assertSame( $expected, $actual, \"actual value is not same as expected value\" ); } } ?> ",
"e": 25517,
"s": 25045,
"text": null
},
{
"code": null,
"e": 25525,
"s": 25517,
"text": "Output:"
},
{
"code": null,
"e": 25992,
"s": 25525,
"text": "PHPUnit 8.5.8 by Sebastian Bergmann and contributors.\n\nF 1 / 1 (100%)\n\nTime: 90 ms, Memory: 10.00 MB\n\nThere was 1 failure:\n\n1) GeeksPhpunitTestCase::testNegativeForassertSame\nactual value is not same as expected value\nFailed asserting that two strings are identical.\n--- Expected\n+++ Actual\n@@ @@\n-'(108) banana'\n+'(108) mango'\n\n/home/lovely/Documents/php/test.php:17\n\nFAILURES!\nTests: 1, Assertions: 1, Failures: 1.\n"
},
{
"code": null,
"e": 26003,
"s": 25992,
"text": "Example 2:"
},
{
"code": null,
"e": 26007,
"s": 26003,
"text": "PHP"
},
{
"code": "<?php use PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testPositiveForassertSame() { $expected = \"(108) mango\"; $actual = \"(108) mango\"; // Assert function to test whether expected // value is same as actual value or not $this->assertSame( $expected, $actual, \"actual value is not same as expected value\" ); } } ?> ",
"e": 26478,
"s": 26007,
"text": null
},
{
"code": null,
"e": 26486,
"s": 26478,
"text": "Output:"
},
{
"code": null,
"e": 26663,
"s": 26486,
"text": "PHPUnit 8.5.8 by Sebastian Bergmann and contributors.\n\n. 1 / 1 (100%)\n\nTime: 89 ms, Memory: 10.00 MB\n\nOK (1 test, 1 assertion)\n"
},
{
"code": null,
"e": 26739,
"s": 26663,
"text": "Reference: https://phpunit.readthedocs.io/en/9.2/assertions.html#assertsame"
},
{
"code": null,
"e": 26751,
"s": 26739,
"text": "PHP-PHPUnit"
},
{
"code": null,
"e": 26755,
"s": 26751,
"text": "PHP"
},
{
"code": null,
"e": 26772,
"s": 26755,
"text": "Web Technologies"
},
{
"code": null,
"e": 26776,
"s": 26772,
"text": "PHP"
},
{
"code": null,
"e": 26874,
"s": 26776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26883,
"s": 26874,
"text": "Comments"
},
{
"code": null,
"e": 26896,
"s": 26883,
"text": "Old Comments"
},
{
"code": null,
"e": 26946,
"s": 26896,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26986,
"s": 26946,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27013,
"s": 26986,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 27058,
"s": 27013,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 27140,
"s": 27058,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27173,
"s": 27140,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27215,
"s": 27173,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27258,
"s": 27215,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27320,
"s": 27258,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
DC.js - Data Table
|
Data table is used to display the records in a tabular format. It lists out the crossfilter dataset records as explained in this chapter in detail.
Before moving on to draw a data table, we should understand the dc.dataTable class and its methods. It uses a mixin to get the basic functionality of drawing a data table chart, which is defined below −
dc.baseMixin
The dc.dataTable gets all the methods of this mixin and has its own methods to draw the data table, which are explained as follows.
This method is used to get or set the index of the beginning slice. This method is useful when implementing pagination.
Similarly, you can perform the endSlice() function as well.
This method is used to get or set the column functions. It uses the following method to specify the columns to display.
chart.columns([
function(d) { return d.mark; },
function(d) { return d.low; },
function(d) { return d.high; },
function(d) { return numberFormat(d.high - d.low); },
function(d) { return d.volume; }
]);
Here, d represents a row in the data set. We can use HTML to display columns in the data table.
This method is used to perform the group function for the data table.
It is used to sort the order function. If the order is ascending, then the dimension() will use .bottom() to fetch the data, otherwise it will use dimension().top().
Let us make a data table in DC. To do this, we need to follow the steps given below −
Let us add styles in the CSS using the coding given below −
.dc-chart { font-size: 12px; }
.dc-table-group { padding-left: 10px; font-size: 14px; font-weight: bold; }
.dc-table-column { padding-left: 10px; font-size: 12px; font-weight: normal; }
Here, we have assigned styles for the chart, table-group and the grid-column.
Let us create a variable in DC as shown below −
var barChart = dc.barChart('#line'); //
var countChart = dc.dataCount("#mystats");
var tableChart = dc.dataTable("#mytable");
Here, we have assigned a barChart variable id in line, countChart id is mystats and the tableChart id is mytable.
Read the data from the people.csv file as shown below −
d3.csv("data/people.csv", function(errors, people) {
var mycrossfilter = crossfilter(people);
}
If the data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we have used the same people.csv file, which was used in our previous charting examples.
It looks like as follows −
id,name,gender,DOB,MaritalStatus,CreditCardType
1,Damaris,Female,1973-02-18,false,visa-electron
2,Barbe,Female,1969-04-10,true,americanexpress
3,Belia,Female,1960-04-16,false,maestro
4,Leoline,Female,1995-01-19,true,bankcard
5,Valentine,Female,1992-04-16,false,
6,Rosanne,Female,1985-01-05,true,bankcard
7,Shalna,Female,1956-11-01,false,jcb
8,Mordy,Male,1990-03-27,true,china-unionpay
..........................................
..........................................
You can set the dimension using the coding given below −
var ageDimension = mycrossfilter.dimension(function(data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000))
});
After the dimension has been assigned, group the age using the coding given below −
var ageGroup = ageDimension.group().reduceCount();
Now, generate a bar chart using the coding given below −
barChart
.width(400)
.height(200)
.x(d3.scale.linear().domain([15,70]))
.yAxisLabel("Count")
.xAxisLabel("Age")
.elasticY(true)
.elasticX(true)
.dimension(ageDimension)
.group(ageGroup);
Here,
We have assigned the chart width as 400 and height as 200.
Next, we have specified the domain range as [15,70].
We have set the x-axis label as age and y-axis label as count.
We have specified the elasticY and X function as true.
Now, create the data table using the coding given below −
countChart
.dimension(mycrossfilter)
.group(mycrossfilter.groupAll());
tableChart
.dimension(ageDimension)
.group(function (data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000));
})
Here, we have specified the age dimension and group the data.
Now, render the grid using the coding below −
.size(Infinity)
.columns(['name', 'DOB'])
.sortBy(function (d) {
return d.value;
})
.order(d3.ascending);
barChart.render();
countChart.render();
tableChart.render();
Here, we have sorted the columns using the DOB and sort the records.
The complete code is as follows. Create a web page datatable.html and add the following changes to it.
<html>
<head>
<title>DC datatable sample</title>
<link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css">
<link rel = "stylesheet" type = "text/css" href = "css/dc.css"/>
<style>
.dc-chart { font-size: 12px; }
.dc-table-group { padding-left: 10px; font-size: 14px; font-weight: bold; }
.dc-table-column { padding-left: 10px; font-size: 12px; font-weight: normal; }
</style>
<script src = "js/d3.js"></script>
<script src = "js/crossfilter.js"></script>
<script src = "js/dc.js"></script>
</head>
<body>
<div>
<div style = "width: 600px;">
<div id = "mystats" class = "dc-data-count" style = "float: right">
<span class = "filter-count"></span> selected out of <span
class = "total-count"></span> | <a href = "javascript:dc.filterAll();
dc.renderAll();">Reset All</a>
</div>
</div>
<div style = "clear: both; padding-top: 20px;">
<div>
<div id = "line"></div>
</div>
</div>
<div style = "clear: both">
<div id = "mytable"></div>
</div>
</div>
<script language = "javascript">
var barChart = dc.barChart('#line'); // , 'myChartGroup');
var countChart = dc.dataCount("#mystats");
var tableChart = dc.dataTable("#mytable");
d3.csv("data/people.csv", function(errors, people) {
var mycrossfilter = crossfilter(people);
// age dimension
var ageDimension = mycrossfilter.dimension(function(data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000))
});
var ageGroup = ageDimension.group().reduceCount();
barChart
.width(400)
.height(200)
.x(d3.scale.linear().domain([15,70]))
.yAxisLabel("Count")
.xAxisLabel("Age")
.elasticY(true)
.elasticX(true)
.dimension(ageDimension)
.group(ageGroup);
countChart
.dimension(mycrossfilter)
.group(mycrossfilter.groupAll());
tableChart
.dimension(ageDimension)
.group(function (data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000));
})
.size(Infinity)
.columns(['name', 'DOB'])
.sortBy(function (d) {
return d.value;
})
.order(d3.ascending);
barChart.render();
countChart.render();
tableChart.render();
});
</script>
</body>
</html>
Now, request the browser and you will see the following response.
After selecting an age between 20 and 30, it displays the table records as shown in the screenshot below −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2207,
"s": 2059,
"text": "Data table is used to display the records in a tabular format. It lists out the crossfilter dataset records as explained in this chapter in detail."
},
{
"code": null,
"e": 2410,
"s": 2207,
"text": "Before moving on to draw a data table, we should understand the dc.dataTable class and its methods. It uses a mixin to get the basic functionality of drawing a data table chart, which is defined below −"
},
{
"code": null,
"e": 2423,
"s": 2410,
"text": "dc.baseMixin"
},
{
"code": null,
"e": 2555,
"s": 2423,
"text": "The dc.dataTable gets all the methods of this mixin and has its own methods to draw the data table, which are explained as follows."
},
{
"code": null,
"e": 2675,
"s": 2555,
"text": "This method is used to get or set the index of the beginning slice. This method is useful when implementing pagination."
},
{
"code": null,
"e": 2735,
"s": 2675,
"text": "Similarly, you can perform the endSlice() function as well."
},
{
"code": null,
"e": 2855,
"s": 2735,
"text": "This method is used to get or set the column functions. It uses the following method to specify the columns to display."
},
{
"code": null,
"e": 3072,
"s": 2855,
"text": "chart.columns([\n function(d) { return d.mark; },\n function(d) { return d.low; },\n function(d) { return d.high; },\n function(d) { return numberFormat(d.high - d.low); },\n function(d) { return d.volume; }\n]);"
},
{
"code": null,
"e": 3168,
"s": 3072,
"text": "Here, d represents a row in the data set. We can use HTML to display columns in the data table."
},
{
"code": null,
"e": 3238,
"s": 3168,
"text": "This method is used to perform the group function for the data table."
},
{
"code": null,
"e": 3404,
"s": 3238,
"text": "It is used to sort the order function. If the order is ascending, then the dimension() will use .bottom() to fetch the data, otherwise it will use dimension().top()."
},
{
"code": null,
"e": 3490,
"s": 3404,
"text": "Let us make a data table in DC. To do this, we need to follow the steps given below −"
},
{
"code": null,
"e": 3550,
"s": 3490,
"text": "Let us add styles in the CSS using the coding given below −"
},
{
"code": null,
"e": 3736,
"s": 3550,
"text": ".dc-chart { font-size: 12px; }\n.dc-table-group { padding-left: 10px; font-size: 14px; font-weight: bold; }\n.dc-table-column { padding-left: 10px; font-size: 12px; font-weight: normal; }"
},
{
"code": null,
"e": 3814,
"s": 3736,
"text": "Here, we have assigned styles for the chart, table-group and the grid-column."
},
{
"code": null,
"e": 3862,
"s": 3814,
"text": "Let us create a variable in DC as shown below −"
},
{
"code": null,
"e": 3989,
"s": 3862,
"text": "var barChart = dc.barChart('#line'); // \nvar countChart = dc.dataCount(\"#mystats\");\nvar tableChart = dc.dataTable(\"#mytable\");"
},
{
"code": null,
"e": 4103,
"s": 3989,
"text": "Here, we have assigned a barChart variable id in line, countChart id is mystats and the tableChart id is mytable."
},
{
"code": null,
"e": 4159,
"s": 4103,
"text": "Read the data from the people.csv file as shown below −"
},
{
"code": null,
"e": 4258,
"s": 4159,
"text": "d3.csv(\"data/people.csv\", function(errors, people) {\n var mycrossfilter = crossfilter(people);\n}"
},
{
"code": null,
"e": 4446,
"s": 4258,
"text": "If the data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we have used the same people.csv file, which was used in our previous charting examples."
},
{
"code": null,
"e": 4473,
"s": 4446,
"text": "It looks like as follows −"
},
{
"code": null,
"e": 4946,
"s": 4473,
"text": "id,name,gender,DOB,MaritalStatus,CreditCardType\n1,Damaris,Female,1973-02-18,false,visa-electron\n2,Barbe,Female,1969-04-10,true,americanexpress\n3,Belia,Female,1960-04-16,false,maestro\n4,Leoline,Female,1995-01-19,true,bankcard\n5,Valentine,Female,1992-04-16,false,\n6,Rosanne,Female,1985-01-05,true,bankcard\n7,Shalna,Female,1956-11-01,false,jcb\n8,Mordy,Male,1990-03-27,true,china-unionpay\n\n..........................................\n..........................................\n"
},
{
"code": null,
"e": 5003,
"s": 4946,
"text": "You can set the dimension using the coding given below −"
},
{
"code": null,
"e": 5133,
"s": 5003,
"text": "var ageDimension = mycrossfilter.dimension(function(data) { \n return ~~((Date.now() - new Date(data.DOB)) / (31557600000)) \n});"
},
{
"code": null,
"e": 5217,
"s": 5133,
"text": "After the dimension has been assigned, group the age using the coding given below −"
},
{
"code": null,
"e": 5268,
"s": 5217,
"text": "var ageGroup = ageDimension.group().reduceCount();"
},
{
"code": null,
"e": 5325,
"s": 5268,
"text": "Now, generate a bar chart using the coding given below −"
},
{
"code": null,
"e": 5539,
"s": 5325,
"text": "barChart\n .width(400)\n .height(200)\n .x(d3.scale.linear().domain([15,70]))\n .yAxisLabel(\"Count\")\n .xAxisLabel(\"Age\")\n .elasticY(true)\n .elasticX(true)\n .dimension(ageDimension)\n .group(ageGroup);"
},
{
"code": null,
"e": 5545,
"s": 5539,
"text": "Here,"
},
{
"code": null,
"e": 5604,
"s": 5545,
"text": "We have assigned the chart width as 400 and height as 200."
},
{
"code": null,
"e": 5657,
"s": 5604,
"text": "Next, we have specified the domain range as [15,70]."
},
{
"code": null,
"e": 5720,
"s": 5657,
"text": "We have set the x-axis label as age and y-axis label as count."
},
{
"code": null,
"e": 5775,
"s": 5720,
"text": "We have specified the elasticY and X function as true."
},
{
"code": null,
"e": 5833,
"s": 5775,
"text": "Now, create the data table using the coding given below −"
},
{
"code": null,
"e": 6052,
"s": 5833,
"text": "countChart\n .dimension(mycrossfilter)\n .group(mycrossfilter.groupAll());\n\ntableChart\n .dimension(ageDimension)\n .group(function (data) {\n return ~~((Date.now() - new Date(data.DOB)) / (31557600000));\n })"
},
{
"code": null,
"e": 6114,
"s": 6052,
"text": "Here, we have specified the age dimension and group the data."
},
{
"code": null,
"e": 6160,
"s": 6114,
"text": "Now, render the grid using the coding below −"
},
{
"code": null,
"e": 6346,
"s": 6160,
"text": ".size(Infinity)\n .columns(['name', 'DOB'])\n .sortBy(function (d) {\n return d.value;\n })\n .order(d3.ascending);\n\nbarChart.render();\ncountChart.render();\ntableChart.render();"
},
{
"code": null,
"e": 6415,
"s": 6346,
"text": "Here, we have sorted the columns using the DOB and sort the records."
},
{
"code": null,
"e": 6518,
"s": 6415,
"text": "The complete code is as follows. Create a web page datatable.html and add the following changes to it."
},
{
"code": null,
"e": 9338,
"s": 6518,
"text": "<html>\n <head>\n <title>DC datatable sample</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"css/bootstrap.css\">\n <link rel = \"stylesheet\" type = \"text/css\" href = \"css/dc.css\"/>\n \n <style>\n .dc-chart { font-size: 12px; }\n .dc-table-group { padding-left: 10px; font-size: 14px; font-weight: bold; }\n .dc-table-column { padding-left: 10px; font-size: 12px; font-weight: normal; }\n </style>\n\n <script src = \"js/d3.js\"></script>\n <script src = \"js/crossfilter.js\"></script>\n <script src = \"js/dc.js\"></script>\n </head>\n \n <body>\n <div>\n <div style = \"width: 600px;\">\n <div id = \"mystats\" class = \"dc-data-count\" style = \"float: right\">\n <span class = \"filter-count\"></span> selected out of <span\n class = \"total-count\"></span> | <a href = \"javascript:dc.filterAll();\n dc.renderAll();\">Reset All</a>\n </div>\n </div>\n\n <div style = \"clear: both; padding-top: 20px;\">\n <div>\n <div id = \"line\"></div>\n </div>\n </div>\n\n <div style = \"clear: both\">\n <div id = \"mytable\"></div>\n </div>\n </div>\n\n <script language = \"javascript\">\n var barChart = dc.barChart('#line'); // , 'myChartGroup');\n var countChart = dc.dataCount(\"#mystats\");\n var tableChart = dc.dataTable(\"#mytable\");\n\n d3.csv(\"data/people.csv\", function(errors, people) {\n var mycrossfilter = crossfilter(people);\n\n // age dimension\n var ageDimension = mycrossfilter.dimension(function(data) { \n return ~~((Date.now() - new Date(data.DOB)) / (31557600000)) \n });\n var ageGroup = ageDimension.group().reduceCount();\n\n barChart\n .width(400)\n .height(200)\n .x(d3.scale.linear().domain([15,70]))\n .yAxisLabel(\"Count\")\n .xAxisLabel(\"Age\")\n .elasticY(true)\n .elasticX(true)\n .dimension(ageDimension)\n .group(ageGroup);\n\n countChart\n .dimension(mycrossfilter)\n .group(mycrossfilter.groupAll());\n\n tableChart\n .dimension(ageDimension)\n .group(function (data) {\n return ~~((Date.now() - new Date(data.DOB)) / (31557600000));\n })\n .size(Infinity)\n .columns(['name', 'DOB'])\n .sortBy(function (d) {\n return d.value;\n })\n .order(d3.ascending);\n\n barChart.render();\n countChart.render();\n tableChart.render();\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9404,
"s": 9338,
"text": "Now, request the browser and you will see the following response."
},
{
"code": null,
"e": 9511,
"s": 9404,
"text": "After selecting an age between 20 and 30, it displays the table records as shown in the screenshot below −"
},
{
"code": null,
"e": 9518,
"s": 9511,
"text": " Print"
},
{
"code": null,
"e": 9529,
"s": 9518,
"text": " Add Notes"
}
] |
Angular Material - Autocomplete
|
The md-autocomplete, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area. <md-autocomplete> can be used to provide search results from local or remote data sources. md-autocomplete caches results when performing a query. After first call, it uses the cached results to eliminate unnecessary server requests or lookup logic and it can be disabled.
The following table lists out the parameters and description of the different attributes of md-autocomplete.
* md-items
An expression in the format of item in items to iterate over matches for your search.
md-selected-item-change
An expression to be run each time a new item is selected.
md-search-text-change
An expression to be run each time the search text updates.
md-search-text
A model to bind the search query text to.
md-selected-item
A model to bind the selected item to.
md-item-text
An expression that will convert your object to a single string.
placeholder
Placeholder text that will be forwarded to the input.
md-no-cache
Disables the internal caching that happens in autocomplete.
ng-disabled
Determines whether or not to disable the input field.
md-min-length
Specifies the minimum length of text before autocomplete will make suggestions.
md-delay
Specifies the amount of time (in milliseconds) to wait before looking for results.
md-autofocus
If true, will immediately focus the input element.
md-autoselect
If true, the first item will be selected by default.
md-menu-class
This will be applied to the dropdown menu for styling.
md-floating-label
This will add a floating label to autocomplete and wrap it in the md-input-container.
md-input-name
The name attribute given to the input element to be used with the FormController.
md-input-id
An ID to be added to the input element.
md-input-minlength
The minimum length for the input's value for validation.
md-input-maxlength
The maximum length for the input's value for validation.
md-select-on-match
When set as true, autocomplete will automatically select the exact item if the search text is an exact match.
The following example shows the use of the md-autocomplete directive and also the use of autocomplete.
am_autocomplete.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('autoCompleteController', autoCompleteController);
function autoCompleteController ($timeout, $q, $log) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
// list of states to be displayed
self.states = loadStates();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
alert("This functionality is yet to be implemented!");
}
function querySearch (query) {
var results = query ? self.states.filter( createFilterFor(query) ) :
self.states, deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () {
deferred.resolve( results );
},
Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
//build list of states as map of key-value pairs
function loadStates() {
var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
Wisconsin, Wyoming';
return allStates.split(/, +/g).map( function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
//filter function for search query
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
}
</script>
</head>
<body ng-app = "firstApplication" ng-cloak>
<div ng-controller = "autoCompleteController as ctrl" layout = "column" ng-cloak>
<md-content class = "md-padding">
<form ng-submit = "$event.preventDefault()">
<p><code>md-autocomplete</code> can be used to provide search results from
local or remote data sources.</p>
<md-autocomplete
ng-disabled = "ctrl.isDisabled"
md-no-cache = "ctrl.noCache"
md-selected-item = "ctrl.selectedItem"
md-search-text-change = "ctrl.searchTextChange(ctrl.searchText)"
md-search-text = "ctrl.searchText"
md-selected-item-change = "ctrl.selectedItemChange(item)"
md-items = "item in ctrl.querySearch(ctrl.searchText)"
md-item-text = "item.display"
md-min-length = "0"
placeholder = "US State?">
<md-item-template>
<span md-highlight-text = "ctrl.searchText"
md-highlight-flags = "^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click = "ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
<br/>
<md-checkbox ng-model = "ctrl.simulateQuery">Show progress for results?
</md-checkbox>
<md-checkbox ng-model = "ctrl.noCache">Disable caching?</md-checkbox>
<md-checkbox ng-model = "ctrl.isDisabled">Disable?</md-checkbox>
<p><code>md-autocomplete</code> caches results when performing a query.
After first call, it uses the cached results to eliminate unnecessary
server requests or lookup logic and it can be disabled.</p>
</form>
</md-content>
</div>
</body>
</html>
Verify the result.
md-autocomplete can be used to provide search results from local or remote data sources.
md-autocomplete caches results when performing a query. After first call, it uses the cached results to eliminate unnecessary server requests or lookup logic and it can be disabled.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2707,
"s": 2190,
"text": "The md-autocomplete, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area. <md-autocomplete> can be used to provide search results from local or remote data sources. md-autocomplete caches results when performing a query. After first call, it uses the cached results to eliminate unnecessary server requests or lookup logic and it can be disabled."
},
{
"code": null,
"e": 2816,
"s": 2707,
"text": "The following table lists out the parameters and description of the different attributes of md-autocomplete."
},
{
"code": null,
"e": 2827,
"s": 2816,
"text": "* md-items"
},
{
"code": null,
"e": 2913,
"s": 2827,
"text": "An expression in the format of item in items to iterate over matches for your search."
},
{
"code": null,
"e": 2937,
"s": 2913,
"text": "md-selected-item-change"
},
{
"code": null,
"e": 2995,
"s": 2937,
"text": "An expression to be run each time a new item is selected."
},
{
"code": null,
"e": 3017,
"s": 2995,
"text": "md-search-text-change"
},
{
"code": null,
"e": 3076,
"s": 3017,
"text": "An expression to be run each time the search text updates."
},
{
"code": null,
"e": 3091,
"s": 3076,
"text": "md-search-text"
},
{
"code": null,
"e": 3133,
"s": 3091,
"text": "A model to bind the search query text to."
},
{
"code": null,
"e": 3150,
"s": 3133,
"text": "md-selected-item"
},
{
"code": null,
"e": 3188,
"s": 3150,
"text": "A model to bind the selected item to."
},
{
"code": null,
"e": 3201,
"s": 3188,
"text": "md-item-text"
},
{
"code": null,
"e": 3265,
"s": 3201,
"text": "An expression that will convert your object to a single string."
},
{
"code": null,
"e": 3277,
"s": 3265,
"text": "placeholder"
},
{
"code": null,
"e": 3331,
"s": 3277,
"text": "Placeholder text that will be forwarded to the input."
},
{
"code": null,
"e": 3343,
"s": 3331,
"text": "md-no-cache"
},
{
"code": null,
"e": 3403,
"s": 3343,
"text": "Disables the internal caching that happens in autocomplete."
},
{
"code": null,
"e": 3415,
"s": 3403,
"text": "ng-disabled"
},
{
"code": null,
"e": 3469,
"s": 3415,
"text": "Determines whether or not to disable the input field."
},
{
"code": null,
"e": 3483,
"s": 3469,
"text": "md-min-length"
},
{
"code": null,
"e": 3563,
"s": 3483,
"text": "Specifies the minimum length of text before autocomplete will make suggestions."
},
{
"code": null,
"e": 3572,
"s": 3563,
"text": "md-delay"
},
{
"code": null,
"e": 3655,
"s": 3572,
"text": "Specifies the amount of time (in milliseconds) to wait before looking for results."
},
{
"code": null,
"e": 3668,
"s": 3655,
"text": "md-autofocus"
},
{
"code": null,
"e": 3719,
"s": 3668,
"text": "If true, will immediately focus the input element."
},
{
"code": null,
"e": 3733,
"s": 3719,
"text": "md-autoselect"
},
{
"code": null,
"e": 3786,
"s": 3733,
"text": "If true, the first item will be selected by default."
},
{
"code": null,
"e": 3800,
"s": 3786,
"text": "md-menu-class"
},
{
"code": null,
"e": 3855,
"s": 3800,
"text": "This will be applied to the dropdown menu for styling."
},
{
"code": null,
"e": 3873,
"s": 3855,
"text": "md-floating-label"
},
{
"code": null,
"e": 3959,
"s": 3873,
"text": "This will add a floating label to autocomplete and wrap it in the md-input-container."
},
{
"code": null,
"e": 3973,
"s": 3959,
"text": "md-input-name"
},
{
"code": null,
"e": 4055,
"s": 3973,
"text": "The name attribute given to the input element to be used with the FormController."
},
{
"code": null,
"e": 4067,
"s": 4055,
"text": "md-input-id"
},
{
"code": null,
"e": 4107,
"s": 4067,
"text": "An ID to be added to the input element."
},
{
"code": null,
"e": 4126,
"s": 4107,
"text": "md-input-minlength"
},
{
"code": null,
"e": 4183,
"s": 4126,
"text": "The minimum length for the input's value for validation."
},
{
"code": null,
"e": 4202,
"s": 4183,
"text": "md-input-maxlength"
},
{
"code": null,
"e": 4259,
"s": 4202,
"text": "The maximum length for the input's value for validation."
},
{
"code": null,
"e": 4278,
"s": 4259,
"text": "md-select-on-match"
},
{
"code": null,
"e": 4388,
"s": 4278,
"text": "When set as true, autocomplete will automatically select the exact item if the search text is an exact match."
},
{
"code": null,
"e": 4491,
"s": 4388,
"text": "The following example shows the use of the md-autocomplete directive and also the use of autocomplete."
},
{
"code": null,
"e": 4511,
"s": 4491,
"text": "am_autocomplete.htm"
},
{
"code": null,
"e": 10422,
"s": 4511,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n \n\t\t<script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('autoCompleteController', autoCompleteController);\n\n function autoCompleteController ($timeout, $q, $log) {\n var self = this;\n self.simulateQuery = false;\n self.isDisabled = false;\n \n // list of states to be displayed\n self.states = loadStates();\n self.querySearch = querySearch;\n self.selectedItemChange = selectedItemChange;\n self.searchTextChange = searchTextChange;\n self.newState = newState;\n \n function newState(state) {\n alert(\"This functionality is yet to be implemented!\");\n }\n \n function querySearch (query) {\n var results = query ? self.states.filter( createFilterFor(query) ) :\n self.states, deferred;\n \n if (self.simulateQuery) {\n deferred = $q.defer();\n \n $timeout(function () { \n deferred.resolve( results ); \n }, \n Math.random() * 1000, false);\n return deferred.promise;\n } else {\n return results;\n }\n }\n function searchTextChange(text) {\n $log.info('Text changed to ' + text);\n }\n function selectedItemChange(item) {\n $log.info('Item changed to ' + JSON.stringify(item));\n }\n \n //build list of states as map of key-value pairs\n function loadStates() {\n var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\\\n Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\\\n Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\\\n Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\\\n North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\\\n South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\\\n Wisconsin, Wyoming';\n \n return allStates.split(/, +/g).map( function (state) {\n return {\n value: state.toLowerCase(),\n display: state\n };\n });\n }\n \n //filter function for search query\n function createFilterFor(query) {\n var lowercaseQuery = angular.lowercase(query);\n return function filterFn(state) {\n return (state.value.indexOf(lowercaseQuery) === 0);\n };\n }\n } \n </script> \n </head>\n \n <body ng-app = \"firstApplication\" ng-cloak>\n <div ng-controller = \"autoCompleteController as ctrl\" layout = \"column\" ng-cloak>\n <md-content class = \"md-padding\">\n <form ng-submit = \"$event.preventDefault()\">\n <p><code>md-autocomplete</code> can be used to provide search results from\n local or remote data sources.</p>\n \n <md-autocomplete\n ng-disabled = \"ctrl.isDisabled\"\n md-no-cache = \"ctrl.noCache\"\n md-selected-item = \"ctrl.selectedItem\"\n md-search-text-change = \"ctrl.searchTextChange(ctrl.searchText)\"\n md-search-text = \"ctrl.searchText\"\n md-selected-item-change = \"ctrl.selectedItemChange(item)\"\n md-items = \"item in ctrl.querySearch(ctrl.searchText)\"\n md-item-text = \"item.display\"\n md-min-length = \"0\"\n placeholder = \"US State?\">\n \n <md-item-template>\n <span md-highlight-text = \"ctrl.searchText\"\n md-highlight-flags = \"^i\">{{item.display}}</span>\n </md-item-template>\n \n <md-not-found>\n No states matching \"{{ctrl.searchText}}\" were found.\n <a ng-click = \"ctrl.newState(ctrl.searchText)\">Create a new one!</a>\n </md-not-found>\n </md-autocomplete>\n <br/>\n \n <md-checkbox ng-model = \"ctrl.simulateQuery\">Show progress for results?\n </md-checkbox>\n <md-checkbox ng-model = \"ctrl.noCache\">Disable caching?</md-checkbox>\n <md-checkbox ng-model = \"ctrl.isDisabled\">Disable?</md-checkbox>\n <p><code>md-autocomplete</code> caches results when performing a query.\n After first call, it uses the cached results to eliminate unnecessary\n server requests or lookup logic and it can be disabled.</p>\n </form>\n </md-content>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 10441,
"s": 10422,
"text": "Verify the result."
},
{
"code": null,
"e": 10530,
"s": 10441,
"text": "md-autocomplete can be used to provide search results from local or remote data sources."
},
{
"code": null,
"e": 10713,
"s": 10530,
"text": "md-autocomplete caches results when performing a query. After first call, it uses the cached results to eliminate unnecessary server requests or lookup logic and it can be disabled."
},
{
"code": null,
"e": 10748,
"s": 10713,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10762,
"s": 10748,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10797,
"s": 10762,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10811,
"s": 10797,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10846,
"s": 10811,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10866,
"s": 10846,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 10901,
"s": 10866,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10918,
"s": 10901,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10951,
"s": 10918,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10963,
"s": 10951,
"text": " Senol Atac"
},
{
"code": null,
"e": 10998,
"s": 10963,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11010,
"s": 10998,
"text": " Senol Atac"
},
{
"code": null,
"e": 11017,
"s": 11010,
"text": " Print"
},
{
"code": null,
"e": 11028,
"s": 11017,
"text": " Add Notes"
}
] |
Convert object to an array in PHP.
|
In a PHP application, we are working with data in various formats such as string, array, objects or more...In a real-time application, we may need to read a php object result in the form of an associative array to get the desired output.
So we will discuss here how to transform a php object to an associative array in PHP.
Let's explain what is an object and associative array in PHP? An object is an instance of a class meaning that from one class you can create many objects. It is simply a specimen of a class and has memory allocated. While on the other hand an array which consists of string as an index is called associative array. It contains a key-value pair in it, in which values are associated with their respective keys.
Let's now discuss various methods of converting the object to an array.
Initially json_encode() function returns a JSON encoded string for a given value.The json_decode() function changes over it into a PHP array.
<?php
class student {
public function __construct($firstname, $lastname) {
$this->firstname = $firstname;
$this->lastname = $lastname;
}
}
$myObj = new student("Alex", "Stokes");
echo "Before conversion:".'</br>';
var_dump($myObj);
$myArray = json_decode(json_encode($myObj), true);
echo "After conversion:".'</br>';
var_dump($myArray);
?>
Before conversion:
object(student)#1 (2) { ["firstname"]=> string(4) "Alex" ["lastname"]=> string(6) "Stokes" }
After conversion:
array(2) { ["firstname"]=> string(4) "Alex" ["lastname"]=> string(6) "Stokes" }
Here we have created a class student and inside that class, we have declared a __construct() function, which is executed when the object is created. The constructor receives arguments that are later provided when creating the object with the help of new keyword. In the first var_dump() expression we are printing the object, but in the second case, we are converting the object into an array with help of json_decode and json_encode technique.
Typecasting is the approach to utilize one data type variable into the different data type and it is simply the exact transformation of a datatype.
<?php
class bag {
public function __construct( $item1, $item2, $item3){
$this->item1 = $item1;
$this->item2 =$item2;
$this->item3 = $item3;
}
}
$myBag = new bag("Books", "Ball", "Pens");
echo "Before conversion :".'</br>';
var_dump($myBag);
$myBagArray = (array)$myBag;
echo "After conversion :".'</br>';
var_dump($myBagArray);
?>
Before conversion :
object(bag)#1 (3) { ["item1"]=> string(5) "Books" ["item2"]=> string(4) "Ball" ["item3"]=> string(4) "Pens" }
After conversion:
array(3) { ["item1"]=> string(5) "Books" ["item2"]=> string(4) "Ball" ["item3"]=> string(4) "Pens" }
Here we have created a class "bag" and inside that class, we have declared a __construct() function, which is executed when the object is created. The constructor receives arguments that are later provided when creating the object with the help of the new keyword. In the first var_dump() expression, we are simply printing the object, but in the second case, we are type-hinting the object into an array with help of type-hinting procedure.
|
[
{
"code": null,
"e": 1300,
"s": 1062,
"text": "In a PHP application, we are working with data in various formats such as string, array, objects or more...In a real-time application, we may need to read a php object result in the form of an associative array to get the desired output."
},
{
"code": null,
"e": 1386,
"s": 1300,
"text": "So we will discuss here how to transform a php object to an associative array in PHP."
},
{
"code": null,
"e": 1796,
"s": 1386,
"text": "Let's explain what is an object and associative array in PHP? An object is an instance of a class meaning that from one class you can create many objects. It is simply a specimen of a class and has memory allocated. While on the other hand an array which consists of string as an index is called associative array. It contains a key-value pair in it, in which values are associated with their respective keys."
},
{
"code": null,
"e": 1868,
"s": 1796,
"text": "Let's now discuss various methods of converting the object to an array."
},
{
"code": null,
"e": 2010,
"s": 1868,
"text": "Initially json_encode() function returns a JSON encoded string for a given value.The json_decode() function changes over it into a PHP array."
},
{
"code": null,
"e": 2404,
"s": 2010,
"text": "<?php\n class student {\n public function __construct($firstname, $lastname) {\n $this->firstname = $firstname;\n $this->lastname = $lastname;\n }\n }\n $myObj = new student(\"Alex\", \"Stokes\");\n echo \"Before conversion:\".'</br>';\n var_dump($myObj);\n $myArray = json_decode(json_encode($myObj), true);\n echo \"After conversion:\".'</br>';\n var_dump($myArray);\n?>"
},
{
"code": null,
"e": 2614,
"s": 2404,
"text": "Before conversion:\nobject(student)#1 (2) { [\"firstname\"]=> string(4) \"Alex\" [\"lastname\"]=> string(6) \"Stokes\" }\nAfter conversion:\narray(2) { [\"firstname\"]=> string(4) \"Alex\" [\"lastname\"]=> string(6) \"Stokes\" }"
},
{
"code": null,
"e": 3059,
"s": 2614,
"text": "Here we have created a class student and inside that class, we have declared a __construct() function, which is executed when the object is created. The constructor receives arguments that are later provided when creating the object with the help of new keyword. In the first var_dump() expression we are printing the object, but in the second case, we are converting the object into an array with help of json_decode and json_encode technique."
},
{
"code": null,
"e": 3207,
"s": 3059,
"text": "Typecasting is the approach to utilize one data type variable into the different data type and it is simply the exact transformation of a datatype."
},
{
"code": null,
"e": 3601,
"s": 3207,
"text": "<?php\n class bag {\n public function __construct( $item1, $item2, $item3){\n $this->item1 = $item1;\n $this->item2 =$item2;\n $this->item3 = $item3;\n }\n }\n $myBag = new bag(\"Books\", \"Ball\", \"Pens\");\n echo \"Before conversion :\".'</br>';\n var_dump($myBag);\n $myBagArray = (array)$myBag;\n echo \"After conversion :\".'</br>';\n var_dump($myBagArray);\n?>"
},
{
"code": null,
"e": 3850,
"s": 3601,
"text": "Before conversion :\nobject(bag)#1 (3) { [\"item1\"]=> string(5) \"Books\" [\"item2\"]=> string(4) \"Ball\" [\"item3\"]=> string(4) \"Pens\" }\nAfter conversion:\narray(3) { [\"item1\"]=> string(5) \"Books\" [\"item2\"]=> string(4) \"Ball\" [\"item3\"]=> string(4) \"Pens\" }"
},
{
"code": null,
"e": 4292,
"s": 3850,
"text": "Here we have created a class \"bag\" and inside that class, we have declared a __construct() function, which is executed when the object is created. The constructor receives arguments that are later provided when creating the object with the help of the new keyword. In the first var_dump() expression, we are simply printing the object, but in the second case, we are type-hinting the object into an array with help of type-hinting procedure."
}
] |
Machine Learning: Handling the missing values in Data: The Easy Way | by Akash Panchal | Towards Data Science
|
Most of the Machine Learning Algorithms cannot work with missing values in the features. See the below example of the Melbourne Housing Data.
Here, BuildingArea has 7130 rows with values while most of the features have 13580 rows with values.
Now, A few things you can do to deal with missing values
melbourne_data.dropna(subset=["BuildingArea"])
This will drop all the rows with the missing values. You can see that the number of rows has decreased now.
melbourne_data.drop("BuildingArea", axis=1)
This will drop the entire feature/attribute. See below, BuildingArea column is dropped now.
Approach A
If you think that the attribute is important enough and you must include for the training. You can fill the missing values.
Fill the missing values with what???
Well, you can replace the missing values with median, mean or zeros.
median = melbourne_data["BuildingArea"].median()melbourne_data["BuildingArea"].fillna(median, inplace=True)
This will replace all the missing values with the calculated median. Also, one thing you will notice now that the mean value of the attribute is changed as we’ve filled the missing values.
You may want to follow a similar process for “YearBuilt” attribute as well. And you will have to save the value of the median, as it will be needed later to fill the missing values in the Test-Set and the new data(Oh yes, didn’t think that).
Approach B: Introducing Imputer
SciKit-Learn provides Imputer class to use the above task with ease. You can use it following way:
First, you need to decide the strategy, it can be one of these: mean, median, most_frequent
Second, create the imputer instance using the decided strategy
# 1. Remove categorial melbourne_data = melbourne_data.select_dtypes(exclude= ["object"]).copy()# 2. Fit the numerical data to Imputerfrom sklearn.impute import SimpleImputerimputer = SimpleImputer(strategy="median")imputer.fit(melbourne_data)# 3.X = imputer.transform(melbourne_data)melbourne_data_tr = pd.DataFrame(X, columns=melbourne_data.columns, index=melbourne_data.index)
Now, this will calculate the median of all the attributes and fill the missing values of an attribute with the respective mean values.
Note: Not focusing on the Categorial values as they are not in the scope of this tutorial.
Python code: Full python code with all the three ways explained.
Streamlit code: Oh..you love streamlit too. Find the streamlit code here.
Data: Used Melbourne housing data.
|
[
{
"code": null,
"e": 314,
"s": 172,
"text": "Most of the Machine Learning Algorithms cannot work with missing values in the features. See the below example of the Melbourne Housing Data."
},
{
"code": null,
"e": 415,
"s": 314,
"text": "Here, BuildingArea has 7130 rows with values while most of the features have 13580 rows with values."
},
{
"code": null,
"e": 472,
"s": 415,
"text": "Now, A few things you can do to deal with missing values"
},
{
"code": null,
"e": 519,
"s": 472,
"text": "melbourne_data.dropna(subset=[\"BuildingArea\"])"
},
{
"code": null,
"e": 627,
"s": 519,
"text": "This will drop all the rows with the missing values. You can see that the number of rows has decreased now."
},
{
"code": null,
"e": 671,
"s": 627,
"text": "melbourne_data.drop(\"BuildingArea\", axis=1)"
},
{
"code": null,
"e": 763,
"s": 671,
"text": "This will drop the entire feature/attribute. See below, BuildingArea column is dropped now."
},
{
"code": null,
"e": 774,
"s": 763,
"text": "Approach A"
},
{
"code": null,
"e": 898,
"s": 774,
"text": "If you think that the attribute is important enough and you must include for the training. You can fill the missing values."
},
{
"code": null,
"e": 935,
"s": 898,
"text": "Fill the missing values with what???"
},
{
"code": null,
"e": 1004,
"s": 935,
"text": "Well, you can replace the missing values with median, mean or zeros."
},
{
"code": null,
"e": 1112,
"s": 1004,
"text": "median = melbourne_data[\"BuildingArea\"].median()melbourne_data[\"BuildingArea\"].fillna(median, inplace=True)"
},
{
"code": null,
"e": 1301,
"s": 1112,
"text": "This will replace all the missing values with the calculated median. Also, one thing you will notice now that the mean value of the attribute is changed as we’ve filled the missing values."
},
{
"code": null,
"e": 1543,
"s": 1301,
"text": "You may want to follow a similar process for “YearBuilt” attribute as well. And you will have to save the value of the median, as it will be needed later to fill the missing values in the Test-Set and the new data(Oh yes, didn’t think that)."
},
{
"code": null,
"e": 1575,
"s": 1543,
"text": "Approach B: Introducing Imputer"
},
{
"code": null,
"e": 1674,
"s": 1575,
"text": "SciKit-Learn provides Imputer class to use the above task with ease. You can use it following way:"
},
{
"code": null,
"e": 1766,
"s": 1674,
"text": "First, you need to decide the strategy, it can be one of these: mean, median, most_frequent"
},
{
"code": null,
"e": 1829,
"s": 1766,
"text": "Second, create the imputer instance using the decided strategy"
},
{
"code": null,
"e": 2248,
"s": 1829,
"text": "# 1. Remove categorial melbourne_data = melbourne_data.select_dtypes(exclude= [\"object\"]).copy()# 2. Fit the numerical data to Imputerfrom sklearn.impute import SimpleImputerimputer = SimpleImputer(strategy=\"median\")imputer.fit(melbourne_data)# 3.X = imputer.transform(melbourne_data)melbourne_data_tr = pd.DataFrame(X, columns=melbourne_data.columns, index=melbourne_data.index)"
},
{
"code": null,
"e": 2383,
"s": 2248,
"text": "Now, this will calculate the median of all the attributes and fill the missing values of an attribute with the respective mean values."
},
{
"code": null,
"e": 2474,
"s": 2383,
"text": "Note: Not focusing on the Categorial values as they are not in the scope of this tutorial."
},
{
"code": null,
"e": 2539,
"s": 2474,
"text": "Python code: Full python code with all the three ways explained."
},
{
"code": null,
"e": 2613,
"s": 2539,
"text": "Streamlit code: Oh..you love streamlit too. Find the streamlit code here."
}
] |
How to create a responsive navigation menu with a login form inside it?
|
Following is the code to create a responsive navigation menu with a login form inside of it −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
margin: 0px;
margin-top: 10px;
padding: 0px;
}
nav {
width: 100%;
background-color: rgb(39, 39, 39);
overflow: auto;
height: auto;
}
.links {
display: inline-block;
text-align: center;
padding: 14px;
color: rgb(178, 137, 253);
text-decoration: none;
font-size: 17px;
}
.links:hover {
background-color: rgb(100, 100, 100);
}
form {
float: right;
margin-top: 8px;
}
form input{
display: inline-block;
padding: 6px;
font-size: 17px;
margin-right: 8px;
border:none;
}
.selected {
background-color: rgb(0, 18, 43);
}
@media screen and (max-width: 977px) {
.links {
display: block;
}
form {
display: block;
color:white;
}
form input{
margin-right: 0px;
display: block;
width: 100vw;
margin: 0px;
border-bottom: 2px solid rgb(178, 137, 253);
text-align: center;
}
}
</style>
</head>
<body>
<nav>
<a class="links selected" href="#">
Home
</a>
<a class="links" href="#">
Login
</a>
<a class="links" href="#">
Register
</a>
<a class="links" href="#">
Contact Us
</a>
<a class="links" href="#">
More Info
</a>
<form>
<input type="text" placeholder="UserName..." />
<input type="password" placeholder="Password...">
</form>
</nav>
</body>
</html>
This will produce the following output −
On resizing the screen, the content inside nav will reflow as follows −
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Following is the code to create a responsive navigation menu with a login form inside of it −"
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": " Live Demo"
},
{
"code": null,
"e": 2703,
"s": 1167,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\nbody {\n margin: 0px;\n margin-top: 10px;\n padding: 0px;\n}\nnav {\n width: 100%;\n background-color: rgb(39, 39, 39);\n overflow: auto;\n height: auto;\n}\n.links {\n display: inline-block;\n text-align: center;\n padding: 14px;\n color: rgb(178, 137, 253);\n text-decoration: none;\n font-size: 17px;\n}\n.links:hover {\n background-color: rgb(100, 100, 100);\n}\nform {\n float: right;\n margin-top: 8px;\n}\nform input{\n display: inline-block;\n padding: 6px;\n font-size: 17px;\n margin-right: 8px;\n border:none;\n}\n.selected {\n background-color: rgb(0, 18, 43);\n}\n@media screen and (max-width: 977px) {\n.links {\n display: block;\n}\nform {\n display: block;\n color:white;\n}\nform input{\n margin-right: 0px;\n display: block;\n width: 100vw;\n margin: 0px;\n border-bottom: 2px solid rgb(178, 137, 253);\n text-align: center;\n}\n}\n</style>\n</head>\n<body>\n <nav>\n <a class=\"links selected\" href=\"#\">\n Home\n </a>\n <a class=\"links\" href=\"#\">\n Login\n </a>\n <a class=\"links\" href=\"#\">\n Register\n </a>\n <a class=\"links\" href=\"#\">\n Contact Us\n </a>\n <a class=\"links\" href=\"#\">\n More Info\n </a>\n <form>\n <input type=\"text\" placeholder=\"UserName...\" />\n <input type=\"password\" placeholder=\"Password...\">\n </form>\n </nav>\n</body>\n</html>"
},
{
"code": null,
"e": 2744,
"s": 2703,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2816,
"s": 2744,
"text": "On resizing the screen, the content inside nav will reflow as follows −"
}
] |
How can Keras be used for feature extraction using a sequential model using Python?
|
Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes. It has optimization techniques that help in performing complicated mathematical operations quickly.
The ‘TensorFlow’ package can be installed on Windows using the below line of code −
pip install tensorflow
Tensor is a data structure used in TensorFlow. It helps connect edges in a flow diagram. This flow diagram is known as the ‘Data flow graph’. Tensors are nothing but a multidimensional array or a list. They can be identified using three main attributes −
Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined.
Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined.
Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n-dimensional tensor.
Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n-dimensional tensor.
Shape − It is the number of rows and columns together.
Shape − It is the number of rows and columns together.
Keras was developed as a part of research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions.
It is highly scalable, and comes with cross platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well.
Keras is already present within the Tensorflow package. It can be accessed using the below line of code.
import tensorflow
from tensorflow import keras
We are using Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −
print("Sequential model created")
initial_model = keras.Sequential(
[
keras.Input(shape=(250, 250, 3)),
layers.Conv2D(32, 5, strides=2, activation="relu"),
layers.Conv2D(32, 3, activation="relu"),
layers.Conv2D(32, 3, activation="relu"),
]
)
print("Feature extraction from the model")
feature_extractor = keras.Model(
inputs=initial_model.inputs,
outputs=[layer.output for layer in initial_model.layers],
)
print("The feature extractor method is called on test data")
x = tf.ones((1, 250, 250, 3))
features = feature_extractor(x)
Code credit − https://www.tensorflow.org/guide/keras/sequential_model
Sequential modal created
Feature extraction form the model
The feature extractor method is called on test data
Once the architecture of the model is ready, it is trained.
Once the architecture of the model is ready, it is trained.
Once the training is completed, it is evaluated.
Once the training is completed, it is evaluated.
This model is saved to disk.
This model is saved to disk.
This can be restored when required.
This can be restored when required.
Multiple GPU’s can be used to speed up the training of the model.
Multiple GPU’s can be used to speed up the training of the model.
Once a model has been built, it behaves like a functional API model.
Once a model has been built, it behaves like a functional API model.
This indicates that every layer has an input and output.
This indicates that every layer has an input and output.
|
[
{
"code": null,
"e": 1415,
"s": 1062,
"text": "Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes. It has optimization techniques that help in performing complicated mathematical operations quickly."
},
{
"code": null,
"e": 1499,
"s": 1415,
"text": "The ‘TensorFlow’ package can be installed on Windows using the below line of code −"
},
{
"code": null,
"e": 1522,
"s": 1499,
"text": "pip install tensorflow"
},
{
"code": null,
"e": 1777,
"s": 1522,
"text": "Tensor is a data structure used in TensorFlow. It helps connect edges in a flow diagram. This flow diagram is known as the ‘Data flow graph’. Tensors are nothing but a multidimensional array or a list. They can be identified using three main attributes −"
},
{
"code": null,
"e": 1946,
"s": 1777,
"text": "Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined."
},
{
"code": null,
"e": 2115,
"s": 1946,
"text": "Rank − It tells about the dimensionality of the tensor. It can be understood as the order of the tensor or the number of dimensions in the tensor that has been defined."
},
{
"code": null,
"e": 2265,
"s": 2115,
"text": "Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n-dimensional tensor."
},
{
"code": null,
"e": 2415,
"s": 2265,
"text": "Type − It tells about the data type associated with the elements of the Tensor. It can be a one dimensional, two dimensional or n-dimensional tensor."
},
{
"code": null,
"e": 2470,
"s": 2415,
"text": "Shape − It is the number of rows and columns together."
},
{
"code": null,
"e": 2525,
"s": 2470,
"text": "Shape − It is the number of rows and columns together."
},
{
"code": null,
"e": 3039,
"s": 2525,
"text": "Keras was developed as a part of research for the project ONEIROS (Open ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems. It runs on top of Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions."
},
{
"code": null,
"e": 3244,
"s": 3039,
"text": "It is highly scalable, and comes with cross platform abilities. This means Keras can be run on TPU or clusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well."
},
{
"code": null,
"e": 3349,
"s": 3244,
"text": "Keras is already present within the Tensorflow package. It can be accessed using the below line of code."
},
{
"code": null,
"e": 3396,
"s": 3349,
"text": "import tensorflow\nfrom tensorflow import keras"
},
{
"code": null,
"e": 3694,
"s": 3396,
"text": "We are using Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −"
},
{
"code": null,
"e": 4260,
"s": 3694,
"text": "print(\"Sequential model created\")\ninitial_model = keras.Sequential(\n [\n keras.Input(shape=(250, 250, 3)),\n layers.Conv2D(32, 5, strides=2, activation=\"relu\"),\n layers.Conv2D(32, 3, activation=\"relu\"),\n layers.Conv2D(32, 3, activation=\"relu\"),\n ]\n)\nprint(\"Feature extraction from the model\")\nfeature_extractor = keras.Model(\n inputs=initial_model.inputs,\n outputs=[layer.output for layer in initial_model.layers],\n)\nprint(\"The feature extractor method is called on test data\")\nx = tf.ones((1, 250, 250, 3))\nfeatures = feature_extractor(x)"
},
{
"code": null,
"e": 4330,
"s": 4260,
"text": "Code credit − https://www.tensorflow.org/guide/keras/sequential_model"
},
{
"code": null,
"e": 4443,
"s": 4330,
"text": "Sequential modal created \nFeature extraction form the model \nThe feature extractor method is called on test data"
},
{
"code": null,
"e": 4503,
"s": 4443,
"text": "Once the architecture of the model is ready, it is trained."
},
{
"code": null,
"e": 4563,
"s": 4503,
"text": "Once the architecture of the model is ready, it is trained."
},
{
"code": null,
"e": 4612,
"s": 4563,
"text": "Once the training is completed, it is evaluated."
},
{
"code": null,
"e": 4661,
"s": 4612,
"text": "Once the training is completed, it is evaluated."
},
{
"code": null,
"e": 4690,
"s": 4661,
"text": "This model is saved to disk."
},
{
"code": null,
"e": 4719,
"s": 4690,
"text": "This model is saved to disk."
},
{
"code": null,
"e": 4755,
"s": 4719,
"text": "This can be restored when required."
},
{
"code": null,
"e": 4791,
"s": 4755,
"text": "This can be restored when required."
},
{
"code": null,
"e": 4857,
"s": 4791,
"text": "Multiple GPU’s can be used to speed up the training of the model."
},
{
"code": null,
"e": 4923,
"s": 4857,
"text": "Multiple GPU’s can be used to speed up the training of the model."
},
{
"code": null,
"e": 4992,
"s": 4923,
"text": "Once a model has been built, it behaves like a functional API model."
},
{
"code": null,
"e": 5061,
"s": 4992,
"text": "Once a model has been built, it behaves like a functional API model."
},
{
"code": null,
"e": 5118,
"s": 5061,
"text": "This indicates that every layer has an input and output."
},
{
"code": null,
"e": 5175,
"s": 5118,
"text": "This indicates that every layer has an input and output."
}
] |
A Brief Introduction to Proximal Policy Optimization - GeeksforGeeks
|
14 Feb, 2022
Proximal Policy Optimisation (PPO) is a recent advancement in the field of Reinforcement Learning, which provides an improvement on Trust Region Policy Optimization (TRPO). This algorithm was proposed in 2017, and showed remarkable performance when it was implemented by OpenAI. To understand and appreciate the algorithm, we first need to understand what a policy is.
Note: This post is ideally targeted towards people who have a fairly basic understanding of Reinforcement Learning.
A policy, in Reinforcement Learning terminology, is a mapping from action space to state space. It can be imagined to be instructions for the RL agent, in terms of what actions it should take based upon which state of the environment it is currently in. When we talk about evaluating an agent, we generally mean evaluating the policy function to find out how well the agent is performing, following the given policy. This is where Policy Gradient methods play a vital role. When an agent is “learning” and doesn’t really know which actions yield the best result in the corresponding states, it does so by calculating the policy gradients. It works like a neural network architecture, whereby the gradient of the output, i.e, the log of probabilities of actions in that particular state, is taken with respect to parameters of the environment and the change is reflected in the policy, based upon the gradients.
While this tried and tested method works well, the major disadvantages with these methods is their hypersensitivity to hyperparameter tuning such as choice of stepsize, learning rate, etc , along with their poor sample efficiency. Unlike supervised learning which has a guaranteed route to success or convergence with relatively less hyperparameter tuning, reinforcement learning is a lot more complex with various moving parts that need to be considered. PPO aims to strike a balance between important factors like ease of implementation, ease of tuning, sample complexity,sample efficiency and trying to compute an update at each step that minimizes the cost function while ensuring the deviation from the previous policy is relatively small. PPO is in fact, a policy gradient method that learns from online data as well. It merely ensures that the updated policy isn’t too much different from the old policy to ensure low variance in training. The most common implementation of PPO is via the Actor-Critic Model which uses 2 Deep Neural Networks, one taking the action(actor) and the other handles the rewards(critic). The mathematical equation of PPO is shown below:
The following important inferences can be drawn from the PPO equation:
It is a policy gradient optimization algorithm, that is, in each step there is an update to an existing policy to seek improvement on certain parameters
It ensures that the update is not too large, that is the old policy is not too different from the new policy (it does so by essentially “clipping” the update region to a very narrow range)
Advantage function is the difference between the future discounted sum of rewards on a certain state and action, and the value function of that policy.
Importance Sampling ratio, or the ratio of the probability under the new and old policies respectively, is used for update
ε is a hyperparameter denotes the limit of the range within which the update is allowed
This is how the working PPO algorithm looks, in it’s entirety when implemented in Actor-Critic style:
What we can observe, is that small batches of observation are used for updation, and then thrown away in order to incorporate new a new batch of observations,aka “minibatch”. The updated policy will be ε-clipped to a small region so as to not allow huge updates which might potentially be irrecoverably harmful. In short, PPO behaves exactly like other policy gradient methods in the sense that it also involves the calculation of output probabilities in the forward pass based on various parameters and calculating the gradients to improve those decisions or probabilities in the backward pass. It involves the usage of importance sampling ration like it’s predecessor, TRPO. However, it also ensures that the old policy and new policy are at least at a certain proximity (denoted by ε), and very large updates are not allowed. It has become one of the most widely used policy optimization algorithms in the field of reinforcement learning.
avtarkumar719
kk773572498
simranarora5sos
Artificial Intelligence
Deep-Learning
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
ML | Logistic Regression using Python
Intuition of Adam Optimizer
Principal Component Analysis with Python
Normalization vs Standardization
CNN | Introduction to Pooling Layer
Python | Decision Tree Regression using sklearn
Difference between Informed and Uninformed Search in AI
|
[
{
"code": null,
"e": 24344,
"s": 24316,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 24713,
"s": 24344,
"text": "Proximal Policy Optimisation (PPO) is a recent advancement in the field of Reinforcement Learning, which provides an improvement on Trust Region Policy Optimization (TRPO). This algorithm was proposed in 2017, and showed remarkable performance when it was implemented by OpenAI. To understand and appreciate the algorithm, we first need to understand what a policy is."
},
{
"code": null,
"e": 24829,
"s": 24713,
"text": "Note: This post is ideally targeted towards people who have a fairly basic understanding of Reinforcement Learning."
},
{
"code": null,
"e": 25740,
"s": 24829,
"text": "A policy, in Reinforcement Learning terminology, is a mapping from action space to state space. It can be imagined to be instructions for the RL agent, in terms of what actions it should take based upon which state of the environment it is currently in. When we talk about evaluating an agent, we generally mean evaluating the policy function to find out how well the agent is performing, following the given policy. This is where Policy Gradient methods play a vital role. When an agent is “learning” and doesn’t really know which actions yield the best result in the corresponding states, it does so by calculating the policy gradients. It works like a neural network architecture, whereby the gradient of the output, i.e, the log of probabilities of actions in that particular state, is taken with respect to parameters of the environment and the change is reflected in the policy, based upon the gradients."
},
{
"code": null,
"e": 26911,
"s": 25740,
"text": "While this tried and tested method works well, the major disadvantages with these methods is their hypersensitivity to hyperparameter tuning such as choice of stepsize, learning rate, etc , along with their poor sample efficiency. Unlike supervised learning which has a guaranteed route to success or convergence with relatively less hyperparameter tuning, reinforcement learning is a lot more complex with various moving parts that need to be considered. PPO aims to strike a balance between important factors like ease of implementation, ease of tuning, sample complexity,sample efficiency and trying to compute an update at each step that minimizes the cost function while ensuring the deviation from the previous policy is relatively small. PPO is in fact, a policy gradient method that learns from online data as well. It merely ensures that the updated policy isn’t too much different from the old policy to ensure low variance in training. The most common implementation of PPO is via the Actor-Critic Model which uses 2 Deep Neural Networks, one taking the action(actor) and the other handles the rewards(critic). The mathematical equation of PPO is shown below:"
},
{
"code": null,
"e": 26982,
"s": 26911,
"text": "The following important inferences can be drawn from the PPO equation:"
},
{
"code": null,
"e": 27135,
"s": 26982,
"text": "It is a policy gradient optimization algorithm, that is, in each step there is an update to an existing policy to seek improvement on certain parameters"
},
{
"code": null,
"e": 27324,
"s": 27135,
"text": "It ensures that the update is not too large, that is the old policy is not too different from the new policy (it does so by essentially “clipping” the update region to a very narrow range)"
},
{
"code": null,
"e": 27476,
"s": 27324,
"text": "Advantage function is the difference between the future discounted sum of rewards on a certain state and action, and the value function of that policy."
},
{
"code": null,
"e": 27599,
"s": 27476,
"text": "Importance Sampling ratio, or the ratio of the probability under the new and old policies respectively, is used for update"
},
{
"code": null,
"e": 27687,
"s": 27599,
"text": "ε is a hyperparameter denotes the limit of the range within which the update is allowed"
},
{
"code": null,
"e": 27789,
"s": 27687,
"text": "This is how the working PPO algorithm looks, in it’s entirety when implemented in Actor-Critic style:"
},
{
"code": null,
"e": 28731,
"s": 27789,
"text": "What we can observe, is that small batches of observation are used for updation, and then thrown away in order to incorporate new a new batch of observations,aka “minibatch”. The updated policy will be ε-clipped to a small region so as to not allow huge updates which might potentially be irrecoverably harmful. In short, PPO behaves exactly like other policy gradient methods in the sense that it also involves the calculation of output probabilities in the forward pass based on various parameters and calculating the gradients to improve those decisions or probabilities in the backward pass. It involves the usage of importance sampling ration like it’s predecessor, TRPO. However, it also ensures that the old policy and new policy are at least at a certain proximity (denoted by ε), and very large updates are not allowed. It has become one of the most widely used policy optimization algorithms in the field of reinforcement learning."
},
{
"code": null,
"e": 28745,
"s": 28731,
"text": "avtarkumar719"
},
{
"code": null,
"e": 28757,
"s": 28745,
"text": "kk773572498"
},
{
"code": null,
"e": 28773,
"s": 28757,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28797,
"s": 28773,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 28811,
"s": 28797,
"text": "Deep-Learning"
},
{
"code": null,
"e": 28828,
"s": 28811,
"text": "Machine Learning"
},
{
"code": null,
"e": 28845,
"s": 28828,
"text": "Machine Learning"
},
{
"code": null,
"e": 28943,
"s": 28845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28976,
"s": 28943,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29015,
"s": 28976,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 29050,
"s": 29015,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29088,
"s": 29050,
"text": "ML | Logistic Regression using Python"
},
{
"code": null,
"e": 29116,
"s": 29088,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 29157,
"s": 29116,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 29190,
"s": 29157,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 29226,
"s": 29190,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 29274,
"s": 29226,
"text": "Python | Decision Tree Regression using sklearn"
}
] |
SQL | INSERT IGNORE Statement - GeeksforGeeks
|
21 Mar, 2018
We know that a primary key of a table cannot be duplicated. For instance, the roll number of a student in the student table must always be distinct. Similarly, the EmployeeID is expected to be unique in an employee table. When we try to insert a tuple into a table where the primary key is repeated, it results in an error. However, with the INSERT IGNORE statement, we can prevent such errors from popping up, especially when inserting entries in bulk and such errors can interrupt the flow of insertion. Instead, only a warning is generated.
Cases where INSERT IGNORE avoids error
Upon insertion of a duplicate key where the column must contain a PRIMARY KEY or UNIQUE constraint
Upon insertion of NULL value where the column has a NOT NULL constraint.
Upon insertion of a row to a partitioned table where the inserted values go against the partition format.
Example:
Say we have a relation, Employee.
Employee Table:
As we can notice, the entries are not sorted on the basis of their primary key, i.e. EmployeeID.
Sample Query:
INSERT IGNORE INTO Employee (EmployeeID, Name, City)
VALUES (15002, 'Ram', 'Mumbai');
Output:No entry inserted.
Sample Query:
Inserting multiple records
When inserting multiple records at once, any that cannot be inserting will not be, but any that can will be:
INSERT IGNORE INTO Employee (EmployeeID, Name, City)
VALUES (15007, 'Shikha', 'Delhi'), (15002, 'Ram', 'Mumbai'), (15009, 'Sam', 'Ahmedabad');
Output:The first and the last entries get inserted; the middle entry is simple ignored. No error is flashed.
Disadvantage
Most users do not prefer INSERT IGNORE over INSERT since some errors may slip unnoticed. This may cause inconsistencies in the table, thereby causing some tuples to not get inserted without the user having a chance to correct them. Hence, INSERT IGNORE must be used in very specific conditions.
This article is contributed by Anannya Uberoi. 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.
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
SQL | GROUP BY
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
SQL - ORDER BY
|
[
{
"code": null,
"e": 24032,
"s": 24004,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 24576,
"s": 24032,
"text": "We know that a primary key of a table cannot be duplicated. For instance, the roll number of a student in the student table must always be distinct. Similarly, the EmployeeID is expected to be unique in an employee table. When we try to insert a tuple into a table where the primary key is repeated, it results in an error. However, with the INSERT IGNORE statement, we can prevent such errors from popping up, especially when inserting entries in bulk and such errors can interrupt the flow of insertion. Instead, only a warning is generated."
},
{
"code": null,
"e": 24615,
"s": 24576,
"text": "Cases where INSERT IGNORE avoids error"
},
{
"code": null,
"e": 24714,
"s": 24615,
"text": "Upon insertion of a duplicate key where the column must contain a PRIMARY KEY or UNIQUE constraint"
},
{
"code": null,
"e": 24787,
"s": 24714,
"text": "Upon insertion of NULL value where the column has a NOT NULL constraint."
},
{
"code": null,
"e": 24893,
"s": 24787,
"text": "Upon insertion of a row to a partitioned table where the inserted values go against the partition format."
},
{
"code": null,
"e": 24902,
"s": 24893,
"text": "Example:"
},
{
"code": null,
"e": 24936,
"s": 24902,
"text": "Say we have a relation, Employee."
},
{
"code": null,
"e": 24952,
"s": 24936,
"text": "Employee Table:"
},
{
"code": null,
"e": 25049,
"s": 24952,
"text": "As we can notice, the entries are not sorted on the basis of their primary key, i.e. EmployeeID."
},
{
"code": null,
"e": 25063,
"s": 25049,
"text": "Sample Query:"
},
{
"code": null,
"e": 25150,
"s": 25063,
"text": "INSERT IGNORE INTO Employee (EmployeeID, Name, City)\nVALUES (15002, 'Ram', 'Mumbai');\n"
},
{
"code": null,
"e": 25176,
"s": 25150,
"text": "Output:No entry inserted."
},
{
"code": null,
"e": 25190,
"s": 25176,
"text": "Sample Query:"
},
{
"code": null,
"e": 25217,
"s": 25190,
"text": "Inserting multiple records"
},
{
"code": null,
"e": 25326,
"s": 25217,
"text": "When inserting multiple records at once, any that cannot be inserting will not be, but any that can will be:"
},
{
"code": null,
"e": 25470,
"s": 25326,
"text": "INSERT IGNORE INTO Employee (EmployeeID, Name, City)\nVALUES (15007, 'Shikha', 'Delhi'), (15002, 'Ram', 'Mumbai'), (15009, 'Sam', 'Ahmedabad');\n"
},
{
"code": null,
"e": 25579,
"s": 25470,
"text": "Output:The first and the last entries get inserted; the middle entry is simple ignored. No error is flashed."
},
{
"code": null,
"e": 25592,
"s": 25579,
"text": "Disadvantage"
},
{
"code": null,
"e": 25887,
"s": 25592,
"text": "Most users do not prefer INSERT IGNORE over INSERT since some errors may slip unnoticed. This may cause inconsistencies in the table, thereby causing some tuples to not get inserted without the user having a chance to correct them. Hence, INSERT IGNORE must be used in very specific conditions."
},
{
"code": null,
"e": 26189,
"s": 25887,
"text": "This article is contributed by Anannya Uberoi. 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": 26314,
"s": 26189,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26336,
"s": 26314,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 26340,
"s": 26336,
"text": "SQL"
},
{
"code": null,
"e": 26344,
"s": 26340,
"text": "SQL"
},
{
"code": null,
"e": 26442,
"s": 26344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26473,
"s": 26442,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 26484,
"s": 26473,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26508,
"s": 26484,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26574,
"s": 26508,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26631,
"s": 26574,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 26646,
"s": 26631,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 26658,
"s": 26646,
"text": "SQL | Views"
},
{
"code": null,
"e": 26703,
"s": 26658,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26735,
"s": 26703,
"text": "MySQL | Group_CONCAT() Function"
}
] |
Create View - Function based Views Django - GeeksforGeeks
|
13 Jan, 2020
Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table. Django provides extra-ordinary support for Create Views but let’s check how it is done manually through a function-based view. This article revolves around Create View which involves concepts such as Django Forms, Django Models.For Create View, we need a project with some models and forms which will be used to create instances of that model.
Illustration of How to create and use create view 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 ?
After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,
# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder,
from django import formsfrom .models import GeeksModel # creating a formclass GeeksForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = GeeksModel # specify fields to be used fields = [ "title", "description", ]
Now we have everything ready for back end. Let’s create a view and template for the same. In geeks/views.py,
from django.shortcuts import render # relative import of formsfrom .models import GeeksModelfrom .forms import GeeksForm def create_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization form = GeeksForm(request.POST or None) if form.is_valid(): form.save() context['form']= form return render(request, "create_view.html", context)
Create a template in templates/create_view.html,
<form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type="submit" value="Submit"></form>
Let’s check what is there on http://localhost:8000/
Now let’s try to enter data in this form,
Bingo.! Create view is working and we can verify it using the instance created through the admin panel.This way one can create create view for a model in Django.
Django-views
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25691,
"s": 25663,
"text": "\n13 Jan, 2020"
},
{
"code": null,
"e": 26203,
"s": 25691,
"text": "Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table. Django provides extra-ordinary support for Create Views but let’s check how it is done manually through a function-based view. This article revolves around Create View which involves concepts such as Django Forms, Django Models.For Create View, we need a project with some models and forms which will be used to create instances of that model."
},
{
"code": null,
"e": 26337,
"s": 26203,
"text": "Illustration of How to create and use create view using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 26424,
"s": 26337,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 26475,
"s": 26424,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 26508,
"s": 26475,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 26643,
"s": 26508,
"text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,"
},
{
"code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title",
"e": 27034,
"s": 26643,
"text": null
},
{
"code": null,
"e": 27131,
"s": 27034,
"text": "After creating this model, we need to run two commands in order to create Database for the same."
},
{
"code": null,
"e": 27189,
"s": 27131,
"text": "Python manage.py makemigrations\nPython manage.py migrate\n"
},
{
"code": null,
"e": 27370,
"s": 27189,
"text": "Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder,"
},
{
"code": "from django import formsfrom .models import GeeksModel # creating a formclass GeeksForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = GeeksModel # specify fields to be used fields = [ \"title\", \"description\", ]",
"e": 27689,
"s": 27370,
"text": null
},
{
"code": null,
"e": 27798,
"s": 27689,
"text": "Now we have everything ready for back end. Let’s create a view and template for the same. In geeks/views.py,"
},
{
"code": "from django.shortcuts import render # relative import of formsfrom .models import GeeksModelfrom .forms import GeeksForm def create_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization form = GeeksForm(request.POST or None) if form.is_valid(): form.save() context['form']= form return render(request, \"create_view.html\", context)",
"e": 28250,
"s": 27798,
"text": null
},
{
"code": null,
"e": 28299,
"s": 28250,
"text": "Create a template in templates/create_view.html,"
},
{
"code": "<form method=\"POST\" enctype=\"multipart/form-data\"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type=\"submit\" value=\"Submit\"></form>",
"e": 28503,
"s": 28299,
"text": null
},
{
"code": null,
"e": 28555,
"s": 28503,
"text": "Let’s check what is there on http://localhost:8000/"
},
{
"code": null,
"e": 28597,
"s": 28555,
"text": "Now let’s try to enter data in this form,"
},
{
"code": null,
"e": 28759,
"s": 28597,
"text": "Bingo.! Create view is working and we can verify it using the instance created through the admin panel.This way one can create create view for a model in Django."
},
{
"code": null,
"e": 28772,
"s": 28759,
"text": "Django-views"
},
{
"code": null,
"e": 28786,
"s": 28772,
"text": "Python Django"
},
{
"code": null,
"e": 28793,
"s": 28786,
"text": "Python"
},
{
"code": null,
"e": 28891,
"s": 28793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28923,
"s": 28891,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28965,
"s": 28923,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29007,
"s": 28965,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29063,
"s": 29007,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29090,
"s": 29063,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29121,
"s": 29090,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29150,
"s": 29121,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29172,
"s": 29150,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29211,
"s": 29172,
"text": "Python | Get unique values from a list"
}
] |
whereis command in Linux with Examples - GeeksforGeeks
|
08 Apr, 2019
whereis command is used to find the location of source/binary file of a command and manuals sections for a specified file in Linux system. If we compare whereis command with find command they will appear similar to each other as both can be used for the same purposes but whereis command produces the result more accurately by consuming less time comparatively. whereis doesn’t require any root privilege to execute in any RHEL/CentOS 7.
The supplied names are first removed from leading pathname/directory components and any (single) trailing extension of the form .ext, for example, .c. Prefixes of s. resulting from use of source code control are also dealt with. whereis then attempts to locate the desired program in a list of standard Linux directories.
Points to be kept on mind while using whereis command:
Since whereis command uses chdir(change directory 2V) to give you the result in fastest possible way, the pathnames given with the -M, -S, or -B must be full and well defined i.e. they must begin with a `/‘ and should be a valid path that exist in the system’s directories, else it exits without any valid result.
whereis command has a hard-coded(code which is not dynamic and changes with specification) path, so you may not always find what you’re looking for.
Syntax:
whereis [options] filename...
Example 1: Let’s say, we want to find the location of apropos command then we need to execute the following command in the terminal:
Example 2: To find the location of lshw command.
Options:
-b : This option is used when we only want to search for binaries.Example: To locate binary of a Linux command let’s say gunzip.
Example: To locate binary of a Linux command let’s say gunzip.
-m : This option is used when we only want to search for manual sections.Example: To locate man page of false command.
Example: To locate man page of false command.
-s : This option is used when we only want to search for sources.
-u: This option search for unusual entries. A source file or a binary file is said to be unusual if it does not have any existence in system as per [-bmsu] described along with “–u”. Thus `whereis -m -u *‘ asks for those files in the current directory which have unsual entries.Example: To display the files in the current directory which have no documentation file.
Example: To display the files in the current directory which have no documentation file.
-B : This option is used to change or otherwise limit the places where whereis searches for binaries.Example: To locate binary of lesspipe in the path, /bin.
Example: To locate binary of lesspipe in the path, /bin.
-M : This option is used to change or otherwise limit the places where whereis searches for manual sections.Example: To check man page of intro that is only in a specific location i.e. /usr/share/man/man1.
Example: To check man page of intro that is only in a specific location i.e. /usr/share/man/man1.
-S : This option is used to change or otherwise limit the places where whereis searches for sources.Example: To Find all files in /usr/bin which are not documented in /usr/man/man1 with source in /usr/src.
Example: To Find all files in /usr/bin which are not documented in /usr/man/man1 with source in /usr/src.
-f : This option simply terminate the last directory list and signals the start of file names. This must be used when any of the -B, -M, or -S options are used.
-V: Displays version information and exit.
-h: Displays this help and exit.
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
scp command in Linux with Examples
Start/Stop/Restart Services Using Systemctl in Linux
Docker - COPY Instruction
SED command in Linux | Set 2
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 24764,
"s": 24326,
"text": "whereis command is used to find the location of source/binary file of a command and manuals sections for a specified file in Linux system. If we compare whereis command with find command they will appear similar to each other as both can be used for the same purposes but whereis command produces the result more accurately by consuming less time comparatively. whereis doesn’t require any root privilege to execute in any RHEL/CentOS 7."
},
{
"code": null,
"e": 25086,
"s": 24764,
"text": "The supplied names are first removed from leading pathname/directory components and any (single) trailing extension of the form .ext, for example, .c. Prefixes of s. resulting from use of source code control are also dealt with. whereis then attempts to locate the desired program in a list of standard Linux directories."
},
{
"code": null,
"e": 25141,
"s": 25086,
"text": "Points to be kept on mind while using whereis command:"
},
{
"code": null,
"e": 25455,
"s": 25141,
"text": "Since whereis command uses chdir(change directory 2V) to give you the result in fastest possible way, the pathnames given with the -M, -S, or -B must be full and well defined i.e. they must begin with a `/‘ and should be a valid path that exist in the system’s directories, else it exits without any valid result."
},
{
"code": null,
"e": 25604,
"s": 25455,
"text": "whereis command has a hard-coded(code which is not dynamic and changes with specification) path, so you may not always find what you’re looking for."
},
{
"code": null,
"e": 25612,
"s": 25604,
"text": "Syntax:"
},
{
"code": null,
"e": 25642,
"s": 25612,
"text": "whereis [options] filename..."
},
{
"code": null,
"e": 25775,
"s": 25642,
"text": "Example 1: Let’s say, we want to find the location of apropos command then we need to execute the following command in the terminal:"
},
{
"code": null,
"e": 25824,
"s": 25775,
"text": "Example 2: To find the location of lshw command."
},
{
"code": null,
"e": 25833,
"s": 25824,
"text": "Options:"
},
{
"code": null,
"e": 25962,
"s": 25833,
"text": "-b : This option is used when we only want to search for binaries.Example: To locate binary of a Linux command let’s say gunzip."
},
{
"code": null,
"e": 26025,
"s": 25962,
"text": "Example: To locate binary of a Linux command let’s say gunzip."
},
{
"code": null,
"e": 26144,
"s": 26025,
"text": "-m : This option is used when we only want to search for manual sections.Example: To locate man page of false command."
},
{
"code": null,
"e": 26190,
"s": 26144,
"text": "Example: To locate man page of false command."
},
{
"code": null,
"e": 26256,
"s": 26190,
"text": "-s : This option is used when we only want to search for sources."
},
{
"code": null,
"e": 26623,
"s": 26256,
"text": "-u: This option search for unusual entries. A source file or a binary file is said to be unusual if it does not have any existence in system as per [-bmsu] described along with “–u”. Thus `whereis -m -u *‘ asks for those files in the current directory which have unsual entries.Example: To display the files in the current directory which have no documentation file."
},
{
"code": null,
"e": 26712,
"s": 26623,
"text": "Example: To display the files in the current directory which have no documentation file."
},
{
"code": null,
"e": 26870,
"s": 26712,
"text": "-B : This option is used to change or otherwise limit the places where whereis searches for binaries.Example: To locate binary of lesspipe in the path, /bin."
},
{
"code": null,
"e": 26927,
"s": 26870,
"text": "Example: To locate binary of lesspipe in the path, /bin."
},
{
"code": null,
"e": 27133,
"s": 26927,
"text": "-M : This option is used to change or otherwise limit the places where whereis searches for manual sections.Example: To check man page of intro that is only in a specific location i.e. /usr/share/man/man1."
},
{
"code": null,
"e": 27231,
"s": 27133,
"text": "Example: To check man page of intro that is only in a specific location i.e. /usr/share/man/man1."
},
{
"code": null,
"e": 27437,
"s": 27231,
"text": "-S : This option is used to change or otherwise limit the places where whereis searches for sources.Example: To Find all files in /usr/bin which are not documented in /usr/man/man1 with source in /usr/src."
},
{
"code": null,
"e": 27543,
"s": 27437,
"text": "Example: To Find all files in /usr/bin which are not documented in /usr/man/man1 with source in /usr/src."
},
{
"code": null,
"e": 27704,
"s": 27543,
"text": "-f : This option simply terminate the last directory list and signals the start of file names. This must be used when any of the -B, -M, or -S options are used."
},
{
"code": null,
"e": 27747,
"s": 27704,
"text": "-V: Displays version information and exit."
},
{
"code": null,
"e": 27780,
"s": 27747,
"text": "-h: Displays this help and exit."
},
{
"code": null,
"e": 27794,
"s": 27780,
"text": "linux-command"
},
{
"code": null,
"e": 27805,
"s": 27794,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27903,
"s": 27805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27912,
"s": 27903,
"text": "Comments"
},
{
"code": null,
"e": 27925,
"s": 27912,
"text": "Old Comments"
},
{
"code": null,
"e": 27951,
"s": 27925,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27988,
"s": 27951,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28028,
"s": 27988,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 28065,
"s": 28028,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28099,
"s": 28065,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28141,
"s": 28099,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28176,
"s": 28141,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28229,
"s": 28176,
"text": "Start/Stop/Restart Services Using Systemctl in Linux"
},
{
"code": null,
"e": 28255,
"s": 28229,
"text": "Docker - COPY Instruction"
}
] |
Container for embedded content (16:9 aspect ratio) in Bootstrap
|
Use the .embed-responsive class in Bootstrap to set a container for embedded content.
For 16:9 aspect ratio for the embedded content, use the embed-responsive-16by9 class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>Eclipse Refactoring</h2>
<p>To refactor code in Eclipse, try the below given steps in the video:</p>
<div class = "embed-responsive embed-responsive-16by9">
<iframe class = "embed-responsive-item" src = "https://www.youtube.com/embed/YFVV6RAUnNg "></iframe>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Use the .embed-responsive class in Bootstrap to set a container for embedded content."
},
{
"code": null,
"e": 1233,
"s": 1148,
"text": "For 16:9 aspect ratio for the embedded content, use the embed-responsive-16by9 class"
},
{
"code": null,
"e": 1243,
"s": 1233,
"text": "Live Demo"
},
{
"code": null,
"e": 1909,
"s": 1243,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Eclipse Refactoring</h2>\n <p>To refactor code in Eclipse, try the below given steps in the video:</p>\n <div class = \"embed-responsive embed-responsive-16by9\">\n <iframe class = \"embed-responsive-item\" src = \"https://www.youtube.com/embed/YFVV6RAUnNg \"></iframe>\n </div>\n </div>\n </body>\n</html>"
}
] |
Node.js – util.inspect() method
|
The util.inspect() method returns the string representation of the objects that are intended for the debugging process.
util.inspect(object, [showHidden], [depth], [colors])
The parameters are defined as below:
object − A JavaScript primitive type or an object is given as input.
optionsshowHidden − This is set as false by default. If true, this option includes the non-enumerable symbols and properties that are included in the formatted result. WeakMap and WeakSet are also included.depth − It specifies the number of recursions to be applied while formatting objects.colors − The output is set styled with ANSI color codes if this value is set to true. Colors passed are customizable.customInspect − The functions are not invoked if this value is set to false.showProxy − Proxy inspection includes the target and handler objects if this value is set to true. Default is "false".maxArrayLength − This value specifies the maximum number of array.maxStringLength − This specifies the maximum number of characters to include while formatting. These values are set to null or infinity to show all elements.breakLength − This is the input value to split across multiple lines.compact − This input will break on new lines in text that are longer than breakLength.sorted − All the entries in map and set as well as the object are sorted if set to true.getters − The getters are inspected if these values are set to true.
showHidden − This is set as false by default. If true, this option includes the non-enumerable symbols and properties that are included in the formatted result. WeakMap and WeakSet are also included.
depth − It specifies the number of recursions to be applied while formatting objects.
colors − The output is set styled with ANSI color codes if this value is set to true. Colors passed are customizable.
customInspect − The functions are not invoked if this value is set to false.
showProxy − Proxy inspection includes the target and handler objects if this value is set to true. Default is "false".
maxArrayLength − This value specifies the maximum number of array.
maxStringLength − This specifies the maximum number of characters to include while formatting. These values are set to null or infinity to show all elements.
breakLength − This is the input value to split across multiple lines.
compact − This input will break on new lines in text that are longer than breakLength.
sorted − All the entries in map and set as well as the object are sorted if set to true.
getters − The getters are inspected if these values are set to true.
Create a file "inspect.js" and copy the following code snippet. After creating the file, use the command "node inspect.js" to run this code.
Live Demo
// Node util.inspect Demo Example
// Importing the util library
const util = require('util');
// Creating nested Objects
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;
// Inspect by basic method
console.log("1. ", util.inspect(nestedObject));
// Random class
class tutorialsPoint { }
// Inspecting the tutorialsPoint class object
console.log("2. ", util.inspect(new tutorialsPoint()));
// Inspect by passing options to method
console.log("3. ", util.inspect(
nestedObject, true, 0, false));
// Inspect by calling option name
console.log("4. ", util.inspect(nestedObject,
showHidden = false, depth = 0, colorize = true));
// Directly passing the JSON data
console.log("5. ", util.inspect([
{ name: "Raj", city: "Delhi" },
{ name: "Arun", city: "Mumbai" },
{ name: "Diva", city: "Chandigarh" }],
false, 3, true));
C:\home\node>> node inspect.js
1. <ref *1> {
a: [ [Circular *1] ],
b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
}
2. tutorialsPoint {}
3. { a: [Array], b: [Object] }
4. { a: [Array], b: [Object] }
5. [
{ name: 'Raj', city: 'Delhi' },
{ name: 'Arun', city: 'Mumbai' },
{ name: 'Diva', city: 'Chandigarh' }
]
You can use different options as per your use-case to get different inspection objects.
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "The util.inspect() method returns the string representation of the objects that are intended for the debugging process."
},
{
"code": null,
"e": 1236,
"s": 1182,
"text": "util.inspect(object, [showHidden], [depth], [colors])"
},
{
"code": null,
"e": 1273,
"s": 1236,
"text": "The parameters are defined as below:"
},
{
"code": null,
"e": 1342,
"s": 1273,
"text": "object − A JavaScript primitive type or an object is given as input."
},
{
"code": null,
"e": 2479,
"s": 1342,
"text": "optionsshowHidden − This is set as false by default. If true, this option includes the non-enumerable symbols and properties that are included in the formatted result. WeakMap and WeakSet are also included.depth − It specifies the number of recursions to be applied while formatting objects.colors − The output is set styled with ANSI color codes if this value is set to true. Colors passed are customizable.customInspect − The functions are not invoked if this value is set to false.showProxy − Proxy inspection includes the target and handler objects if this value is set to true. Default is \"false\".maxArrayLength − This value specifies the maximum number of array.maxStringLength − This specifies the maximum number of characters to include while formatting. These values are set to null or infinity to show all elements.breakLength − This is the input value to split across multiple lines.compact − This input will break on new lines in text that are longer than breakLength.sorted − All the entries in map and set as well as the object are sorted if set to true.getters − The getters are inspected if these values are set to true."
},
{
"code": null,
"e": 2679,
"s": 2479,
"text": "showHidden − This is set as false by default. If true, this option includes the non-enumerable symbols and properties that are included in the formatted result. WeakMap and WeakSet are also included."
},
{
"code": null,
"e": 2765,
"s": 2679,
"text": "depth − It specifies the number of recursions to be applied while formatting objects."
},
{
"code": null,
"e": 2883,
"s": 2765,
"text": "colors − The output is set styled with ANSI color codes if this value is set to true. Colors passed are customizable."
},
{
"code": null,
"e": 2960,
"s": 2883,
"text": "customInspect − The functions are not invoked if this value is set to false."
},
{
"code": null,
"e": 3079,
"s": 2960,
"text": "showProxy − Proxy inspection includes the target and handler objects if this value is set to true. Default is \"false\"."
},
{
"code": null,
"e": 3146,
"s": 3079,
"text": "maxArrayLength − This value specifies the maximum number of array."
},
{
"code": null,
"e": 3304,
"s": 3146,
"text": "maxStringLength − This specifies the maximum number of characters to include while formatting. These values are set to null or infinity to show all elements."
},
{
"code": null,
"e": 3374,
"s": 3304,
"text": "breakLength − This is the input value to split across multiple lines."
},
{
"code": null,
"e": 3461,
"s": 3374,
"text": "compact − This input will break on new lines in text that are longer than breakLength."
},
{
"code": null,
"e": 3550,
"s": 3461,
"text": "sorted − All the entries in map and set as well as the object are sorted if set to true."
},
{
"code": null,
"e": 3619,
"s": 3550,
"text": "getters − The getters are inspected if these values are set to true."
},
{
"code": null,
"e": 3760,
"s": 3619,
"text": "Create a file \"inspect.js\" and copy the following code snippet. After creating the file, use the command \"node inspect.js\" to run this code."
},
{
"code": null,
"e": 3771,
"s": 3760,
"text": " Live Demo"
},
{
"code": null,
"e": 4754,
"s": 3771,
"text": "// Node util.inspect Demo Example\n\n// Importing the util library\nconst util = require('util');\n\n// Creating nested Objects\nconst nestedObject = {};\nnestedObject.a = [nestedObject];\nnestedObject.b = [['a', ['b']], 'b', 'c', 'd'];\nnestedObject.b = {};\nnestedObject.b.inner = nestedObject.b;\nnestedObject.b.obj = nestedObject;\n\n// Inspect by basic method\nconsole.log(\"1. \", util.inspect(nestedObject));\n\n// Random class\nclass tutorialsPoint { }\n\n// Inspecting the tutorialsPoint class object\nconsole.log(\"2. \", util.inspect(new tutorialsPoint()));\n\n// Inspect by passing options to method\nconsole.log(\"3. \", util.inspect(\nnestedObject, true, 0, false));\n\n// Inspect by calling option name\nconsole.log(\"4. \", util.inspect(nestedObject,\nshowHidden = false, depth = 0, colorize = true));\n\n// Directly passing the JSON data\nconsole.log(\"5. \", util.inspect([\n { name: \"Raj\", city: \"Delhi\" },\n { name: \"Arun\", city: \"Mumbai\" },\n { name: \"Diva\", city: \"Chandigarh\" }],\nfalse, 3, true));"
},
{
"code": null,
"e": 5088,
"s": 4754,
"text": "C:\\home\\node>> node inspect.js\n1. <ref *1> {\n a: [ [Circular *1] ],\n b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n}\n2. tutorialsPoint {}\n3. { a: [Array], b: [Object] }\n4. { a: [Array], b: [Object] }\n5. [\n { name: 'Raj', city: 'Delhi' },\n { name: 'Arun', city: 'Mumbai' },\n { name: 'Diva', city: 'Chandigarh' }\n]"
},
{
"code": null,
"e": 5176,
"s": 5088,
"text": "You can use different options as per your use-case to get different inspection objects."
}
] |
Search a string in Matrix Using Split function in Java - GeeksforGeeks
|
21 Nov, 2018
Given a string str and a matrix mat[][] of lowercase English alphabets, the task is to find whether the string str appears in the matrix (either row-wise or column-wise).
Examples:
Input: str = "GFG"
mat[][] = {{'G', 'E', 'E', 'K', 'S'},
{'F', 'O', 'R', 'A', 'N'},
{'G', 'E', 'E', 'K', 'S'}}
Output: Yes
GFG is present in the first column.
Input: str = "SSS"
mat[][] = {{'G', 'E', 'E', 'K', 'S'},
{'F', 'O', 'R', 'A', 'N'},
{'G', 'E', 'E', 'K', 'S'}}
Output: No
Approach:If the search string is present in any row of the matrix the following results will be produced by the split function:
If the string occupies the whole row then the split function will return an array of length zero.If the string is present in between characters then the array length will be greater than one.If the array length is one then three possible cases can be there-The string occurs in first half.The string occurs in second half.The string is not present in that row.To search the string column wise transpose the matrix and repeat step one.Print Yes if the string is found else print No.
If the string occupies the whole row then the split function will return an array of length zero.
If the string is present in between characters then the array length will be greater than one.
If the array length is one then three possible cases can be there-The string occurs in first half.The string occurs in second half.The string is not present in that row.
The string occurs in first half.
The string occurs in second half.
The string is not present in that row.
To search the string column wise transpose the matrix and repeat step one.
Print Yes if the string is found else print No.
Below is the implementation of the above approach:
// Java program to search a string in// the matrix using split functionimport java.util.*;public class GFG { // Function to check the occurrence of string in the matrix public static int check(String[] matrix, String string) { // Looping the contents in the matrix for (String input : matrix) { // using split operator String[] value = input.split(string); if (value.length >= 2 || value.length == 0) { return 1; } else if (value.length == 1 && input.length() != value[0].length()) { return 1; } } return 0; } // Function to transpose the given matrix public static String[] vertical(String[] matrix) { String[] vertical_value = new String[matrix[0].length()]; for (int i = 0; i < matrix[0].length(); i++) { String temp = ""; for (int j = 0; j < matrix.length; j++) temp += matrix[j].charAt(i); vertical_value[i] = temp; } // returning the transposed matrix return vertical_value; } // Driver code public static void main(String[] args) { // Input matrix of characters String[] matrix = { "GEEKS", "FORAN", "GEEKS" }; // element to be searched String search = "GFG"; // Transpose of the matrix String[] verticalMatrix = vertical(matrix); // Searching process int horizontal_search = check(matrix, search); int vertical_search = check(verticalMatrix, search); // If found if (horizontal_search == 1 || vertical_search == 1) System.out.println("Yes"); else System.out.println("No"); }}
Yes
Searching Quiz
Arrays
Java Programs
Matrix
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 24600,
"s": 24429,
"text": "Given a string str and a matrix mat[][] of lowercase English alphabets, the task is to find whether the string str appears in the matrix (either row-wise or column-wise)."
},
{
"code": null,
"e": 24610,
"s": 24600,
"text": "Examples:"
},
{
"code": null,
"e": 25039,
"s": 24610,
"text": "Input: str = \"GFG\"\n mat[][] = {{'G', 'E', 'E', 'K', 'S'}, \n {'F', 'O', 'R', 'A', 'N'}, \n {'G', 'E', 'E', 'K', 'S'}}\nOutput: Yes\nGFG is present in the first column.\n\nInput: str = \"SSS\"\n mat[][] = {{'G', 'E', 'E', 'K', 'S'}, \n {'F', 'O', 'R', 'A', 'N'}, \n {'G', 'E', 'E', 'K', 'S'}}\nOutput: No\n"
},
{
"code": null,
"e": 25167,
"s": 25039,
"text": "Approach:If the search string is present in any row of the matrix the following results will be produced by the split function:"
},
{
"code": null,
"e": 25649,
"s": 25167,
"text": "If the string occupies the whole row then the split function will return an array of length zero.If the string is present in between characters then the array length will be greater than one.If the array length is one then three possible cases can be there-The string occurs in first half.The string occurs in second half.The string is not present in that row.To search the string column wise transpose the matrix and repeat step one.Print Yes if the string is found else print No."
},
{
"code": null,
"e": 25747,
"s": 25649,
"text": "If the string occupies the whole row then the split function will return an array of length zero."
},
{
"code": null,
"e": 25842,
"s": 25747,
"text": "If the string is present in between characters then the array length will be greater than one."
},
{
"code": null,
"e": 26012,
"s": 25842,
"text": "If the array length is one then three possible cases can be there-The string occurs in first half.The string occurs in second half.The string is not present in that row."
},
{
"code": null,
"e": 26045,
"s": 26012,
"text": "The string occurs in first half."
},
{
"code": null,
"e": 26079,
"s": 26045,
"text": "The string occurs in second half."
},
{
"code": null,
"e": 26118,
"s": 26079,
"text": "The string is not present in that row."
},
{
"code": null,
"e": 26193,
"s": 26118,
"text": "To search the string column wise transpose the matrix and repeat step one."
},
{
"code": null,
"e": 26241,
"s": 26193,
"text": "Print Yes if the string is found else print No."
},
{
"code": null,
"e": 26292,
"s": 26241,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to search a string in// the matrix using split functionimport java.util.*;public class GFG { // Function to check the occurrence of string in the matrix public static int check(String[] matrix, String string) { // Looping the contents in the matrix for (String input : matrix) { // using split operator String[] value = input.split(string); if (value.length >= 2 || value.length == 0) { return 1; } else if (value.length == 1 && input.length() != value[0].length()) { return 1; } } return 0; } // Function to transpose the given matrix public static String[] vertical(String[] matrix) { String[] vertical_value = new String[matrix[0].length()]; for (int i = 0; i < matrix[0].length(); i++) { String temp = \"\"; for (int j = 0; j < matrix.length; j++) temp += matrix[j].charAt(i); vertical_value[i] = temp; } // returning the transposed matrix return vertical_value; } // Driver code public static void main(String[] args) { // Input matrix of characters String[] matrix = { \"GEEKS\", \"FORAN\", \"GEEKS\" }; // element to be searched String search = \"GFG\"; // Transpose of the matrix String[] verticalMatrix = vertical(matrix); // Searching process int horizontal_search = check(matrix, search); int vertical_search = check(verticalMatrix, search); // If found if (horizontal_search == 1 || vertical_search == 1) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 28067,
"s": 26292,
"text": null
},
{
"code": null,
"e": 28072,
"s": 28067,
"text": "Yes\n"
},
{
"code": null,
"e": 28087,
"s": 28072,
"text": "Searching Quiz"
},
{
"code": null,
"e": 28094,
"s": 28087,
"text": "Arrays"
},
{
"code": null,
"e": 28108,
"s": 28094,
"text": "Java Programs"
},
{
"code": null,
"e": 28115,
"s": 28108,
"text": "Matrix"
},
{
"code": null,
"e": 28122,
"s": 28115,
"text": "Arrays"
},
{
"code": null,
"e": 28129,
"s": 28122,
"text": "Matrix"
},
{
"code": null,
"e": 28227,
"s": 28129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28236,
"s": 28227,
"text": "Comments"
},
{
"code": null,
"e": 28249,
"s": 28236,
"text": "Old Comments"
},
{
"code": null,
"e": 28270,
"s": 28249,
"text": "Next Greater Element"
},
{
"code": null,
"e": 28295,
"s": 28270,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28322,
"s": 28295,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 28371,
"s": 28322,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28409,
"s": 28371,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28453,
"s": 28409,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28481,
"s": 28453,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 28507,
"s": 28481,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28541,
"s": 28507,
"text": "Convert Double to Integer in Java"
}
] |
Explain Net operating income theory of capital structure.
|
Capital structure of a company depends on mix or ratio of debt and equity in their mode of their
financing. Depending on what company prefer, some may have more debt or more equity in financing
their asset, but final goal is to maximize their market value and their profits.
Net operating income (NOI) was developed by David Durand. According to net operating income approach, firm value is not affected by change in company or firm’s debt components.
Net operating income approach says that value of a firm depends on operating income and associated
business risk. Value of firm will not be affected by change in debt components.
Assumptions are as follows −
Debt and equity are source of financing.
Debt and equity are source of financing.
Dividend pay-out ratio is 1.
Dividend pay-out ratio is 1.
No taxes.
No taxes.
No retained earnings.
No retained earnings.
Constant debt capitalisation.
Constant debt capitalisation.
Constant WACC.
Constant WACC.
Difference between firm value and value of debt is value of equity.
Difference between firm value and value of debt is value of equity.
Cost of equity is larger than cost of debt.
Cost of equity is larger than cost of debt.
Market value of a firm (V) is ratio of earnings before income taxes (EBIT) and weighted average cost of capital (WACC).
V = EBIT/WACC
Total equity (E) is difference of market value of a firm (V) and market value of Debt (D).
E = V – D
Cost of equity (Ke) is ratio of difference between Earnings per share (EBIT) and interest (I) to market value of equity shareholder’s (Es).
Ke= (EBIT-I)/Es
Disadvantages of NOI are as follows −
No corporate tax.
No corporate tax.
If cost of debt increases, then financial leverage also increases which also, increases the capital cost.
If cost of debt increases, then financial leverage also increases which also, increases the capital cost.
Investors will have different view of firm’s having high debt in their capital structure.
Investors will have different view of firm’s having high debt in their capital structure.
|
[
{
"code": null,
"e": 1337,
"s": 1062,
"text": "Capital structure of a company depends on mix or ratio of debt and equity in their mode of their\nfinancing. Depending on what company prefer, some may have more debt or more equity in financing\ntheir asset, but final goal is to maximize their market value and their profits."
},
{
"code": null,
"e": 1514,
"s": 1337,
"text": "Net operating income (NOI) was developed by David Durand. According to net operating income approach, firm value is not affected by change in company or firm’s debt components."
},
{
"code": null,
"e": 1693,
"s": 1514,
"text": "Net operating income approach says that value of a firm depends on operating income and associated\nbusiness risk. Value of firm will not be affected by change in debt components."
},
{
"code": null,
"e": 1722,
"s": 1693,
"text": "Assumptions are as follows −"
},
{
"code": null,
"e": 1763,
"s": 1722,
"text": "Debt and equity are source of financing."
},
{
"code": null,
"e": 1804,
"s": 1763,
"text": "Debt and equity are source of financing."
},
{
"code": null,
"e": 1833,
"s": 1804,
"text": "Dividend pay-out ratio is 1."
},
{
"code": null,
"e": 1862,
"s": 1833,
"text": "Dividend pay-out ratio is 1."
},
{
"code": null,
"e": 1872,
"s": 1862,
"text": "No taxes."
},
{
"code": null,
"e": 1882,
"s": 1872,
"text": "No taxes."
},
{
"code": null,
"e": 1904,
"s": 1882,
"text": "No retained earnings."
},
{
"code": null,
"e": 1926,
"s": 1904,
"text": "No retained earnings."
},
{
"code": null,
"e": 1956,
"s": 1926,
"text": "Constant debt capitalisation."
},
{
"code": null,
"e": 1986,
"s": 1956,
"text": "Constant debt capitalisation."
},
{
"code": null,
"e": 2001,
"s": 1986,
"text": "Constant WACC."
},
{
"code": null,
"e": 2016,
"s": 2001,
"text": "Constant WACC."
},
{
"code": null,
"e": 2084,
"s": 2016,
"text": "Difference between firm value and value of debt is value of equity."
},
{
"code": null,
"e": 2152,
"s": 2084,
"text": "Difference between firm value and value of debt is value of equity."
},
{
"code": null,
"e": 2196,
"s": 2152,
"text": "Cost of equity is larger than cost of debt."
},
{
"code": null,
"e": 2240,
"s": 2196,
"text": "Cost of equity is larger than cost of debt."
},
{
"code": null,
"e": 2360,
"s": 2240,
"text": "Market value of a firm (V) is ratio of earnings before income taxes (EBIT) and weighted average cost of capital (WACC)."
},
{
"code": null,
"e": 2374,
"s": 2360,
"text": "V = EBIT/WACC"
},
{
"code": null,
"e": 2465,
"s": 2374,
"text": "Total equity (E) is difference of market value of a firm (V) and market value of Debt (D)."
},
{
"code": null,
"e": 2475,
"s": 2465,
"text": "E = V – D"
},
{
"code": null,
"e": 2615,
"s": 2475,
"text": "Cost of equity (Ke) is ratio of difference between Earnings per share (EBIT) and interest (I) to market value of equity shareholder’s (Es)."
},
{
"code": null,
"e": 2631,
"s": 2615,
"text": "Ke= (EBIT-I)/Es"
},
{
"code": null,
"e": 2669,
"s": 2631,
"text": "Disadvantages of NOI are as follows −"
},
{
"code": null,
"e": 2687,
"s": 2669,
"text": "No corporate tax."
},
{
"code": null,
"e": 2705,
"s": 2687,
"text": "No corporate tax."
},
{
"code": null,
"e": 2811,
"s": 2705,
"text": "If cost of debt increases, then financial leverage also increases which also, increases the capital cost."
},
{
"code": null,
"e": 2917,
"s": 2811,
"text": "If cost of debt increases, then financial leverage also increases which also, increases the capital cost."
},
{
"code": null,
"e": 3007,
"s": 2917,
"text": "Investors will have different view of firm’s having high debt in their capital structure."
},
{
"code": null,
"e": 3097,
"s": 3007,
"text": "Investors will have different view of firm’s having high debt in their capital structure."
}
] |
String Property codeUnits
|
Returns a list of the UTF-16 code units of a given string.
String.codeUnits
void main() {
String str = "Hello";
print(str.codeUnits);
}
It will produce the following output −.
[72, 101, 108, 108, 111]
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2584,
"s": 2525,
"text": "Returns a list of the UTF-16 code units of a given string."
},
{
"code": null,
"e": 2602,
"s": 2584,
"text": "String.codeUnits\n"
},
{
"code": null,
"e": 2672,
"s": 2602,
"text": "void main() { \n String str = \"Hello\"; \n print(str.codeUnits); \n} "
},
{
"code": null,
"e": 2712,
"s": 2672,
"text": "It will produce the following output −."
},
{
"code": null,
"e": 2739,
"s": 2712,
"text": "[72, 101, 108, 108, 111] \n"
},
{
"code": null,
"e": 2774,
"s": 2739,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2794,
"s": 2774,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2827,
"s": 2794,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2847,
"s": 2827,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 2880,
"s": 2847,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2897,
"s": 2880,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2932,
"s": 2897,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 2949,
"s": 2932,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 2984,
"s": 2949,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3004,
"s": 2984,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3037,
"s": 3004,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3057,
"s": 3037,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3064,
"s": 3057,
"text": " Print"
},
{
"code": null,
"e": 3075,
"s": 3064,
"text": " Add Notes"
}
] |
Flattening JSON records using PySpark | by Shreyas M S | Towards Data Science
|
JavaScript Object Notation (JSON) is a text-based, flexible, lightweight data-interchange format for semi-structured data. It is heavily used in transferring data between servers, web applications, and web-connected devices.
More often than not, events that are generated by a service or a product are in JSON format. These JSON records can have multi-level nesting, array-type fields which in turn have their own schema. Additionally, some of these fields are mandatory, some are optional. Hence, retrieving the schema and extracting only required columns becomes a tedious task.
This article presents an approach to minimize the amount of effort that is spent to retrieve the schema of the JSON records to extract specific columns and flattens out the entire JSON data passed as input.
Let’s say that two people have ordered items from an online delivery platform and the events generated were dumped as ORC files in an S3 location, here s3://mybucket/orders/ . To read these records, execute this piece of code:
df = spark.read.orc('s3://mybucket/orders/')
When you do a df.show(5, False) , it displays up to 5 records without truncating the output of each column.
Let’s print the schema of the JSON and visualize it. To do that, execute this piece of code:
json_df = spark.read.json(df.rdd.map(lambda row: row.json))json_df.printSchema()
Note: Reading a collection of files from a path ensures that a global schema is captured over all the records stored in those files.
The JSON schema can be visualized as a tree where each field can be considered as a node. If a field contains sub-fields then that node can be considered to have multiple child nodes. The tree for this schema would look like this:
The first record in the JSON data belongs to a person named John who ordered 2 items. The second record belongs to Chris who ordered 3 items. The expectation of our algorithm would be to extract all fields and generate a total of 5 records, each record for each item.
The key to flattening these JSON records is to obtain:
the path to every leaf node (these nodes could be of string or bigint or timestamp etc. types but not of struct-type or array-type)order of exploding (provides the sequence in which columns are to be exploded, in case of array-type).order of opening (provides the sequence in which columns are to be opened, in case a struct-type is a parent of array-type).
the path to every leaf node (these nodes could be of string or bigint or timestamp etc. types but not of struct-type or array-type)
order of exploding (provides the sequence in which columns are to be exploded, in case of array-type).
order of opening (provides the sequence in which columns are to be opened, in case a struct-type is a parent of array-type).
It is crucial to use a spark configuration:
--conf spark.sql.caseSensitive=True
as there might be different fields, considering spark’s default case insensitivity, having the same leaf name for e.g. product & Product are essentially different fields but are considered as same due spark’s default case-insensitivity property.
First import the necessary library:
import json
Next, the class variables are defined:
where get_fields_in_json function is defined as:
A brief explanation of each of the class variables is given below:
fields_in_json : This variable contains the metadata of the fields in the schema.all_fields : This variable contains a 1–1 mapping between the path to a leaf field and the column name that would appear in the flattened dataframe.cols_to_explode : This variable is a set containing paths to array-type fields.structure : This variable is a dictionary that is used for step by step node traversal to the array-type fields in cols_to_explode .order : This is a list containing the order in which array-type fields have to be exploded. If the array-type is inside a struct-type then the struct-type has to be opened first, hence has to appear before the array-type.bottom_to_top : This contains a dictionary where each key maps to a list of mutually exclusive leaf fields for every array-type/struct-type field (if struct type field is a parent of array type field).rest : Contains fields that are directly accessible with or without dot notation.
fields_in_json : This variable contains the metadata of the fields in the schema.
all_fields : This variable contains a 1–1 mapping between the path to a leaf field and the column name that would appear in the flattened dataframe.
cols_to_explode : This variable is a set containing paths to array-type fields.
structure : This variable is a dictionary that is used for step by step node traversal to the array-type fields in cols_to_explode .
order : This is a list containing the order in which array-type fields have to be exploded. If the array-type is inside a struct-type then the struct-type has to be opened first, hence has to appear before the array-type.
bottom_to_top : This contains a dictionary where each key maps to a list of mutually exclusive leaf fields for every array-type/struct-type field (if struct type field is a parent of array type field).
rest : Contains fields that are directly accessible with or without dot notation.
All these class variables are then used to perform exploding/opening the fields. But how are these class variables computed? Let us analyze this in steps.
Step 1: When the compute function is called from the object of AutoFlatten class, the class variables get updated where the compute function is defined as follows:
Each of the class variables would then look like this:
Step 2: The unnest_dict function unnests the dictionaries in the json_schema recursively and maps the hierarchical path to the field to the column name in the all_fields dictionary whenever it encounters a leaf node (check done in is_leaf function). Additionally, it also stored the path to the array-type fields in cols_to_explode set.
Step 3: Next, all the leaf fields are obtained by checking if elements of all_fields start with any element in cols_to_explode and are stored in all_cols_in_explode_cols .
Step 4: Using all_cols_in_explode_cols, rest is calculated which contains fields directly accessible with or without the dot notation, using a simple set difference operation.
Step 5: Now, structure is computed using cols_to_explode that is used for step by step node traversal to get to the array-type fields.
Step 6: Next, a BFS traversal is performed on structure to obtain the order in which the array explode has to take place and this order is stored in order class variable.
Step 7: Finally, order and all_cols_in_explode_cols is used to get all mutually exclusive fields for each element in order . To do this, a bottom-to-top approach is used i.e. the order list is reversed and the leaf fields inside each of the fields in order are mapped and stored in bottom_to_top. Note that '.order_details' key in bottom_to_top has no elements it. If there were leaf nodes under it, those would be directly accessible and would appear in rest .
Combining all the functions, the class would look like this:
To make use of the class variables to open/explode, this block of code is executed:
Here, the JSON records are read from the S3 path, and the global schema is computed. This schema is then passed while creating an object of the AutoFlatten class that initializes all class variables. When the compute function is called from the object of AutoFlatten class, the class variables are updated.
To open/explode, all first-level columns are selected with the columns in rest which haven’t appeared already. A counter is kept on the target names which counts the duplicate target column names. Any target column name having a count greater than 1 is renamed as <path_to_target_field> with each level separated by a > . All paths to those fields are added to the visited set of paths.
Then a check is done if order is empty or not. An empty order list means that there is no array-type field in the schema and vice-versa. In case, the order list isn’t empty, a traversal is done over each element in order and based on its type array/struct (only appears if an array-type field is a child of struct-type field), the columns are exploded/opened respectively and only those columns are selected which already haven’t appeared. Additionally, duplicate target column names are replaced by <path_to_target_field> with each level separated by a > and the paths to those fields are added to the visited set of paths.
Let's see what columns appear in final_df .
>>> final_df.columns['city', 'country', 'house_number', 'street', 'pincode', 'state', 'email', 'id', 'name', 'discount', 'order_details>id', 'price', 'product_name', 'quantity', 'ordered_time']
Since id in the order_details field was a duplicate, it was renamed as order_details>id .
Looking at the counts of the initial dataframe df and final_df dataframe, we know that the array explode has occurred properly.
Let's now verify by looking at the records belonging to the final_df dataframe.
As you can see, there is one record for every item that was purchased, and the algorithm has worked as expected.
There are few things to keep in mind while using this approach.
All the target column names have been retrieved by using the name of the leaf node in the metadata of the JSON schema.If you are working in a constrained environment then the column names will have to be changed with respect to the compliance standards after performing flattening.Incorporating regexp_replace, epoch to timestamp conversion, string to timestamp conversion and others are regarded as custom transformations on the raw data extracted from each of the columns. Hence, it has to be defined by the developer after performing the autoflatten operation.Beware of exposing Personally Identifiable Information (PII) columns as this mechanism exposes all columns. You would have to perform custom operations like hashes on those columns.
All the target column names have been retrieved by using the name of the leaf node in the metadata of the JSON schema.
If you are working in a constrained environment then the column names will have to be changed with respect to the compliance standards after performing flattening.
Incorporating regexp_replace, epoch to timestamp conversion, string to timestamp conversion and others are regarded as custom transformations on the raw data extracted from each of the columns. Hence, it has to be defined by the developer after performing the autoflatten operation.
Beware of exposing Personally Identifiable Information (PII) columns as this mechanism exposes all columns. You would have to perform custom operations like hashes on those columns.
That’s it! I hope this helps people who are looking to flatten out their JSON data without defining and passing a schema to extract required fields and also those who are looking to learn new stuff.
Thanks to Sandesh for collaborating with me on this!
Cheers!
UPDATE: Hello all, the operations described above are a good way to start the understanding of the core autoflatten mechanism. I have curated an optimized approach (the crux of which is more or less the same) for the same here which avoids using up a significant amount of memory compared to the approach described in the article. You can start off by calling the execute function that returns the flattened dataframe. Please feel free to reach out to me in case you have any questions!
|
[
{
"code": null,
"e": 396,
"s": 171,
"text": "JavaScript Object Notation (JSON) is a text-based, flexible, lightweight data-interchange format for semi-structured data. It is heavily used in transferring data between servers, web applications, and web-connected devices."
},
{
"code": null,
"e": 752,
"s": 396,
"text": "More often than not, events that are generated by a service or a product are in JSON format. These JSON records can have multi-level nesting, array-type fields which in turn have their own schema. Additionally, some of these fields are mandatory, some are optional. Hence, retrieving the schema and extracting only required columns becomes a tedious task."
},
{
"code": null,
"e": 959,
"s": 752,
"text": "This article presents an approach to minimize the amount of effort that is spent to retrieve the schema of the JSON records to extract specific columns and flattens out the entire JSON data passed as input."
},
{
"code": null,
"e": 1186,
"s": 959,
"text": "Let’s say that two people have ordered items from an online delivery platform and the events generated were dumped as ORC files in an S3 location, here s3://mybucket/orders/ . To read these records, execute this piece of code:"
},
{
"code": null,
"e": 1231,
"s": 1186,
"text": "df = spark.read.orc('s3://mybucket/orders/')"
},
{
"code": null,
"e": 1339,
"s": 1231,
"text": "When you do a df.show(5, False) , it displays up to 5 records without truncating the output of each column."
},
{
"code": null,
"e": 1432,
"s": 1339,
"text": "Let’s print the schema of the JSON and visualize it. To do that, execute this piece of code:"
},
{
"code": null,
"e": 1513,
"s": 1432,
"text": "json_df = spark.read.json(df.rdd.map(lambda row: row.json))json_df.printSchema()"
},
{
"code": null,
"e": 1646,
"s": 1513,
"text": "Note: Reading a collection of files from a path ensures that a global schema is captured over all the records stored in those files."
},
{
"code": null,
"e": 1877,
"s": 1646,
"text": "The JSON schema can be visualized as a tree where each field can be considered as a node. If a field contains sub-fields then that node can be considered to have multiple child nodes. The tree for this schema would look like this:"
},
{
"code": null,
"e": 2145,
"s": 1877,
"text": "The first record in the JSON data belongs to a person named John who ordered 2 items. The second record belongs to Chris who ordered 3 items. The expectation of our algorithm would be to extract all fields and generate a total of 5 records, each record for each item."
},
{
"code": null,
"e": 2200,
"s": 2145,
"text": "The key to flattening these JSON records is to obtain:"
},
{
"code": null,
"e": 2558,
"s": 2200,
"text": "the path to every leaf node (these nodes could be of string or bigint or timestamp etc. types but not of struct-type or array-type)order of exploding (provides the sequence in which columns are to be exploded, in case of array-type).order of opening (provides the sequence in which columns are to be opened, in case a struct-type is a parent of array-type)."
},
{
"code": null,
"e": 2690,
"s": 2558,
"text": "the path to every leaf node (these nodes could be of string or bigint or timestamp etc. types but not of struct-type or array-type)"
},
{
"code": null,
"e": 2793,
"s": 2690,
"text": "order of exploding (provides the sequence in which columns are to be exploded, in case of array-type)."
},
{
"code": null,
"e": 2918,
"s": 2793,
"text": "order of opening (provides the sequence in which columns are to be opened, in case a struct-type is a parent of array-type)."
},
{
"code": null,
"e": 2962,
"s": 2918,
"text": "It is crucial to use a spark configuration:"
},
{
"code": null,
"e": 2998,
"s": 2962,
"text": "--conf spark.sql.caseSensitive=True"
},
{
"code": null,
"e": 3244,
"s": 2998,
"text": "as there might be different fields, considering spark’s default case insensitivity, having the same leaf name for e.g. product & Product are essentially different fields but are considered as same due spark’s default case-insensitivity property."
},
{
"code": null,
"e": 3280,
"s": 3244,
"text": "First import the necessary library:"
},
{
"code": null,
"e": 3292,
"s": 3280,
"text": "import json"
},
{
"code": null,
"e": 3331,
"s": 3292,
"text": "Next, the class variables are defined:"
},
{
"code": null,
"e": 3380,
"s": 3331,
"text": "where get_fields_in_json function is defined as:"
},
{
"code": null,
"e": 3447,
"s": 3380,
"text": "A brief explanation of each of the class variables is given below:"
},
{
"code": null,
"e": 4391,
"s": 3447,
"text": "fields_in_json : This variable contains the metadata of the fields in the schema.all_fields : This variable contains a 1–1 mapping between the path to a leaf field and the column name that would appear in the flattened dataframe.cols_to_explode : This variable is a set containing paths to array-type fields.structure : This variable is a dictionary that is used for step by step node traversal to the array-type fields in cols_to_explode .order : This is a list containing the order in which array-type fields have to be exploded. If the array-type is inside a struct-type then the struct-type has to be opened first, hence has to appear before the array-type.bottom_to_top : This contains a dictionary where each key maps to a list of mutually exclusive leaf fields for every array-type/struct-type field (if struct type field is a parent of array type field).rest : Contains fields that are directly accessible with or without dot notation."
},
{
"code": null,
"e": 4473,
"s": 4391,
"text": "fields_in_json : This variable contains the metadata of the fields in the schema."
},
{
"code": null,
"e": 4622,
"s": 4473,
"text": "all_fields : This variable contains a 1–1 mapping between the path to a leaf field and the column name that would appear in the flattened dataframe."
},
{
"code": null,
"e": 4702,
"s": 4622,
"text": "cols_to_explode : This variable is a set containing paths to array-type fields."
},
{
"code": null,
"e": 4835,
"s": 4702,
"text": "structure : This variable is a dictionary that is used for step by step node traversal to the array-type fields in cols_to_explode ."
},
{
"code": null,
"e": 5057,
"s": 4835,
"text": "order : This is a list containing the order in which array-type fields have to be exploded. If the array-type is inside a struct-type then the struct-type has to be opened first, hence has to appear before the array-type."
},
{
"code": null,
"e": 5259,
"s": 5057,
"text": "bottom_to_top : This contains a dictionary where each key maps to a list of mutually exclusive leaf fields for every array-type/struct-type field (if struct type field is a parent of array type field)."
},
{
"code": null,
"e": 5341,
"s": 5259,
"text": "rest : Contains fields that are directly accessible with or without dot notation."
},
{
"code": null,
"e": 5496,
"s": 5341,
"text": "All these class variables are then used to perform exploding/opening the fields. But how are these class variables computed? Let us analyze this in steps."
},
{
"code": null,
"e": 5660,
"s": 5496,
"text": "Step 1: When the compute function is called from the object of AutoFlatten class, the class variables get updated where the compute function is defined as follows:"
},
{
"code": null,
"e": 5715,
"s": 5660,
"text": "Each of the class variables would then look like this:"
},
{
"code": null,
"e": 6052,
"s": 5715,
"text": "Step 2: The unnest_dict function unnests the dictionaries in the json_schema recursively and maps the hierarchical path to the field to the column name in the all_fields dictionary whenever it encounters a leaf node (check done in is_leaf function). Additionally, it also stored the path to the array-type fields in cols_to_explode set."
},
{
"code": null,
"e": 6224,
"s": 6052,
"text": "Step 3: Next, all the leaf fields are obtained by checking if elements of all_fields start with any element in cols_to_explode and are stored in all_cols_in_explode_cols ."
},
{
"code": null,
"e": 6400,
"s": 6224,
"text": "Step 4: Using all_cols_in_explode_cols, rest is calculated which contains fields directly accessible with or without the dot notation, using a simple set difference operation."
},
{
"code": null,
"e": 6535,
"s": 6400,
"text": "Step 5: Now, structure is computed using cols_to_explode that is used for step by step node traversal to get to the array-type fields."
},
{
"code": null,
"e": 6706,
"s": 6535,
"text": "Step 6: Next, a BFS traversal is performed on structure to obtain the order in which the array explode has to take place and this order is stored in order class variable."
},
{
"code": null,
"e": 7168,
"s": 6706,
"text": "Step 7: Finally, order and all_cols_in_explode_cols is used to get all mutually exclusive fields for each element in order . To do this, a bottom-to-top approach is used i.e. the order list is reversed and the leaf fields inside each of the fields in order are mapped and stored in bottom_to_top. Note that '.order_details' key in bottom_to_top has no elements it. If there were leaf nodes under it, those would be directly accessible and would appear in rest ."
},
{
"code": null,
"e": 7229,
"s": 7168,
"text": "Combining all the functions, the class would look like this:"
},
{
"code": null,
"e": 7313,
"s": 7229,
"text": "To make use of the class variables to open/explode, this block of code is executed:"
},
{
"code": null,
"e": 7620,
"s": 7313,
"text": "Here, the JSON records are read from the S3 path, and the global schema is computed. This schema is then passed while creating an object of the AutoFlatten class that initializes all class variables. When the compute function is called from the object of AutoFlatten class, the class variables are updated."
},
{
"code": null,
"e": 8007,
"s": 7620,
"text": "To open/explode, all first-level columns are selected with the columns in rest which haven’t appeared already. A counter is kept on the target names which counts the duplicate target column names. Any target column name having a count greater than 1 is renamed as <path_to_target_field> with each level separated by a > . All paths to those fields are added to the visited set of paths."
},
{
"code": null,
"e": 8632,
"s": 8007,
"text": "Then a check is done if order is empty or not. An empty order list means that there is no array-type field in the schema and vice-versa. In case, the order list isn’t empty, a traversal is done over each element in order and based on its type array/struct (only appears if an array-type field is a child of struct-type field), the columns are exploded/opened respectively and only those columns are selected which already haven’t appeared. Additionally, duplicate target column names are replaced by <path_to_target_field> with each level separated by a > and the paths to those fields are added to the visited set of paths."
},
{
"code": null,
"e": 8676,
"s": 8632,
"text": "Let's see what columns appear in final_df ."
},
{
"code": null,
"e": 8870,
"s": 8676,
"text": ">>> final_df.columns['city', 'country', 'house_number', 'street', 'pincode', 'state', 'email', 'id', 'name', 'discount', 'order_details>id', 'price', 'product_name', 'quantity', 'ordered_time']"
},
{
"code": null,
"e": 8960,
"s": 8870,
"text": "Since id in the order_details field was a duplicate, it was renamed as order_details>id ."
},
{
"code": null,
"e": 9088,
"s": 8960,
"text": "Looking at the counts of the initial dataframe df and final_df dataframe, we know that the array explode has occurred properly."
},
{
"code": null,
"e": 9168,
"s": 9088,
"text": "Let's now verify by looking at the records belonging to the final_df dataframe."
},
{
"code": null,
"e": 9281,
"s": 9168,
"text": "As you can see, there is one record for every item that was purchased, and the algorithm has worked as expected."
},
{
"code": null,
"e": 9345,
"s": 9281,
"text": "There are few things to keep in mind while using this approach."
},
{
"code": null,
"e": 10090,
"s": 9345,
"text": "All the target column names have been retrieved by using the name of the leaf node in the metadata of the JSON schema.If you are working in a constrained environment then the column names will have to be changed with respect to the compliance standards after performing flattening.Incorporating regexp_replace, epoch to timestamp conversion, string to timestamp conversion and others are regarded as custom transformations on the raw data extracted from each of the columns. Hence, it has to be defined by the developer after performing the autoflatten operation.Beware of exposing Personally Identifiable Information (PII) columns as this mechanism exposes all columns. You would have to perform custom operations like hashes on those columns."
},
{
"code": null,
"e": 10209,
"s": 10090,
"text": "All the target column names have been retrieved by using the name of the leaf node in the metadata of the JSON schema."
},
{
"code": null,
"e": 10373,
"s": 10209,
"text": "If you are working in a constrained environment then the column names will have to be changed with respect to the compliance standards after performing flattening."
},
{
"code": null,
"e": 10656,
"s": 10373,
"text": "Incorporating regexp_replace, epoch to timestamp conversion, string to timestamp conversion and others are regarded as custom transformations on the raw data extracted from each of the columns. Hence, it has to be defined by the developer after performing the autoflatten operation."
},
{
"code": null,
"e": 10838,
"s": 10656,
"text": "Beware of exposing Personally Identifiable Information (PII) columns as this mechanism exposes all columns. You would have to perform custom operations like hashes on those columns."
},
{
"code": null,
"e": 11037,
"s": 10838,
"text": "That’s it! I hope this helps people who are looking to flatten out their JSON data without defining and passing a schema to extract required fields and also those who are looking to learn new stuff."
},
{
"code": null,
"e": 11090,
"s": 11037,
"text": "Thanks to Sandesh for collaborating with me on this!"
},
{
"code": null,
"e": 11098,
"s": 11090,
"text": "Cheers!"
}
] |
\leqslant - Tex Command
|
\leqslant - Used to draw less than or equal to symbol.
{ \leqslant }
\leqslant command is used to draw less than or equal to symbol.
\leqslant
⩽
\leqslant
⩽
\leqslant
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8041,
"s": 7986,
"text": "\\leqslant - Used to draw less than or equal to symbol."
},
{
"code": null,
"e": 8055,
"s": 8041,
"text": "{ \\leqslant }"
},
{
"code": null,
"e": 8119,
"s": 8055,
"text": "\\leqslant command is used to draw less than or equal to symbol."
},
{
"code": null,
"e": 8136,
"s": 8119,
"text": "\n\\leqslant\n\n⩽\n\n\n"
},
{
"code": null,
"e": 8151,
"s": 8136,
"text": "\\leqslant\n\n⩽\n\n"
},
{
"code": null,
"e": 8161,
"s": 8151,
"text": "\\leqslant"
},
{
"code": null,
"e": 8193,
"s": 8161,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8206,
"s": 8193,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8239,
"s": 8206,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8252,
"s": 8239,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8284,
"s": 8252,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8320,
"s": 8284,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8355,
"s": 8320,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8372,
"s": 8355,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8405,
"s": 8372,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8419,
"s": 8405,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8451,
"s": 8419,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8466,
"s": 8451,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8473,
"s": 8466,
"text": " Print"
},
{
"code": null,
"e": 8484,
"s": 8473,
"text": " Add Notes"
}
] |
Non Repeating Numbers | Practice | GeeksforGeeks
|
Given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers.
Example 1:
Input:
N = 2
arr[] = {1, 2, 3, 2, 1, 4}
Output:
3 4
Explanation:
3 and 4 occur exactly once.
Example 2:
Input:
N = 1
arr[] = {2, 1, 3, 2}
Output:
1 3
Explanation:
1 3 occur exactly once.
Your Task:
You do not need to read or print anything. Your task is to complete the function singleNumber() which takes the array as input parameter and returns a list of two numbers which occur exactly once in the array. The list must be in ascending order.
Expected Time Complexity: O(N)
Expected Space Complexity: O(1)
Constraints:
1 <= length of array <= 106
1 <= Elements in array <= 5 * 106
0
vishnu12656 days ago
public int[] singleNumber(int[] nums)
{
int xor = 0;
for(int i=0;i<nums.length;i++){
xor = xor ^ nums[i];
}
int setBit = xor & ~(xor - 1);
int num1 = 0,num2=0;
for(int i=0;i<nums.length;i++){
if((setBit & nums[i]) == setBit){
num1 = num1 ^ nums[i];
}
else{
num2 = num2 ^ nums[i];
}
}
if(num1>num2){
return new int[]{num2,num1};
}
else{
return new int[]{num1,num2};
}
}
+1
ayushrkacholia1 week ago
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
vector<int> singleNumber(vector<int> nums)
{
vector<int> v;
int res = 0;
int c =0;
for(int i=0;i<nums.size();i++){
res^=nums[i];
}
int k =res;
while(k){
if((k&1) == 1){
break;
}
c++;
k = k>>1;
}
int j = 1<<c;
int l = res;
for(int i=0;i<nums.size();i++){
if((nums[i]&j)==j){
l^=nums[i];
}
}
res^=l;
if(res>l){
v.push_back(l);
v.push_back(res);
}
else{
v.push_back(res);
v.push_back(l);
}
return v;
}
};
Time taken 0.02/2.2
+1
shikhardubey94577568751 week ago
I don't know why my code passes all the test case when i have use Map technique :
Because the map solution has the TC --→ O ( n logn ) and in the question the tc given is the o ( n ) and it should not pass the test case .....
But it is fine for me that it passes all test case without using the bit magic ....
0
mitradiptamoy1 week ago
vector<int> singleNumber(vector<int> nums) { // Code here. //O(nlogn) — T.C
vector<int>ans; unordered_set<int>s; int n=nums.size(); for(auto it:nums){ if(s.find(it)!=s.end()){ s.erase(it); } else{ s.insert(it); } } for(int val:s){ ans.push_back(val); } sort(ans.begin(),ans.end()); return ans; }
+1
himanshukug19cs2 weeks ago
java solution
int xor=0; for(int i=0;i<nums.length;i++){ xor^=nums[i]; } // return xor; int a=xor; int b=xor; int i=1; while(xor>0&&(xor&1)==0){ xor=xor>>1; i=i<<1; } //System.out.println(b); int[] ans=new int[2]; for(int j=0;j<nums.length;j++){ if((i&nums[j])==0){ a=a^nums[j]; } else{ b=b^nums[j]; } } ans[0]=a; ans[1]=b; Arrays.sort(ans); return ans; }
0
stoicamm95
This comment was deleted.
+3
sanikajainece193 weeks ago
vector<int> singleNumber(vector<int> nums) { // Code here. int n=nums.size(); int x=0; for(int i=0;i<n;i++) { x=x^nums[i]; } int mask=0; for(int i=0;i<31;i++) { if(x&1<<i) { mask=1<<i; } } int a=0,b=0; for(int i=0;i<n;i++) { if(nums[i]&mask) { a=a^nums[i]; } else { b=b^nums[i]; } } vector<int>v; v.push_back(a); v.push_back(b); sort(v.begin(),v.end()); return v; }
-1
amnks11
This comment was deleted.
0
sanikajainece19
This comment was deleted.
0
adityagagtiwari3 weeks ago
Bit manipulation is fun!!
class Solution{ public int findRsb(int n) { return (int)(Math.log10(n)/Math.log10(2)); } public int[] singleNumber(int[] arr) { // Code here int[] result = new int[2]; int wholexor = arr[0]; for(int i=1;i<arr.length;i++) { wholexor =wholexor^arr[i]; } int rsbofwhole = findRsb(wholexor); int rsbmask = 1<<rsbofwhole; for(int i=0;i<arr.length;i++) { if((arr[i]&rsbmask)>0) { result[1] = result[1]^arr[i]; } else if((arr[i]&rsbmask)==0) { result[0] = result[0]^arr[i]; } } return result; }}
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": 424,
"s": 238,
"text": "Given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers."
},
{
"code": null,
"e": 436,
"s": 424,
"text": "\nExample 1:"
},
{
"code": null,
"e": 532,
"s": 436,
"text": "Input: \nN = 2\narr[] = {1, 2, 3, 2, 1, 4}\nOutput:\n3 4 \nExplanation:\n3 and 4 occur exactly once.\n"
},
{
"code": null,
"e": 543,
"s": 532,
"text": "Example 2:"
},
{
"code": null,
"e": 627,
"s": 543,
"text": "Input:\nN = 1\narr[] = {2, 1, 3, 2}\nOutput:\n1 3\nExplanation:\n1 3 occur exactly once.\n"
},
{
"code": null,
"e": 886,
"s": 627,
"text": "\nYour Task:\nYou do not need to read or print anything. Your task is to complete the function singleNumber() which takes the array as input parameter and returns a list of two numbers which occur exactly once in the array. The list must be in ascending order."
},
{
"code": null,
"e": 950,
"s": 886,
"text": "\nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)"
},
{
"code": null,
"e": 1027,
"s": 950,
"text": "\nConstraints:\n1 <= length of array <= 106 \n1 <= Elements in array <= 5 * 106"
},
{
"code": null,
"e": 1029,
"s": 1027,
"text": "0"
},
{
"code": null,
"e": 1050,
"s": 1029,
"text": "vishnu12656 days ago"
},
{
"code": null,
"e": 1640,
"s": 1050,
"text": "public int[] singleNumber(int[] nums)\n {\n int xor = 0;\n for(int i=0;i<nums.length;i++){\n xor = xor ^ nums[i];\n }\n int setBit = xor & ~(xor - 1);\n int num1 = 0,num2=0;\n for(int i=0;i<nums.length;i++){\n if((setBit & nums[i]) == setBit){\n num1 = num1 ^ nums[i];\n }\n else{\n num2 = num2 ^ nums[i];\n }\n }\n if(num1>num2){\n return new int[]{num2,num1};\n }\n else{\n return new int[]{num1,num2};\n }\n \n }"
},
{
"code": null,
"e": 1643,
"s": 1640,
"text": "+1"
},
{
"code": null,
"e": 1668,
"s": 1643,
"text": "ayushrkacholia1 week ago"
},
{
"code": null,
"e": 2540,
"s": 1668,
"text": "// { Driver Code Starts\n#include<bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution\n{\npublic:\n vector<int> singleNumber(vector<int> nums) \n {\n vector<int> v;\n int res = 0;\n int c =0;\n for(int i=0;i<nums.size();i++){\n res^=nums[i];\n }\n int k =res;\n while(k){\n if((k&1) == 1){\n break;\n }\n c++;\n k = k>>1;\n }\n int j = 1<<c;\n int l = res;\n for(int i=0;i<nums.size();i++){\n if((nums[i]&j)==j){\n l^=nums[i];\n }\n }\n res^=l;\n \n if(res>l){\n \n v.push_back(l);\n v.push_back(res);\n }\n else{\n v.push_back(res);\n v.push_back(l);\n }\n \n return v;\n }\n};"
},
{
"code": null,
"e": 2560,
"s": 2540,
"text": "Time taken 0.02/2.2"
},
{
"code": null,
"e": 2563,
"s": 2560,
"text": "+1"
},
{
"code": null,
"e": 2596,
"s": 2563,
"text": "shikhardubey94577568751 week ago"
},
{
"code": null,
"e": 2678,
"s": 2596,
"text": "I don't know why my code passes all the test case when i have use Map technique :"
},
{
"code": null,
"e": 2824,
"s": 2678,
"text": "Because the map solution has the TC --→ O ( n logn ) and in the question the tc given is the o ( n ) and it should not pass the test case ....."
},
{
"code": null,
"e": 2908,
"s": 2824,
"text": "But it is fine for me that it passes all test case without using the bit magic ...."
},
{
"code": null,
"e": 2912,
"s": 2910,
"text": "0"
},
{
"code": null,
"e": 2936,
"s": 2912,
"text": "mitradiptamoy1 week ago"
},
{
"code": null,
"e": 3029,
"s": 2936,
"text": " vector<int> singleNumber(vector<int> nums) { // Code here. //O(nlogn) — T.C"
},
{
"code": null,
"e": 3384,
"s": 3029,
"text": " vector<int>ans; unordered_set<int>s; int n=nums.size(); for(auto it:nums){ if(s.find(it)!=s.end()){ s.erase(it); } else{ s.insert(it); } } for(int val:s){ ans.push_back(val); } sort(ans.begin(),ans.end()); return ans; }"
},
{
"code": null,
"e": 3387,
"s": 3384,
"text": "+1"
},
{
"code": null,
"e": 3414,
"s": 3387,
"text": "himanshukug19cs2 weeks ago"
},
{
"code": null,
"e": 3428,
"s": 3414,
"text": "java solution"
},
{
"code": null,
"e": 3951,
"s": 3428,
"text": " int xor=0; for(int i=0;i<nums.length;i++){ xor^=nums[i]; } // return xor; int a=xor; int b=xor; int i=1; while(xor>0&&(xor&1)==0){ xor=xor>>1; i=i<<1; } //System.out.println(b); int[] ans=new int[2]; for(int j=0;j<nums.length;j++){ if((i&nums[j])==0){ a=a^nums[j]; } else{ b=b^nums[j]; } } ans[0]=a; ans[1]=b; Arrays.sort(ans); return ans; }"
},
{
"code": null,
"e": 3953,
"s": 3951,
"text": "0"
},
{
"code": null,
"e": 3964,
"s": 3953,
"text": "stoicamm95"
},
{
"code": null,
"e": 3990,
"s": 3964,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3993,
"s": 3990,
"text": "+3"
},
{
"code": null,
"e": 4020,
"s": 3993,
"text": "sanikajainece193 weeks ago"
},
{
"code": null,
"e": 4647,
"s": 4020,
"text": "vector<int> singleNumber(vector<int> nums) { // Code here. int n=nums.size(); int x=0; for(int i=0;i<n;i++) { x=x^nums[i]; } int mask=0; for(int i=0;i<31;i++) { if(x&1<<i) { mask=1<<i; } } int a=0,b=0; for(int i=0;i<n;i++) { if(nums[i]&mask) { a=a^nums[i]; } else { b=b^nums[i]; } } vector<int>v; v.push_back(a); v.push_back(b); sort(v.begin(),v.end()); return v; }"
},
{
"code": null,
"e": 4650,
"s": 4647,
"text": "-1"
},
{
"code": null,
"e": 4658,
"s": 4650,
"text": "amnks11"
},
{
"code": null,
"e": 4684,
"s": 4658,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4686,
"s": 4684,
"text": "0"
},
{
"code": null,
"e": 4702,
"s": 4686,
"text": "sanikajainece19"
},
{
"code": null,
"e": 4728,
"s": 4702,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4730,
"s": 4728,
"text": "0"
},
{
"code": null,
"e": 4757,
"s": 4730,
"text": "adityagagtiwari3 weeks ago"
},
{
"code": null,
"e": 4783,
"s": 4757,
"text": "Bit manipulation is fun!!"
},
{
"code": null,
"e": 5469,
"s": 4785,
"text": "class Solution{ public int findRsb(int n) { return (int)(Math.log10(n)/Math.log10(2)); } public int[] singleNumber(int[] arr) { // Code here int[] result = new int[2]; int wholexor = arr[0]; for(int i=1;i<arr.length;i++) { wholexor =wholexor^arr[i]; } int rsbofwhole = findRsb(wholexor); int rsbmask = 1<<rsbofwhole; for(int i=0;i<arr.length;i++) { if((arr[i]&rsbmask)>0) { result[1] = result[1]^arr[i]; } else if((arr[i]&rsbmask)==0) { result[0] = result[0]^arr[i]; } } return result; }}"
},
{
"code": null,
"e": 5615,
"s": 5469,
"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": 5651,
"s": 5615,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5661,
"s": 5651,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5671,
"s": 5661,
"text": "\nContest\n"
},
{
"code": null,
"e": 5734,
"s": 5671,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5882,
"s": 5734,
"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": 6090,
"s": 5882,
"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": 6196,
"s": 6090,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to create a temporary MySQL table in a SELECT statement without a separate CREATE TABLE?
|
To create a temporary table in a SELECT statement we use TEMPORARY keyword.
This temporary table will be visible for the current session and whenever a session is closed, it is automatically destroyed. Two sessions can use the same temporary table.
Creating a table.
mysql> create table MyTableDemo
-> (
-> id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.69 sec)
Inserting some records.
mysql> insert into MyTableDemo values(1,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into MyTableDemo values(2,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into MyTableDemo values(3,'Bob');
Query OK, 1 row affected (0.12 sec)
To display all records.
mysql> select *from MyTemporaryTableDemo;
Here is the output.
+------+-------+
| id | Name |
+------+-------+
| 1 | John |
| 2 | Carol |
| 3 | Bob |
+------+-------+
3 rows in set (0.00 sec)
The syntax to create a temporary table.
CREATE TEMPORARY TABLE IF NOT EXISTS yourTemporaryTableName AS (SELECT * FROM yourTableName);
Let us now implement the above syntax in the following query −
mysql> CREATE TEMPORARY TABLE IF NOT EXISTS MyTemporaryTableDemo AS (SELECT * FROM MyTableDemo);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
To check if all records are copied successfully.
mysql> select *from MyTemporaryTableDemo;
Here is the output.
+------+-------+
| id | Name |
+------+-------+
| 1 | John |
| 2 | Carol |
| 3 | Bob |
+------+-------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To create a temporary table in a SELECT statement we use TEMPORARY keyword."
},
{
"code": null,
"e": 1311,
"s": 1138,
"text": "This temporary table will be visible for the current session and whenever a session is closed, it is automatically destroyed. Two sessions can use the same temporary table."
},
{
"code": null,
"e": 1329,
"s": 1311,
"text": "Creating a table."
},
{
"code": null,
"e": 1453,
"s": 1329,
"text": "mysql> create table MyTableDemo\n -> (\n -> id int,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.69 sec)"
},
{
"code": null,
"e": 1477,
"s": 1453,
"text": "Inserting some records."
},
{
"code": null,
"e": 1736,
"s": 1477,
"text": "mysql> insert into MyTableDemo values(1,'John');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into MyTableDemo values(2,'Carol');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into MyTableDemo values(3,'Bob');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1760,
"s": 1736,
"text": "To display all records."
},
{
"code": null,
"e": 1802,
"s": 1760,
"text": "mysql> select *from MyTemporaryTableDemo;"
},
{
"code": null,
"e": 1822,
"s": 1802,
"text": "Here is the output."
},
{
"code": null,
"e": 1967,
"s": 1822,
"text": "+------+-------+\n| id | Name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n+------+-------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2007,
"s": 1967,
"text": "The syntax to create a temporary table."
},
{
"code": null,
"e": 2102,
"s": 2007,
"text": " CREATE TEMPORARY TABLE IF NOT EXISTS yourTemporaryTableName AS (SELECT * FROM yourTableName);"
},
{
"code": null,
"e": 2165,
"s": 2102,
"text": "Let us now implement the above syntax in the following query −"
},
{
"code": null,
"e": 2338,
"s": 2165,
"text": "mysql> CREATE TEMPORARY TABLE IF NOT EXISTS MyTemporaryTableDemo AS (SELECT * FROM MyTableDemo);\nQuery OK, 3 rows affected (0.01 sec)\nRecords: 3 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2387,
"s": 2338,
"text": "To check if all records are copied successfully."
},
{
"code": null,
"e": 2429,
"s": 2387,
"text": "mysql> select *from MyTemporaryTableDemo;"
},
{
"code": null,
"e": 2449,
"s": 2429,
"text": "Here is the output."
},
{
"code": null,
"e": 2594,
"s": 2449,
"text": "+------+-------+\n| id | Name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n+------+-------+\n3 rows in set (0.00 sec)\n"
}
] |
\overbrace - Tex Command
|
\overbrace - Used to put a (stretchy) over-brace over the argument.
{ \overbrace #1}
\overbrace command puts a (stretchy) over-brace over the argument. Can use '^' to place an optional superscript over the overbrace; can use ‘_’ to place an optional subscript below the argument.
\overbrace{x + \cdots + x}^{n\rm\ times}_{\text{(note here)}}
x+⋯+x⏞(note here)n times
\overbrace{x + \cdots + x}^{n\rm\ times}_{\text{(note here)}}
x+⋯+x⏞(note here)n times
\overbrace{x + \cdots + x}^{n\rm\ times}_{\text{(note here)}}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8054,
"s": 7986,
"text": "\\overbrace - Used to put a (stretchy) over-brace over the argument."
},
{
"code": null,
"e": 8071,
"s": 8054,
"text": "{ \\overbrace #1}"
},
{
"code": null,
"e": 8266,
"s": 8071,
"text": "\\overbrace command puts a (stretchy) over-brace over the argument. Can use '^' to place an optional superscript over the overbrace; can use ‘_’ to place an optional subscript below the argument."
},
{
"code": null,
"e": 8358,
"s": 8266,
"text": "\n\\overbrace{x + \\cdots + x}^{n\\rm\\ times}_{\\text{(note here)}}\n\nx+⋯+x⏞(note here)n times\n\n\n"
},
{
"code": null,
"e": 8448,
"s": 8358,
"text": "\\overbrace{x + \\cdots + x}^{n\\rm\\ times}_{\\text{(note here)}}\n\nx+⋯+x⏞(note here)n times\n\n"
},
{
"code": null,
"e": 8510,
"s": 8448,
"text": "\\overbrace{x + \\cdots + x}^{n\\rm\\ times}_{\\text{(note here)}}"
},
{
"code": null,
"e": 8542,
"s": 8510,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8555,
"s": 8542,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8588,
"s": 8555,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8601,
"s": 8588,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8633,
"s": 8601,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8669,
"s": 8633,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8704,
"s": 8669,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8721,
"s": 8704,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8754,
"s": 8721,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8768,
"s": 8754,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8800,
"s": 8768,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8815,
"s": 8800,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8822,
"s": 8815,
"text": " Print"
},
{
"code": null,
"e": 8833,
"s": 8822,
"text": " Add Notes"
}
] |
Java - String trim() Method
|
This method returns a copy of the string, with leading and trailing whitespace omitted.
Here is the syntax of this method −
public String trim()
Here is the detail of parameters −
NA
NA
It returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
It returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String(" Welcome to Tutorialspoint.com ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
}
}
This will produce the following result −
Return Value :Welcome to Tutorialspoint.com
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2465,
"s": 2377,
"text": "This method returns a copy of the string, with leading and trailing whitespace omitted."
},
{
"code": null,
"e": 2501,
"s": 2465,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2523,
"s": 2501,
"text": "public String trim()\n"
},
{
"code": null,
"e": 2558,
"s": 2523,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2561,
"s": 2558,
"text": "NA"
},
{
"code": null,
"e": 2564,
"s": 2561,
"text": "NA"
},
{
"code": null,
"e": 2705,
"s": 2564,
"text": "It returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space."
},
{
"code": null,
"e": 2846,
"s": 2705,
"text": "It returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space."
},
{
"code": null,
"e": 3089,
"s": 2846,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\" Welcome to Tutorialspoint.com \");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.trim() );\n }\n}"
},
{
"code": null,
"e": 3130,
"s": 3089,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3175,
"s": 3130,
"text": "Return Value :Welcome to Tutorialspoint.com\n"
},
{
"code": null,
"e": 3208,
"s": 3175,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3224,
"s": 3208,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3257,
"s": 3224,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3273,
"s": 3257,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3308,
"s": 3273,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3322,
"s": 3308,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3356,
"s": 3322,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3370,
"s": 3356,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3407,
"s": 3370,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3422,
"s": 3407,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3455,
"s": 3422,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3474,
"s": 3455,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3481,
"s": 3474,
"text": " Print"
},
{
"code": null,
"e": 3492,
"s": 3481,
"text": " Add Notes"
}
] |
Singleton Class in C#
|
Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance.
To prevent multiple instances of the class, the private constructor is used.
Let us see an example −
public class Singleton {
static Singleton b = null;
private Singleton() {
}
}
The following is another example displaying how to display Singleton class −
Live Demo
using System;
class Singleton {
public static readonly Singleton _obj = new Singleton();
public void Display() {
Console.WriteLine(true);
}
Singleton() {}
}
class Demo {
public static void Main() {
Singleton._obj.Display();
}
}
True
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance."
},
{
"code": null,
"e": 1268,
"s": 1191,
"text": "To prevent multiple instances of the class, the private constructor is used."
},
{
"code": null,
"e": 1292,
"s": 1268,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1384,
"s": 1292,
"text": "public class Singleton {\n static Singleton b = null;\n private Singleton() {\n } \n}"
},
{
"code": null,
"e": 1461,
"s": 1384,
"text": "The following is another example displaying how to display Singleton class −"
},
{
"code": null,
"e": 1472,
"s": 1461,
"text": " Live Demo"
},
{
"code": null,
"e": 1738,
"s": 1472,
"text": "using System;\n\nclass Singleton {\n public static readonly Singleton _obj = new Singleton();\n \n public void Display() {\n Console.WriteLine(true);\n }\n Singleton() {}\n}\n\nclass Demo {\n public static void Main() {\n Singleton._obj.Display();\n }\n}"
},
{
"code": null,
"e": 1743,
"s": 1738,
"text": "True"
}
] |
Check whether a node is leaf node or not for multiple queries - GeeksforGeeks
|
13 Aug, 2021
Given a tree with N vertices numbered from 0 to N – 1 where 0 is the root node. The task is to check if a node is leaf node or not for multiple queries.Examples:
Input:
0
/ \
1 2
/ \
3 4
/
5
q[] = {0, 3, 4, 5}
Output:
No
Yes
No
Yes
From the graph, 2, 3 and 5 are the only leaf nodes.
Approach: Store the degree of all the vertices in an array degree[]. For each edge from A to B, degree[A] and degree[B] are incremented by 1. Now every node which not a root node and it has a degree of 1 is a leaf node and all the other nodes are not.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to calculate the degree of all the verticesvoid init(int degree[], vector<pair<int, int> > edges, int n){ // Initializing degree of all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.size(); i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesvoid performQueries(vector<pair<int, int> > edges, vector<int> q, int n){ // To store the of degree // of all the vertices int degree[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.size(); i++) { int node = q[i]; if (node == 0) { cout << "No\n"; continue; } // If the current node has 1 degree if (degree[node] == 1) cout << "Yes\n"; else cout << "No\n"; }} // Driver codeint main(){ // Number of vertices int n = 6; // Edges of the tree vector<pair<int, int> > edges = { { 0, 1 }, { 0, 2 }, { 1, 3 }, { 1, 4 }, { 4, 5 } }; // Queries vector<int> q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to calculate the degree// of all the verticesstatic void init(int degree[], pair[] edges, int n){ // Initializing degree of // all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, // degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.length; i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesstatic void performQueries(pair [] edges, int []q, int n){ // To store the of degree // of all the vertices int []degree = new int[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.length; i++) { int node = q[i]; if (node == 0) { System.out.println("No"); continue; } // If the current node has 1 degree if (degree[node] == 1) System.out.println("Yes"); else System.out.println("No"); }} // Driver codepublic static void main(String[] args){ // Number of vertices int n = 6; // Edges of the tree pair[] edges = {new pair(0, 1), new pair(0, 2), new pair(1, 3), new pair(1, 4), new pair(4, 5)}; // Queries int []q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n);}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to calculate the degree# of all the verticesdef init(degree, edges, n) : # Initializing degree of # all the vertices as 0 for i in range(n) : degree[i] = 0; # For each edge from A to B, # degree[A] and degree[B] # are increased by 1 for i in range(len(edges)) : degree[edges[i][0]] += 1; degree[edges[i][1]] += 1; # Function to perform the queriesdef performQueries(edges, q, n) : # To store the of degree # of all the vertices degree = [0] * n; # Calculate the degree for all the vertices init(degree, edges, n); # For every query for i in range(len(q)) : node = q[i]; if (node == 0) : print("No"); continue; # If the current node has 1 degree if (degree[node] == 1) : print("Yes"); else : print("No"); # Driver codeif __name__ == "__main__" : # Number of vertices n = 6; # Edges of the tree edges = [[ 0, 1 ], [ 0, 2 ], [ 1, 3 ], [ 1, 4 ], [ 4, 5 ]]; # Queries q = [ 0, 3, 4, 5 ]; # Perform the queries performQueries(edges, q, n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to calculate the degree// of all the verticesstatic void init(int []degree, pair[] edges, int n){ // Initializing degree of // all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, // degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.Length; i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesstatic void performQueries(pair [] edges, int []q, int n){ // To store the of degree // of all the vertices int []degree = new int[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.Length; i++) { int node = q[i]; if (node == 0) { Console.WriteLine("No"); continue; } // If the current node has 1 degree if (degree[node] == 1) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // Driver codepublic static void Main(String[] args){ // Number of vertices int n = 6; // Edges of the tree pair[] edges = {new pair(0, 1), new pair(0, 2), new pair(1, 3), new pair(1, 4), new pair(4, 5)}; // Queries int []q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Function to calculate the degree of all the verticesfunction init(degree, edges, n){ // Initializing degree of all the vertices as 0 for (var i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, degree[A] and degree[B] // are increased by 1 for (var i = 0; i < edges.length; i++) { degree[edges[i][0]]++; degree[edges[i][1]]++; }} // Function to perform the queriesfunction performQueries( edges, q, n){ // To store the of degree // of all the vertices var degree = Array(n); // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (var i = 0; i < q.length; i++) { var node = q[i]; if (node == 0) { document.write( "No<br>"); continue; } // If the current node has 1 degree if (degree[node] == 1) document.write( "Yes<br>"); else document.write( "No<br>"); }} // Driver code// Number of verticesvar n = 6;// Edges of the treevar edges = [ [ 0, 1 ], [ 0, 2 ], [ 1, 3 ], [ 1, 4 ], [ 4, 5 ]];// Queriesvar q = [ 0, 3, 4, 5 ];// Perform the queriesperformQueries(edges, q, n); </script>
No
Yes
No
Yes
Time complexity: O(n)Auxiliary Space: O(n).
Arrays
Competitive Programming
Data Structures
Technical Scripter
Tree
Data Structures
Arrays
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Window Sliding Technique
Practice for cracking any coding interview
Competitive Programming - A Complete Guide
Arrow operator -> in C/C++ with Examples
Bits manipulation (Important tactics)
Pairs with same Manhattan and Euclidean distance
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 24569,
"s": 24405,
"text": "Given a tree with N vertices numbered from 0 to N – 1 where 0 is the root node. The task is to check if a node is leaf node or not for multiple queries.Examples: "
},
{
"code": null,
"e": 24725,
"s": 24569,
"text": "Input:\n 0\n / \\\n 1 2\n / \\\n3 4 \n /\n 5\nq[] = {0, 3, 4, 5}\nOutput:\nNo\nYes\nNo\nYes\nFrom the graph, 2, 3 and 5 are the only leaf nodes."
},
{
"code": null,
"e": 25031,
"s": 24727,
"text": "Approach: Store the degree of all the vertices in an array degree[]. For each edge from A to B, degree[A] and degree[B] are incremented by 1. Now every node which not a root node and it has a degree of 1 is a leaf node and all the other nodes are not.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25035,
"s": 25031,
"text": "C++"
},
{
"code": null,
"e": 25040,
"s": 25035,
"text": "Java"
},
{
"code": null,
"e": 25048,
"s": 25040,
"text": "Python3"
},
{
"code": null,
"e": 25051,
"s": 25048,
"text": "C#"
},
{
"code": null,
"e": 25062,
"s": 25051,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to calculate the degree of all the verticesvoid init(int degree[], vector<pair<int, int> > edges, int n){ // Initializing degree of all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.size(); i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesvoid performQueries(vector<pair<int, int> > edges, vector<int> q, int n){ // To store the of degree // of all the vertices int degree[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.size(); i++) { int node = q[i]; if (node == 0) { cout << \"No\\n\"; continue; } // If the current node has 1 degree if (degree[node] == 1) cout << \"Yes\\n\"; else cout << \"No\\n\"; }} // Driver codeint main(){ // Number of vertices int n = 6; // Edges of the tree vector<pair<int, int> > edges = { { 0, 1 }, { 0, 2 }, { 1, 3 }, { 1, 4 }, { 4, 5 } }; // Queries vector<int> q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n); return 0;}",
"e": 26478,
"s": 25062,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to calculate the degree// of all the verticesstatic void init(int degree[], pair[] edges, int n){ // Initializing degree of // all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, // degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.length; i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesstatic void performQueries(pair [] edges, int []q, int n){ // To store the of degree // of all the vertices int []degree = new int[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.length; i++) { int node = q[i]; if (node == 0) { System.out.println(\"No\"); continue; } // If the current node has 1 degree if (degree[node] == 1) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // Driver codepublic static void main(String[] args){ // Number of vertices int n = 6; // Edges of the tree pair[] edges = {new pair(0, 1), new pair(0, 2), new pair(1, 3), new pair(1, 4), new pair(4, 5)}; // Queries int []q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n);}} // This code is contributed by Rajput-Ji",
"e": 28235,
"s": 26478,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to calculate the degree# of all the verticesdef init(degree, edges, n) : # Initializing degree of # all the vertices as 0 for i in range(n) : degree[i] = 0; # For each edge from A to B, # degree[A] and degree[B] # are increased by 1 for i in range(len(edges)) : degree[edges[i][0]] += 1; degree[edges[i][1]] += 1; # Function to perform the queriesdef performQueries(edges, q, n) : # To store the of degree # of all the vertices degree = [0] * n; # Calculate the degree for all the vertices init(degree, edges, n); # For every query for i in range(len(q)) : node = q[i]; if (node == 0) : print(\"No\"); continue; # If the current node has 1 degree if (degree[node] == 1) : print(\"Yes\"); else : print(\"No\"); # Driver codeif __name__ == \"__main__\" : # Number of vertices n = 6; # Edges of the tree edges = [[ 0, 1 ], [ 0, 2 ], [ 1, 3 ], [ 1, 4 ], [ 4, 5 ]]; # Queries q = [ 0, 3, 4, 5 ]; # Perform the queries performQueries(edges, q, n); # This code is contributed by AnkitRai01",
"e": 29463,
"s": 28235,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to calculate the degree// of all the verticesstatic void init(int []degree, pair[] edges, int n){ // Initializing degree of // all the vertices as 0 for (int i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, // degree[A] and degree[B] // are increased by 1 for (int i = 0; i < edges.Length; i++) { degree[edges[i].first]++; degree[edges[i].second]++; }} // Function to perform the queriesstatic void performQueries(pair [] edges, int []q, int n){ // To store the of degree // of all the vertices int []degree = new int[n]; // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (int i = 0; i < q.Length; i++) { int node = q[i]; if (node == 0) { Console.WriteLine(\"No\"); continue; } // If the current node has 1 degree if (degree[node] == 1) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // Driver codepublic static void Main(String[] args){ // Number of vertices int n = 6; // Edges of the tree pair[] edges = {new pair(0, 1), new pair(0, 2), new pair(1, 3), new pair(1, 4), new pair(4, 5)}; // Queries int []q = { 0, 3, 4, 5 }; // Perform the queries performQueries(edges, q, n);}} // This code is contributed by 29AjayKumar",
"e": 31235,
"s": 29463,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to calculate the degree of all the verticesfunction init(degree, edges, n){ // Initializing degree of all the vertices as 0 for (var i = 0; i < n; i++) { degree[i] = 0; } // For each edge from A to B, degree[A] and degree[B] // are increased by 1 for (var i = 0; i < edges.length; i++) { degree[edges[i][0]]++; degree[edges[i][1]]++; }} // Function to perform the queriesfunction performQueries( edges, q, n){ // To store the of degree // of all the vertices var degree = Array(n); // Calculate the degree for all the vertices init(degree, edges, n); // For every query for (var i = 0; i < q.length; i++) { var node = q[i]; if (node == 0) { document.write( \"No<br>\"); continue; } // If the current node has 1 degree if (degree[node] == 1) document.write( \"Yes<br>\"); else document.write( \"No<br>\"); }} // Driver code// Number of verticesvar n = 6;// Edges of the treevar edges = [ [ 0, 1 ], [ 0, 2 ], [ 1, 3 ], [ 1, 4 ], [ 4, 5 ]];// Queriesvar q = [ 0, 3, 4, 5 ];// Perform the queriesperformQueries(edges, q, n); </script>",
"e": 32485,
"s": 31235,
"text": null
},
{
"code": null,
"e": 32499,
"s": 32485,
"text": "No\nYes\nNo\nYes"
},
{
"code": null,
"e": 32547,
"s": 32501,
"text": "Time complexity: O(n)Auxiliary Space: O(n). "
},
{
"code": null,
"e": 32554,
"s": 32547,
"text": "Arrays"
},
{
"code": null,
"e": 32578,
"s": 32554,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32594,
"s": 32578,
"text": "Data Structures"
},
{
"code": null,
"e": 32613,
"s": 32594,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32618,
"s": 32613,
"text": "Tree"
},
{
"code": null,
"e": 32634,
"s": 32618,
"text": "Data Structures"
},
{
"code": null,
"e": 32641,
"s": 32634,
"text": "Arrays"
},
{
"code": null,
"e": 32646,
"s": 32641,
"text": "Tree"
},
{
"code": null,
"e": 32744,
"s": 32646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32753,
"s": 32744,
"text": "Comments"
},
{
"code": null,
"e": 32766,
"s": 32753,
"text": "Old Comments"
},
{
"code": null,
"e": 32815,
"s": 32766,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32835,
"s": 32815,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 32873,
"s": 32835,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32958,
"s": 32873,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 32983,
"s": 32958,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33026,
"s": 32983,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 33069,
"s": 33026,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 33110,
"s": 33069,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 33148,
"s": 33110,
"text": "Bits manipulation (Important tactics)"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.