title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Permutation and Combination in Java
|
Permutation and Combination are a part of Combinatorics. Permutation is the different arrangements that a set of elements can make if the elements are taken one at a time, some at a time or all at a time. Combination is is the different ways of selecting elements if the elements are taken one at a time, some at a time or all at a time.
An example of this is given as follows −
Permutation = factorial(n) / factorial(n-r);
Combination = factorial(n) / (factorial(r) * factorial(n-r));
n = 5
r = 3
Permutation = 60
Combination = 10
A program that demonstrates this is given as follows −
Live Demo
public class Example {
static int factorial(int n) {
int fact = 1;
int i = 1;
while(i <= n) {
fact *= i;
i++;
}
return fact;
}
public static void main(String args[]) {
int n = 7, r = 3, comb, per;
per = factorial(n) / factorial(n-r);
System.out.println("Permutation: " + per);
comb = factorial(n) / (factorial(r) * factorial(n-r));
System.out.println("Combination: " + comb);
}
}
The output of the above program is as follows −
Permutation: 210
Combination: 35
Now let us understand the above program.
The function factorial finds the factorial of the number n using a while loop. Then it returns fact. The code snippet that demonstrates this is given as follows −
static int factorial(int n) {
int fact = 1;
int i = 1;
while(i <= n) {
fact *= i;
i++;
}
return fact;
}
In the function main(), the permutation and combination of n and r are found using their respective formulas. Then the results are displayed. The code snippet that demonstrates this is given as follows −
public static void main(String args[]) {
int n = 7, r = 3, comb, per;
per = factorial(n) / factorial(n-r);
System.out.println("Permutation: " + per);
comb = factorial(n) / (factorial(r) * factorial(n-r));
System.out.println("Combination: " + comb);
}
|
[
{
"code": null,
"e": 1525,
"s": 1187,
"text": "Permutation and Combination are a part of Combinatorics. Permutation is the different arrangements that a set of elements can make if the elements are taken one at a time, some at a time or all at a time. Combination is is the different ways of selecting elements if the elements are taken one at a time, some at a time or all at a time."
},
{
"code": null,
"e": 1566,
"s": 1525,
"text": "An example of this is given as follows −"
},
{
"code": null,
"e": 1719,
"s": 1566,
"text": "Permutation = factorial(n) / factorial(n-r);\nCombination = factorial(n) / (factorial(r) * factorial(n-r));\nn = 5\nr = 3\nPermutation = 60\nCombination = 10"
},
{
"code": null,
"e": 1774,
"s": 1719,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1785,
"s": 1774,
"text": " Live Demo"
},
{
"code": null,
"e": 2255,
"s": 1785,
"text": "public class Example {\n static int factorial(int n) {\n int fact = 1;\n int i = 1;\n while(i <= n) {\n fact *= i;\n i++;\n }\n return fact;\n }\n public static void main(String args[]) {\n int n = 7, r = 3, comb, per;\n per = factorial(n) / factorial(n-r);\n System.out.println(\"Permutation: \" + per);\n comb = factorial(n) / (factorial(r) * factorial(n-r));\n System.out.println(\"Combination: \" + comb);\n }\n}"
},
{
"code": null,
"e": 2303,
"s": 2255,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2336,
"s": 2303,
"text": "Permutation: 210\nCombination: 35"
},
{
"code": null,
"e": 2377,
"s": 2336,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2540,
"s": 2377,
"text": "The function factorial finds the factorial of the number n using a while loop. Then it returns fact. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2671,
"s": 2540,
"text": "static int factorial(int n) {\n int fact = 1;\n int i = 1;\n while(i <= n) {\n fact *= i;\n i++;\n }\n return fact;\n}"
},
{
"code": null,
"e": 2875,
"s": 2671,
"text": "In the function main(), the permutation and combination of n and r are found using their respective formulas. Then the results are displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 3141,
"s": 2875,
"text": "public static void main(String args[]) {\n int n = 7, r = 3, comb, per;\n per = factorial(n) / factorial(n-r);\n System.out.println(\"Permutation: \" + per);\n comb = factorial(n) / (factorial(r) * factorial(n-r));\n System.out.println(\"Combination: \" + comb);\n}"
}
] |
Setting up the environment in Java
|
27 May, 2022
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 17. Below are the environment settings for both Linux and Windows. JVM, JRE, and JDK three are all platform-dependent because the configuration of each Operating System is different. But, Java is platform-independent. Few things must be clear before setting up the environment which can better be perceived from the below image provided as follows:
JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.
JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs and is intended for end-users. JRE can be viewed as a subset of JDK.
JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms.
Now let us discuss the steps for setting up a Java environment with visual aids. Let’s use the Windows operating system to illustrate visual aids.
Steps: Here we will be proposing steps for three different operating systems as listed:
Windows operating systemLinux operating systemmacOS operating system
Windows operating system
Linux operating system
macOS operating system
Steps for setting the environment in Windows operating system are as follows:
Step 1: Java8 JDK is available at Download Java 8. Click the second last link for Windows(32 bit) and the last link for Windows(64 bit) as highlighted below.
Step 2: After download, run the .exe file and follow the instructions to install Java on your machine. Once you install Java on your machine, you have to set up the environment variable.
Step 3: Go to Control Panel -> System and Security -> System. Under the Advanced System Setting option click on Environment Variables as highlighted below.
Step 4: Now, you have to alter the “Path” variable under System variables so that it also contains the path to the Java environment. Select the “Path” variable and click on the Edit button as highlighted below.
Step 5: You will see a list of different paths, click on the New button, and then add the path where java is installed. By default, java is installed in “C:\Program Files\Java\jdk\bin” folder OR “C:\Program Files(x86)\Java\jdk\bin”. In case, you have installed java at any other location, then add that path.
Step 6: Click on OK, Save the settings, and you are done !! Now to check whether the installation is done correctly, open the command prompt and type javac -version. You will see that java is running on your machine.
Note: To make sure whether the compiler is set up, type javac in the command prompt. You will see a list related to javac.
In Linux, there are several ways to install java. But we will refer to the simplest and easy way to install java using a terminal. For Linux, we will install OpenJDK. OpenJDK is a free and open-source implementation of the Java programming language. Steps for setting the environment in the Linux operating system are as follows:
Step 1: Go to Application -> Accessories -> Terminal.
Step 2: Type command as below as follows:
sudo apt-get install openjdk-8-jdk
Step 3: For the “JAVA_HOME” (Environment Variable) type command as shown below, in “Terminal” using your installation path...(Note: the default path is as shown, but if you have to install OpenJDK at another location then set that path.)
export JAVA_HOME = /usr/lib/jvm/java-8-openjdk
Step 4: For “PATH” (Environment Value) type command as shown below, in “Terminal” using your installation path...Note: the default path is as shown, but if you have to install OpenJDK at another location then set that path.)
export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin
Note: We are done setting up the environment in Java for Linux OS.
Note: Now to check whether the installation is done correctly, type java -version in the Terminal. You will see that java is running on your machine.
Notepad/gedit : They are simple text-editors for writing java programs. Notepad is available on Windows and gedit is available on Linux.
Eclipse IDE : It is the most widely used IDE(Integrated Development Environment) for developing software in java. You can download Eclipse.
Step 1: Open the terminal from the application folder or simply press the “command” and “shift” key together and write initials of the terminal and press enter.
It will be good to have package manager such as homebrew installed in your machine as we can operate to install any software from here itself simply by using terminal commands.
Step 2: Now in order to configure first write the command ‘java –version ‘ where the message below it will pop that there is no
java --version
javac --version
Note: If it was set up then you would have been getting the version displayed on the screen as it is shown below where in that machine it was already set up. So remember to cross-check in your machine once you have successfully set it up in yours.
Step 2: Once we are done with installing JDK now let us move on setting up the java_home environment variable for that you will have to look into something called s ‘bash_profie’ using the below command
ls -al
You will notice that in your terminal there will be no bash_profile set but it is shown below so here in this machine it is already set up. In order to set up if not there we have to create it for which lets us prior seek into java home variables whether it is set up or not.
Step 3: Setting up the home java variable. Using the below command to check or setup if not installed as follows on the terminal:
echo $JAVA_HOME
If it is showing blank then the java home variable is not set up as perceived from the above image.
Step 4: Installing bash_profile
Make sure to go to the root folder in the terminal and write the command ‘touch ./bash_profile ‘
Now you will see that bash-profile s created which is as shown in step2 in your machine which hone can verify by writing command as follows:
ls -al
Step 5: Edit the .bash_profile created and for java, you just have to write the command marked in below media and provided below as follows:
export JAVA_HOME=$(/usr/libexec/java_home)
// No need to remember this command
Save this file and relaunch the terminal by closing it.
Step 5: Verifying whether it is installed by entering the following two commands
source .bash_profile
echo $JAVA_HOME
Now from the above media, we can see the java variable is all set to go as earlier there was a blank therein the above media.
SahilKhanna2
imdp
munmunpink
sahilkansal09
vaibhavsinghtanwar
solankimayank
mayurrokade09
avtarkumar719
prashanthpai
rajnimehta7838
java-basics
Java
School Programming
TechTips
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 678,
"s": 53,
"text": "Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 17. Below are the environment settings for both Linux and Windows. JVM, JRE, and JDK three are all platform-dependent because the configuration of each Operating System is different. But, Java is platform-independent. Few things must be clear before setting up the environment which can better be perceived from the below image provided as follows:"
},
{
"code": null,
"e": 833,
"s": 678,
"text": "JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger."
},
{
"code": null,
"e": 1008,
"s": 833,
"text": "JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs and is intended for end-users. JRE can be viewed as a subset of JDK."
},
{
"code": null,
"e": 1223,
"s": 1008,
"text": "JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms."
},
{
"code": null,
"e": 1370,
"s": 1223,
"text": "Now let us discuss the steps for setting up a Java environment with visual aids. Let’s use the Windows operating system to illustrate visual aids."
},
{
"code": null,
"e": 1458,
"s": 1370,
"text": "Steps: Here we will be proposing steps for three different operating systems as listed:"
},
{
"code": null,
"e": 1527,
"s": 1458,
"text": "Windows operating systemLinux operating systemmacOS operating system"
},
{
"code": null,
"e": 1552,
"s": 1527,
"text": "Windows operating system"
},
{
"code": null,
"e": 1575,
"s": 1552,
"text": "Linux operating system"
},
{
"code": null,
"e": 1598,
"s": 1575,
"text": "macOS operating system"
},
{
"code": null,
"e": 1677,
"s": 1598,
"text": "Steps for setting the environment in Windows operating system are as follows: "
},
{
"code": null,
"e": 1837,
"s": 1677,
"text": "Step 1: Java8 JDK is available at Download Java 8. Click the second last link for Windows(32 bit) and the last link for Windows(64 bit) as highlighted below. "
},
{
"code": null,
"e": 2024,
"s": 1837,
"text": "Step 2: After download, run the .exe file and follow the instructions to install Java on your machine. Once you install Java on your machine, you have to set up the environment variable."
},
{
"code": null,
"e": 2182,
"s": 2024,
"text": "Step 3: Go to Control Panel -> System and Security -> System. Under the Advanced System Setting option click on Environment Variables as highlighted below. "
},
{
"code": null,
"e": 2395,
"s": 2182,
"text": "Step 4: Now, you have to alter the “Path” variable under System variables so that it also contains the path to the Java environment. Select the “Path” variable and click on the Edit button as highlighted below. "
},
{
"code": null,
"e": 2705,
"s": 2395,
"text": "Step 5: You will see a list of different paths, click on the New button, and then add the path where java is installed. By default, java is installed in “C:\\Program Files\\Java\\jdk\\bin” folder OR “C:\\Program Files(x86)\\Java\\jdk\\bin”. In case, you have installed java at any other location, then add that path. "
},
{
"code": null,
"e": 2922,
"s": 2705,
"text": "Step 6: Click on OK, Save the settings, and you are done !! Now to check whether the installation is done correctly, open the command prompt and type javac -version. You will see that java is running on your machine."
},
{
"code": null,
"e": 3045,
"s": 2922,
"text": "Note: To make sure whether the compiler is set up, type javac in the command prompt. You will see a list related to javac."
},
{
"code": null,
"e": 3376,
"s": 3045,
"text": "In Linux, there are several ways to install java. But we will refer to the simplest and easy way to install java using a terminal. For Linux, we will install OpenJDK. OpenJDK is a free and open-source implementation of the Java programming language. Steps for setting the environment in the Linux operating system are as follows: "
},
{
"code": null,
"e": 3430,
"s": 3376,
"text": "Step 1: Go to Application -> Accessories -> Terminal."
},
{
"code": null,
"e": 3472,
"s": 3430,
"text": "Step 2: Type command as below as follows:"
},
{
"code": null,
"e": 3507,
"s": 3472,
"text": "sudo apt-get install openjdk-8-jdk"
},
{
"code": null,
"e": 3746,
"s": 3507,
"text": "Step 3: For the “JAVA_HOME” (Environment Variable) type command as shown below, in “Terminal” using your installation path...(Note: the default path is as shown, but if you have to install OpenJDK at another location then set that path.) "
},
{
"code": null,
"e": 3793,
"s": 3746,
"text": "export JAVA_HOME = /usr/lib/jvm/java-8-openjdk"
},
{
"code": null,
"e": 4019,
"s": 3793,
"text": "Step 4: For “PATH” (Environment Value) type command as shown below, in “Terminal” using your installation path...Note: the default path is as shown, but if you have to install OpenJDK at another location then set that path.) "
},
{
"code": null,
"e": 4071,
"s": 4019,
"text": "export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin"
},
{
"code": null,
"e": 4138,
"s": 4071,
"text": "Note: We are done setting up the environment in Java for Linux OS."
},
{
"code": null,
"e": 4288,
"s": 4138,
"text": "Note: Now to check whether the installation is done correctly, type java -version in the Terminal. You will see that java is running on your machine."
},
{
"code": null,
"e": 4425,
"s": 4288,
"text": "Notepad/gedit : They are simple text-editors for writing java programs. Notepad is available on Windows and gedit is available on Linux."
},
{
"code": null,
"e": 4565,
"s": 4425,
"text": "Eclipse IDE : It is the most widely used IDE(Integrated Development Environment) for developing software in java. You can download Eclipse."
},
{
"code": null,
"e": 4728,
"s": 4565,
"text": "Step 1: Open the terminal from the application folder or simply press the “command” and “shift” key together and write initials of the terminal and press enter. "
},
{
"code": null,
"e": 4905,
"s": 4728,
"text": "It will be good to have package manager such as homebrew installed in your machine as we can operate to install any software from here itself simply by using terminal commands."
},
{
"code": null,
"e": 5036,
"s": 4905,
"text": "Step 2: Now in order to configure first write the command ‘java –version ‘ where the message below it will pop that there is no "
},
{
"code": null,
"e": 5068,
"s": 5036,
"text": "java --version\njavac --version "
},
{
"code": null,
"e": 5316,
"s": 5068,
"text": "Note: If it was set up then you would have been getting the version displayed on the screen as it is shown below where in that machine it was already set up. So remember to cross-check in your machine once you have successfully set it up in yours."
},
{
"code": null,
"e": 5519,
"s": 5316,
"text": "Step 2: Once we are done with installing JDK now let us move on setting up the java_home environment variable for that you will have to look into something called s ‘bash_profie’ using the below command"
},
{
"code": null,
"e": 5526,
"s": 5519,
"text": "ls -al"
},
{
"code": null,
"e": 5803,
"s": 5526,
"text": "You will notice that in your terminal there will be no bash_profile set but it is shown below so here in this machine it is already set up. In order to set up if not there we have to create it for which lets us prior seek into java home variables whether it is set up or not. "
},
{
"code": null,
"e": 5933,
"s": 5803,
"text": "Step 3: Setting up the home java variable. Using the below command to check or setup if not installed as follows on the terminal:"
},
{
"code": null,
"e": 5949,
"s": 5933,
"text": "echo $JAVA_HOME"
},
{
"code": null,
"e": 6049,
"s": 5949,
"text": "If it is showing blank then the java home variable is not set up as perceived from the above image."
},
{
"code": null,
"e": 6082,
"s": 6049,
"text": "Step 4: Installing bash_profile "
},
{
"code": null,
"e": 6179,
"s": 6082,
"text": "Make sure to go to the root folder in the terminal and write the command ‘touch ./bash_profile ‘"
},
{
"code": null,
"e": 6320,
"s": 6179,
"text": "Now you will see that bash-profile s created which is as shown in step2 in your machine which hone can verify by writing command as follows:"
},
{
"code": null,
"e": 6328,
"s": 6320,
"text": "ls -al "
},
{
"code": null,
"e": 6469,
"s": 6328,
"text": "Step 5: Edit the .bash_profile created and for java, you just have to write the command marked in below media and provided below as follows:"
},
{
"code": null,
"e": 6550,
"s": 6469,
"text": "export JAVA_HOME=$(/usr/libexec/java_home)\n// No need to remember this command "
},
{
"code": null,
"e": 6607,
"s": 6550,
"text": "Save this file and relaunch the terminal by closing it. "
},
{
"code": null,
"e": 6690,
"s": 6607,
"text": " Step 5: Verifying whether it is installed by entering the following two commands "
},
{
"code": null,
"e": 6727,
"s": 6690,
"text": "source .bash_profile\necho $JAVA_HOME"
},
{
"code": null,
"e": 6853,
"s": 6727,
"text": "Now from the above media, we can see the java variable is all set to go as earlier there was a blank therein the above media."
},
{
"code": null,
"e": 6866,
"s": 6853,
"text": "SahilKhanna2"
},
{
"code": null,
"e": 6871,
"s": 6866,
"text": "imdp"
},
{
"code": null,
"e": 6882,
"s": 6871,
"text": "munmunpink"
},
{
"code": null,
"e": 6896,
"s": 6882,
"text": "sahilkansal09"
},
{
"code": null,
"e": 6915,
"s": 6896,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 6929,
"s": 6915,
"text": "solankimayank"
},
{
"code": null,
"e": 6943,
"s": 6929,
"text": "mayurrokade09"
},
{
"code": null,
"e": 6957,
"s": 6943,
"text": "avtarkumar719"
},
{
"code": null,
"e": 6970,
"s": 6957,
"text": "prashanthpai"
},
{
"code": null,
"e": 6985,
"s": 6970,
"text": "rajnimehta7838"
},
{
"code": null,
"e": 6997,
"s": 6985,
"text": "java-basics"
},
{
"code": null,
"e": 7002,
"s": 6997,
"text": "Java"
},
{
"code": null,
"e": 7021,
"s": 7002,
"text": "School Programming"
},
{
"code": null,
"e": 7030,
"s": 7021,
"text": "TechTips"
},
{
"code": null,
"e": 7035,
"s": 7030,
"text": "Java"
},
{
"code": null,
"e": 7133,
"s": 7035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7169,
"s": 7133,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 7213,
"s": 7169,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 7238,
"s": 7213,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7269,
"s": 7238,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 7284,
"s": 7269,
"text": "Stream In Java"
},
{
"code": null,
"e": 7302,
"s": 7284,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7327,
"s": 7302,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7343,
"s": 7327,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "Introduction To PYTHON"
}
] |
Program to check if a String in Java contains only whitespaces
|
22 Jan, 2020
Given a string str, the task is to check if this string contains only whitespaces or some text, in Java.
Examples:
Input: str = " "
Output: True
Input: str = "GFG"
Output: False
Approach:
Get the String to be checked in str
We can use the trim() method of String class to remove the leading whitespaces in the string.Syntax:str.trim()
str.trim()
Then we can use the isEmpty() method of String class to check if the resultant string is empty or not. If the string contained only whitespaces, then this method will return trueSyntax:str.isEmpty()
str.isEmpty()
Combine the use of both methods using Method Chaining.str.trim().isEmpty();
str.trim().isEmpty();
Print true if the above condition is true. Else print false.
Below is the implementation of the above approach:
// Java Program to check if// the String is not all whitespaces class GFG { // Function to check if the String is all whitespaces public static boolean isStringAllWhiteSpace(String str) { // Remove the leading whitespaces using trim() // and then check if this string is empty if (str.trim().isEmpty()) return true; else return false; } // Driver code public static void main(String[] args) { String str1 = "GeeksforGeeks"; String str2 = " "; System.out.println("Is string [" + str1 + "] only whitespaces? " + isStringAllWhiteSpace(str1)); System.out.println("Is string [" + str2 + "] only whitespaces? " + isStringAllWhiteSpace(str2)); }}
Is string [GeeksforGeeks] only whitespaces? false
Is string [ ] only whitespaces? true
Java-String-Programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jan, 2020"
},
{
"code": null,
"e": 157,
"s": 52,
"text": "Given a string str, the task is to check if this string contains only whitespaces or some text, in Java."
},
{
"code": null,
"e": 167,
"s": 157,
"text": "Examples:"
},
{
"code": null,
"e": 246,
"s": 167,
"text": "Input: str = \" \" \nOutput: True\n\nInput: str = \"GFG\"\nOutput: False\n"
},
{
"code": null,
"e": 256,
"s": 246,
"text": "Approach:"
},
{
"code": null,
"e": 292,
"s": 256,
"text": "Get the String to be checked in str"
},
{
"code": null,
"e": 404,
"s": 292,
"text": "We can use the trim() method of String class to remove the leading whitespaces in the string.Syntax:str.trim()\n"
},
{
"code": null,
"e": 416,
"s": 404,
"text": "str.trim()\n"
},
{
"code": null,
"e": 616,
"s": 416,
"text": "Then we can use the isEmpty() method of String class to check if the resultant string is empty or not. If the string contained only whitespaces, then this method will return trueSyntax:str.isEmpty()\n"
},
{
"code": null,
"e": 631,
"s": 616,
"text": "str.isEmpty()\n"
},
{
"code": null,
"e": 708,
"s": 631,
"text": "Combine the use of both methods using Method Chaining.str.trim().isEmpty();\n"
},
{
"code": null,
"e": 731,
"s": 708,
"text": "str.trim().isEmpty();\n"
},
{
"code": null,
"e": 792,
"s": 731,
"text": "Print true if the above condition is true. Else print false."
},
{
"code": null,
"e": 843,
"s": 792,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java Program to check if// the String is not all whitespaces class GFG { // Function to check if the String is all whitespaces public static boolean isStringAllWhiteSpace(String str) { // Remove the leading whitespaces using trim() // and then check if this string is empty if (str.trim().isEmpty()) return true; else return false; } // Driver code public static void main(String[] args) { String str1 = \"GeeksforGeeks\"; String str2 = \" \"; System.out.println(\"Is string [\" + str1 + \"] only whitespaces? \" + isStringAllWhiteSpace(str1)); System.out.println(\"Is string [\" + str2 + \"] only whitespaces? \" + isStringAllWhiteSpace(str2)); }}",
"e": 1711,
"s": 843,
"text": null
},
{
"code": null,
"e": 1812,
"s": 1711,
"text": "Is string [GeeksforGeeks] only whitespaces? false\nIs string [ ] only whitespaces? true\n"
},
{
"code": null,
"e": 1833,
"s": 1812,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 1838,
"s": 1833,
"text": "Java"
},
{
"code": null,
"e": 1846,
"s": 1838,
"text": "Strings"
},
{
"code": null,
"e": 1854,
"s": 1846,
"text": "Strings"
},
{
"code": null,
"e": 1859,
"s": 1854,
"text": "Java"
}
] |
Bitmasking and Dynamic Programming | Set-2 (TSP)
|
25 Apr, 2022
In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem “Traveling Salesman Problem”.Before solving the problem, we assume that the reader has the knowledge of
DP and formation of DP transition relation
Bitmasking in DP
Traveling Salesman problem
To understand this concept lets consider the below problem : Problem Description:
Given a 2D grid of characters representing
a town where '*' represents the
houses, '#' represents the blockage,
'.' represents the vacant street
area. Currently you are (0, 0) position.
Our task is to determine the minimum distance
to be moved to visit all the houses and return
to our initial position at (0, 0). You can
only move to adjacent cells that share exactly
1 edge with the current cell.
The above problem is the well-known Travelling Salesman Problem.The first part is to calculate the minimum distance between the two cells. We can do it by simply using a BFS as all the distances are unit distance. To optimize our solution we will be pre-calculating the distances taking the initial location and the location of the houses as the source point for our BFS.Each BFS traversal takes O(size of grid) time. Therefore, it is O(X * size_of_grid) for overall pre-calculation, where X = number of houses + 1 (initial position)Now let’s think of a DP state So we will be needing to track the visited houses and the last visited house to uniquely identify a state in this problem.Therefore, we will be taking dp[index][mask] as our DP state.
Here, index : tells us the location of current housemask : tells us the houses that are visited ( if ith bit is set in mask then this means that the ith dirty tile is cleaned)
Whereas dp[index][mask] will tell us the minimum distance to visit X(number of set bits in mask) houses corresponding to their order of their occurrence in the mask where the last visited house is house at location index.State transition relationSo our initial state will be dp[0][0] this tells that we are currently at initial tile that is our initial location and mask is 0 that states that no house is visited till now.And our final destination state will be dp[any index][LIMIT_MASK], here LIMIT_MASK = (1<<N) – 1 and N = number of houses.Therefore our DP state transition can be stated as
dp(curr_idx)(curr_mask) = min{
for idx : off_bits_in_curr_mask
dp(idx)(cur_mask.set_bit(idx)) + dist[curr_idx][idx]
}
The above relation can be visualized as the minimum distance to visit all the houses by standing at curr_idx house and by already visiting cur_mask houses is equal to min of distance between the curr_idx house and idx house + minimum distance to visit all the houses by standing at idx house and by already visiting ( cur_mask | (1 <<idx) ) houses.So, here we iterate over all possible idx values such that cur_mask has ith bit as 0 that tells us that ith house is not visited.Whenever we have our mask = LIMIT_MASK, this means that we have visited all the houses in the town. So, we will add the distance from the last visited town (i.e the town at cur_idx position) to the initial position (0, 0).The C++ program for the above implementation is given below:
C++
#include <bits/stdc++.h>using namespace std; #define INF 99999999#define MAXR 12#define MAXC 12#define MAXMASK 2048#define MAXHOUSE 12 // stores distance taking source// as every dirty tileint dist[MAXR][MAXC][MAXHOUSE]; // memoization for dp statesint dp[MAXHOUSE][MAXMASK]; // stores coordinates for// dirty tilesvector < pair < int, int > > dirty; // Directionsint X[] = {-1, 0, 0, 1};int Y[] = {0, 1, -1, 0}; char arr[21][21]; // len : number of dirty tiles + 1// limit : 2 ^ len -1// r, c : number of rows and columnsint len, limit, r, c; // Returns true if current position// is safe to visit// else returns false// Time Complexity : O(1)bool safe(int x, int y){ if (x >= r or y>= c or x<0 or y<0) return false; if (arr[x][y] == '#') return false; return true;} // runs BFS traversal at tile idx// calculates distance to every cell// in the grid// Time Complexity : O(r*c)void getDist(int idx){ // visited array to track visited cells bool vis[21][21]; memset(vis, false, sizeof(vis)); // getting current position int cx = dirty[idx].first; int cy = dirty[idx].second; // initializing queue for bfs queue < pair < int, int > > pq; pq.push({cx, cy}); // initializing the dist to max // because some cells cannot be visited // by taking source cell as idx for (int i = 0;i<= r;i++) for (int j = 0;j<= c;j++) dist[i][j][idx] = INF; // base conditions vis[cx][cy] = true; dist[cx][cy][idx] = 0; while (! pq.empty()) { auto x = pq.front(); pq.pop(); for (int i = 0;i<4;i++) { cx = x.first + X[i]; cy = x.second + Y[i]; if (safe(cx, cy)) { if (vis[cx][cy]) continue; vis[cx][cy] = true; dist[cx][cy][idx] = dist[x.first][x.second][idx] + 1; pq.push({cx, cy}); } } }} // Dynamic Programming state transition recursion// with memoization. Time Complexity: O(n*n*2 ^ n)int solve(int idx, int mask){ // goal state if (mask == limit) return dist[0][0][idx]; // if already visited state if (dp[idx][mask] != -1) return dp[idx][mask]; int ret = INT_MAX; // state transition relation for (int i = 0;i<len;i++) { if ((mask & (1<<i)) == 0) { int newMask = mask | (1<<i); ret = min( ret, solve(i, newMask) + dist[dirty[i].first][dirty[i].second][idx]); } } // adding memoization and returning return dp[idx][mask] = ret;} void init(){ // initializing containers memset(dp, -1, sizeof(dp)); dirty.clear(); // populating dirty tile positions for (int i = 0;i<r;i++) for (int j = 0;j<c;j++) { if (arr[i][j] == '*') dirty.push_back({i, j}); } // inserting ronot's location at the // beginning of the dirty tile dirty.insert(dirty.begin(), {0, 0}); len = dirty.size(); // calculating LIMIT_MASK limit = (1<<len) - 1; // precalculating distances from all // dirty tiles to each cell in the grid for (int i = 0;i<len;i++) getDist(i);} int main(int argc, char const *argv[]){ // Test case #1: // .....*. // ...#... // .*.#.*. // ....... char A[4][7] = { {'.', '.', '.', '.', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'}, {'.', '*', '.', '#', '.', '*', '.'}, {'.', '.', '.', '.', '.', '.', '.'} }; r = 4; c = 7; cout << "The given grid : " << endl; for (int i = 0;i<r;i++) { for (int j = 0;j<c;j++) { cout << A[i][j] << " "; arr[i][j] = A[i][j]; } cout << endl; } // - initialization // - precalculations init(); int ans = solve(0, 1); cout << "Minimum distance for the given grid : "; cout << ans << endl; // Test Case #2 // ...#... // ...#.*. // ...#... // .*.#.*. // ...#... char Arr[5][7] = { {'.', '.', '.', '#', '.', '.', '.'}, {'.', '.', '.', '#', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'}, {'.', '*', '.', '#', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'} }; r = 5; c = 7; cout << "The given grid : " << endl; for (int i = 0;i<r;i++) { for (int j = 0;j<c;j++) { cout << Arr[i][j] << " "; arr[i][j] = Arr[i][j]; } cout << endl; } // - initialization // - precalculations init(); ans = solve(0, 1); cout << "Minimum distance for the given grid : "; if (ans >= INF) cout << "not possible" << endl; else cout << ans << endl; return 0;}
Output:
The given grid :
. . . . . * .
. . . # . . .
. * . # . * .
. . . . . . .
Minimum distance for the given grid : 16
The given grid :
. . . # . . .
. . . # . * .
. . . # . . .
. * . # . * .
. . . # . . .
Minimum distance for the given grid : not possible
Note:We have used the initial state to be dp[0][1] because we have pushed the start location at the first position in the container of houses. Hence, our Bit Mask will be 1 as the 0th bit is set i.e we have visited the starting location for our trip.Time Complexity:Consider the number of houses to be n. So, there are n * (2n) states and at every state, we are looping over n houses to transit over to next state and because of memoization we are doing this looping transition only once for each state. Therefore, our Time Complexity is O(n2 * 2n).Recommended:
http://www.spoj.com/problems/CLEANRBT/
https://www.youtube.com/watch?v=-JjA4BLQyqE
This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
ManasChhabra2
erikbrobyn
gabaa406
saurabh1990aror
simmytarika5
Bit Magic
Dynamic Programming
Dynamic Programming
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 296,
"s": 54,
"text": "In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem “Traveling Salesman Problem”.Before solving the problem, we assume that the reader has the knowledge of "
},
{
"code": null,
"e": 339,
"s": 296,
"text": "DP and formation of DP transition relation"
},
{
"code": null,
"e": 356,
"s": 339,
"text": "Bitmasking in DP"
},
{
"code": null,
"e": 383,
"s": 356,
"text": "Traveling Salesman problem"
},
{
"code": null,
"e": 467,
"s": 383,
"text": "To understand this concept lets consider the below problem : Problem Description: "
},
{
"code": null,
"e": 873,
"s": 467,
"text": "Given a 2D grid of characters representing \na town where '*' represents the \nhouses, '#' represents the blockage, \n'.' represents the vacant street \narea. Currently you are (0, 0) position.\n\nOur task is to determine the minimum distance \nto be moved to visit all the houses and return\nto our initial position at (0, 0). You can \nonly move to adjacent cells that share exactly\n1 edge with the current cell."
},
{
"code": null,
"e": 1622,
"s": 873,
"text": "The above problem is the well-known Travelling Salesman Problem.The first part is to calculate the minimum distance between the two cells. We can do it by simply using a BFS as all the distances are unit distance. To optimize our solution we will be pre-calculating the distances taking the initial location and the location of the houses as the source point for our BFS.Each BFS traversal takes O(size of grid) time. Therefore, it is O(X * size_of_grid) for overall pre-calculation, where X = number of houses + 1 (initial position)Now let’s think of a DP state So we will be needing to track the visited houses and the last visited house to uniquely identify a state in this problem.Therefore, we will be taking dp[index][mask] as our DP state. "
},
{
"code": null,
"e": 1800,
"s": 1622,
"text": "Here, index : tells us the location of current housemask : tells us the houses that are visited ( if ith bit is set in mask then this means that the ith dirty tile is cleaned) "
},
{
"code": null,
"e": 2396,
"s": 1800,
"text": "Whereas dp[index][mask] will tell us the minimum distance to visit X(number of set bits in mask) houses corresponding to their order of their occurrence in the mask where the last visited house is house at location index.State transition relationSo our initial state will be dp[0][0] this tells that we are currently at initial tile that is our initial location and mask is 0 that states that no house is visited till now.And our final destination state will be dp[any index][LIMIT_MASK], here LIMIT_MASK = (1<<N) – 1 and N = number of houses.Therefore our DP state transition can be stated as "
},
{
"code": null,
"e": 2525,
"s": 2396,
"text": "dp(curr_idx)(curr_mask) = min{\n for idx : off_bits_in_curr_mask\n dp(idx)(cur_mask.set_bit(idx)) + dist[curr_idx][idx]\n}"
},
{
"code": null,
"e": 3286,
"s": 2525,
"text": "The above relation can be visualized as the minimum distance to visit all the houses by standing at curr_idx house and by already visiting cur_mask houses is equal to min of distance between the curr_idx house and idx house + minimum distance to visit all the houses by standing at idx house and by already visiting ( cur_mask | (1 <<idx) ) houses.So, here we iterate over all possible idx values such that cur_mask has ith bit as 0 that tells us that ith house is not visited.Whenever we have our mask = LIMIT_MASK, this means that we have visited all the houses in the town. So, we will add the distance from the last visited town (i.e the town at cur_idx position) to the initial position (0, 0).The C++ program for the above implementation is given below: "
},
{
"code": null,
"e": 3292,
"s": 3288,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; #define INF 99999999#define MAXR 12#define MAXC 12#define MAXMASK 2048#define MAXHOUSE 12 // stores distance taking source// as every dirty tileint dist[MAXR][MAXC][MAXHOUSE]; // memoization for dp statesint dp[MAXHOUSE][MAXMASK]; // stores coordinates for// dirty tilesvector < pair < int, int > > dirty; // Directionsint X[] = {-1, 0, 0, 1};int Y[] = {0, 1, -1, 0}; char arr[21][21]; // len : number of dirty tiles + 1// limit : 2 ^ len -1// r, c : number of rows and columnsint len, limit, r, c; // Returns true if current position// is safe to visit// else returns false// Time Complexity : O(1)bool safe(int x, int y){ if (x >= r or y>= c or x<0 or y<0) return false; if (arr[x][y] == '#') return false; return true;} // runs BFS traversal at tile idx// calculates distance to every cell// in the grid// Time Complexity : O(r*c)void getDist(int idx){ // visited array to track visited cells bool vis[21][21]; memset(vis, false, sizeof(vis)); // getting current position int cx = dirty[idx].first; int cy = dirty[idx].second; // initializing queue for bfs queue < pair < int, int > > pq; pq.push({cx, cy}); // initializing the dist to max // because some cells cannot be visited // by taking source cell as idx for (int i = 0;i<= r;i++) for (int j = 0;j<= c;j++) dist[i][j][idx] = INF; // base conditions vis[cx][cy] = true; dist[cx][cy][idx] = 0; while (! pq.empty()) { auto x = pq.front(); pq.pop(); for (int i = 0;i<4;i++) { cx = x.first + X[i]; cy = x.second + Y[i]; if (safe(cx, cy)) { if (vis[cx][cy]) continue; vis[cx][cy] = true; dist[cx][cy][idx] = dist[x.first][x.second][idx] + 1; pq.push({cx, cy}); } } }} // Dynamic Programming state transition recursion// with memoization. Time Complexity: O(n*n*2 ^ n)int solve(int idx, int mask){ // goal state if (mask == limit) return dist[0][0][idx]; // if already visited state if (dp[idx][mask] != -1) return dp[idx][mask]; int ret = INT_MAX; // state transition relation for (int i = 0;i<len;i++) { if ((mask & (1<<i)) == 0) { int newMask = mask | (1<<i); ret = min( ret, solve(i, newMask) + dist[dirty[i].first][dirty[i].second][idx]); } } // adding memoization and returning return dp[idx][mask] = ret;} void init(){ // initializing containers memset(dp, -1, sizeof(dp)); dirty.clear(); // populating dirty tile positions for (int i = 0;i<r;i++) for (int j = 0;j<c;j++) { if (arr[i][j] == '*') dirty.push_back({i, j}); } // inserting ronot's location at the // beginning of the dirty tile dirty.insert(dirty.begin(), {0, 0}); len = dirty.size(); // calculating LIMIT_MASK limit = (1<<len) - 1; // precalculating distances from all // dirty tiles to each cell in the grid for (int i = 0;i<len;i++) getDist(i);} int main(int argc, char const *argv[]){ // Test case #1: // .....*. // ...#... // .*.#.*. // ....... char A[4][7] = { {'.', '.', '.', '.', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'}, {'.', '*', '.', '#', '.', '*', '.'}, {'.', '.', '.', '.', '.', '.', '.'} }; r = 4; c = 7; cout << \"The given grid : \" << endl; for (int i = 0;i<r;i++) { for (int j = 0;j<c;j++) { cout << A[i][j] << \" \"; arr[i][j] = A[i][j]; } cout << endl; } // - initialization // - precalculations init(); int ans = solve(0, 1); cout << \"Minimum distance for the given grid : \"; cout << ans << endl; // Test Case #2 // ...#... // ...#.*. // ...#... // .*.#.*. // ...#... char Arr[5][7] = { {'.', '.', '.', '#', '.', '.', '.'}, {'.', '.', '.', '#', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'}, {'.', '*', '.', '#', '.', '*', '.'}, {'.', '.', '.', '#', '.', '.', '.'} }; r = 5; c = 7; cout << \"The given grid : \" << endl; for (int i = 0;i<r;i++) { for (int j = 0;j<c;j++) { cout << Arr[i][j] << \" \"; arr[i][j] = Arr[i][j]; } cout << endl; } // - initialization // - precalculations init(); ans = solve(0, 1); cout << \"Minimum distance for the given grid : \"; if (ans >= INF) cout << \"not possible\" << endl; else cout << ans << endl; return 0;}",
"e": 8162,
"s": 3292,
"text": null
},
{
"code": null,
"e": 8172,
"s": 8162,
"text": "Output: "
},
{
"code": null,
"e": 8435,
"s": 8172,
"text": "The given grid : \n. . . . . * . \n. . . # . . . \n. * . # . * . \n. . . . . . . \nMinimum distance for the given grid : 16\nThe given grid : \n. . . # . . . \n. . . # . * . \n. . . # . . . \n. * . # . * . \n. . . # . . . \nMinimum distance for the given grid : not possible"
},
{
"code": null,
"e": 8999,
"s": 8435,
"text": "Note:We have used the initial state to be dp[0][1] because we have pushed the start location at the first position in the container of houses. Hence, our Bit Mask will be 1 as the 0th bit is set i.e we have visited the starting location for our trip.Time Complexity:Consider the number of houses to be n. So, there are n * (2n) states and at every state, we are looping over n houses to transit over to next state and because of memoization we are doing this looping transition only once for each state. Therefore, our Time Complexity is O(n2 * 2n).Recommended: "
},
{
"code": null,
"e": 9038,
"s": 8999,
"text": "http://www.spoj.com/problems/CLEANRBT/"
},
{
"code": null,
"e": 9082,
"s": 9038,
"text": "https://www.youtube.com/watch?v=-JjA4BLQyqE"
},
{
"code": null,
"e": 9503,
"s": 9082,
"text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9516,
"s": 9503,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9530,
"s": 9516,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 9541,
"s": 9530,
"text": "erikbrobyn"
},
{
"code": null,
"e": 9550,
"s": 9541,
"text": "gabaa406"
},
{
"code": null,
"e": 9566,
"s": 9550,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 9579,
"s": 9566,
"text": "simmytarika5"
},
{
"code": null,
"e": 9589,
"s": 9579,
"text": "Bit Magic"
},
{
"code": null,
"e": 9609,
"s": 9589,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9629,
"s": 9609,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9639,
"s": 9629,
"text": "Bit Magic"
}
] |
Python | fabs() vs abs()
|
09 Aug, 2021
Both the abs() and the fabs() function is used to find the absolute value of a number, i.e., remove the negative sign of a number.
Syntax of abs():
abs(number)
Syntax of fabs():
math.fabs(number)
Both will return the absolute value of a number.
The difference is that math.fabs(number) will always return a floating-point number even if the argument is an integer, whereas abs() will return a floating-point or an integer depending upon the argument.
In case the argument is a complex number, abs() will return the magnitude part whereas fabs() will return an error.To use the fabs() function we need to import the library “math” while the abs() function comes with the standard library of Python.
Python3
# Python code to demonstrate working# of fabs() and abs()import math ################################## When the argument is an integer##################################number = -10 # abs() will return an integer as# the argument is an integerprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ############################################ When the input is a floating point number############################################number = -12.08 # abs() will return an floating point number# as the argument is a floating point numberprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ##################################### When the input is a complex number#####################################number = complex(3, 4) # abs() will return the magnitudeprint(abs(number)) # fabs() will return an error# print(math.fabs(number))
Output:
10
10.0
12.08
12.08
5.0
nidhi_biet
sheetal18june
Python-Built-in-functions
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 186,
"s": 53,
"text": "Both the abs() and the fabs() function is used to find the absolute value of a number, i.e., remove the negative sign of a number. "
},
{
"code": null,
"e": 204,
"s": 186,
"text": "Syntax of abs(): "
},
{
"code": null,
"e": 216,
"s": 204,
"text": "abs(number)"
},
{
"code": null,
"e": 234,
"s": 216,
"text": "Syntax of fabs():"
},
{
"code": null,
"e": 252,
"s": 234,
"text": "math.fabs(number)"
},
{
"code": null,
"e": 301,
"s": 252,
"text": "Both will return the absolute value of a number."
},
{
"code": null,
"e": 507,
"s": 301,
"text": "The difference is that math.fabs(number) will always return a floating-point number even if the argument is an integer, whereas abs() will return a floating-point or an integer depending upon the argument."
},
{
"code": null,
"e": 754,
"s": 507,
"text": "In case the argument is a complex number, abs() will return the magnitude part whereas fabs() will return an error.To use the fabs() function we need to import the library “math” while the abs() function comes with the standard library of Python."
},
{
"code": null,
"e": 762,
"s": 754,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working# of fabs() and abs()import math ################################## When the argument is an integer##################################number = -10 # abs() will return an integer as# the argument is an integerprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ############################################ When the input is a floating point number############################################number = -12.08 # abs() will return an floating point number# as the argument is a floating point numberprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ##################################### When the input is a complex number#####################################number = complex(3, 4) # abs() will return the magnitudeprint(abs(number)) # fabs() will return an error# print(math.fabs(number))",
"e": 1655,
"s": 762,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1655,
"text": "Output: "
},
{
"code": null,
"e": 1688,
"s": 1664,
"text": "10\n10.0\n12.08\n12.08\n5.0"
},
{
"code": null,
"e": 1699,
"s": 1688,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1713,
"s": 1699,
"text": "sheetal18june"
},
{
"code": null,
"e": 1739,
"s": 1713,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1754,
"s": 1739,
"text": "Python-Library"
},
{
"code": null,
"e": 1761,
"s": 1754,
"text": "Python"
},
{
"code": null,
"e": 1859,
"s": 1761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1877,
"s": 1859,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1919,
"s": 1877,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1941,
"s": 1919,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1976,
"s": 1941,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2002,
"s": 1976,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2034,
"s": 2002,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2063,
"s": 2034,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2093,
"s": 2063,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2120,
"s": 2093,
"text": "Python Classes and Objects"
}
] |
SQL Natural Join - GeeksforGeeks
|
13 Apr, 2021
In this article, we will discuss the overview of SQL Natural Join and then mainly focus to implement query with the help of examples. Let’s discuss it one by one.
Overview :Natural join is an SQL join operation that creates join on the base of the common columns in the tables. To perform natural join there must be one common attribute(Column) between two tables. Natural join will retrieve from multiple relations. It works in three steps.
Syntax :We will perform the natural join query by using the following syntax.
SELECT *
FROM TABLE1
NATURAL JOIN TABLE2;
Features of Natural Join :Here, we will discuss the features of natural join.
It will perform the Cartesian product.It finds consistent tuples and deletes inconsistent tuples.Then it deletes the duplicate attributes.
It will perform the Cartesian product.
It finds consistent tuples and deletes inconsistent tuples.
Then it deletes the duplicate attributes.
Steps to implement SQL Natural Join :Here, we will discuss the steps to implement SQL Natural Join as follows.
Step-1:Creating Database :
create database geeks;
Step-2: Using the database :To use this database as follows.
use geeks;
Step-3: Reference tables into the database :This is our tables in the geeks database as follows.
Table-1: department –
Create Table department
(
DEPT_NAME Varchar(20),
MANAGER_NAME Varchar(255)
);
Table-2: employee –
Create Table employee
(
EMP_ID int,
EMP_NAME Varchar(20),
DEPT_NAME Varchar(255)
);
Step-4: Inserting values :Add value into the tables as follows.
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "IT", "ROHAN");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "SALES", "RAHUL");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "HR", "TANMAY");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "FINANCE", "ASHISH");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ("MARKETING", "SAMAY");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (1, "SUMIT", "HR");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (2, "JOEL", "IT");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (3, "BISWA", "MARKETING");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (4, "VAIBHAV", "IT");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (5, "SAGAR", "SALES");
Step-5: Verifying inserted data :This is our data inside the table as follows.
SELECT * FROM EMPLOYEE;
Output :
SELECT * FROM DEPARTMENT;
Output :
Step-6: Query to implement SQL Natural Join :
SELECT *
FROM EMPLOYEE
NATURAL JOIN DEPARTMENT;
Output :
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
|
[
{
"code": null,
"e": 23902,
"s": 23874,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 24065,
"s": 23902,
"text": "In this article, we will discuss the overview of SQL Natural Join and then mainly focus to implement query with the help of examples. Let’s discuss it one by one."
},
{
"code": null,
"e": 24344,
"s": 24065,
"text": "Overview :Natural join is an SQL join operation that creates join on the base of the common columns in the tables. To perform natural join there must be one common attribute(Column) between two tables. Natural join will retrieve from multiple relations. It works in three steps."
},
{
"code": null,
"e": 24422,
"s": 24344,
"text": "Syntax :We will perform the natural join query by using the following syntax."
},
{
"code": null,
"e": 24464,
"s": 24422,
"text": "SELECT *\nFROM TABLE1\nNATURAL JOIN TABLE2;"
},
{
"code": null,
"e": 24542,
"s": 24464,
"text": "Features of Natural Join :Here, we will discuss the features of natural join."
},
{
"code": null,
"e": 24681,
"s": 24542,
"text": "It will perform the Cartesian product.It finds consistent tuples and deletes inconsistent tuples.Then it deletes the duplicate attributes."
},
{
"code": null,
"e": 24720,
"s": 24681,
"text": "It will perform the Cartesian product."
},
{
"code": null,
"e": 24780,
"s": 24720,
"text": "It finds consistent tuples and deletes inconsistent tuples."
},
{
"code": null,
"e": 24822,
"s": 24780,
"text": "Then it deletes the duplicate attributes."
},
{
"code": null,
"e": 24933,
"s": 24822,
"text": "Steps to implement SQL Natural Join :Here, we will discuss the steps to implement SQL Natural Join as follows."
},
{
"code": null,
"e": 24960,
"s": 24933,
"text": "Step-1:Creating Database :"
},
{
"code": null,
"e": 24983,
"s": 24960,
"text": "create database geeks;"
},
{
"code": null,
"e": 25044,
"s": 24983,
"text": "Step-2: Using the database :To use this database as follows."
},
{
"code": null,
"e": 25055,
"s": 25044,
"text": "use geeks;"
},
{
"code": null,
"e": 25152,
"s": 25055,
"text": "Step-3: Reference tables into the database :This is our tables in the geeks database as follows."
},
{
"code": null,
"e": 25174,
"s": 25152,
"text": "Table-1: department –"
},
{
"code": null,
"e": 25258,
"s": 25174,
"text": "Create Table department\n(\n DEPT_NAME Varchar(20),\n MANAGER_NAME Varchar(255)\n);"
},
{
"code": null,
"e": 25278,
"s": 25258,
"text": "Table-2: employee –"
},
{
"code": null,
"e": 25371,
"s": 25278,
"text": "Create Table employee\n(\n EMP_ID int,\n EMP_NAME Varchar(20),\n DEPT_NAME Varchar(255)\n);"
},
{
"code": null,
"e": 25435,
"s": 25371,
"text": "Step-4: Inserting values :Add value into the tables as follows."
},
{
"code": null,
"e": 26208,
"s": 25435,
"text": "INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( \"IT\", \"ROHAN\");\nINSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( \"SALES\", \"RAHUL\");\nINSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( \"HR\", \"TANMAY\");\nINSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( \"FINANCE\", \"ASHISH\");\nINSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES (\"MARKETING\", \"SAMAY\");\n\nINSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (1, \"SUMIT\", \"HR\");\nINSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (2, \"JOEL\", \"IT\");\nINSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (3, \"BISWA\", \"MARKETING\");\nINSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (4, \"VAIBHAV\", \"IT\");\nINSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (5, \"SAGAR\", \"SALES\");"
},
{
"code": null,
"e": 26287,
"s": 26208,
"text": "Step-5: Verifying inserted data :This is our data inside the table as follows."
},
{
"code": null,
"e": 26311,
"s": 26287,
"text": "SELECT * FROM EMPLOYEE;"
},
{
"code": null,
"e": 26320,
"s": 26311,
"text": "Output :"
},
{
"code": null,
"e": 26346,
"s": 26320,
"text": "SELECT * FROM DEPARTMENT;"
},
{
"code": null,
"e": 26355,
"s": 26346,
"text": "Output :"
},
{
"code": null,
"e": 26401,
"s": 26355,
"text": "Step-6: Query to implement SQL Natural Join :"
},
{
"code": null,
"e": 26449,
"s": 26401,
"text": "SELECT *\nFROM EMPLOYEE\nNATURAL JOIN DEPARTMENT;"
},
{
"code": null,
"e": 26458,
"s": 26449,
"text": "Output :"
},
{
"code": null,
"e": 26467,
"s": 26458,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26474,
"s": 26467,
"text": "Picked"
},
{
"code": null,
"e": 26478,
"s": 26474,
"text": "SQL"
},
{
"code": null,
"e": 26482,
"s": 26478,
"text": "SQL"
},
{
"code": null,
"e": 26580,
"s": 26482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26589,
"s": 26580,
"text": "Comments"
},
{
"code": null,
"e": 26602,
"s": 26589,
"text": "Old Comments"
},
{
"code": null,
"e": 26668,
"s": 26602,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26700,
"s": 26668,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26778,
"s": 26700,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26795,
"s": 26778,
"text": "SQL using Python"
},
{
"code": null,
"e": 26810,
"s": 26795,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26876,
"s": 26810,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26912,
"s": 26876,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26947,
"s": 26912,
"text": "SQL Query to Delete Duplicate Rows"
},
{
"code": null,
"e": 26978,
"s": 26947,
"text": "SQL Query to Compare Two Dates"
}
] |
Animations with Matplotlib. Animations are an interesting way of... | by Parul Pandey | Towards Data Science
|
Animations are an interesting way of demonstrating a phenomenon. We as humans are always enthralled by animated and interactive charts rather than the static ones. Animations make even more sense when depicting time-series data like stock prices over the years, climate change over the past decade, seasonalities and trends since we can then see how a particular parameter behaves with time.
The above image is a simulation of Rain and has been achieved with Matplotlib library which is fondly known as the grandfather of python visualization packages. Matplotlib simulates raindrops on a surface by animating the scale and opacity of 50 scatter points. Today Python boasts of a large number of powerful visualization tools like Plotly, Bokeh, Altair to name a few. These libraries are able to achieve state of the art animations and interactiveness. Nonetheless, the aim of this article is to highlight one aspect of this library which isn’t explored much and that is Animations and we are going to look at some of the ways of doing that.
Matplotlib is a Python 2D plotting library and also the most popular one. Most of the people start their Data Visualisation journey with Matplotlib. One can generate plots, histograms, power spectra, bar charts, error charts, scatterplots, etc easily with matplotlib. It also integrates seamlessly with libraries like Pandas and Seaborn to create even more sophisticated visualizations.
Some of the nice features of matplotlib are:
It is designed like MATLAB hence switching between the two is fairly easy.
Comprises of a lot of rendering backends.
It can reproduce just about any plots( with a bit of effort).
Has been out there for over a decade, therefore, boasts of a huge user base.
However, there are also areas where Matplotlib doesn’t shine out so much and lags behind its powerful counterparts.
Matplotlib has an imperative API which is often overly verbose.
Sometimes poor stylistic defaults.
Poor support for web and interactive graphs.
Often slow for large & complicated data.
As for a refresher here is a Matplotlib Cheatsheet from Datacamp which you can go through to brush up your basics.
Python For Data Science Cheat Sheet
Matplotlib
Learn Python Interactively at www.DataCamp.com
Matplotlib
DataCamp
Learn Python for Data Science Interactively
Prepare The Data Also see Lists & NumPy
Matplotlib is a Python 2D plotting library which produces
publication-quality figures in a variety of hardcopy formats
and interactive environments across
platforms.
1
>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)
Show Plot
>>> plt.show()
Save Plot
Save figures
>>> plt.savefig('foo.png')
Save transparent figures
>>> plt.savefig('foo.png', transparent=True)
6
5
>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
2 Create Plot
Plot Anatomy & Workflow
All plotting is done with respect to an Axes. In most cases, a
subplot will fit your needs. A subplot is an axes on a grid system.
>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) # row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)
Customize Plot
Colors, Color Bars & Color Maps
Markers
Linestyles
Mathtext
Text & Annotations
Limits, Legends & Layouts
The basic steps to creating plots with matplotlib are:
1 Prepare data 2 Create plot 3 Plot 4 Customize plot 5 Save plot 6Show plot
>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]
>>> y = [10,20,25,30]
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(x, y, color='lightblue', linewidth=3)
>>> ax.scatter([2,4,6],
[5,15,25],
color='darkgreen',
marker='^')
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png')
>>> plt.show()
Step 3, 4
Step 2
Step 1
Step 3
Step 6
Plot Anatomy Workflow
4
Limits & Autoscaling
>>> ax.margins(x=0.0,y=0.1) Add padding to a plot
>>> ax.axis('equal') Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) Set limits for x-axis
Legends
>>> ax.set(title='An Example Axes', Set a title and x-and y-axis labels
ylabel='Y-Axis', xlabel='X-Axis')
>>> ax.legend(loc='best') No overlapping plot elements
Ticks
>>> ax.xaxis.set(ticks=range(1,5), Manually set x-ticks
ticklabels=[3,100,-12,"foo"])
>>> ax.tick_params(axis='y', Make y-ticks longer and go in and out
direction='inout', length=10)
Subplot Spacing
>>> fig3.subplots_adjust(wspace=0.5, Adjust the spacing between subplots
hspace=0.3,
left=0.125,
right=0.9,
top=0.9,
bottom=0.1)
>>> fig.tight_layout() Fit subplot(s) in to the figure area
Axis Spines
>>> ax1.spines['top'].set_visible(False) Make the top axis line for a plot invisible
>>> ax1.spines['bottom'].set_position(('outward',10)) Move the bottom axis line outward
Figure
Axes
>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = -1 - X**2 + Y
>>> V = 1 + X - Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))
>>> lines = ax.plot(x,y) Draw points with lines or markers connecting them
>>> ax.scatter(x,y) Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') Fill between y-values and 0
3 Plotting Routines
1D Data
>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, Colormapped or RGB arrays cmap='gist_earth', interpolation='nearest',
vmin=-2,
vmax=2)
2D Data or Images
Vector Fields
>>> axes[0,1].arrow(0,0,0.5,0.5) Add an arrow to the axes
>>> axes[1,1].quiver(y,z) Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) Plot 2D vector fields
Data Distributions
>>> ax1.hist(y) Plot a histogram
>>> ax3.boxplot(y) Make a box and whisker plot
>>> ax3.violinplot(z) Make a violin plot
>>> axes2[0].pcolor(data2) Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) Plot contours
>>> axes2[2].contourf(data1) Plot filled contours
>>> axes2[2]= ax.clabel(CS) Label a contour plot
Figure
Axes/Subplot
Y-axis
X-axis
1D Data
2D Data or Images
>>> plt.plot(x, x, x, x**2, x, x**3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c='k')
>>> fig.colorbar(im, orientation='horizontal')
>>> im = ax.imshow(img,
cmap='seismic')
>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker=".")
>>> ax.plot(x,y,marker="o")
>>> plt.title(r'$sigma_i=15$', fontsize=20)
>>> ax.text(1,
-2.1, 'Example Graph', style='italic')
>>> ax.annotate("Sine", xy=(8, 0),
xycoords='data', xytext=(10.5, 0),
textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"),)
>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls='solid')
>>> plt.plot(x,y,ls='--')
>>> plt.plot(x,y,'--',x**2,y**2,'-.')
>>> plt.setp(lines,color='r',linewidth=4.0)
>>> import matplotlib.pyplot as plt
Close & Clear
>>> plt.cla() Clear an axis
>>> plt.clf() Clear the entire figure
>>> plt.close() Close a window
Matplotlib’s animation base class deals with the animation part. It provides a framework around which the animation functionality is built. There are two main interfaces to achieve that using:
FuncAnimation makes an animation by repeatedly calling a function func.
ArtistAnimation: Animation using a fixed set of Artist objects.
However, out of the two, FuncAnimation is the most convenient one to use. You can read more about them in the documentation since we will only concern ourselves with the FuncAnimation tool.
Modules including numpy and matplotlib should be installed.
To save the animation on your system as mp4 or gif, ffmpeg or imagemagick is required to be installed.
Once ready, we can begin with our first basic animation in the Jupyter Notebooks. The code for this article can be accessed from the associated Github Repository or you can view it on my binder by clicking the image below.
Let’s use FuncAnimation to create a basic animation of a sine wave moving across the screen. The source code for the animation has been taken from the Matplotlib Animation tutorial. Let’s first see the output and then we shall break down the code to understand what’s going under the hood.
In lines(7–9), we simply create a figure window with a single axis in the figure. Then we create our empty line object which is essentially the one to be modified in the animation. The line object will be populated with data later.
In lines(11–13), we create the init function that will make the animation happen. The init function initializes the data and also sets the axis limits.
In lines(14–18), we finally define the animation function which takes in the frame number(i) as the parameter and creates a sine wave(or any other animation) which a shift depending upon the value of i. This function here returns a tuple of the plot objects which have been modified which tells the animation framework what parts of the plot should be animated.
In line 20, we create the actual animation object. The blit parameter ensures that only those pieces of the plot are re-drawn which have been changed.
This is the basic intuition behind creating animations in Matplotlib. With a little tweak in the code, interesting visualizations can be created. Let’s have a look at some of them
Similarly, there is a nice example of creating shapes at GeeksforGeeks. Let’s now create a moving coil that slowly unwinds, with the help of animation class of matplotlib. The code is quite similar to the sine wave plot with minor adjustments.
Live updating graphs come in handy when plotting dynamic quantities like stock data, sensor data or any other time-dependent data. We plot a base graph which automatically gets updated as more data is fed into the system. This example has been taken from sentdex. Be sure to visit this youtube channel for some awesome tutorials.
Let’s plot stock prices of a hypothetical company in a month.
Now, open the terminal and run the python file. You will get a graph like the one below which automatically updates as follows:
Here interval is 1000 milliseconds or one second.
Creating 3D graphs is common but what if we can animate the angle of view of those graphs. The idea is to change the camera view and then use every resulting image to create an animation. There is a nice section dedicated to it at The Python Graph Gallery.
Create a folder called volcano in the same directory as the notebook. All the images will be stored in this folder which will be then used in the animation.
This will create multiple PNG files in the Volcano folder. Now, use ImageMagick to transform them into animation. Open Terminal and navigate to the Volcano folder and enter the following command:
convert -delay 10 Volcano*.png animated_volcano.gif
Celluloid is a Python module that simplifies the process of creating animations in matplotlib. This library creates a matplotlib figure and creates a Camera from it. It then reuses figure and after each frame is created, take a snapshot with the camera. Finally, an animation is created with all the captured frames.
pip install celluloid
Here are a few examples using the Celluloid module.
Animations help to highlight certain features of the visualisation which otherwise cannot be communicated easily with static charts. Having said that it is also important to keep in mind that unnecessary and overuse of visualisations can sometimes complicate things. Every feature in data visualisation should be used judiciously to have the best impact.
|
[
{
"code": null,
"e": 564,
"s": 172,
"text": "Animations are an interesting way of demonstrating a phenomenon. We as humans are always enthralled by animated and interactive charts rather than the static ones. Animations make even more sense when depicting time-series data like stock prices over the years, climate change over the past decade, seasonalities and trends since we can then see how a particular parameter behaves with time."
},
{
"code": null,
"e": 1212,
"s": 564,
"text": "The above image is a simulation of Rain and has been achieved with Matplotlib library which is fondly known as the grandfather of python visualization packages. Matplotlib simulates raindrops on a surface by animating the scale and opacity of 50 scatter points. Today Python boasts of a large number of powerful visualization tools like Plotly, Bokeh, Altair to name a few. These libraries are able to achieve state of the art animations and interactiveness. Nonetheless, the aim of this article is to highlight one aspect of this library which isn’t explored much and that is Animations and we are going to look at some of the ways of doing that."
},
{
"code": null,
"e": 1599,
"s": 1212,
"text": "Matplotlib is a Python 2D plotting library and also the most popular one. Most of the people start their Data Visualisation journey with Matplotlib. One can generate plots, histograms, power spectra, bar charts, error charts, scatterplots, etc easily with matplotlib. It also integrates seamlessly with libraries like Pandas and Seaborn to create even more sophisticated visualizations."
},
{
"code": null,
"e": 1644,
"s": 1599,
"text": "Some of the nice features of matplotlib are:"
},
{
"code": null,
"e": 1719,
"s": 1644,
"text": "It is designed like MATLAB hence switching between the two is fairly easy."
},
{
"code": null,
"e": 1761,
"s": 1719,
"text": "Comprises of a lot of rendering backends."
},
{
"code": null,
"e": 1823,
"s": 1761,
"text": "It can reproduce just about any plots( with a bit of effort)."
},
{
"code": null,
"e": 1900,
"s": 1823,
"text": "Has been out there for over a decade, therefore, boasts of a huge user base."
},
{
"code": null,
"e": 2016,
"s": 1900,
"text": "However, there are also areas where Matplotlib doesn’t shine out so much and lags behind its powerful counterparts."
},
{
"code": null,
"e": 2080,
"s": 2016,
"text": "Matplotlib has an imperative API which is often overly verbose."
},
{
"code": null,
"e": 2115,
"s": 2080,
"text": "Sometimes poor stylistic defaults."
},
{
"code": null,
"e": 2160,
"s": 2115,
"text": "Poor support for web and interactive graphs."
},
{
"code": null,
"e": 2201,
"s": 2160,
"text": "Often slow for large & complicated data."
},
{
"code": null,
"e": 2316,
"s": 2201,
"text": "As for a refresher here is a Matplotlib Cheatsheet from Datacamp which you can go through to brush up your basics."
},
{
"code": null,
"e": 2353,
"s": 2316,
"text": "Python For Data Science Cheat Sheet\n"
},
{
"code": null,
"e": 2365,
"s": 2353,
"text": "Matplotlib\n"
},
{
"code": null,
"e": 2413,
"s": 2365,
"text": "Learn Python Interactively at www.DataCamp.com\n"
},
{
"code": null,
"e": 2425,
"s": 2413,
"text": "Matplotlib\n"
},
{
"code": null,
"e": 2435,
"s": 2425,
"text": "DataCamp\n"
},
{
"code": null,
"e": 2480,
"s": 2435,
"text": "Learn Python for Data Science Interactively\n"
},
{
"code": null,
"e": 2521,
"s": 2480,
"text": "Prepare The Data Also see Lists & NumPy\n"
},
{
"code": null,
"e": 2580,
"s": 2521,
"text": "Matplotlib is a Python 2D plotting library which produces\n"
},
{
"code": null,
"e": 2642,
"s": 2580,
"text": "publication-quality figures in a variety of hardcopy formats\n"
},
{
"code": null,
"e": 2679,
"s": 2642,
"text": "and interactive environments across\n"
},
{
"code": null,
"e": 2691,
"s": 2679,
"text": "platforms.\n"
},
{
"code": null,
"e": 2694,
"s": 2691,
"text": "1\n"
},
{
"code": null,
"e": 2718,
"s": 2694,
"text": ">>> import numpy as np\n"
},
{
"code": null,
"e": 2751,
"s": 2718,
"text": ">>> x = np.linspace(0, 10, 100)\n"
},
{
"code": null,
"e": 2770,
"s": 2751,
"text": ">>> y = np.cos(x)\n"
},
{
"code": null,
"e": 2789,
"s": 2770,
"text": ">>> z = np.sin(x)\n"
},
{
"code": null,
"e": 2800,
"s": 2789,
"text": "Show Plot\n"
},
{
"code": null,
"e": 2816,
"s": 2800,
"text": ">>> plt.show()\n"
},
{
"code": null,
"e": 2827,
"s": 2816,
"text": "Save Plot\n"
},
{
"code": null,
"e": 2841,
"s": 2827,
"text": "Save figures\n"
},
{
"code": null,
"e": 2869,
"s": 2841,
"text": ">>> plt.savefig('foo.png')\n"
},
{
"code": null,
"e": 2895,
"s": 2869,
"text": "Save transparent figures\n"
},
{
"code": null,
"e": 2941,
"s": 2895,
"text": ">>> plt.savefig('foo.png', transparent=True)\n"
},
{
"code": null,
"e": 2944,
"s": 2941,
"text": "6\n"
},
{
"code": null,
"e": 2947,
"s": 2944,
"text": "5\n"
},
{
"code": null,
"e": 2971,
"s": 2947,
"text": ">>> fig = plt.figure()\n"
},
{
"code": null,
"e": 3022,
"s": 2971,
"text": ">>> fig2 = plt.figure(figsize=plt.figaspect(2.0))\n"
},
{
"code": null,
"e": 3037,
"s": 3022,
"text": "2 Create Plot\n"
},
{
"code": null,
"e": 3062,
"s": 3037,
"text": "Plot Anatomy & Workflow\n"
},
{
"code": null,
"e": 3126,
"s": 3062,
"text": "All plotting is done with respect to an Axes. In most cases, a\n"
},
{
"code": null,
"e": 3195,
"s": 3126,
"text": "subplot will fit your needs. A subplot is an axes on a grid system.\n"
},
{
"code": null,
"e": 3215,
"s": 3195,
"text": ">>> fig.add_axes()\n"
},
{
"code": null,
"e": 3261,
"s": 3215,
"text": ">>> ax1 = fig.add_subplot(221) # row-col-num\n"
},
{
"code": null,
"e": 3293,
"s": 3261,
"text": ">>> ax3 = fig.add_subplot(212)\n"
},
{
"code": null,
"e": 3341,
"s": 3293,
"text": ">>> fig3, axes = plt.subplots(nrows=2,ncols=2)\n"
},
{
"code": null,
"e": 3382,
"s": 3341,
"text": ">>> fig4, axes2 = plt.subplots(ncols=3)\n"
},
{
"code": null,
"e": 3398,
"s": 3382,
"text": "Customize Plot\n"
},
{
"code": null,
"e": 3431,
"s": 3398,
"text": "Colors, Color Bars & Color Maps\n"
},
{
"code": null,
"e": 3440,
"s": 3431,
"text": "Markers\n"
},
{
"code": null,
"e": 3452,
"s": 3440,
"text": "Linestyles\n"
},
{
"code": null,
"e": 3462,
"s": 3452,
"text": "Mathtext\n"
},
{
"code": null,
"e": 3482,
"s": 3462,
"text": "Text & Annotations\n"
},
{
"code": null,
"e": 3509,
"s": 3482,
"text": "Limits, Legends & Layouts\n"
},
{
"code": null,
"e": 3565,
"s": 3509,
"text": "The basic steps to creating plots with matplotlib are:\n"
},
{
"code": null,
"e": 3642,
"s": 3565,
"text": "1 Prepare data 2 Create plot 3 Plot 4 Customize plot 5 Save plot 6Show plot\n"
},
{
"code": null,
"e": 3679,
"s": 3642,
"text": ">>> import matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 3698,
"s": 3679,
"text": ">>> x = [1,2,3,4]\n"
},
{
"code": null,
"e": 3721,
"s": 3698,
"text": ">>> y = [10,20,25,30]\n"
},
{
"code": null,
"e": 3745,
"s": 3721,
"text": ">>> fig = plt.figure()\n"
},
{
"code": null,
"e": 3776,
"s": 3745,
"text": ">>> ax = fig.add_subplot(111)\n"
},
{
"code": null,
"e": 3827,
"s": 3776,
"text": ">>> ax.plot(x, y, color='lightblue', linewidth=3)\n"
},
{
"code": null,
"e": 3852,
"s": 3827,
"text": ">>> ax.scatter([2,4,6],\n"
},
{
"code": null,
"e": 3864,
"s": 3852,
"text": "[5,15,25],\n"
},
{
"code": null,
"e": 3884,
"s": 3864,
"text": "color='darkgreen',\n"
},
{
"code": null,
"e": 3897,
"s": 3884,
"text": "marker='^')\n"
},
{
"code": null,
"e": 3922,
"s": 3897,
"text": ">>> ax.set_xlim(1, 6.5)\n"
},
{
"code": null,
"e": 3950,
"s": 3922,
"text": ">>> plt.savefig('foo.png')\n"
},
{
"code": null,
"e": 3966,
"s": 3950,
"text": ">>> plt.show()\n"
},
{
"code": null,
"e": 3977,
"s": 3966,
"text": "Step 3, 4\n"
},
{
"code": null,
"e": 3985,
"s": 3977,
"text": "Step 2\n"
},
{
"code": null,
"e": 3993,
"s": 3985,
"text": "Step 1\n"
},
{
"code": null,
"e": 4001,
"s": 3993,
"text": "Step 3\n"
},
{
"code": null,
"e": 4009,
"s": 4001,
"text": "Step 6\n"
},
{
"code": null,
"e": 4032,
"s": 4009,
"text": "Plot Anatomy Workflow\n"
},
{
"code": null,
"e": 4035,
"s": 4032,
"text": "4\n"
},
{
"code": null,
"e": 4057,
"s": 4035,
"text": "Limits & Autoscaling\n"
},
{
"code": null,
"e": 4108,
"s": 4057,
"text": ">>> ax.margins(x=0.0,y=0.1) Add padding to a plot\n"
},
{
"code": null,
"e": 4168,
"s": 4108,
"text": ">>> ax.axis('equal') Set the aspect ratio of the plot to 1\n"
},
{
"code": null,
"e": 4239,
"s": 4168,
"text": ">>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) Set limits for x-and y-axis\n"
},
{
"code": null,
"e": 4286,
"s": 4239,
"text": ">>> ax.set_xlim(0,10.5) Set limits for x-axis\n"
},
{
"code": null,
"e": 4295,
"s": 4286,
"text": "Legends\n"
},
{
"code": null,
"e": 4368,
"s": 4295,
"text": ">>> ax.set(title='An Example Axes', Set a title and x-and y-axis labels\n"
},
{
"code": null,
"e": 4403,
"s": 4368,
"text": "ylabel='Y-Axis', xlabel='X-Axis')\n"
},
{
"code": null,
"e": 4459,
"s": 4403,
"text": ">>> ax.legend(loc='best') No overlapping plot elements\n"
},
{
"code": null,
"e": 4466,
"s": 4459,
"text": "Ticks\n"
},
{
"code": null,
"e": 4523,
"s": 4466,
"text": ">>> ax.xaxis.set(ticks=range(1,5), Manually set x-ticks\n"
},
{
"code": null,
"e": 4554,
"s": 4523,
"text": "ticklabels=[3,100,-12,\"foo\"])\n"
},
{
"code": null,
"e": 4622,
"s": 4554,
"text": ">>> ax.tick_params(axis='y', Make y-ticks longer and go in and out\n"
},
{
"code": null,
"e": 4653,
"s": 4622,
"text": "direction='inout', length=10)\n"
},
{
"code": null,
"e": 4670,
"s": 4653,
"text": "Subplot Spacing\n"
},
{
"code": null,
"e": 4744,
"s": 4670,
"text": ">>> fig3.subplots_adjust(wspace=0.5, Adjust the spacing between subplots\n"
},
{
"code": null,
"e": 4757,
"s": 4744,
"text": "hspace=0.3,\n"
},
{
"code": null,
"e": 4770,
"s": 4757,
"text": "left=0.125,\n"
},
{
"code": null,
"e": 4782,
"s": 4770,
"text": "right=0.9,\n"
},
{
"code": null,
"e": 4792,
"s": 4782,
"text": "top=0.9,\n"
},
{
"code": null,
"e": 4805,
"s": 4792,
"text": "bottom=0.1)\n"
},
{
"code": null,
"e": 4866,
"s": 4805,
"text": ">>> fig.tight_layout() Fit subplot(s) in to the figure area\n"
},
{
"code": null,
"e": 4879,
"s": 4866,
"text": "Axis Spines\n"
},
{
"code": null,
"e": 4965,
"s": 4879,
"text": ">>> ax1.spines['top'].set_visible(False) Make the top axis line for a plot invisible\n"
},
{
"code": null,
"e": 5054,
"s": 4965,
"text": ">>> ax1.spines['bottom'].set_position(('outward',10)) Move the bottom axis line outward\n"
},
{
"code": null,
"e": 5062,
"s": 5054,
"text": "Figure\n"
},
{
"code": null,
"e": 5068,
"s": 5062,
"text": "Axes\n"
},
{
"code": null,
"e": 5111,
"s": 5068,
"text": ">>> data = 2 * np.random.random((10, 10))\n"
},
{
"code": null,
"e": 5155,
"s": 5111,
"text": ">>> data2 = 3 * np.random.random((10, 10))\n"
},
{
"code": null,
"e": 5198,
"s": 5155,
"text": ">>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]\n"
},
{
"code": null,
"e": 5221,
"s": 5198,
"text": ">>> U = -1 - X**2 + Y\n"
},
{
"code": null,
"e": 5243,
"s": 5221,
"text": ">>> V = 1 + X - Y**2\n"
},
{
"code": null,
"e": 5293,
"s": 5243,
"text": ">>> from matplotlib.cbook import get_sample_data\n"
},
{
"code": null,
"e": 5363,
"s": 5293,
"text": ">>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))\n"
},
{
"code": null,
"e": 5439,
"s": 5363,
"text": ">>> lines = ax.plot(x,y) Draw points with lines or markers connecting them\n"
},
{
"code": null,
"e": 5503,
"s": 5439,
"text": ">>> ax.scatter(x,y) Draw unconnected points, scaled or colored\n"
},
{
"code": null,
"e": 5581,
"s": 5503,
"text": ">>> axes[0,0].bar([1,2,3],[3,4,5]) Plot vertical rectangles (constant width)\n"
},
{
"code": null,
"e": 5666,
"s": 5581,
"text": ">>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) Plot horiontal rectangles (constant height)\n"
},
{
"code": null,
"e": 5730,
"s": 5666,
"text": ">>> axes[1,1].axhline(0.45) Draw a horizontal line across axes\n"
},
{
"code": null,
"e": 5792,
"s": 5730,
"text": ">>> axes[0,1].axvline(0.65) Draw a vertical line across axes\n"
},
{
"code": null,
"e": 5844,
"s": 5792,
"text": ">>> ax.fill(x,y,color='blue') Draw filled polygons\n"
},
{
"code": null,
"e": 5913,
"s": 5844,
"text": ">>> ax.fill_between(x,y,color='yellow') Fill between y-values and 0\n"
},
{
"code": null,
"e": 5934,
"s": 5913,
"text": "3 Plotting Routines\n"
},
{
"code": null,
"e": 5943,
"s": 5934,
"text": "1D Data\n"
},
{
"code": null,
"e": 5973,
"s": 5943,
"text": ">>> fig, ax = plt.subplots()\n"
},
{
"code": null,
"e": 6068,
"s": 5973,
"text": ">>> im = ax.imshow(img, Colormapped or RGB arrays cmap='gist_earth', interpolation='nearest',\n"
},
{
"code": null,
"e": 6078,
"s": 6068,
"text": "vmin=-2,\n"
},
{
"code": null,
"e": 6087,
"s": 6078,
"text": "vmax=2)\n"
},
{
"code": null,
"e": 6106,
"s": 6087,
"text": "2D Data or Images\n"
},
{
"code": null,
"e": 6121,
"s": 6106,
"text": "Vector Fields\n"
},
{
"code": null,
"e": 6180,
"s": 6121,
"text": ">>> axes[0,1].arrow(0,0,0.5,0.5) Add an arrow to the axes\n"
},
{
"code": null,
"e": 6233,
"s": 6180,
"text": ">>> axes[1,1].quiver(y,z) Plot a 2D field of arrows\n"
},
{
"code": null,
"e": 6290,
"s": 6233,
"text": ">>> axes[0,1].streamplot(X,Y,U,V) Plot 2D vector fields\n"
},
{
"code": null,
"e": 6310,
"s": 6290,
"text": "Data Distributions\n"
},
{
"code": null,
"e": 6344,
"s": 6310,
"text": ">>> ax1.hist(y) Plot a histogram\n"
},
{
"code": null,
"e": 6392,
"s": 6344,
"text": ">>> ax3.boxplot(y) Make a box and whisker plot\n"
},
{
"code": null,
"e": 6434,
"s": 6392,
"text": ">>> ax3.violinplot(z) Make a violin plot\n"
},
{
"code": null,
"e": 6491,
"s": 6434,
"text": ">>> axes2[0].pcolor(data2) Pseudocolor plot of 2D array\n"
},
{
"code": null,
"e": 6551,
"s": 6491,
"text": ">>> axes2[0].pcolormesh(data) Pseudocolor plot of 2D array\n"
},
{
"code": null,
"e": 6594,
"s": 6551,
"text": ">>> CS = plt.contour(Y,X,U) Plot contours\n"
},
{
"code": null,
"e": 6645,
"s": 6594,
"text": ">>> axes2[2].contourf(data1) Plot filled contours\n"
},
{
"code": null,
"e": 6695,
"s": 6645,
"text": ">>> axes2[2]= ax.clabel(CS) Label a contour plot\n"
},
{
"code": null,
"e": 6703,
"s": 6695,
"text": "Figure\n"
},
{
"code": null,
"e": 6717,
"s": 6703,
"text": "Axes/Subplot\n"
},
{
"code": null,
"e": 6725,
"s": 6717,
"text": "Y-axis\n"
},
{
"code": null,
"e": 6733,
"s": 6725,
"text": "X-axis\n"
},
{
"code": null,
"e": 6742,
"s": 6733,
"text": "1D Data\n"
},
{
"code": null,
"e": 6761,
"s": 6742,
"text": "2D Data or Images\n"
},
{
"code": null,
"e": 6799,
"s": 6761,
"text": ">>> plt.plot(x, x, x, x**2, x, x**3)\n"
},
{
"code": null,
"e": 6831,
"s": 6799,
"text": ">>> ax.plot(x, y, alpha = 0.4)\n"
},
{
"code": null,
"e": 6857,
"s": 6831,
"text": ">>> ax.plot(x, y, c='k')\n"
},
{
"code": null,
"e": 6905,
"s": 6857,
"text": ">>> fig.colorbar(im, orientation='horizontal')\n"
},
{
"code": null,
"e": 6930,
"s": 6905,
"text": ">>> im = ax.imshow(img,\n"
},
{
"code": null,
"e": 6947,
"s": 6930,
"text": "cmap='seismic')\n"
},
{
"code": null,
"e": 6977,
"s": 6947,
"text": ">>> fig, ax = plt.subplots()\n"
},
{
"code": null,
"e": 7009,
"s": 6977,
"text": ">>> ax.scatter(x,y,marker=\".\")\n"
},
{
"code": null,
"e": 7038,
"s": 7009,
"text": ">>> ax.plot(x,y,marker=\"o\")\n"
},
{
"code": null,
"e": 7083,
"s": 7038,
"text": ">>> plt.title(r'$sigma_i=15$', fontsize=20)\n"
},
{
"code": null,
"e": 7099,
"s": 7083,
"text": ">>> ax.text(1,\n"
},
{
"code": null,
"e": 7139,
"s": 7099,
"text": "-2.1, 'Example Graph', style='italic')\n"
},
{
"code": null,
"e": 7175,
"s": 7139,
"text": ">>> ax.annotate(\"Sine\", xy=(8, 0),\n"
},
{
"code": null,
"e": 7211,
"s": 7175,
"text": "xycoords='data', xytext=(10.5, 0),\n"
},
{
"code": null,
"e": 7290,
"s": 7211,
"text": "textcoords='data', arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"),)\n"
},
{
"code": null,
"e": 7323,
"s": 7290,
"text": ">>> plt.plot(x,y,linewidth=4.0)\n"
},
{
"code": null,
"e": 7353,
"s": 7323,
"text": ">>> plt.plot(x,y,ls='solid')\n"
},
{
"code": null,
"e": 7380,
"s": 7353,
"text": ">>> plt.plot(x,y,ls='--')\n"
},
{
"code": null,
"e": 7419,
"s": 7380,
"text": ">>> plt.plot(x,y,'--',x**2,y**2,'-.')\n"
},
{
"code": null,
"e": 7464,
"s": 7419,
"text": ">>> plt.setp(lines,color='r',linewidth=4.0)\n"
},
{
"code": null,
"e": 7501,
"s": 7464,
"text": ">>> import matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 7516,
"s": 7501,
"text": "Close & Clear\n"
},
{
"code": null,
"e": 7545,
"s": 7516,
"text": ">>> plt.cla() Clear an axis\n"
},
{
"code": null,
"e": 7584,
"s": 7545,
"text": ">>> plt.clf() Clear the entire figure\n"
},
{
"code": null,
"e": 7616,
"s": 7584,
"text": ">>> plt.close() Close a window\n"
},
{
"code": null,
"e": 7809,
"s": 7616,
"text": "Matplotlib’s animation base class deals with the animation part. It provides a framework around which the animation functionality is built. There are two main interfaces to achieve that using:"
},
{
"code": null,
"e": 7881,
"s": 7809,
"text": "FuncAnimation makes an animation by repeatedly calling a function func."
},
{
"code": null,
"e": 7945,
"s": 7881,
"text": "ArtistAnimation: Animation using a fixed set of Artist objects."
},
{
"code": null,
"e": 8135,
"s": 7945,
"text": "However, out of the two, FuncAnimation is the most convenient one to use. You can read more about them in the documentation since we will only concern ourselves with the FuncAnimation tool."
},
{
"code": null,
"e": 8195,
"s": 8135,
"text": "Modules including numpy and matplotlib should be installed."
},
{
"code": null,
"e": 8298,
"s": 8195,
"text": "To save the animation on your system as mp4 or gif, ffmpeg or imagemagick is required to be installed."
},
{
"code": null,
"e": 8521,
"s": 8298,
"text": "Once ready, we can begin with our first basic animation in the Jupyter Notebooks. The code for this article can be accessed from the associated Github Repository or you can view it on my binder by clicking the image below."
},
{
"code": null,
"e": 8811,
"s": 8521,
"text": "Let’s use FuncAnimation to create a basic animation of a sine wave moving across the screen. The source code for the animation has been taken from the Matplotlib Animation tutorial. Let’s first see the output and then we shall break down the code to understand what’s going under the hood."
},
{
"code": null,
"e": 9043,
"s": 8811,
"text": "In lines(7–9), we simply create a figure window with a single axis in the figure. Then we create our empty line object which is essentially the one to be modified in the animation. The line object will be populated with data later."
},
{
"code": null,
"e": 9195,
"s": 9043,
"text": "In lines(11–13), we create the init function that will make the animation happen. The init function initializes the data and also sets the axis limits."
},
{
"code": null,
"e": 9557,
"s": 9195,
"text": "In lines(14–18), we finally define the animation function which takes in the frame number(i) as the parameter and creates a sine wave(or any other animation) which a shift depending upon the value of i. This function here returns a tuple of the plot objects which have been modified which tells the animation framework what parts of the plot should be animated."
},
{
"code": null,
"e": 9708,
"s": 9557,
"text": "In line 20, we create the actual animation object. The blit parameter ensures that only those pieces of the plot are re-drawn which have been changed."
},
{
"code": null,
"e": 9888,
"s": 9708,
"text": "This is the basic intuition behind creating animations in Matplotlib. With a little tweak in the code, interesting visualizations can be created. Let’s have a look at some of them"
},
{
"code": null,
"e": 10132,
"s": 9888,
"text": "Similarly, there is a nice example of creating shapes at GeeksforGeeks. Let’s now create a moving coil that slowly unwinds, with the help of animation class of matplotlib. The code is quite similar to the sine wave plot with minor adjustments."
},
{
"code": null,
"e": 10462,
"s": 10132,
"text": "Live updating graphs come in handy when plotting dynamic quantities like stock data, sensor data or any other time-dependent data. We plot a base graph which automatically gets updated as more data is fed into the system. This example has been taken from sentdex. Be sure to visit this youtube channel for some awesome tutorials."
},
{
"code": null,
"e": 10524,
"s": 10462,
"text": "Let’s plot stock prices of a hypothetical company in a month."
},
{
"code": null,
"e": 10652,
"s": 10524,
"text": "Now, open the terminal and run the python file. You will get a graph like the one below which automatically updates as follows:"
},
{
"code": null,
"e": 10702,
"s": 10652,
"text": "Here interval is 1000 milliseconds or one second."
},
{
"code": null,
"e": 10959,
"s": 10702,
"text": "Creating 3D graphs is common but what if we can animate the angle of view of those graphs. The idea is to change the camera view and then use every resulting image to create an animation. There is a nice section dedicated to it at The Python Graph Gallery."
},
{
"code": null,
"e": 11116,
"s": 10959,
"text": "Create a folder called volcano in the same directory as the notebook. All the images will be stored in this folder which will be then used in the animation."
},
{
"code": null,
"e": 11312,
"s": 11116,
"text": "This will create multiple PNG files in the Volcano folder. Now, use ImageMagick to transform them into animation. Open Terminal and navigate to the Volcano folder and enter the following command:"
},
{
"code": null,
"e": 11364,
"s": 11312,
"text": "convert -delay 10 Volcano*.png animated_volcano.gif"
},
{
"code": null,
"e": 11681,
"s": 11364,
"text": "Celluloid is a Python module that simplifies the process of creating animations in matplotlib. This library creates a matplotlib figure and creates a Camera from it. It then reuses figure and after each frame is created, take a snapshot with the camera. Finally, an animation is created with all the captured frames."
},
{
"code": null,
"e": 11703,
"s": 11681,
"text": "pip install celluloid"
},
{
"code": null,
"e": 11755,
"s": 11703,
"text": "Here are a few examples using the Celluloid module."
}
] |
MFC - Strings
|
Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++.
This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.
This string is actually a one-dimensional array of characters which is terminated by a null character '\0'.
A null-terminated string contains the characters that comprise the string followed by a null.
A null-terminated string contains the characters that comprise the string followed by a null.
Here is the simple example of character array.
char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0' };
Following is another way to represent it.
char word[] = "Hello, World";
Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString.
CString does not have a base class.
CString does not have a base class.
A CString object consists of a variable-length sequence of characters.
A CString object consists of a variable-length sequence of characters.
CString provides functions and operators using a syntax similar to that of Basic.
CString provides functions and operators using a syntax similar to that of Basic.
Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.
Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.
Here is the constructor of CString.
CString
Constructs CString objects in various ways
Here is a list of Array Methods −
GetLength
Returns the number of characters in a CString object.
IsEmpty
Tests whether a CString object contains no characters.
Empty
Forces a string to have 0 length.
GetAt
Returns the character at a specified position.
SetAt
Sets a character at a specified position.
Here is a list of Comparison Methods −
Compare
Compares two strings (case sensitive).
CompareNoCase
Compares two strings (case insensitive).
Here is a list of Extraction Methods −
Mid
Extracts the middle part of a string (like the Basic MID$ function).
Left
Extracts the left part of a string (like the Basic LEFT$ function).
Right
Extracts the right part of a string (like the Basic RIGHT$ function).
SpanIncluding
Extracts the characters from the string, which are in the given character set.
SpanExcluding
Extracts the characters from the string which are not in the given character set.
Here is a list of Conversion Methods.
MakeUpper
Converts all the characters in this string to uppercase characters.
MakeLower
Converts all the characters in this string to lowercase characters.
MakeReverse
Reverses the characters in this string.
Format
Format the string as sprintf does.
TrimLeft
Trim leading white-space characters from the string.
TrimRight
Trim trailing white-space characters from the string.
Here is a list of Searching Methods.
Find
Finds a character or substring inside a larger string.
ReverseFind
Finds a character inside a larger string; starts from the end.
FindOneOf
Finds the first matching character from a set.
Here is a list of Buffer Access Methods.
GetBuffer
Returns a pointer to the characters in the CString.
GetBufferSetLength
Returns a pointer to the characters in the CString, truncating to the specified length.
ReleaseBuffer
Releases control of the buffer returned by GetBuffer
FreeExtra
Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
LockBuffer
Disables reference counting and protects the string in the buffer.
UnlockBuffer
Enables reference counting and releases the string in the buffer.
Here is a list of Windows-Specific Methods.
AllocSysString
Allocates a BSTR from CString data.
SetSysString
Sets an existing BSTR object with data from a CString object.
LoadString
Loads an existing CString object from a Windows CE resource.
Following are the different operations on CString objects −
You can create a string by either using a string literal or creating an instance of CString class.
BOOL CMFCStringDemoDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CString string1 = _T("This is a string1");
CString string2("This is a string2");
m_strText.Append(string1 + L"\n");
m_strText.Append(string2);
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed, you will see the following output.
You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty.
BOOL CMFCStringDemoDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CString string1 = _T("");
CString string2;
string2.Empty();
if(string1.IsEmpty())
m_strText.Append(L"String1 is empty\n");
else
m_strText.Append(string1 + L"\n");
if(string2.IsEmpty())
m_strText.Append(L"String2 is empty");
else
m_strText.Append(string2);
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method.
BOOL CMFCStringDemoDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//To concatenate two CString objects
CString s1 = _T("This "); // Cascading concatenation
s1 += _T("is a ");
CString s2 = _T("test");
CString message = s1;
message.Append(_T("big ") + s2);
// Message contains "This is a big test".
m_strText = L"message: " + message;
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object.
BOOL CMFCStringDemoDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CString string1 = _T("This is string 1");
int length = string1.GetLength();
CString strLen;
strLen.Format(L"\nString1 contains %d characters", length);
m_strText = string1 + strLen;
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
To compare two strings variables you can use == operator
BOOL CMFCStringDemoDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
CString string1 = _T("Hello");
CString string2 = _T("World");
CString string3 = _T("MFC Tutorial");
CString string4 = _T("MFC Tutorial");
if (string1 == string2)
m_strText = "string1 and string1 are same\n";
else
m_strText = "string1 and string1 are not same\n";
if (string3 == string4)
m_strText += "string3 and string4 are same";
else
m_strText += "string3 and string4 are not same";
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
}
When the above code is compiled and executed you will see the following output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2231,
"s": 2067,
"text": "Strings are objects that represent sequences of characters. The C-style character string originated within the C language and continues to be supported within C++."
},
{
"code": null,
"e": 2339,
"s": 2231,
"text": "This string is actually a one-dimensional array of characters which is terminated by a null character '\\0'."
},
{
"code": null,
"e": 2447,
"s": 2339,
"text": "This string is actually a one-dimensional array of characters which is terminated by a null character '\\0'."
},
{
"code": null,
"e": 2541,
"s": 2447,
"text": "A null-terminated string contains the characters that comprise the string followed by a null."
},
{
"code": null,
"e": 2635,
"s": 2541,
"text": "A null-terminated string contains the characters that comprise the string followed by a null."
},
{
"code": null,
"e": 2682,
"s": 2635,
"text": "Here is the simple example of character array."
},
{
"code": null,
"e": 2763,
"s": 2682,
"text": "char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\\0' };"
},
{
"code": null,
"e": 2805,
"s": 2763,
"text": "Following is another way to represent it."
},
{
"code": null,
"e": 2835,
"s": 2805,
"text": "char word[] = \"Hello, World\";"
},
{
"code": null,
"e": 2980,
"s": 2835,
"text": "Microsoft Foundation Class (MFC) library provides a class to manipulate string called CString. Following are some important features of CString."
},
{
"code": null,
"e": 3016,
"s": 2980,
"text": "CString does not have a base class."
},
{
"code": null,
"e": 3052,
"s": 3016,
"text": "CString does not have a base class."
},
{
"code": null,
"e": 3123,
"s": 3052,
"text": "A CString object consists of a variable-length sequence of characters."
},
{
"code": null,
"e": 3194,
"s": 3123,
"text": "A CString object consists of a variable-length sequence of characters."
},
{
"code": null,
"e": 3276,
"s": 3194,
"text": "CString provides functions and operators using a syntax similar to that of Basic."
},
{
"code": null,
"e": 3358,
"s": 3276,
"text": "CString provides functions and operators using a syntax similar to that of Basic."
},
{
"code": null,
"e": 3509,
"s": 3358,
"text": "Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays."
},
{
"code": null,
"e": 3660,
"s": 3509,
"text": "Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays."
},
{
"code": null,
"e": 3696,
"s": 3660,
"text": "Here is the constructor of CString."
},
{
"code": null,
"e": 3704,
"s": 3696,
"text": "CString"
},
{
"code": null,
"e": 3747,
"s": 3704,
"text": "Constructs CString objects in various ways"
},
{
"code": null,
"e": 3781,
"s": 3747,
"text": "Here is a list of Array Methods −"
},
{
"code": null,
"e": 3791,
"s": 3781,
"text": "GetLength"
},
{
"code": null,
"e": 3845,
"s": 3791,
"text": "Returns the number of characters in a CString object."
},
{
"code": null,
"e": 3853,
"s": 3845,
"text": "IsEmpty"
},
{
"code": null,
"e": 3908,
"s": 3853,
"text": "Tests whether a CString object contains no characters."
},
{
"code": null,
"e": 3914,
"s": 3908,
"text": "Empty"
},
{
"code": null,
"e": 3948,
"s": 3914,
"text": "Forces a string to have 0 length."
},
{
"code": null,
"e": 3954,
"s": 3948,
"text": "GetAt"
},
{
"code": null,
"e": 4001,
"s": 3954,
"text": "Returns the character at a specified position."
},
{
"code": null,
"e": 4007,
"s": 4001,
"text": "SetAt"
},
{
"code": null,
"e": 4049,
"s": 4007,
"text": "Sets a character at a specified position."
},
{
"code": null,
"e": 4088,
"s": 4049,
"text": "Here is a list of Comparison Methods −"
},
{
"code": null,
"e": 4096,
"s": 4088,
"text": "Compare"
},
{
"code": null,
"e": 4135,
"s": 4096,
"text": "Compares two strings (case sensitive)."
},
{
"code": null,
"e": 4149,
"s": 4135,
"text": "CompareNoCase"
},
{
"code": null,
"e": 4190,
"s": 4149,
"text": "Compares two strings (case insensitive)."
},
{
"code": null,
"e": 4229,
"s": 4190,
"text": "Here is a list of Extraction Methods −"
},
{
"code": null,
"e": 4233,
"s": 4229,
"text": "Mid"
},
{
"code": null,
"e": 4302,
"s": 4233,
"text": "Extracts the middle part of a string (like the Basic MID$ function)."
},
{
"code": null,
"e": 4307,
"s": 4302,
"text": "Left"
},
{
"code": null,
"e": 4375,
"s": 4307,
"text": "Extracts the left part of a string (like the Basic LEFT$ function)."
},
{
"code": null,
"e": 4381,
"s": 4375,
"text": "Right"
},
{
"code": null,
"e": 4451,
"s": 4381,
"text": "Extracts the right part of a string (like the Basic RIGHT$ function)."
},
{
"code": null,
"e": 4465,
"s": 4451,
"text": "SpanIncluding"
},
{
"code": null,
"e": 4544,
"s": 4465,
"text": "Extracts the characters from the string, which are in the given character set."
},
{
"code": null,
"e": 4558,
"s": 4544,
"text": "SpanExcluding"
},
{
"code": null,
"e": 4640,
"s": 4558,
"text": "Extracts the characters from the string which are not in the given character set."
},
{
"code": null,
"e": 4678,
"s": 4640,
"text": "Here is a list of Conversion Methods."
},
{
"code": null,
"e": 4688,
"s": 4678,
"text": "MakeUpper"
},
{
"code": null,
"e": 4756,
"s": 4688,
"text": "Converts all the characters in this string to uppercase characters."
},
{
"code": null,
"e": 4766,
"s": 4756,
"text": "MakeLower"
},
{
"code": null,
"e": 4834,
"s": 4766,
"text": "Converts all the characters in this string to lowercase characters."
},
{
"code": null,
"e": 4846,
"s": 4834,
"text": "MakeReverse"
},
{
"code": null,
"e": 4886,
"s": 4846,
"text": "Reverses the characters in this string."
},
{
"code": null,
"e": 4893,
"s": 4886,
"text": "Format"
},
{
"code": null,
"e": 4928,
"s": 4893,
"text": "Format the string as sprintf does."
},
{
"code": null,
"e": 4937,
"s": 4928,
"text": "TrimLeft"
},
{
"code": null,
"e": 4990,
"s": 4937,
"text": "Trim leading white-space characters from the string."
},
{
"code": null,
"e": 5000,
"s": 4990,
"text": "TrimRight"
},
{
"code": null,
"e": 5054,
"s": 5000,
"text": "Trim trailing white-space characters from the string."
},
{
"code": null,
"e": 5091,
"s": 5054,
"text": "Here is a list of Searching Methods."
},
{
"code": null,
"e": 5096,
"s": 5091,
"text": "Find"
},
{
"code": null,
"e": 5151,
"s": 5096,
"text": "Finds a character or substring inside a larger string."
},
{
"code": null,
"e": 5163,
"s": 5151,
"text": "ReverseFind"
},
{
"code": null,
"e": 5226,
"s": 5163,
"text": "Finds a character inside a larger string; starts from the end."
},
{
"code": null,
"e": 5236,
"s": 5226,
"text": "FindOneOf"
},
{
"code": null,
"e": 5283,
"s": 5236,
"text": "Finds the first matching character from a set."
},
{
"code": null,
"e": 5324,
"s": 5283,
"text": "Here is a list of Buffer Access Methods."
},
{
"code": null,
"e": 5334,
"s": 5324,
"text": "GetBuffer"
},
{
"code": null,
"e": 5386,
"s": 5334,
"text": "Returns a pointer to the characters in the CString."
},
{
"code": null,
"e": 5405,
"s": 5386,
"text": "GetBufferSetLength"
},
{
"code": null,
"e": 5493,
"s": 5405,
"text": "Returns a pointer to the characters in the CString, truncating to the specified length."
},
{
"code": null,
"e": 5507,
"s": 5493,
"text": "ReleaseBuffer"
},
{
"code": null,
"e": 5561,
"s": 5507,
"text": "Releases control of the buffer returned by GetBuffer "
},
{
"code": null,
"e": 5571,
"s": 5561,
"text": "FreeExtra"
},
{
"code": null,
"e": 5678,
"s": 5571,
"text": "Removes any overhead of this string object by freeing any extra memory previously allocated to the string."
},
{
"code": null,
"e": 5689,
"s": 5678,
"text": "LockBuffer"
},
{
"code": null,
"e": 5757,
"s": 5689,
"text": "Disables reference counting and protects the string in the buffer. "
},
{
"code": null,
"e": 5770,
"s": 5757,
"text": "UnlockBuffer"
},
{
"code": null,
"e": 5837,
"s": 5770,
"text": "Enables reference counting and releases the string in the buffer. "
},
{
"code": null,
"e": 5881,
"s": 5837,
"text": "Here is a list of Windows-Specific Methods."
},
{
"code": null,
"e": 5896,
"s": 5881,
"text": "AllocSysString"
},
{
"code": null,
"e": 5932,
"s": 5896,
"text": "Allocates a BSTR from CString data."
},
{
"code": null,
"e": 5945,
"s": 5932,
"text": "SetSysString"
},
{
"code": null,
"e": 6007,
"s": 5945,
"text": "Sets an existing BSTR object with data from a CString object."
},
{
"code": null,
"e": 6018,
"s": 6007,
"text": "LoadString"
},
{
"code": null,
"e": 6079,
"s": 6018,
"text": "Loads an existing CString object from a Windows CE resource."
},
{
"code": null,
"e": 6139,
"s": 6079,
"text": "Following are the different operations on CString objects −"
},
{
"code": null,
"e": 6238,
"s": 6139,
"text": "You can create a string by either using a string literal or creating an instance of CString class."
},
{
"code": null,
"e": 6797,
"s": 6238,
"text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"This is a string1\");\n CString string2(\"This is a string2\");\n\n m_strText.Append(string1 + L\"\\n\");\n m_strText.Append(string2);\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 6878,
"s": 6797,
"text": "When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 7070,
"s": 6878,
"text": "You can create an empty string by either using an empty string literal or by using CString::Empty() method. You can also check whether a string is empty or not using Boolean property isEmpty."
},
{
"code": null,
"e": 7783,
"s": 7070,
"text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"\");\n CString string2;\n string2.Empty();\n\n if(string1.IsEmpty())\n m_strText.Append(L\"String1 is empty\\n\");\n else\n m_strText.Append(string1 + L\"\\n\");\n \n if(string2.IsEmpty())\n m_strText.Append(L\"String2 is empty\");\n else\n m_strText.Append(string2);\n UpdateData(FALSE);\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 7863,
"s": 7783,
"text": "When the above code is compiled and executed you will see the following output."
},
{
"code": null,
"e": 7980,
"s": 7863,
"text": "To concatenate two or more strings, you can use + operator to concatenate two strings or a CString::Append() method."
},
{
"code": null,
"e": 8696,
"s": 7980,
"text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n //To concatenate two CString objects\n CString s1 = _T(\"This \"); // Cascading concatenation\n s1 += _T(\"is a \");\n CString s2 = _T(\"test\");\n CString message = s1;\n message.Append(_T(\"big \") + s2);\n // Message contains \"This is a big test\".\n\n m_strText = L\"message: \" + message;\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 8776,
"s": 8696,
"text": "When the above code is compiled and executed you will see the following output."
},
{
"code": null,
"e": 8914,
"s": 8776,
"text": "To find the length of the string you can use the CString::GetLength() method, which returns the number of characters in a CString object."
},
{
"code": null,
"e": 9529,
"s": 8914,
"text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"This is string 1\");\n int length = string1.GetLength();\n CString strLen;\n\n strLen.Format(L\"\\nString1 contains %d characters\", length);\n m_strText = string1 + strLen;\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 9609,
"s": 9529,
"text": "When the above code is compiled and executed you will see the following output."
},
{
"code": null,
"e": 9666,
"s": 9609,
"text": "To compare two strings variables you can use == operator"
},
{
"code": null,
"e": 10514,
"s": 9666,
"text": "BOOL CMFCStringDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n CString string1 = _T(\"Hello\");\n CString string2 = _T(\"World\");\n\n CString string3 = _T(\"MFC Tutorial\");\n CString string4 = _T(\"MFC Tutorial\");\n\n if (string1 == string2)\n m_strText = \"string1 and string1 are same\\n\";\n else\n m_strText = \"string1 and string1 are not same\\n\";\n\n if (string3 == string4)\n m_strText += \"string3 and string4 are same\";\n else\n m_strText += \"string3 and string4 are not same\";\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 10594,
"s": 10514,
"text": "When the above code is compiled and executed you will see the following output."
},
{
"code": null,
"e": 10601,
"s": 10594,
"text": " Print"
},
{
"code": null,
"e": 10612,
"s": 10601,
"text": " Add Notes"
}
] |
Python - Working with PNG Images using Matplotlib
|
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
#applying pseudocolor
# importing pyplot and image from matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image
im = img.imread('imR.png')
# applying pseudocolor
# default value of colormap is used.
lum = im[:, :, 0]
# show image
plt.imshow(lum)
#colorbar
# importing pyplot and image from matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image
im = img.imread('imR.png')
lum = im[:, :, 0]
# setting colormap as hot
plt.imshow(lum, cmap ='hot')
plt.colorbar()
#interpolation
# importing PIL and matplotlib
from PIL import Image
import matplotlib.pyplot as plt
# reading png image file
img = Image.open('imR.png')
# resizing the image
img.thumbnail((50, 50), Image.ANTIALIAS)
imgplot = plt.imshow(img)
#bicubic value for interpolation
# importing pyplot from matplotlib
import matplotlib.pyplot as plt
# importing image from PIL
from PIL import Image
# reading image
img = Image.open('imR.png')
img.thumbnail((30, 30), Image.ANTIALIAS)
# bicubic used for interpolation
imgplot = plt.imshow(img, interpolation ='bicubic')#sinc value for interpolation
# sinc value for interpolation
# importing PIL and matplotlib
from PIL import Image
import matplotlib.pyplot as plt
# reading image
img = Image.open('imR.png')
img.thumbnail((30, 30), Image.ANTIALIAS)
# sinc used for interpolation
imgplot = plt.imshow(img, interpolation ='sinc')
|
[
{
"code": null,
"e": 1274,
"s": 1062,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 2693,
"s": 1274,
"text": "#applying pseudocolor\n# importing pyplot and image from matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img \n# reading png image\nim = img.imread('imR.png') \n# applying pseudocolor\n# default value of colormap is used.\nlum = im[:, :, 0] \n# show image\nplt.imshow(lum)\n#colorbar\n# importing pyplot and image from matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\n# reading png image\nim = img.imread('imR.png')\nlum = im[:, :, 0] \n# setting colormap as hot\nplt.imshow(lum, cmap ='hot')\nplt.colorbar()\n#interpolation\n# importing PIL and matplotlib\nfrom PIL import Image\nimport matplotlib.pyplot as plt \n# reading png image file\nimg = Image.open('imR.png') \n# resizing the image\nimg.thumbnail((50, 50), Image.ANTIALIAS)\nimgplot = plt.imshow(img)\n#bicubic value for interpolation\n# importing pyplot from matplotlib\nimport matplotlib.pyplot as plt\n# importing image from PIL\nfrom PIL import Image\n# reading image\nimg = Image.open('imR.png')\nimg.thumbnail((30, 30), Image.ANTIALIAS)\n# bicubic used for interpolation\nimgplot = plt.imshow(img, interpolation ='bicubic')#sinc value for interpolation\n# sinc value for interpolation\n# importing PIL and matplotlib\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n# reading image\nimg = Image.open('imR.png')\nimg.thumbnail((30, 30), Image.ANTIALIAS)\n# sinc used for interpolation\nimgplot = plt.imshow(img, interpolation ='sinc')"
}
] |
Check whether two strings are equivalent or not according to given condition - GeeksforGeeks
|
09 Nov, 2021
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct:
A1 is recursively equivalent to B1 and A2 is recursively equivalent to B2
A1 is recursively equivalent to B2 and A2 is recursively equivalent to B1
Check whether given strings are equivalent or not. Print YES or NO.Examples:
Input : A = “aaba”, B = “abaa” Output : YES Explanation : Since condition 1 doesn’t hold true, we can divide string A into “aaba” = “aa” + “ba” and string B into “abaa” = “ab” + “aa”. Here, 2nd subcondition holds true where A1 is equal to B2 and A2 is recursively equal to B1Input : A = “aabb”, B = “abab” Output : NO
Naive Solution : A simple solution is to consider all possible scenarios. Check first if the both strings are equal return “YES”, otherwise divide the strings and check if A1 = B1 and A2 = B2 or A1 = B2 and A2 = B1 by using four recursive calls. Complexity of this solution would be O(n2), where n is the size of the string.Efficient Solution : Let’s define following operation on string S. We can divide it into two halves and if we want we can swap them. And also, we can recursively apply this operation to both of its halves. By careful observation, we can see that if after applying the operation on some string A, we can obtain B, then after applying the operation on B we can obtain A. And for the given two strings, we can recursively find the least lexicographically string that can be obtained from them. Those obtained strings if are equal, answer is YES, otherwise NO. For example, least lexicographically string for “aaba” is “aaab”. And least lexicographically string for “abaa” is also “aaab”. Hence both of these are equivalent.Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
PHP
// CPP Program to find whether two strings// are equivalent or not according to given// condition#include <bits/stdc++.h>using namespace std; // This function returns the least lexicogr// aphical string obtained from its two halvesstring leastLexiString(string s){ // Base Case - If string size is 1 if (s.size() & 1) return s; // Divide the string into its two halves string x = leastLexiString(s.substr(0, s.size() / 2)); string y = leastLexiString(s.substr(s.size() / 2)); // Form least lexicographical string return min(x + y, y + x);} bool areEquivalent(string a, string b){ return (leastLexiString(a) == leastLexiString(b));} // Driver Codeint main(){ string a = "aaba"; string b = "abaa"; if (areEquivalent(a, b)) cout << "YES" << endl; else cout << "NO" << endl; a = "aabb"; b = "abab"; if (areEquivalent(a, b)) cout << "YES" << endl; else cout << "NO" << endl; return 0;}
// Java Program to find whether two strings// are equivalent or not according to given// conditionclass GfG{ // This function returns the least lexicogr// aphical String obtained from its two halvesstatic String leastLexiString(String s){ // Base Case - If String size is 1 if (s.length() == 1) return s; // Divide the String into its two halves String x = leastLexiString(s.substring(0, s.length() / 2)); String y = leastLexiString(s.substring(s.length() / 2)); // Form least lexicographical String return String.valueOf((x + y).compareTo(y + x));} static boolean areEquivalent(String a, String b){ return !(leastLexiString(a).equals(leastLexiString(b)));} // Driver Codepublic static void main(String[] args){ String a = "aaba"; String b = "abaa"; if (areEquivalent(a, b)) System.out.println("Yes"); else System.out.println("No"); a = "aabb"; b = "abab"; if (areEquivalent(a, b)) System.out.println("Yes"); else System.out.println("No"); }} /* This code contributed by PrinciRaj1992 */
# Python 3 Program to find whether two strings# are equivalent or not according to given# condition # This function returns the least lexicogr# aphical string obtained from its two halvesdef leastLexiString(s): # Base Case - If string size is 1 if (len(s) & 1 != 0): return s # Divide the string into its two halves x = leastLexiString(s[0:int(len(s) / 2)]) y = leastLexiString(s[int(len(s) / 2):len(s)]) # Form least lexicographical string return min(x + y, y + x) def areEquivalent(a,b): return (leastLexiString(a) == leastLexiString(b)) # Driver Codeif __name__ == '__main__': a = "aaba" b = "abaa" if (areEquivalent(a, b)): print("YES") else: print("NO") a = "aabb" b = "abab" if (areEquivalent(a, b)): print("YES") else: print("NO") # This code is contributed by# Surendra_Gangwar
// C# Program to find whether two strings// are equivalent or not according to given// conditionusing System;class GFG{ // This function returns the least lexicogr-// aphical String obtained from its two halvesstatic String leastLexiString(String s){ // Base Case - If String size is 1 if (s.Length == 1) return s; // Divide the String into its two halves String x = leastLexiString(s.Substring(0, s.Length / 2)); String y = leastLexiString(s.Substring( s.Length / 2)); // Form least lexicographical String return ((x + y).CompareTo(y + x).ToString());} static Boolean areEquivalent(String a, String b){ return !(leastLexiString(a).Equals( leastLexiString(b)));} // Driver Codepublic static void Main(String[] args){ String a = "aaba"; String b = "abaa"; if (areEquivalent(a, b)) Console.WriteLine("YES"); else Console.WriteLine("NO"); a = "aabb"; b = "abab"; if (areEquivalent(a, b)) Console.WriteLine("YES"); else Console.WriteLine("NO");}} // This code is contributed by PrinciRaj1992
<script> // Javascript Program to find whether two strings // are equivalent or not according to given // condition // This function returns the least lexicogr- // aphical String obtained from its two halves function leastLexiString(s) { // Base Case - If String size is 1 if (s.length == 1) return s; // Divide the String into its two halves let x = leastLexiString(s.substring(0, s.length / 2)); let y = leastLexiString(s.substring( s.length / 2)); // Form least lexicographical String if((x + y) < (y + x)) { return (x+y); } else{ return (y+x); } } function areEquivalent(a, b) { return (leastLexiString(a) == leastLexiString(b)); } let a = "aaba"; let b = "abaa"; if (areEquivalent(a, b)) document.write("YES" + "</br>"); else document.write("NO" + "</br>"); a = "aabb"; b = "abab"; if (areEquivalent(a, b)) document.write("YES" + "</br>"); else document.write("NO" + "</br>"); // This code is contributed by decode2207.</script>
<?php// PHP Program to find whether two strings// are equivalent or not according to given// condition // This function returns the least lexicogr// aphical string obtained from its two halvesfunction leastLexiString($s){ // Base Case - If string size is 1 if (strlen($s) & 1) return $s; // Divide the string into its two halves $x = leastLexiString(substr($s, 0,floor(strlen($s) / 2))); $y = leastLexiString(substr($s,floor(strlen($s) / 2),strlen($s))); // Form least lexicographical string return min($x.$y, $y.$x);} function areEquivalent($a, $b){ return (leastLexiString($a) == leastLexiString($b));} // Driver Code $a = "aaba"; $b = "abaa"; if (areEquivalent($a, $b)) echo "YES", "\n"; else echo "NO", "\n"; $a = "aabb"; $b = "abab"; if (areEquivalent($a, $b)) echo "YES", "\n"; else echo "NO","\n"; // This code is contributed by Ryuga?>
YES
NO
Time Complexity: O(N*logN), where N is the size of the string.Auxiliary Space: O(logN)
SURENDRA_GANGWAR
ankthon
princiraj1992
pankajsharmagfg
decode2207
cpp-strings
tail-recursion
Algorithms
Recursion
Strings
cpp-strings
Strings
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Difference between Informed and Uninformed Search in AI
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
K means Clustering - Introduction
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Program for Sum of the digits of a given number
Backtracking | Introduction
|
[
{
"code": null,
"e": 24299,
"s": 24271,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24639,
"s": 24299,
"text": "Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct: "
},
{
"code": null,
"e": 24713,
"s": 24639,
"text": "A1 is recursively equivalent to B1 and A2 is recursively equivalent to B2"
},
{
"code": null,
"e": 24787,
"s": 24713,
"text": "A1 is recursively equivalent to B2 and A2 is recursively equivalent to B1"
},
{
"code": null,
"e": 24866,
"s": 24787,
"text": "Check whether given strings are equivalent or not. Print YES or NO.Examples: "
},
{
"code": null,
"e": 25186,
"s": 24866,
"text": "Input : A = “aaba”, B = “abaa” Output : YES Explanation : Since condition 1 doesn’t hold true, we can divide string A into “aaba” = “aa” + “ba” and string B into “abaa” = “ab” + “aa”. Here, 2nd subcondition holds true where A1 is equal to B2 and A2 is recursively equal to B1Input : A = “aabb”, B = “abab” Output : NO "
},
{
"code": null,
"e": 26283,
"s": 25186,
"text": "Naive Solution : A simple solution is to consider all possible scenarios. Check first if the both strings are equal return “YES”, otherwise divide the strings and check if A1 = B1 and A2 = B2 or A1 = B2 and A2 = B1 by using four recursive calls. Complexity of this solution would be O(n2), where n is the size of the string.Efficient Solution : Let’s define following operation on string S. We can divide it into two halves and if we want we can swap them. And also, we can recursively apply this operation to both of its halves. By careful observation, we can see that if after applying the operation on some string A, we can obtain B, then after applying the operation on B we can obtain A. And for the given two strings, we can recursively find the least lexicographically string that can be obtained from them. Those obtained strings if are equal, answer is YES, otherwise NO. For example, least lexicographically string for “aaba” is “aaab”. And least lexicographically string for “abaa” is also “aaab”. Hence both of these are equivalent.Below is the implementation of the above approach. "
},
{
"code": null,
"e": 26287,
"s": 26283,
"text": "C++"
},
{
"code": null,
"e": 26292,
"s": 26287,
"text": "Java"
},
{
"code": null,
"e": 26300,
"s": 26292,
"text": "Python3"
},
{
"code": null,
"e": 26303,
"s": 26300,
"text": "C#"
},
{
"code": null,
"e": 26314,
"s": 26303,
"text": "Javascript"
},
{
"code": null,
"e": 26318,
"s": 26314,
"text": "PHP"
},
{
"code": "// CPP Program to find whether two strings// are equivalent or not according to given// condition#include <bits/stdc++.h>using namespace std; // This function returns the least lexicogr// aphical string obtained from its two halvesstring leastLexiString(string s){ // Base Case - If string size is 1 if (s.size() & 1) return s; // Divide the string into its two halves string x = leastLexiString(s.substr(0, s.size() / 2)); string y = leastLexiString(s.substr(s.size() / 2)); // Form least lexicographical string return min(x + y, y + x);} bool areEquivalent(string a, string b){ return (leastLexiString(a) == leastLexiString(b));} // Driver Codeint main(){ string a = \"aaba\"; string b = \"abaa\"; if (areEquivalent(a, b)) cout << \"YES\" << endl; else cout << \"NO\" << endl; a = \"aabb\"; b = \"abab\"; if (areEquivalent(a, b)) cout << \"YES\" << endl; else cout << \"NO\" << endl; return 0;}",
"e": 27325,
"s": 26318,
"text": null
},
{
"code": "// Java Program to find whether two strings// are equivalent or not according to given// conditionclass GfG{ // This function returns the least lexicogr// aphical String obtained from its two halvesstatic String leastLexiString(String s){ // Base Case - If String size is 1 if (s.length() == 1) return s; // Divide the String into its two halves String x = leastLexiString(s.substring(0, s.length() / 2)); String y = leastLexiString(s.substring(s.length() / 2)); // Form least lexicographical String return String.valueOf((x + y).compareTo(y + x));} static boolean areEquivalent(String a, String b){ return !(leastLexiString(a).equals(leastLexiString(b)));} // Driver Codepublic static void main(String[] args){ String a = \"aaba\"; String b = \"abaa\"; if (areEquivalent(a, b)) System.out.println(\"Yes\"); else System.out.println(\"No\"); a = \"aabb\"; b = \"abab\"; if (areEquivalent(a, b)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} /* This code contributed by PrinciRaj1992 */",
"e": 28441,
"s": 27325,
"text": null
},
{
"code": "# Python 3 Program to find whether two strings# are equivalent or not according to given# condition # This function returns the least lexicogr# aphical string obtained from its two halvesdef leastLexiString(s): # Base Case - If string size is 1 if (len(s) & 1 != 0): return s # Divide the string into its two halves x = leastLexiString(s[0:int(len(s) / 2)]) y = leastLexiString(s[int(len(s) / 2):len(s)]) # Form least lexicographical string return min(x + y, y + x) def areEquivalent(a,b): return (leastLexiString(a) == leastLexiString(b)) # Driver Codeif __name__ == '__main__': a = \"aaba\" b = \"abaa\" if (areEquivalent(a, b)): print(\"YES\") else: print(\"NO\") a = \"aabb\" b = \"abab\" if (areEquivalent(a, b)): print(\"YES\") else: print(\"NO\") # This code is contributed by# Surendra_Gangwar",
"e": 29318,
"s": 28441,
"text": null
},
{
"code": "// C# Program to find whether two strings// are equivalent or not according to given// conditionusing System;class GFG{ // This function returns the least lexicogr-// aphical String obtained from its two halvesstatic String leastLexiString(String s){ // Base Case - If String size is 1 if (s.Length == 1) return s; // Divide the String into its two halves String x = leastLexiString(s.Substring(0, s.Length / 2)); String y = leastLexiString(s.Substring( s.Length / 2)); // Form least lexicographical String return ((x + y).CompareTo(y + x).ToString());} static Boolean areEquivalent(String a, String b){ return !(leastLexiString(a).Equals( leastLexiString(b)));} // Driver Codepublic static void Main(String[] args){ String a = \"aaba\"; String b = \"abaa\"; if (areEquivalent(a, b)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); a = \"aabb\"; b = \"abab\"; if (areEquivalent(a, b)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");}} // This code is contributed by PrinciRaj1992",
"e": 30464,
"s": 29318,
"text": null
},
{
"code": "<script> // Javascript Program to find whether two strings // are equivalent or not according to given // condition // This function returns the least lexicogr- // aphical String obtained from its two halves function leastLexiString(s) { // Base Case - If String size is 1 if (s.length == 1) return s; // Divide the String into its two halves let x = leastLexiString(s.substring(0, s.length / 2)); let y = leastLexiString(s.substring( s.length / 2)); // Form least lexicographical String if((x + y) < (y + x)) { return (x+y); } else{ return (y+x); } } function areEquivalent(a, b) { return (leastLexiString(a) == leastLexiString(b)); } let a = \"aaba\"; let b = \"abaa\"; if (areEquivalent(a, b)) document.write(\"YES\" + \"</br>\"); else document.write(\"NO\" + \"</br>\"); a = \"aabb\"; b = \"abab\"; if (areEquivalent(a, b)) document.write(\"YES\" + \"</br>\"); else document.write(\"NO\" + \"</br>\"); // This code is contributed by decode2207.</script>",
"e": 31683,
"s": 30464,
"text": null
},
{
"code": "<?php// PHP Program to find whether two strings// are equivalent or not according to given// condition // This function returns the least lexicogr// aphical string obtained from its two halvesfunction leastLexiString($s){ // Base Case - If string size is 1 if (strlen($s) & 1) return $s; // Divide the string into its two halves $x = leastLexiString(substr($s, 0,floor(strlen($s) / 2))); $y = leastLexiString(substr($s,floor(strlen($s) / 2),strlen($s))); // Form least lexicographical string return min($x.$y, $y.$x);} function areEquivalent($a, $b){ return (leastLexiString($a) == leastLexiString($b));} // Driver Code $a = \"aaba\"; $b = \"abaa\"; if (areEquivalent($a, $b)) echo \"YES\", \"\\n\"; else echo \"NO\", \"\\n\"; $a = \"aabb\"; $b = \"abab\"; if (areEquivalent($a, $b)) echo \"YES\", \"\\n\"; else echo \"NO\",\"\\n\"; // This code is contributed by Ryuga?>",
"e": 32617,
"s": 31683,
"text": null
},
{
"code": null,
"e": 32624,
"s": 32617,
"text": "YES\nNO"
},
{
"code": null,
"e": 32714,
"s": 32626,
"text": "Time Complexity: O(N*logN), where N is the size of the string.Auxiliary Space: O(logN) "
},
{
"code": null,
"e": 32731,
"s": 32714,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32739,
"s": 32731,
"text": "ankthon"
},
{
"code": null,
"e": 32753,
"s": 32739,
"text": "princiraj1992"
},
{
"code": null,
"e": 32769,
"s": 32753,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32780,
"s": 32769,
"text": "decode2207"
},
{
"code": null,
"e": 32792,
"s": 32780,
"text": "cpp-strings"
},
{
"code": null,
"e": 32807,
"s": 32792,
"text": "tail-recursion"
},
{
"code": null,
"e": 32818,
"s": 32807,
"text": "Algorithms"
},
{
"code": null,
"e": 32828,
"s": 32818,
"text": "Recursion"
},
{
"code": null,
"e": 32836,
"s": 32828,
"text": "Strings"
},
{
"code": null,
"e": 32848,
"s": 32836,
"text": "cpp-strings"
},
{
"code": null,
"e": 32856,
"s": 32848,
"text": "Strings"
},
{
"code": null,
"e": 32866,
"s": 32856,
"text": "Recursion"
},
{
"code": null,
"e": 32877,
"s": 32866,
"text": "Algorithms"
},
{
"code": null,
"e": 32975,
"s": 32877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32984,
"s": 32975,
"text": "Comments"
},
{
"code": null,
"e": 32997,
"s": 32984,
"text": "Old Comments"
},
{
"code": null,
"e": 33022,
"s": 32997,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33078,
"s": 33022,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 33121,
"s": 33078,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 33150,
"s": 33121,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33184,
"s": 33150,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 33244,
"s": 33184,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33329,
"s": 33244,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33356,
"s": 33329,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 33404,
"s": 33356,
"text": "Program for Sum of the digits of a given number"
}
] |
Erlang - Tuples
|
A tuple is a compound data type with a fixed number of terms. Each term in the Tuple is called an element. The number of elements is said to be the size of the Tuple.
An example of how the Tuple data type can be used is shown in the following program.
Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang which can be used to determine the size of the Tuple.
-module(helloworld).
-export([start/0]).
start() ->
P = {john,24,{june,25}} ,
io:fwrite("~w",[tuple_size(P)]).
The output of the above program will be as follows.
3
Let’s look at some more operations which are available for tuples.
is_tuple
This method is used to determine is the term provided is indeed a tuple.
list_to_tuple
This method is to convert a list to a tuple.
tuple_to_list
This method is convert a tuple to a list.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2468,
"s": 2301,
"text": "A tuple is a compound data type with a fixed number of terms. Each term in the Tuple is called an element. The number of elements is said to be the size of the Tuple."
},
{
"code": null,
"e": 2553,
"s": 2468,
"text": "An example of how the Tuple data type can be used is shown in the following program."
},
{
"code": null,
"e": 2713,
"s": 2553,
"text": "Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang which can be used to determine the size of the Tuple."
},
{
"code": null,
"e": 2834,
"s": 2713,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n P = {john,24,{june,25}} , \n io:fwrite(\"~w\",[tuple_size(P)])."
},
{
"code": null,
"e": 2886,
"s": 2834,
"text": "The output of the above program will be as follows."
},
{
"code": null,
"e": 2889,
"s": 2886,
"text": "3\n"
},
{
"code": null,
"e": 2956,
"s": 2889,
"text": "Let’s look at some more operations which are available for tuples."
},
{
"code": null,
"e": 2965,
"s": 2956,
"text": "is_tuple"
},
{
"code": null,
"e": 3038,
"s": 2965,
"text": "This method is used to determine is the term provided is indeed a tuple."
},
{
"code": null,
"e": 3052,
"s": 3038,
"text": "list_to_tuple"
},
{
"code": null,
"e": 3097,
"s": 3052,
"text": "This method is to convert a list to a tuple."
},
{
"code": null,
"e": 3111,
"s": 3097,
"text": "tuple_to_list"
},
{
"code": null,
"e": 3153,
"s": 3111,
"text": "This method is convert a tuple to a list."
},
{
"code": null,
"e": 3160,
"s": 3153,
"text": " Print"
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": " Add Notes"
}
] |
Python script to monitor website changes
|
24 Nov, 2021
In this article, we are going to discuss how to create a python script to monitor website changes. You can code a program to monitor a website and it will notify you if there are any changes. This program has many useful scenarios for example if your school website has updated something you will come to know about it.
We will follow the following steps to write this program:
Read the URL you want to monitor.Hash the entire website.Wait for a specified amount of seconds.If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash.
Read the URL you want to monitor.
Hash the entire website.
Wait for a specified amount of seconds.
If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash.
Libraries we will be using are:
time: To wait for a specified amount of time.
hashlib: To hash the content of the entire website.
urllib: To perform the get request and load the content of the website.
Python3
# Importing librariesimport timeimport hashlibfrom urllib.request import urlopen, Request # setting the URL you want to monitorurl = Request('https://leetcode.com/', headers={'User-Agent': 'Mozilla/5.0'}) # to perform a GET request and load the# content of the website and store it in a varresponse = urlopen(url).read() # to create the initial hashcurrentHash = hashlib.sha224(response).hexdigest()print("running")time.sleep(10)while True: try: # perform the get request and store it in a var response = urlopen(url).read() # create a hash currentHash = hashlib.sha224(response).hexdigest() # wait for 30 seconds time.sleep(30) # perform the get request response = urlopen(url).read() # create a new hash newHash = hashlib.sha224(response).hexdigest() # check if new hash is same as the previous hash if newHash == currentHash: continue # if something changed in the hashes else: # notify print("something changed") # again read the website response = urlopen(url).read() # create a hash currentHash = hashlib.sha224(response).hexdigest() # wait for 30 seconds time.sleep(30) continue # To handle exceptions except Exception as e: print("error")
Output:
output
Note: time.sleep() takes seconds as a parameter. You can make changes for notification instead of printing the status on the terminal you can write a program to get an email.
kapoorsagar226
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 375,
"s": 54,
"text": "In this article, we are going to discuss how to create a python script to monitor website changes. You can code a program to monitor a website and it will notify you if there are any changes. This program has many useful scenarios for example if your school website has updated something you will come to know about it. "
},
{
"code": null,
"e": 433,
"s": 375,
"text": "We will follow the following steps to write this program:"
},
{
"code": null,
"e": 647,
"s": 433,
"text": "Read the URL you want to monitor.Hash the entire website.Wait for a specified amount of seconds.If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash."
},
{
"code": null,
"e": 681,
"s": 647,
"text": "Read the URL you want to monitor."
},
{
"code": null,
"e": 706,
"s": 681,
"text": "Hash the entire website."
},
{
"code": null,
"e": 746,
"s": 706,
"text": "Wait for a specified amount of seconds."
},
{
"code": null,
"e": 864,
"s": 746,
"text": "If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash."
},
{
"code": null,
"e": 896,
"s": 864,
"text": "Libraries we will be using are:"
},
{
"code": null,
"e": 942,
"s": 896,
"text": "time: To wait for a specified amount of time."
},
{
"code": null,
"e": 994,
"s": 942,
"text": "hashlib: To hash the content of the entire website."
},
{
"code": null,
"e": 1066,
"s": 994,
"text": "urllib: To perform the get request and load the content of the website."
},
{
"code": null,
"e": 1074,
"s": 1066,
"text": "Python3"
},
{
"code": "# Importing librariesimport timeimport hashlibfrom urllib.request import urlopen, Request # setting the URL you want to monitorurl = Request('https://leetcode.com/', headers={'User-Agent': 'Mozilla/5.0'}) # to perform a GET request and load the# content of the website and store it in a varresponse = urlopen(url).read() # to create the initial hashcurrentHash = hashlib.sha224(response).hexdigest()print(\"running\")time.sleep(10)while True: try: # perform the get request and store it in a var response = urlopen(url).read() # create a hash currentHash = hashlib.sha224(response).hexdigest() # wait for 30 seconds time.sleep(30) # perform the get request response = urlopen(url).read() # create a new hash newHash = hashlib.sha224(response).hexdigest() # check if new hash is same as the previous hash if newHash == currentHash: continue # if something changed in the hashes else: # notify print(\"something changed\") # again read the website response = urlopen(url).read() # create a hash currentHash = hashlib.sha224(response).hexdigest() # wait for 30 seconds time.sleep(30) continue # To handle exceptions except Exception as e: print(\"error\")",
"e": 2512,
"s": 1074,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2512,
"text": "Output:"
},
{
"code": null,
"e": 2527,
"s": 2520,
"text": "output"
},
{
"code": null,
"e": 2702,
"s": 2527,
"text": "Note: time.sleep() takes seconds as a parameter. You can make changes for notification instead of printing the status on the terminal you can write a program to get an email."
},
{
"code": null,
"e": 2717,
"s": 2702,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2724,
"s": 2717,
"text": "Picked"
},
{
"code": null,
"e": 2739,
"s": 2724,
"text": "python-utility"
},
{
"code": null,
"e": 2746,
"s": 2739,
"text": "Python"
}
] |
Python | Prefix extraction before specific character
|
25 Jun, 2022
Sometimes, we might have a use case in which we need to find a prefix in a string. But sometimes, the requirement can be something dynamic like a specific input character than number of elements for the decision of getting prefix. Let’s discuss certain ways in which we can find the prefix of a string before a certain character.
Method #1: Using rsplit() This method originally performs the task of splitting the string from the rear end rather than the conventional left to right fashion. This can though be limited to 1, for solving this particular problem.
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rsplit() # initializing stringtest_str = "GeeksforGeeks & quot # initializing split characterspl_char = "r & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using rsplit()# Prefix extraction before specific characterres = test_str.rsplit(spl_char, 1)[0] # printing resultprint(& quot The prefix string is : & quot + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
Method #2: Using rpartition() If we need to solve this particular problem, this inbuilt function is recommended to perform this particular task. This function performs the partition as required just once from the rear end.
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rpartition() # initializing stringtest_str = "GeeksforGeeks & quot # initializing split characterspl_char = "r & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using rpartition()# Prefix extraction before specific characterres = test_str.rpartition(spl_char)[0] # printing resultprint(& quot The prefix string is : & quot + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
Method #3 : Using find() method.You can also use index() instead of find().
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using find() # initializing stringtest_str = "GeeksforGeeks" # initializing split characterspl_char = "r" # printing original stringprint("The original string is : " + str(test_str)) # Using find()# Prefix extraction before specific characterind=test_str.find(spl_char)res = test_str[0:ind] # printing resultprint("The prefix string is : " + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
kogantibhavya
Python string-programs
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
Introduction To PYTHON
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 Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Sometimes, we might have a use case in which we need to find a prefix in a string. But sometimes, the requirement can be something dynamic like a specific input character than number of elements for the decision of getting prefix. Let’s discuss certain ways in which we can find the prefix of a string before a certain character."
},
{
"code": null,
"e": 590,
"s": 358,
"text": "Method #1: Using rsplit() This method originally performs the task of splitting the string from the rear end rather than the conventional left to right fashion. This can though be limited to 1, for solving this particular problem. "
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rsplit() # initializing stringtest_str = \"GeeksforGeeks & quot # initializing split characterspl_char = \"r & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using rsplit()# Prefix extraction before specific characterres = test_str.rsplit(spl_char, 1)[0] # printing resultprint(& quot The prefix string is : & quot + str(res))",
"e": 1088,
"s": 598,
"text": null
},
{
"code": null,
"e": 1158,
"s": 1088,
"text": "The original string is : GeeksforGeeks\nThe prefix string is : Geeksfo"
},
{
"code": null,
"e": 1382,
"s": 1158,
"text": "Method #2: Using rpartition() If we need to solve this particular problem, this inbuilt function is recommended to perform this particular task. This function performs the partition as required just once from the rear end. "
},
{
"code": null,
"e": 1390,
"s": 1382,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rpartition() # initializing stringtest_str = \"GeeksforGeeks & quot # initializing split characterspl_char = \"r & quot # printing original stringprint(& quot The original string is : & quot + str(test_str)) # Using rpartition()# Prefix extraction before specific characterres = test_str.rpartition(spl_char)[0] # printing resultprint(& quot The prefix string is : & quot + str(res))",
"e": 1889,
"s": 1390,
"text": null
},
{
"code": null,
"e": 1959,
"s": 1889,
"text": "The original string is : GeeksforGeeks\nThe prefix string is : Geeksfo"
},
{
"code": null,
"e": 2035,
"s": 1959,
"text": "Method #3 : Using find() method.You can also use index() instead of find()."
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Prefix extraction before specific character# Using find() # initializing stringtest_str = \"GeeksforGeeks\" # initializing split characterspl_char = \"r\" # printing original stringprint(\"The original string is : \" + str(test_str)) # Using find()# Prefix extraction before specific characterind=test_str.find(spl_char)res = test_str[0:ind] # printing resultprint(\"The prefix string is : \" + str(res))",
"e": 2482,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2552,
"s": 2482,
"text": "The original string is : GeeksforGeeks\nThe prefix string is : Geeksfo"
},
{
"code": null,
"e": 2566,
"s": 2552,
"text": "kogantibhavya"
},
{
"code": null,
"e": 2589,
"s": 2566,
"text": "Python string-programs"
},
{
"code": null,
"e": 2596,
"s": 2589,
"text": "Python"
},
{
"code": null,
"e": 2612,
"s": 2596,
"text": "Python Programs"
},
{
"code": null,
"e": 2710,
"s": 2612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2742,
"s": 2710,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2769,
"s": 2742,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2790,
"s": 2769,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2813,
"s": 2790,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2869,
"s": 2813,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2891,
"s": 2869,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2930,
"s": 2891,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2968,
"s": 2930,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3005,
"s": 2968,
"text": "Python Program for Fibonacci numbers"
}
] |
How to create a skewed background using CSS ?
|
13 May, 2020
The skewed background design pattern is used as a banner on the front page of a website. It gives the website more natural and pleasing look. The skewed background can be easily created using CSS before and after selectors and using skew function.
Approach: The approach is simple. We will use a skew function with before and after selector to turn our borderline into a 2-D plane. The left side portion will be done using the before selector and the right side portion will be done using after selector. You can also change the order by doing a left side using the after selector and right side using before selector.
HTML Code: HTML code is used to design the basic structure of the web page. The following code contains two <section> element with id attribute.
<!DOCTYPE html><html lang="en"> <head> <title>Skewed Background</title></head> <body> <section id="geeks1"> <h1>GeeksforGeeks</h1> </section> <section id="geeks2"></section></body> </html>
CSS Code:
Step 1: First, provide background to both sections and set width to 100% and height can be set according to need.
Step 2: Now, use before selector on bottom section and decrease its width to 50% as we want our border to be skewed from the center. Height can be set as per the requirement. Then use skew function to transform it into a 2-D plane at a particular angle.
Step 3: Repeat the step-2 and change left to right and negate the degree of skewness.
The below code will show the implementation of the above steps.
Tip: You can choose your degree of skewness using the inspect feature and adjusting the degree through it to get the perfect angle.
<style> #geeks1 { width: 100%; height: 400px; position: relative; background: rgb(58, 238, 58); } h1 { text-align: center; padding: 200px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; color: white; font-size: 40px; } #geeks2 { width: 100%; height: 400px; position: relative; background: rgb(2, 94, 25); } #geeks2::before { content: ""; width: 50%; height: 100px; position: absolute; top: -48px; left: 0; background: rgb(2, 94, 25); transform: skewY(8deg); } #geeks2::after { content: ""; width: 50%; height: 100px; position: absolute; top: -48px; right: 0; background: rgb(2, 94, 25); transform: skewY(-8deg); }</style>
Complete Code: It is the combination of the above two sections to create a skewed background.
<!DOCTYPE html><html lang="en"> <head> <title>Skewed Background</title> <style> #geeks1 { width: 100%; height: 400px; position: relative; background: rgb(58, 238, 58); } h1 { text-align: center; padding: 200px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; color: white; font-size: 40px; } #geeks2 { width: 100%; height: 400px; position: relative; background: rgb(2, 94, 25); } #geeks2::before { content: ""; width: 50%; height: 100px; position: absolute; top: -48px; left: 0; background: rgb(2, 94, 25); transform: skewY(8deg); } #geeks2::after { content: ""; width: 50%; height: 100px; position: absolute; top: -48px; right: 0; background: rgb(2, 94, 25); transform: skewY(-8deg); } </style></head> <body> <section id="geeks1"> <h1>GeeksforGeeks</h1> </section> <section id="geeks2"></section></body> </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
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": "\n13 May, 2020"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "The skewed background design pattern is used as a banner on the front page of a website. It gives the website more natural and pleasing look. The skewed background can be easily created using CSS before and after selectors and using skew function."
},
{
"code": null,
"e": 647,
"s": 276,
"text": "Approach: The approach is simple. We will use a skew function with before and after selector to turn our borderline into a 2-D plane. The left side portion will be done using the before selector and the right side portion will be done using after selector. You can also change the order by doing a left side using the after selector and right side using before selector."
},
{
"code": null,
"e": 792,
"s": 647,
"text": "HTML Code: HTML code is used to design the basic structure of the web page. The following code contains two <section> element with id attribute."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Skewed Background</title></head> <body> <section id=\"geeks1\"> <h1>GeeksforGeeks</h1> </section> <section id=\"geeks2\"></section></body> </html>",
"e": 1003,
"s": 792,
"text": null
},
{
"code": null,
"e": 1013,
"s": 1003,
"text": "CSS Code:"
},
{
"code": null,
"e": 1127,
"s": 1013,
"text": "Step 1: First, provide background to both sections and set width to 100% and height can be set according to need."
},
{
"code": null,
"e": 1381,
"s": 1127,
"text": "Step 2: Now, use before selector on bottom section and decrease its width to 50% as we want our border to be skewed from the center. Height can be set as per the requirement. Then use skew function to transform it into a 2-D plane at a particular angle."
},
{
"code": null,
"e": 1467,
"s": 1381,
"text": "Step 3: Repeat the step-2 and change left to right and negate the degree of skewness."
},
{
"code": null,
"e": 1531,
"s": 1467,
"text": "The below code will show the implementation of the above steps."
},
{
"code": null,
"e": 1663,
"s": 1531,
"text": "Tip: You can choose your degree of skewness using the inspect feature and adjusting the degree through it to get the perfect angle."
},
{
"code": "<style> #geeks1 { width: 100%; height: 400px; position: relative; background: rgb(58, 238, 58); } h1 { text-align: center; padding: 200px; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Open Sans\", \"Helvetica Neue\", sans-serif; color: white; font-size: 40px; } #geeks2 { width: 100%; height: 400px; position: relative; background: rgb(2, 94, 25); } #geeks2::before { content: \"\"; width: 50%; height: 100px; position: absolute; top: -48px; left: 0; background: rgb(2, 94, 25); transform: skewY(8deg); } #geeks2::after { content: \"\"; width: 50%; height: 100px; position: absolute; top: -48px; right: 0; background: rgb(2, 94, 25); transform: skewY(-8deg); }</style>",
"e": 2662,
"s": 1663,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2662,
"text": "Complete Code: It is the combination of the above two sections to create a skewed background."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Skewed Background</title> <style> #geeks1 { width: 100%; height: 400px; position: relative; background: rgb(58, 238, 58); } h1 { text-align: center; padding: 200px; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Open Sans\", \"Helvetica Neue\", sans-serif; color: white; font-size: 40px; } #geeks2 { width: 100%; height: 400px; position: relative; background: rgb(2, 94, 25); } #geeks2::before { content: \"\"; width: 50%; height: 100px; position: absolute; top: -48px; left: 0; background: rgb(2, 94, 25); transform: skewY(8deg); } #geeks2::after { content: \"\"; width: 50%; height: 100px; position: absolute; top: -48px; right: 0; background: rgb(2, 94, 25); transform: skewY(-8deg); } </style></head> <body> <section id=\"geeks1\"> <h1>GeeksforGeeks</h1> </section> <section id=\"geeks2\"></section></body> </html>",
"e": 4147,
"s": 2756,
"text": null
},
{
"code": null,
"e": 4155,
"s": 4147,
"text": "Output:"
},
{
"code": null,
"e": 4164,
"s": 4155,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4174,
"s": 4164,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4178,
"s": 4174,
"text": "CSS"
},
{
"code": null,
"e": 4183,
"s": 4178,
"text": "HTML"
},
{
"code": null,
"e": 4200,
"s": 4183,
"text": "Web Technologies"
},
{
"code": null,
"e": 4227,
"s": 4200,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4232,
"s": 4227,
"text": "HTML"
}
] |
p5.js | center() Function
|
20 Aug, 2019
The center() function is used to set the alignment of element into the center either vertically, horizontally, or both, relative to its parent element or according to the body if the element has no parent. If this function does not contain any parameters then the element will align both vertically and horizontally.
Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file.
<script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
center( align )
Parameters: This function accepts single parameter align which holds the string ‘vertical’ or ‘horizontal’ to align the element.
Below examples illustrate the center() function in p5.js:
Example 1:
function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); var div = createDiv('').size(200, 70); div.html('Welcome to GeeksforGeeks', true); // Set the position of div into center div.center(); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); div.style('border', '1px solid white'); div.style('text-align', 'center'); }
Output:
Example 2:
function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div into center input_val.center(); // Set font-size of text input_val.style('font-size', '24px'); // Set the width of input area input_val.style('width', '300px'); }
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2019"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "The center() function is used to set the alignment of element into the center either vertically, horizontally, or both, relative to its parent element or according to the body if the element has no parent. If this function does not contain any parameters then the element will align both vertically and horizontally."
},
{
"code": null,
"e": 464,
"s": 345,
"text": "Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file."
},
{
"code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>",
"e": 554,
"s": 464,
"text": null
},
{
"code": null,
"e": 562,
"s": 554,
"text": "Syntax:"
},
{
"code": null,
"e": 578,
"s": 562,
"text": "center( align )"
},
{
"code": null,
"e": 707,
"s": 578,
"text": "Parameters: This function accepts single parameter align which holds the string ‘vertical’ or ‘horizontal’ to align the element."
},
{
"code": null,
"e": 765,
"s": 707,
"text": "Below examples illustrate the center() function in p5.js:"
},
{
"code": null,
"e": 776,
"s": 765,
"text": "Example 1:"
},
{
"code": "function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); var div = createDiv('').size(200, 70); div.html('Welcome to GeeksforGeeks', true); // Set the position of div into center div.center(); // Set font-size of text div.style('font-size', '24px'); // Set font-color of text div.style('color', 'white'); div.style('border', '1px solid white'); div.style('text-align', 'center'); } ",
"e": 1312,
"s": 776,
"text": null
},
{
"code": null,
"e": 1320,
"s": 1312,
"text": "Output:"
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": "Example 2:"
},
{
"code": "function setup() { // Create canvas of given size createCanvas(1000, 200); // Set background color background('green'); // Create an input element var input_val = createInput(''); // Set the attribute and its value input_val.attribute('value', 'Welcome to GeeksforGeeks'); // Set the position of div into center input_val.center(); // Set font-size of text input_val.style('font-size', '24px'); // Set the width of input area input_val.style('width', '300px'); } ",
"e": 1889,
"s": 1331,
"text": null
},
{
"code": null,
"e": 1897,
"s": 1889,
"text": "Output:"
},
{
"code": null,
"e": 1914,
"s": 1897,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1925,
"s": 1914,
"text": "JavaScript"
},
{
"code": null,
"e": 1942,
"s": 1925,
"text": "Web Technologies"
}
] |
Python – Efficient Text Data Cleaning
|
18 Oct, 2021
Gone are the days when we used to have data mostly in row-column format, or we can say Structured data. In present times, the data being collected is more unstructured than structured. We have data in the form of text, images, audio etc and the ratio of Structured to Unstructured data has decreased over the years. Unstructured data is increasing at 55-65% every year.
Thus, we need to learn how to work with unstructured data to be able to extract relevant information from it and make it useful. While working with text data it is very important to pre-process it before using it for predictions or analysis.In this article, we will be learning various text data cleaning techniques using python.
Let’s take a tweet for example:
I enjoyd the event which took place yesteday & I luvd it ! The link to the show is
http://t.co/4ftYom0i It's awesome you'll luv it #HadFun #Enjoyed BFN GN
We will be performing data cleaning on this tweet step-wise.
1) Clear out HTML characters: A Lot of HTML entities like ' ,& ,< etc can be found in most of the data available on the web. We need to get rid of these from our data. You can do this in two ways:
By using specific regular expressions or
By using modules or packages available(htmlparser of python)
We will be using the module already available in python.
Code:
python3
#Escaping out HTML charactersfrom html.parser import HTMLParser tweet="I enjoyd the event which took place yesteday & I lovdddd itttt ! The link to the show is http://t.co/4ftYom0i It's awesome you'll luv it #HadFun #Enjoyed BFN GN" tweet=HTMLParser().unescape(tweet)print("After removing HTML characters the tweet is:-\n{}".format(tweet))
Output:
2) Encoding & Decoding Data: It is the process of converting information from simple understandable characters to complex symbols and vice versa. There are different forms of encoding &decoding like “UTF8′′,”ascii” etc. available for text data. We should keep our data in a standard encoding format. The most common format is the UTF-8 format.
The given tweet is already in the UTF-8 format so we encoded it to ascii format and then decoded it to UTF-8 format to explain the process.
Code:
python3
#Encode from UTF-8 to asciiencode_tweet =tweet.encode('ascii','ignore')print("encode_tweet = \n{}".format(encode_tweet)) #decode from ascii to UTF-8decode_tweet=encode_tweet.decode(encoding='UTF-8')print("decode_tweet = \n{}".format(decode_tweet))
Output:
3) Removing URLs, Hashtags and Styles: In our text dataset, we can have hyperlinks, hashtags or styles like retweet text for twitter dataset etc. These provide no relevant information and can be removed. In hashtags, only the hash sign ‘#’ will be removed. For this, we will use the re library to perform regular expression operations.
Code:
python3
#library for regular expressionsimport re # remove hyperlinkstweet = re.sub(r'https?:\/\/.\S+', "", tweet) # remove hashtags# only removing the hash # sign from the wordtweet = re.sub(r'#', '', tweet) # remove old style retweet text "RT"tweet = re.sub(r'^RT[\s]+', '', tweet) print("After removing Hashtags,URLs and Styles the tweet is:-\n{}".format(tweet))
Output:
4) Contraction Replacement: The text data might contain apostrophe’s used for contractions. Example- “didn’t” for “did not” etc. This can change the sense of the word or sentence. Hence we need to replace these apostrophes with the standard lexicons. To do so we can have a dictionary which consists of the value with which the word needs to be replaced and use that.
Few of the contractions used are:-
n't --> not 'll --> will
's --> is 'd --> would
'm --> am 've --> have
're --> are
Code:
python3
#dictionary consisting of the contraction and the actual valueApos_dict={"'s":" is","n't":" not","'m":" am","'ll":" will", "'d":" would","'ve":" have","'re":" are"} #replace the contractionsfor key,value in Apos_dict.items(): if key in tweet: tweet=tweet.replace(key,value) print("After Contraction replacement the tweet is:-\n{}".format(tweet))
Output:
5) Split attached words: Some words are joined together for example – “ForTheWin”. These need to be separated to be able to extract the meaning out of it. After splitting, it will be “For The Win”.
Code:
python3
import re#separate the wordstweet = " ".join([s for s in re.split("([A-Z][a-z]+[^A-Z]*)",tweet) if s])print("After splitting attached words the tweet is:-\n{}".format(tweet))
Output:
6 )Convert to lower case: Convert your text to lower case to avoid case sensitivity related issues.
Code:
python3
#convert to lower casetweet=tweet.lower()print("After converting to lower case the tweet is:-\n{}".format(tweet))
Output:
7) Slang lookup: There are many slang words which are used nowadays, and they can be found in the text data. So we need to replace them with their meanings. We can use a dictionary of slang words as we did for the contraction replacement, or we can create a file consisting of the slang words. Examples of slang words are:-
asap --> as soon as possible
b4 --> before
lol --> laugh out loud
luv --> love
wtg --> way to go
We are using a file which consists of the words. You can download the file slang.txt. Source of this file was taken from here.
Code:
python3
#open the file slang.txtfile=open("slang.txt","r")slang=file.read() #separating each line present in the fileslang=slang.split('\n') tweet_tokens=tweet.split()slang_word=[]meaning=[] #store the slang words and meanings in different listsfor line in slang: temp=line.split("=") slang_word.append(temp[0]) meaning.append(temp[-1]) #replace the slang word with meaningfor i,word in enumerate(tweet_tokens): if word in slang_word: idx=slang_word.index(word) tweet_tokens[i]=meaning[idx] tweet=" ".join(tweet_tokens)print("After slang replacement the tweet is:-\n{}".format(tweet))
Output:
8) Standardizing and Spell Check: There might be spelling errors in the text or it might not be in the correct format. For example – “drivng” for “driving” or “I misssss this” for “I miss this”. We can correct these by using the autocorrect library for python. There are other libraries available which you can use as well. First, you will have to install the library by using the command-
#install autocorrect library
pip install autocorrect
Code:
python3
import itertools#One letter in a word should not be present more than twice in continuationtweet = ''.join(''.join(s)[:2] for _, s in itertools.groupby(tweet))print("After standardizing the tweet is:-\n{}".format(tweet)) from autocorrect import Spellerspell = Speller(lang='en')#spell checktweet=spell(tweet)print("After Spell check the tweet is:-\n{}".format(tweet))
Output:
9) Remove Stopwords: Stop words are the words which occur frequently in the text but add no significant meaning to it. For this, we will be using the nltk library which consists of modules for pre-processing data. It provides us with a list of stop words. You can create your own stopwords list as well according to the use case.
First, make sure you have the nltk library installed. If not then download it using the command-
#install nltk library
pip install nltk
Code:
python3
import nltk#download the stopwords from nltk usingnltk.download('stopwords')#import stopwordsfrom nltk.corpus import stopwords #import english stopwords list from nltkstopwords_eng = stopwords.words('english') tweet_tokens=tweet.split()tweet_list=[]#remove stopwordsfor word in tweet_tokens: if word not in stopwords_eng: tweet_list.append(word) print("tweet_list = {}".format(tweet_list))
Output:
10) Remove Punctuations: Punctuations consists of !,<@#&$ etc.
Code:
python3
#for string operationsimport string clean_tweet=[]#remove punctuationsfor word in tweet_list: if word not in string.punctuation: clean_tweet.append(word) print("clean_tweet = {}".format(clean_tweet))
Output:
These were some data cleaning techniques which we usually perform on the text data format. You can also perform some advanced data cleaning like grammar check etc.
gabaa406
adnanirshad158
gulshankumarar231
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 398,
"s": 28,
"text": "Gone are the days when we used to have data mostly in row-column format, or we can say Structured data. In present times, the data being collected is more unstructured than structured. We have data in the form of text, images, audio etc and the ratio of Structured to Unstructured data has decreased over the years. Unstructured data is increasing at 55-65% every year."
},
{
"code": null,
"e": 728,
"s": 398,
"text": "Thus, we need to learn how to work with unstructured data to be able to extract relevant information from it and make it useful. While working with text data it is very important to pre-process it before using it for predictions or analysis.In this article, we will be learning various text data cleaning techniques using python."
},
{
"code": null,
"e": 760,
"s": 728,
"text": "Let’s take a tweet for example:"
},
{
"code": null,
"e": 920,
"s": 760,
"text": "I enjoyd the event which took place yesteday & I luvd it ! The link to the show is \nhttp://t.co/4ftYom0i It's awesome you'll luv it #HadFun #Enjoyed BFN GN"
},
{
"code": null,
"e": 981,
"s": 920,
"text": "We will be performing data cleaning on this tweet step-wise."
},
{
"code": null,
"e": 1190,
"s": 981,
"text": "1) Clear out HTML characters: A Lot of HTML entities like ' ,& ,< etc can be found in most of the data available on the web. We need to get rid of these from our data. You can do this in two ways:"
},
{
"code": null,
"e": 1231,
"s": 1190,
"text": "By using specific regular expressions or"
},
{
"code": null,
"e": 1292,
"s": 1231,
"text": "By using modules or packages available(htmlparser of python)"
},
{
"code": null,
"e": 1350,
"s": 1292,
"text": "We will be using the module already available in python. "
},
{
"code": null,
"e": 1357,
"s": 1350,
"text": "Code: "
},
{
"code": null,
"e": 1365,
"s": 1357,
"text": "python3"
},
{
"code": "#Escaping out HTML charactersfrom html.parser import HTMLParser tweet=\"I enjoyd the event which took place yesteday & I lovdddd itttt ! The link to the show is http://t.co/4ftYom0i It's awesome you'll luv it #HadFun #Enjoyed BFN GN\" tweet=HTMLParser().unescape(tweet)print(\"After removing HTML characters the tweet is:-\\n{}\".format(tweet))",
"e": 1705,
"s": 1365,
"text": null
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "Output:"
},
{
"code": null,
"e": 2057,
"s": 1713,
"text": "2) Encoding & Decoding Data: It is the process of converting information from simple understandable characters to complex symbols and vice versa. There are different forms of encoding &decoding like “UTF8′′,”ascii” etc. available for text data. We should keep our data in a standard encoding format. The most common format is the UTF-8 format."
},
{
"code": null,
"e": 2197,
"s": 2057,
"text": "The given tweet is already in the UTF-8 format so we encoded it to ascii format and then decoded it to UTF-8 format to explain the process."
},
{
"code": null,
"e": 2204,
"s": 2197,
"text": "Code: "
},
{
"code": null,
"e": 2212,
"s": 2204,
"text": "python3"
},
{
"code": "#Encode from UTF-8 to asciiencode_tweet =tweet.encode('ascii','ignore')print(\"encode_tweet = \\n{}\".format(encode_tweet)) #decode from ascii to UTF-8decode_tweet=encode_tweet.decode(encoding='UTF-8')print(\"decode_tweet = \\n{}\".format(decode_tweet))",
"e": 2460,
"s": 2212,
"text": null
},
{
"code": null,
"e": 2469,
"s": 2460,
"text": " Output:"
},
{
"code": null,
"e": 2805,
"s": 2469,
"text": "3) Removing URLs, Hashtags and Styles: In our text dataset, we can have hyperlinks, hashtags or styles like retweet text for twitter dataset etc. These provide no relevant information and can be removed. In hashtags, only the hash sign ‘#’ will be removed. For this, we will use the re library to perform regular expression operations."
},
{
"code": null,
"e": 2812,
"s": 2805,
"text": "Code: "
},
{
"code": null,
"e": 2820,
"s": 2812,
"text": "python3"
},
{
"code": "#library for regular expressionsimport re # remove hyperlinkstweet = re.sub(r'https?:\\/\\/.\\S+', \"\", tweet) # remove hashtags# only removing the hash # sign from the wordtweet = re.sub(r'#', '', tweet) # remove old style retweet text \"RT\"tweet = re.sub(r'^RT[\\s]+', '', tweet) print(\"After removing Hashtags,URLs and Styles the tweet is:-\\n{}\".format(tweet))",
"e": 3181,
"s": 2820,
"text": null
},
{
"code": null,
"e": 3189,
"s": 3181,
"text": "Output:"
},
{
"code": null,
"e": 3557,
"s": 3189,
"text": "4) Contraction Replacement: The text data might contain apostrophe’s used for contractions. Example- “didn’t” for “did not” etc. This can change the sense of the word or sentence. Hence we need to replace these apostrophes with the standard lexicons. To do so we can have a dictionary which consists of the value with which the word needs to be replaced and use that."
},
{
"code": null,
"e": 3699,
"s": 3557,
"text": "Few of the contractions used are:-\nn't --> not 'll --> will\n's --> is 'd --> would\n'm --> am 've --> have\n're --> are"
},
{
"code": null,
"e": 3706,
"s": 3699,
"text": "Code: "
},
{
"code": null,
"e": 3714,
"s": 3706,
"text": "python3"
},
{
"code": "#dictionary consisting of the contraction and the actual valueApos_dict={\"'s\":\" is\",\"n't\":\" not\",\"'m\":\" am\",\"'ll\":\" will\", \"'d\":\" would\",\"'ve\":\" have\",\"'re\":\" are\"} #replace the contractionsfor key,value in Apos_dict.items(): if key in tweet: tweet=tweet.replace(key,value) print(\"After Contraction replacement the tweet is:-\\n{}\".format(tweet))",
"e": 4080,
"s": 3714,
"text": null
},
{
"code": null,
"e": 4088,
"s": 4080,
"text": "Output:"
},
{
"code": null,
"e": 4288,
"s": 4088,
"text": "5) Split attached words: Some words are joined together for example – “ForTheWin”. These need to be separated to be able to extract the meaning out of it. After splitting, it will be “For The Win”. "
},
{
"code": null,
"e": 4295,
"s": 4288,
"text": "Code: "
},
{
"code": null,
"e": 4303,
"s": 4295,
"text": "python3"
},
{
"code": "import re#separate the wordstweet = \" \".join([s for s in re.split(\"([A-Z][a-z]+[^A-Z]*)\",tweet) if s])print(\"After splitting attached words the tweet is:-\\n{}\".format(tweet))",
"e": 4478,
"s": 4303,
"text": null
},
{
"code": null,
"e": 4486,
"s": 4478,
"text": "Output:"
},
{
"code": null,
"e": 4586,
"s": 4486,
"text": "6 )Convert to lower case: Convert your text to lower case to avoid case sensitivity related issues."
},
{
"code": null,
"e": 4593,
"s": 4586,
"text": "Code: "
},
{
"code": null,
"e": 4601,
"s": 4593,
"text": "python3"
},
{
"code": "#convert to lower casetweet=tweet.lower()print(\"After converting to lower case the tweet is:-\\n{}\".format(tweet))",
"e": 4715,
"s": 4601,
"text": null
},
{
"code": null,
"e": 4723,
"s": 4715,
"text": "Output:"
},
{
"code": null,
"e": 5047,
"s": 4723,
"text": "7) Slang lookup: There are many slang words which are used nowadays, and they can be found in the text data. So we need to replace them with their meanings. We can use a dictionary of slang words as we did for the contraction replacement, or we can create a file consisting of the slang words. Examples of slang words are:-"
},
{
"code": null,
"e": 5149,
"s": 5047,
"text": "asap --> as soon as possible\nb4 --> before\nlol --> laugh out loud\nluv --> love\nwtg --> way to go"
},
{
"code": null,
"e": 5276,
"s": 5149,
"text": "We are using a file which consists of the words. You can download the file slang.txt. Source of this file was taken from here."
},
{
"code": null,
"e": 5283,
"s": 5276,
"text": "Code: "
},
{
"code": null,
"e": 5291,
"s": 5283,
"text": "python3"
},
{
"code": "#open the file slang.txtfile=open(\"slang.txt\",\"r\")slang=file.read() #separating each line present in the fileslang=slang.split('\\n') tweet_tokens=tweet.split()slang_word=[]meaning=[] #store the slang words and meanings in different listsfor line in slang: temp=line.split(\"=\") slang_word.append(temp[0]) meaning.append(temp[-1]) #replace the slang word with meaningfor i,word in enumerate(tweet_tokens): if word in slang_word: idx=slang_word.index(word) tweet_tokens[i]=meaning[idx] tweet=\" \".join(tweet_tokens)print(\"After slang replacement the tweet is:-\\n{}\".format(tweet))",
"e": 5902,
"s": 5291,
"text": null
},
{
"code": null,
"e": 5910,
"s": 5902,
"text": "Output:"
},
{
"code": null,
"e": 6300,
"s": 5910,
"text": "8) Standardizing and Spell Check: There might be spelling errors in the text or it might not be in the correct format. For example – “drivng” for “driving” or “I misssss this” for “I miss this”. We can correct these by using the autocorrect library for python. There are other libraries available which you can use as well. First, you will have to install the library by using the command-"
},
{
"code": null,
"e": 6354,
"s": 6300,
"text": "#install autocorrect library\n pip install autocorrect"
},
{
"code": null,
"e": 6361,
"s": 6354,
"text": "Code: "
},
{
"code": null,
"e": 6369,
"s": 6361,
"text": "python3"
},
{
"code": "import itertools#One letter in a word should not be present more than twice in continuationtweet = ''.join(''.join(s)[:2] for _, s in itertools.groupby(tweet))print(\"After standardizing the tweet is:-\\n{}\".format(tweet)) from autocorrect import Spellerspell = Speller(lang='en')#spell checktweet=spell(tweet)print(\"After Spell check the tweet is:-\\n{}\".format(tweet))",
"e": 6737,
"s": 6369,
"text": null
},
{
"code": null,
"e": 6745,
"s": 6737,
"text": "Output:"
},
{
"code": null,
"e": 7075,
"s": 6745,
"text": "9) Remove Stopwords: Stop words are the words which occur frequently in the text but add no significant meaning to it. For this, we will be using the nltk library which consists of modules for pre-processing data. It provides us with a list of stop words. You can create your own stopwords list as well according to the use case."
},
{
"code": null,
"e": 7172,
"s": 7075,
"text": "First, make sure you have the nltk library installed. If not then download it using the command-"
},
{
"code": null,
"e": 7212,
"s": 7172,
"text": "#install nltk library\n pip install nltk"
},
{
"code": null,
"e": 7219,
"s": 7212,
"text": "Code: "
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "python3"
},
{
"code": "import nltk#download the stopwords from nltk usingnltk.download('stopwords')#import stopwordsfrom nltk.corpus import stopwords #import english stopwords list from nltkstopwords_eng = stopwords.words('english') tweet_tokens=tweet.split()tweet_list=[]#remove stopwordsfor word in tweet_tokens: if word not in stopwords_eng: tweet_list.append(word) print(\"tweet_list = {}\".format(tweet_list))",
"e": 7627,
"s": 7227,
"text": null
},
{
"code": null,
"e": 7635,
"s": 7627,
"text": "Output:"
},
{
"code": null,
"e": 7699,
"s": 7635,
"text": "10) Remove Punctuations: Punctuations consists of !,<@#&$ etc. "
},
{
"code": null,
"e": 7706,
"s": 7699,
"text": "Code: "
},
{
"code": null,
"e": 7714,
"s": 7706,
"text": "python3"
},
{
"code": "#for string operationsimport string clean_tweet=[]#remove punctuationsfor word in tweet_list: if word not in string.punctuation: clean_tweet.append(word) print(\"clean_tweet = {}\".format(clean_tweet))",
"e": 7932,
"s": 7714,
"text": null
},
{
"code": null,
"e": 7940,
"s": 7932,
"text": "Output:"
},
{
"code": null,
"e": 8105,
"s": 7940,
"text": "These were some data cleaning techniques which we usually perform on the text data format. You can also perform some advanced data cleaning like grammar check etc. "
},
{
"code": null,
"e": 8114,
"s": 8105,
"text": "gabaa406"
},
{
"code": null,
"e": 8129,
"s": 8114,
"text": "adnanirshad158"
},
{
"code": null,
"e": 8147,
"s": 8129,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 8164,
"s": 8147,
"text": "Machine Learning"
},
{
"code": null,
"e": 8171,
"s": 8164,
"text": "Python"
},
{
"code": null,
"e": 8188,
"s": 8171,
"text": "Machine Learning"
},
{
"code": null,
"e": 8286,
"s": 8188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8309,
"s": 8286,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 8332,
"s": 8309,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 8369,
"s": 8332,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 8409,
"s": 8369,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 8433,
"s": 8409,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 8461,
"s": 8433,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 8511,
"s": 8461,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 8533,
"s": 8511,
"text": "Python map() function"
}
] |
Maximum Product Subarray | Set 3
|
12 May, 2021
Given an array A[] that contains both positive and negative integers, find the maximum product subarray.Examples :
Input: A[] = { 6, -3, -10, 0, 2 }
Output: 180 // The subarray is {6, -3, -10}
Input: A[] = {-1, -3, -10, 0, 60 }
Output: 60 // The subarray is {60}
Input: A[] = { -2, -3, 0, -2, -40 }
Output: 80 // The subarray is {-2, -40}
The idea is to traverse array from left to right keeping two variables minVal and maxVal which represents the minimum and maximum product value till the ith index of the array. Now, if the ith element of the array is negative that means now the values of minVal and maxVal will be swapped as value of maxVal will become minimum by multiplying it with a negative number. Now, compare the minVal and maxVal. The value of minVal and maxVal depends on the current index element or the product of the current index element and the previous minVal and maxVal respectively.Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum product subarray#include <bits/stdc++.h>using namespace std; // Function to find maximum product subarrayint maxProduct(int* arr, int n){ // Variables to store maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) swap(maxVal, minVal); // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = max(arr[i], maxVal * arr[i]); minVal = min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct;} // Driver Codeint main(){ int arr[] = { -1, -3, -10, 0, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum Subarray product is " << maxProduct(arr, n) << endl; return 0;}
// Java program to find maximum product subarrayimport java.io.*; class GFG { // Function to find maximum product subarray static int maxProduct(int arr[], int n) { // Variables to store maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) { int temp = maxVal; maxVal = minVal; minVal =temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = Math.max(arr[i], maxVal * arr[i]); minVal = Math.min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct; } // Driver Code public static void main (String[] args) { int arr[] = { -1, -3, -10, 0, 60 }; int n = arr.length; System.out.println( "Maximum Subarray product is " + maxProduct(arr, n)); }} // This code is contributed by anuj_67.
# Python 3 program to find maximum# product subarray # Function to find maximum# product subarraydef maxProduct(arr, n): # Variables to store maximum and # minimum product till ith index. minVal = arr[0] maxVal = arr[0] maxProduct = arr[0] for i in range(1, n, 1): # When multiplied by -ve number, # maxVal becomes minVal # and minVal becomes maxVal. if (arr[i] < 0): temp = maxVal maxVal = minVal minVal = temp # maxVal and minVal stores the # product of subarray ending at arr[i]. maxVal = max(arr[i], maxVal * arr[i]) minVal = min(arr[i], minVal * arr[i]) # Max Product of array. maxProduct = max(maxProduct, maxVal) # Return maximum product # found in array. return maxProduct # Driver Codeif __name__ == '__main__': arr = [-1, -3, -10, 0, 60] n = len(arr) print("Maximum Subarray product is", maxProduct(arr, n)) # This code is contributed by# Surendra_Gangwar
// C# program to find// maximum product subarrayusing System; class GFG{ // Function to find maximum // product subarray static int maxProduct(int []arr, int n) { // Variables to store // maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve // number, maxVal becomes // minVal and minVal // becomes maxVal. if (arr[i] < 0) { int temp = maxVal; maxVal = minVal; minVal = temp; } // maxVal and minVal stores // the product of subarray // ending at arr[i]. maxVal = Math.Max(arr[i], maxVal * arr[i]); minVal = Math.Min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.Max(maxProduct, maxVal); } // Return maximum product // found in array. return maxProduct; } // Driver Code public static void Main () { int []arr = {-1, -3, -10, 0, 60}; int n = arr.Length; Console.WriteLine("Maximum Subarray " + "product is " + maxProduct(arr, n)); }} // This code is contributed by anuj_67.
<?php// PHP program to find maximum// product subarray // Function to find maximum// product subarrayfunction maxProduct(&$arr, $n){ // Variables to store maximum and // minimum product till ith index. $minVal = $arr[0]; $maxVal = $arr[0]; $maxProduct = $arr[0]; for ($i = 1; $i < $n; $i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if ($arr[$i] < 0) { $temp = $maxVal; $maxVal = $minVal; $minVal = $temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. $maxVal = max($arr[$i], $maxVal * $arr[$i]); $minVal = min($arr[$i], $minVal * $arr[$i]); // Max Product of array. $maxProduct = max($maxProduct, $maxVal); } // Return maximum product found in array. return $maxProduct;} // Driver Code$arr = array( -1, -3, -10, 0, 60 );$n = sizeof($arr);echo "Maximum Subarray product is " . maxProduct($arr, $n) . "\n"; // This code is contributed by ita_c?>
<script>// Javascript program to find maximum product subarray // Function to find maximum product subarray function maxProduct(arr,n) { // Variables to store maximum and minimum // product till ith index. let minVal = arr[0]; let maxVal = arr[0]; let maxProduct = arr[0]; for (let i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) { let temp = maxVal; maxVal = minVal; minVal =temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = Math.max(arr[i], maxVal * arr[i]); minVal = Math.min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct; } // Driver Code let arr=[ -1, -3, -10, 0, 60 ]; let n = arr.length; document.write( "Maximum Subarray product is " + maxProduct(arr, n)); // This code is contributed by rag2127</script>
Maximum Sub array product is 60
Time Complexity: O( n ) Auxiliary Space: O( 1 )Related Articles:
Maximum Product Subarray | Set 1
Maximum Product Subarray | Set 2 (Using Two Traversals)
vt_m
ukasp
SURENDRA_GANGWAR
rag2127
Constructive Algorithms
subarray
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 169,
"s": 52,
"text": "Given an array A[] that contains both positive and negative integers, find the maximum product subarray.Examples : "
},
{
"code": null,
"e": 398,
"s": 169,
"text": "Input: A[] = { 6, -3, -10, 0, 2 }\nOutput: 180 // The subarray is {6, -3, -10}\n\nInput: A[] = {-1, -3, -10, 0, 60 }\nOutput: 60 // The subarray is {60}\n\nInput: A[] = { -2, -3, 0, -2, -40 }\nOutput: 80 // The subarray is {-2, -40}"
},
{
"code": null,
"e": 1015,
"s": 400,
"text": "The idea is to traverse array from left to right keeping two variables minVal and maxVal which represents the minimum and maximum product value till the ith index of the array. Now, if the ith element of the array is negative that means now the values of minVal and maxVal will be swapped as value of maxVal will become minimum by multiplying it with a negative number. Now, compare the minVal and maxVal. The value of minVal and maxVal depends on the current index element or the product of the current index element and the previous minVal and maxVal respectively.Below is the implementation of above approach: "
},
{
"code": null,
"e": 1019,
"s": 1015,
"text": "C++"
},
{
"code": null,
"e": 1024,
"s": 1019,
"text": "Java"
},
{
"code": null,
"e": 1032,
"s": 1024,
"text": "Python3"
},
{
"code": null,
"e": 1035,
"s": 1032,
"text": "C#"
},
{
"code": null,
"e": 1039,
"s": 1035,
"text": "PHP"
},
{
"code": null,
"e": 1050,
"s": 1039,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum product subarray#include <bits/stdc++.h>using namespace std; // Function to find maximum product subarrayint maxProduct(int* arr, int n){ // Variables to store maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) swap(maxVal, minVal); // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = max(arr[i], maxVal * arr[i]); minVal = min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct;} // Driver Codeint main(){ int arr[] = { -1, -3, -10, 0, 60 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum Subarray product is \" << maxProduct(arr, n) << endl; return 0;}",
"e": 2108,
"s": 1050,
"text": null
},
{
"code": "// Java program to find maximum product subarrayimport java.io.*; class GFG { // Function to find maximum product subarray static int maxProduct(int arr[], int n) { // Variables to store maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) { int temp = maxVal; maxVal = minVal; minVal =temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = Math.max(arr[i], maxVal * arr[i]); minVal = Math.min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct; } // Driver Code public static void main (String[] args) { int arr[] = { -1, -3, -10, 0, 60 }; int n = arr.length; System.out.println( \"Maximum Subarray product is \" + maxProduct(arr, n)); }} // This code is contributed by anuj_67.",
"e": 3512,
"s": 2108,
"text": null
},
{
"code": "# Python 3 program to find maximum# product subarray # Function to find maximum# product subarraydef maxProduct(arr, n): # Variables to store maximum and # minimum product till ith index. minVal = arr[0] maxVal = arr[0] maxProduct = arr[0] for i in range(1, n, 1): # When multiplied by -ve number, # maxVal becomes minVal # and minVal becomes maxVal. if (arr[i] < 0): temp = maxVal maxVal = minVal minVal = temp # maxVal and minVal stores the # product of subarray ending at arr[i]. maxVal = max(arr[i], maxVal * arr[i]) minVal = min(arr[i], minVal * arr[i]) # Max Product of array. maxProduct = max(maxProduct, maxVal) # Return maximum product # found in array. return maxProduct # Driver Codeif __name__ == '__main__': arr = [-1, -3, -10, 0, 60] n = len(arr) print(\"Maximum Subarray product is\", maxProduct(arr, n)) # This code is contributed by# Surendra_Gangwar",
"e": 4570,
"s": 3512,
"text": null
},
{
"code": "// C# program to find// maximum product subarrayusing System; class GFG{ // Function to find maximum // product subarray static int maxProduct(int []arr, int n) { // Variables to store // maximum and minimum // product till ith index. int minVal = arr[0]; int maxVal = arr[0]; int maxProduct = arr[0]; for (int i = 1; i < n; i++) { // When multiplied by -ve // number, maxVal becomes // minVal and minVal // becomes maxVal. if (arr[i] < 0) { int temp = maxVal; maxVal = minVal; minVal = temp; } // maxVal and minVal stores // the product of subarray // ending at arr[i]. maxVal = Math.Max(arr[i], maxVal * arr[i]); minVal = Math.Min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.Max(maxProduct, maxVal); } // Return maximum product // found in array. return maxProduct; } // Driver Code public static void Main () { int []arr = {-1, -3, -10, 0, 60}; int n = arr.Length; Console.WriteLine(\"Maximum Subarray \" + \"product is \" + maxProduct(arr, n)); }} // This code is contributed by anuj_67.",
"e": 6150,
"s": 4570,
"text": null
},
{
"code": "<?php// PHP program to find maximum// product subarray // Function to find maximum// product subarrayfunction maxProduct(&$arr, $n){ // Variables to store maximum and // minimum product till ith index. $minVal = $arr[0]; $maxVal = $arr[0]; $maxProduct = $arr[0]; for ($i = 1; $i < $n; $i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if ($arr[$i] < 0) { $temp = $maxVal; $maxVal = $minVal; $minVal = $temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. $maxVal = max($arr[$i], $maxVal * $arr[$i]); $minVal = min($arr[$i], $minVal * $arr[$i]); // Max Product of array. $maxProduct = max($maxProduct, $maxVal); } // Return maximum product found in array. return $maxProduct;} // Driver Code$arr = array( -1, -3, -10, 0, 60 );$n = sizeof($arr);echo \"Maximum Subarray product is \" . maxProduct($arr, $n) . \"\\n\"; // This code is contributed by ita_c?>",
"e": 7235,
"s": 6150,
"text": null
},
{
"code": "<script>// Javascript program to find maximum product subarray // Function to find maximum product subarray function maxProduct(arr,n) { // Variables to store maximum and minimum // product till ith index. let minVal = arr[0]; let maxVal = arr[0]; let maxProduct = arr[0]; for (let i = 1; i < n; i++) { // When multiplied by -ve number, // maxVal becomes minVal // and minVal becomes maxVal. if (arr[i] < 0) { let temp = maxVal; maxVal = minVal; minVal =temp; } // maxVal and minVal stores the // product of subarray ending at arr[i]. maxVal = Math.max(arr[i], maxVal * arr[i]); minVal = Math.min(arr[i], minVal * arr[i]); // Max Product of array. maxProduct = Math.max(maxProduct, maxVal); } // Return maximum product found in array. return maxProduct; } // Driver Code let arr=[ -1, -3, -10, 0, 60 ]; let n = arr.length; document.write( \"Maximum Subarray product is \" + maxProduct(arr, n)); // This code is contributed by rag2127</script>",
"e": 8555,
"s": 7235,
"text": null
},
{
"code": null,
"e": 8587,
"s": 8555,
"text": "Maximum Sub array product is 60"
},
{
"code": null,
"e": 8656,
"s": 8589,
"text": "Time Complexity: O( n ) Auxiliary Space: O( 1 )Related Articles: "
},
{
"code": null,
"e": 8689,
"s": 8656,
"text": "Maximum Product Subarray | Set 1"
},
{
"code": null,
"e": 8745,
"s": 8689,
"text": "Maximum Product Subarray | Set 2 (Using Two Traversals)"
},
{
"code": null,
"e": 8752,
"s": 8747,
"text": "vt_m"
},
{
"code": null,
"e": 8758,
"s": 8752,
"text": "ukasp"
},
{
"code": null,
"e": 8775,
"s": 8758,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8783,
"s": 8775,
"text": "rag2127"
},
{
"code": null,
"e": 8807,
"s": 8783,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 8816,
"s": 8807,
"text": "subarray"
},
{
"code": null,
"e": 8823,
"s": 8816,
"text": "Arrays"
},
{
"code": null,
"e": 8830,
"s": 8823,
"text": "Arrays"
}
] |
D3.js | d3.select() Function
|
17 Jul, 2019
The d3.select() function in D3.js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
Syntax:
d3.select("element")
Parameters: This function accepts single parameter which holds the element name.
Return Value: This function returns the selected elements.
Below programs illustrate the d3.select() function in D3.js:
Example 1:
<!DOCTYPE html><html> <head> <title> D3.js | d3.select() Function </title> <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body> <div>GeeksforGeeks</div> <script> // Calling the select() function var a = d3.select("div").text(); // Getting the selected element console.log(a); </script></body> </html>
Output:
GeeksforGeeks
Example 2:
<!DOCTYPE html><html> <head> <title> D3.js | d3.select() Function </title> <script src="https://d3js.org/d3.v4.min.js"></script></head> <body> <p>GeeksforGeeks</p> <p>A computer science portal for geeks</p> <script> // Calling the select() function var a = d3.select("p").text(); // Getting the selected element console.log(a); </script></body> </html>
Output:
GeeksforGeeks
Reference: https://devdocs.io/d3~5/d3-selection#select
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": "\n17 Jul, 2019"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "The d3.select() function in D3.js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected."
},
{
"code": null,
"e": 323,
"s": 315,
"text": "Syntax:"
},
{
"code": null,
"e": 344,
"s": 323,
"text": "d3.select(\"element\")"
},
{
"code": null,
"e": 425,
"s": 344,
"text": "Parameters: This function accepts single parameter which holds the element name."
},
{
"code": null,
"e": 484,
"s": 425,
"text": "Return Value: This function returns the selected elements."
},
{
"code": null,
"e": 545,
"s": 484,
"text": "Below programs illustrate the d3.select() function in D3.js:"
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.select() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"></script></head> <body> <div>GeeksforGeeks</div> <script> // Calling the select() function var a = d3.select(\"div\").text(); // Getting the selected element console.log(a); </script></body> </html> ",
"e": 984,
"s": 556,
"text": null
},
{
"code": null,
"e": 992,
"s": 984,
"text": "Output:"
},
{
"code": null,
"e": 1008,
"s": 992,
"text": "GeeksforGeeks \n"
},
{
"code": null,
"e": 1019,
"s": 1008,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.select() Function </title> <script src=\"https://d3js.org/d3.v4.min.js\"></script></head> <body> <p>GeeksforGeeks</p> <p>A computer science portal for geeks</p> <script> // Calling the select() function var a = d3.select(\"p\").text(); // Getting the selected element console.log(a); </script></body> </html>",
"e": 1489,
"s": 1019,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1489,
"text": "Output:"
},
{
"code": null,
"e": 1511,
"s": 1497,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1566,
"s": 1511,
"text": "Reference: https://devdocs.io/d3~5/d3-selection#select"
},
{
"code": null,
"e": 1572,
"s": 1566,
"text": "D3.js"
},
{
"code": null,
"e": 1583,
"s": 1572,
"text": "JavaScript"
},
{
"code": null,
"e": 1600,
"s": 1583,
"text": "Web Technologies"
},
{
"code": null,
"e": 1698,
"s": 1600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1759,
"s": 1698,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1831,
"s": 1759,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1871,
"s": 1831,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1912,
"s": 1871,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1964,
"s": 1912,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1997,
"s": 1964,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2059,
"s": 1997,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2120,
"s": 2059,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2170,
"s": 2120,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Vector in C++ STL
|
06 Jul, 2022
Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes the array may need to be extended. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.
begin() – Returns an iterator pointing to the first element in the vectorend() – Returns an iterator pointing to the theoretical element that follows the last element in the vectorrbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first elementrend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)cbegin() – Returns a constant iterator pointing to the first element in the vector.cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first elementcrend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
begin() – Returns an iterator pointing to the first element in the vector
end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector
rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
cbegin() – Returns a constant iterator pointing to the first element in the vector.
cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
CPP
// C++ program to illustrate the// iterators in vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 5; i++) g1.push_back(i); cout << "Output of begin and end: "; for (auto i = g1.begin(); i != g1.end(); ++i) cout << *i << " "; cout << "\nOutput of cbegin and cend: "; for (auto i = g1.cbegin(); i != g1.cend(); ++i) cout << *i << " "; cout << "\nOutput of rbegin and rend: "; for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) cout << *ir << " "; cout << "\nOutput of crbegin and crend : "; for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir) cout << *ir << " "; return 0;}
Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
Output of crbegin and crend : 5 4 3 2 1
Capacity
size() – Returns the number of elements in the vector.max_size() – Returns the maximum number of elements that the vector can hold.capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.resize(n) – Resizes the container so that it contains ‘n’ elements.empty() – Returns whether the container is empty.shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.reserve() – Requests that the vector capacity be at least enough to contain n elements.
size() – Returns the number of elements in the vector.
max_size() – Returns the maximum number of elements that the vector can hold.
capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.
resize(n) – Resizes the container so that it contains ‘n’ elements.
empty() – Returns whether the container is empty.
shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
reserve() – Requests that the vector capacity be at least enough to contain n elements.
CPP
// C++ program to illustrate the// capacity function in vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 5; i++) g1.push_back(i); cout << "Size : " << g1.size(); cout << "\nCapacity : " << g1.capacity(); cout << "\nMax_Size : " << g1.max_size(); // resizes the vector size to 4 g1.resize(4); // prints the vector size after resize() cout << "\nSize : " << g1.size(); // checks if the vector is empty or not if (g1.empty() == false) cout << "\nVector is not empty"; else cout << "\nVector is empty"; // Shrinks the vector g1.shrink_to_fit(); cout << "\nVector elements are: "; for (auto it = g1.begin(); it != g1.end(); it++) cout << *it << " "; return 0;}
Size : 5
Capacity : 8
Max_Size : 4611686018427387903
Size : 4
Vector is not empty
Vector elements are: 1 2 3 4
Element access:
reference operator [g] – Returns a reference to the element at position ‘g’ in the vectorat(g) – Returns a reference to the element at position ‘g’ in the vectorfront() – Returns a reference to the first element in the vectorback() – Returns a reference to the last element in the vectordata() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
reference operator [g] – Returns a reference to the element at position ‘g’ in the vector
at(g) – Returns a reference to the element at position ‘g’ in the vector
front() – Returns a reference to the first element in the vector
back() – Returns a reference to the last element in the vector
data() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
CPP
// C++ program to illustrate the// element accesser in vector#include <bits/stdc++.h>using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 10; i++) g1.push_back(i * 10); cout << "\nReference operator [g] : g1[2] = " << g1[2]; cout << "\nat : g1.at(4) = " << g1.at(4); cout << "\nfront() : g1.front() = " << g1.front(); cout << "\nback() : g1.back() = " << g1.back(); // pointer to the first element int* pos = g1.data(); cout << "\nThe first element is " << *pos; return 0;}
Reference operator [g] : g1[2] = 30
at : g1.at(4) = 50
front() : g1.front() = 10
back() : g1.back() = 100
The first element is 10
Modifiers:
assign() – It assigns new value to the vector elements by replacing old onespush_back() – It push the elements into a vector from the backpop_back() – It is used to pop or remove elements from a vector from the back.insert() – It inserts new elements before the element at the specified positionerase() – It is used to remove elements from a container from the specified position or range.swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.clear() – It is used to remove all the elements of the vector containeremplace() – It extends the container by inserting new element at positionemplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
assign() – It assigns new value to the vector elements by replacing old ones
push_back() – It push the elements into a vector from the back
pop_back() – It is used to pop or remove elements from a vector from the back.
insert() – It inserts new elements before the element at the specified position
erase() – It is used to remove elements from a container from the specified position or range.
swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.
clear() – It is used to remove all the elements of the vector container
emplace() – It extends the container by inserting new element at position
emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
CPP
// C++ program to illustrate the// Modifiers in vector#include <bits/stdc++.h>#include <vector>using namespace std; int main(){ // Assign vector vector<int> v; // fill the array with 10 five times v.assign(5, 10); cout << "The vector elements are: "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; // inserts 15 to the last position v.push_back(15); int n = v.size(); cout << "\nThe last element is: " << v[n - 1]; // removes last element v.pop_back(); // prints the vector cout << "\nThe vector elements are: "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; // inserts 5 at the beginning v.insert(v.begin(), 5); cout << "\nThe first element is: " << v[0]; // removes the first element v.erase(v.begin()); cout << "\nThe first element is: " << v[0]; // inserts at the beginning v.emplace(v.begin(), 5); cout << "\nThe first element is: " << v[0]; // Inserts 20 at the end v.emplace_back(20); n = v.size(); cout << "\nThe last element is: " << v[n - 1]; // erases the vector v.clear(); cout << "\nVector size after erase(): " << v.size(); // two vector to perform swap vector<int> v1, v2; v1.push_back(1); v1.push_back(2); v2.push_back(3); v2.push_back(4); cout << "\n\nVector 1: "; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; cout << "\nVector 2: "; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; // Swaps v1 and v2 v1.swap(v2); cout << "\nAfter Swap \nVector 1: "; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; cout << "\nVector 2: "; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " ";}
The vector elements are: 10 10 10 10 10
The last element is: 15
The vector elements are: 10 10 10 10 10
The first element is: 5
The first element is: 10
The first element is: 5
The last element is: 20
Vector size after erase(): 0
Vector 1: 1 2
Vector 2: 3 4
After Swap
Vector 1: 3 4
Vector 2: 1 2
The time complexity for doing various operations on vectors is-
Random access – constant O(1)
Insertion or removal of elements at the end – constant O(1)
Insertion or removal of elements – linear in the distance to the end of the vector O(N)
Knowing the size – constant O(1)
Resizing the vector- Linear O(N)
All Vector Functions :
C++ Programming Language Tutorial | Vector in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersC++ Programming Language Tutorial | Vector in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Y29tlyp_jBA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
estenger
msakibhr
utkarshgupta110092
cpp-containers-library
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Virtual Function in C++
C++ Data Types
Templates in C++ with Examples
Operator Overloading in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 643,
"s": 52,
"text": "Vectors are the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes the array may need to be extended. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time."
},
{
"code": null,
"e": 1600,
"s": 643,
"text": "begin() – Returns an iterator pointing to the first element in the vectorend() – Returns an iterator pointing to the theoretical element that follows the last element in the vectorrbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first elementrend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)cbegin() – Returns a constant iterator pointing to the first element in the vector.cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first elementcrend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)"
},
{
"code": null,
"e": 1674,
"s": 1600,
"text": "begin() – Returns an iterator pointing to the first element in the vector"
},
{
"code": null,
"e": 1782,
"s": 1674,
"text": "end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector"
},
{
"code": null,
"e": 1920,
"s": 1782,
"text": "rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element"
},
{
"code": null,
"e": 2062,
"s": 1920,
"text": "rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)"
},
{
"code": null,
"e": 2146,
"s": 2062,
"text": "cbegin() – Returns a constant iterator pointing to the first element in the vector."
},
{
"code": null,
"e": 2264,
"s": 2146,
"text": "cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector."
},
{
"code": null,
"e": 2412,
"s": 2264,
"text": "crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element"
},
{
"code": null,
"e": 2564,
"s": 2412,
"text": "crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)"
},
{
"code": null,
"e": 2568,
"s": 2564,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// iterators in vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 5; i++) g1.push_back(i); cout << \"Output of begin and end: \"; for (auto i = g1.begin(); i != g1.end(); ++i) cout << *i << \" \"; cout << \"\\nOutput of cbegin and cend: \"; for (auto i = g1.cbegin(); i != g1.cend(); ++i) cout << *i << \" \"; cout << \"\\nOutput of rbegin and rend: \"; for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) cout << *ir << \" \"; cout << \"\\nOutput of crbegin and crend : \"; for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir) cout << *ir << \" \"; return 0;}",
"e": 3286,
"s": 2568,
"text": null
},
{
"code": null,
"e": 3438,
"s": 3286,
"text": "Output of begin and end: 1 2 3 4 5 \nOutput of cbegin and cend: 1 2 3 4 5 \nOutput of rbegin and rend: 5 4 3 2 1 \nOutput of crbegin and crend : 5 4 3 2 1"
},
{
"code": null,
"e": 3447,
"s": 3438,
"text": "Capacity"
},
{
"code": null,
"e": 4017,
"s": 3447,
"text": "size() – Returns the number of elements in the vector.max_size() – Returns the maximum number of elements that the vector can hold.capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.resize(n) – Resizes the container so that it contains ‘n’ elements.empty() – Returns whether the container is empty.shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.reserve() – Requests that the vector capacity be at least enough to contain n elements."
},
{
"code": null,
"e": 4072,
"s": 4017,
"text": "size() – Returns the number of elements in the vector."
},
{
"code": null,
"e": 4150,
"s": 4072,
"text": "max_size() – Returns the maximum number of elements that the vector can hold."
},
{
"code": null,
"e": 4268,
"s": 4150,
"text": "capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements."
},
{
"code": null,
"e": 4336,
"s": 4268,
"text": "resize(n) – Resizes the container so that it contains ‘n’ elements."
},
{
"code": null,
"e": 4386,
"s": 4336,
"text": "empty() – Returns whether the container is empty."
},
{
"code": null,
"e": 4505,
"s": 4386,
"text": "shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity."
},
{
"code": null,
"e": 4593,
"s": 4505,
"text": "reserve() – Requests that the vector capacity be at least enough to contain n elements."
},
{
"code": null,
"e": 4597,
"s": 4593,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// capacity function in vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 5; i++) g1.push_back(i); cout << \"Size : \" << g1.size(); cout << \"\\nCapacity : \" << g1.capacity(); cout << \"\\nMax_Size : \" << g1.max_size(); // resizes the vector size to 4 g1.resize(4); // prints the vector size after resize() cout << \"\\nSize : \" << g1.size(); // checks if the vector is empty or not if (g1.empty() == false) cout << \"\\nVector is not empty\"; else cout << \"\\nVector is empty\"; // Shrinks the vector g1.shrink_to_fit(); cout << \"\\nVector elements are: \"; for (auto it = g1.begin(); it != g1.end(); it++) cout << *it << \" \"; return 0;}",
"e": 5412,
"s": 4597,
"text": null
},
{
"code": null,
"e": 5523,
"s": 5412,
"text": "Size : 5\nCapacity : 8\nMax_Size : 4611686018427387903\nSize : 4\nVector is not empty\nVector elements are: 1 2 3 4"
},
{
"code": null,
"e": 5539,
"s": 5523,
"text": "Element access:"
},
{
"code": null,
"e": 5939,
"s": 5539,
"text": "reference operator [g] – Returns a reference to the element at position ‘g’ in the vectorat(g) – Returns a reference to the element at position ‘g’ in the vectorfront() – Returns a reference to the first element in the vectorback() – Returns a reference to the last element in the vectordata() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements."
},
{
"code": null,
"e": 6029,
"s": 5939,
"text": "reference operator [g] – Returns a reference to the element at position ‘g’ in the vector"
},
{
"code": null,
"e": 6102,
"s": 6029,
"text": "at(g) – Returns a reference to the element at position ‘g’ in the vector"
},
{
"code": null,
"e": 6167,
"s": 6102,
"text": "front() – Returns a reference to the first element in the vector"
},
{
"code": null,
"e": 6230,
"s": 6167,
"text": "back() – Returns a reference to the last element in the vector"
},
{
"code": null,
"e": 6343,
"s": 6230,
"text": "data() – Returns a direct pointer to the memory array used internally by the vector to store its owned elements."
},
{
"code": null,
"e": 6347,
"s": 6343,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// element accesser in vector#include <bits/stdc++.h>using namespace std; int main(){ vector<int> g1; for (int i = 1; i <= 10; i++) g1.push_back(i * 10); cout << \"\\nReference operator [g] : g1[2] = \" << g1[2]; cout << \"\\nat : g1.at(4) = \" << g1.at(4); cout << \"\\nfront() : g1.front() = \" << g1.front(); cout << \"\\nback() : g1.back() = \" << g1.back(); // pointer to the first element int* pos = g1.data(); cout << \"\\nThe first element is \" << *pos; return 0;}",
"e": 6890,
"s": 6347,
"text": null
},
{
"code": null,
"e": 7020,
"s": 6890,
"text": "Reference operator [g] : g1[2] = 30\nat : g1.at(4) = 50\nfront() : g1.front() = 10\nback() : g1.back() = 100\nThe first element is 10"
},
{
"code": null,
"e": 7032,
"s": 7020,
"text": "Modifiers: "
},
{
"code": null,
"e": 7800,
"s": 7032,
"text": "assign() – It assigns new value to the vector elements by replacing old onespush_back() – It push the elements into a vector from the backpop_back() – It is used to pop or remove elements from a vector from the back.insert() – It inserts new elements before the element at the specified positionerase() – It is used to remove elements from a container from the specified position or range.swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.clear() – It is used to remove all the elements of the vector containeremplace() – It extends the container by inserting new element at positionemplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector"
},
{
"code": null,
"e": 7877,
"s": 7800,
"text": "assign() – It assigns new value to the vector elements by replacing old ones"
},
{
"code": null,
"e": 7940,
"s": 7877,
"text": "push_back() – It push the elements into a vector from the back"
},
{
"code": null,
"e": 8019,
"s": 7940,
"text": "pop_back() – It is used to pop or remove elements from a vector from the back."
},
{
"code": null,
"e": 8099,
"s": 8019,
"text": "insert() – It inserts new elements before the element at the specified position"
},
{
"code": null,
"e": 8194,
"s": 8099,
"text": "erase() – It is used to remove elements from a container from the specified position or range."
},
{
"code": null,
"e": 8301,
"s": 8194,
"text": "swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ."
},
{
"code": null,
"e": 8373,
"s": 8301,
"text": "clear() – It is used to remove all the elements of the vector container"
},
{
"code": null,
"e": 8447,
"s": 8373,
"text": "emplace() – It extends the container by inserting new element at position"
},
{
"code": null,
"e": 8576,
"s": 8447,
"text": "emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector"
},
{
"code": null,
"e": 8580,
"s": 8576,
"text": "CPP"
},
{
"code": "// C++ program to illustrate the// Modifiers in vector#include <bits/stdc++.h>#include <vector>using namespace std; int main(){ // Assign vector vector<int> v; // fill the array with 10 five times v.assign(5, 10); cout << \"The vector elements are: \"; for (int i = 0; i < v.size(); i++) cout << v[i] << \" \"; // inserts 15 to the last position v.push_back(15); int n = v.size(); cout << \"\\nThe last element is: \" << v[n - 1]; // removes last element v.pop_back(); // prints the vector cout << \"\\nThe vector elements are: \"; for (int i = 0; i < v.size(); i++) cout << v[i] << \" \"; // inserts 5 at the beginning v.insert(v.begin(), 5); cout << \"\\nThe first element is: \" << v[0]; // removes the first element v.erase(v.begin()); cout << \"\\nThe first element is: \" << v[0]; // inserts at the beginning v.emplace(v.begin(), 5); cout << \"\\nThe first element is: \" << v[0]; // Inserts 20 at the end v.emplace_back(20); n = v.size(); cout << \"\\nThe last element is: \" << v[n - 1]; // erases the vector v.clear(); cout << \"\\nVector size after erase(): \" << v.size(); // two vector to perform swap vector<int> v1, v2; v1.push_back(1); v1.push_back(2); v2.push_back(3); v2.push_back(4); cout << \"\\n\\nVector 1: \"; for (int i = 0; i < v1.size(); i++) cout << v1[i] << \" \"; cout << \"\\nVector 2: \"; for (int i = 0; i < v2.size(); i++) cout << v2[i] << \" \"; // Swaps v1 and v2 v1.swap(v2); cout << \"\\nAfter Swap \\nVector 1: \"; for (int i = 0; i < v1.size(); i++) cout << v1[i] << \" \"; cout << \"\\nVector 2: \"; for (int i = 0; i < v2.size(); i++) cout << v2[i] << \" \";}",
"e": 10351,
"s": 8580,
"text": null
},
{
"code": null,
"e": 10655,
"s": 10351,
"text": "The vector elements are: 10 10 10 10 10 \nThe last element is: 15\nThe vector elements are: 10 10 10 10 10 \nThe first element is: 5\nThe first element is: 10\nThe first element is: 5\nThe last element is: 20\nVector size after erase(): 0\n\nVector 1: 1 2 \nVector 2: 3 4 \nAfter Swap \nVector 1: 3 4 \nVector 2: 1 2"
},
{
"code": null,
"e": 10719,
"s": 10655,
"text": "The time complexity for doing various operations on vectors is-"
},
{
"code": null,
"e": 10749,
"s": 10719,
"text": "Random access – constant O(1)"
},
{
"code": null,
"e": 10809,
"s": 10749,
"text": "Insertion or removal of elements at the end – constant O(1)"
},
{
"code": null,
"e": 10897,
"s": 10809,
"text": "Insertion or removal of elements – linear in the distance to the end of the vector O(N)"
},
{
"code": null,
"e": 10930,
"s": 10897,
"text": "Knowing the size – constant O(1)"
},
{
"code": null,
"e": 10964,
"s": 10930,
"text": "Resizing the vector- Linear O(N) "
},
{
"code": null,
"e": 10987,
"s": 10964,
"text": "All Vector Functions :"
},
{
"code": null,
"e": 11911,
"s": 10987,
"text": "C++ Programming Language Tutorial | Vector in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersC++ Programming Language Tutorial | Vector in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Y29tlyp_jBA\" 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": 12036,
"s": 11911,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 12045,
"s": 12036,
"text": "estenger"
},
{
"code": null,
"e": 12054,
"s": 12045,
"text": "msakibhr"
},
{
"code": null,
"e": 12073,
"s": 12054,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 12096,
"s": 12073,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 12107,
"s": 12096,
"text": "cpp-vector"
},
{
"code": null,
"e": 12111,
"s": 12107,
"text": "STL"
},
{
"code": null,
"e": 12115,
"s": 12111,
"text": "C++"
},
{
"code": null,
"e": 12119,
"s": 12115,
"text": "STL"
},
{
"code": null,
"e": 12123,
"s": 12119,
"text": "CPP"
},
{
"code": null,
"e": 12221,
"s": 12123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12264,
"s": 12221,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 12289,
"s": 12264,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 12323,
"s": 12289,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 12340,
"s": 12323,
"text": "Substring in C++"
},
{
"code": null,
"e": 12394,
"s": 12340,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 12418,
"s": 12394,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 12442,
"s": 12418,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 12457,
"s": 12442,
"text": "C++ Data Types"
},
{
"code": null,
"e": 12488,
"s": 12457,
"text": "Templates in C++ with Examples"
}
] |
MongoDB – copyTo() Method
|
16 Mar, 2021
In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name. This method uses eval command internally.
Important Note: As CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0.
Syntax:
db.sourceCollection.copyTo(targetCollection)
Parameter:
It takes only the name of the target collection where you want to copy the documents of the source collection. The type of this parameter is string.
Return:
This method returns the number of documents copied and if that process fails it throws an exception.
Example 1: In the following example, we are working with:
Database: gfg
Collections: collectionA and collectionB
The collectionA contains three documents:
The collectionB contains two documents:
Now we copy the documents of collectionA to collectionB using copyTo() method.
db.collectionA.copyTo("collectionB")
Example 2: In the following example, we are working with:
Database: gfg
Collection: sCollection
Documents: Three documents contains name and age of the students
Now we going to copy the documents of sCollection to a new collection i.e., tCollection using copyTo() method. Here, the tCollection is not present in gfg database so MongoDB create this collection.
db.sCollection.copyTo("tCollection")
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Mongoose | updateOne() Function
Aggregation in MongoDB
Mongoose | findOne() Function
MongoDB - Check the existence of the fields in the specified collection
Upsert in MongoDB
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name. This method uses eval command internally. "
},
{
"code": null,
"e": 508,
"s": 365,
"text": "Important Note: As CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0."
},
{
"code": null,
"e": 516,
"s": 508,
"text": "Syntax:"
},
{
"code": null,
"e": 628,
"s": 516,
"text": "db.sourceCollection.copyTo(targetCollection) "
},
{
"code": null,
"e": 639,
"s": 628,
"text": "Parameter:"
},
{
"code": null,
"e": 788,
"s": 639,
"text": "It takes only the name of the target collection where you want to copy the documents of the source collection. The type of this parameter is string."
},
{
"code": null,
"e": 797,
"s": 788,
"text": "Return: "
},
{
"code": null,
"e": 898,
"s": 797,
"text": "This method returns the number of documents copied and if that process fails it throws an exception."
},
{
"code": null,
"e": 956,
"s": 898,
"text": "Example 1: In the following example, we are working with:"
},
{
"code": null,
"e": 970,
"s": 956,
"text": "Database: gfg"
},
{
"code": null,
"e": 1011,
"s": 970,
"text": "Collections: collectionA and collectionB"
},
{
"code": null,
"e": 1053,
"s": 1011,
"text": "The collectionA contains three documents:"
},
{
"code": null,
"e": 1093,
"s": 1053,
"text": "The collectionB contains two documents:"
},
{
"code": null,
"e": 1172,
"s": 1093,
"text": "Now we copy the documents of collectionA to collectionB using copyTo() method."
},
{
"code": null,
"e": 1209,
"s": 1172,
"text": "db.collectionA.copyTo(\"collectionB\")"
},
{
"code": null,
"e": 1267,
"s": 1209,
"text": "Example 2: In the following example, we are working with:"
},
{
"code": null,
"e": 1281,
"s": 1267,
"text": "Database: gfg"
},
{
"code": null,
"e": 1305,
"s": 1281,
"text": "Collection: sCollection"
},
{
"code": null,
"e": 1370,
"s": 1305,
"text": "Documents: Three documents contains name and age of the students"
},
{
"code": null,
"e": 1569,
"s": 1370,
"text": "Now we going to copy the documents of sCollection to a new collection i.e., tCollection using copyTo() method. Here, the tCollection is not present in gfg database so MongoDB create this collection."
},
{
"code": null,
"e": 1606,
"s": 1569,
"text": "db.sCollection.copyTo(\"tCollection\")"
},
{
"code": null,
"e": 1621,
"s": 1606,
"text": "MongoDB-method"
},
{
"code": null,
"e": 1628,
"s": 1621,
"text": "Picked"
},
{
"code": null,
"e": 1636,
"s": 1628,
"text": "MongoDB"
},
{
"code": null,
"e": 1734,
"s": 1636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1773,
"s": 1734,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 1800,
"s": 1773,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 1838,
"s": 1800,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 1870,
"s": 1838,
"text": "Mongoose | updateOne() Function"
},
{
"code": null,
"e": 1893,
"s": 1870,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 1923,
"s": 1893,
"text": "Mongoose | findOne() Function"
},
{
"code": null,
"e": 1995,
"s": 1923,
"text": "MongoDB - Check the existence of the fields in the specified collection"
},
{
"code": null,
"e": 2013,
"s": 1995,
"text": "Upsert in MongoDB"
},
{
"code": null,
"e": 2051,
"s": 2013,
"text": "How to connect MongoDB with ReactJS ?"
}
] |
Google Interview Experience | Set 4
|
04 Jun, 2019
Though I didn’t clear google but I want to share my Google interview experience , so it can help other’s . Please find my interview experience below:
My Google Interview Experience for Software Developer Position [Android Core Team], London, United Kingdom
Like many other enthusiastic engineers, I too applied for a job at Google. I know that its very difficult that a resume gets noticed by google.Suddenly, one fine day I received a Mail( “Hello from Google !”) from Google’s HR saying that they are interested in my profile and asked me if I was ready to go ahead with the interview process[Come on! you cant say no to Google].
Round1(Phone interview) :
By:Talent Scout @Google:
* Questions from Project :Spell Corrector:How it works , Bigram and ngram model approach, etc.
* Why should one use merge sort over quick sort and vice-versa.
* You have a very large array of ‘Person’ objects .Sort the people in increasing order of age .
General :
Then came the exciting part when he asked me to choose location b/w Google Paris(Text-Speech Team) or Google London(Android Core Team).
He explained how Google work’s on their projects !
About Google interview process ( 2-3 phone interview + 4-5 onsite interview in London ).
Round2:(Phone interview + coding on shared google doc)
By:Software Developer @Google :
* Questions from Project:Bi-directional Sync b/w mysql and sqilte db.
* Given a number , check if it can be represented in 5^n form , where n is positive integer .
* Given a string of words with lots of spaces between the words , remove all the unnecessary spaces like
input: I live on earth
output: I live on earth
Round3:(Phone interview + coding on shared google doc)
By:Software developer @Google :
* Optimize a^b
* How would you split a search query across multiple machines?
* You need to develop the game Snake. What data structures will you use? Code your solution.
Some additional hints for the interview:
Clarify the question – make sure you understand everything.
Try to find the most efficient solution.
Come up with solutions quickly: even if its a brute force solution. Always iterate away from the original solution.
Before you start coding explain why you’re approaching it that way ,its ok to start off with a naive solution and try to make it more efficient.
Explain the rationale behind the steps you are doing.
Think out loud, keep things technical. The engineers will give you hints: take a hint! They are there to help you!
Always write “compilable” code.
Mind edge cases. Find bugs in your code.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jun, 2019"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "Though I didn’t clear google but I want to share my Google interview experience , so it can help other’s . Please find my interview experience below:"
},
{
"code": null,
"e": 309,
"s": 202,
"text": "My Google Interview Experience for Software Developer Position [Android Core Team], London, United Kingdom"
},
{
"code": null,
"e": 684,
"s": 309,
"text": "Like many other enthusiastic engineers, I too applied for a job at Google. I know that its very difficult that a resume gets noticed by google.Suddenly, one fine day I received a Mail( “Hello from Google !”) from Google’s HR saying that they are interested in my profile and asked me if I was ready to go ahead with the interview process[Come on! you cant say no to Google]."
},
{
"code": null,
"e": 710,
"s": 684,
"text": "Round1(Phone interview) :"
},
{
"code": null,
"e": 735,
"s": 710,
"text": "By:Talent Scout @Google:"
},
{
"code": null,
"e": 830,
"s": 735,
"text": "* Questions from Project :Spell Corrector:How it works , Bigram and ngram model approach, etc."
},
{
"code": null,
"e": 894,
"s": 830,
"text": "* Why should one use merge sort over quick sort and vice-versa."
},
{
"code": null,
"e": 990,
"s": 894,
"text": "* You have a very large array of ‘Person’ objects .Sort the people in increasing order of age ."
},
{
"code": null,
"e": 1000,
"s": 990,
"text": "General :"
},
{
"code": null,
"e": 1136,
"s": 1000,
"text": "Then came the exciting part when he asked me to choose location b/w Google Paris(Text-Speech Team) or Google London(Android Core Team)."
},
{
"code": null,
"e": 1187,
"s": 1136,
"text": "He explained how Google work’s on their projects !"
},
{
"code": null,
"e": 1276,
"s": 1187,
"text": "About Google interview process ( 2-3 phone interview + 4-5 onsite interview in London )."
},
{
"code": null,
"e": 1331,
"s": 1276,
"text": "Round2:(Phone interview + coding on shared google doc)"
},
{
"code": null,
"e": 1363,
"s": 1331,
"text": "By:Software Developer @Google :"
},
{
"code": null,
"e": 1433,
"s": 1363,
"text": "* Questions from Project:Bi-directional Sync b/w mysql and sqilte db."
},
{
"code": null,
"e": 1527,
"s": 1433,
"text": "* Given a number , check if it can be represented in 5^n form , where n is positive integer ."
},
{
"code": null,
"e": 1632,
"s": 1527,
"text": "* Given a string of words with lots of spaces between the words , remove all the unnecessary spaces like"
},
{
"code": null,
"e": 1694,
"s": 1632,
"text": " input: I live on earth \n output: I live on earth"
},
{
"code": null,
"e": 1749,
"s": 1694,
"text": "Round3:(Phone interview + coding on shared google doc)"
},
{
"code": null,
"e": 1781,
"s": 1749,
"text": "By:Software developer @Google :"
},
{
"code": null,
"e": 1796,
"s": 1781,
"text": "* Optimize a^b"
},
{
"code": null,
"e": 1859,
"s": 1796,
"text": "* How would you split a search query across multiple machines?"
},
{
"code": null,
"e": 1952,
"s": 1859,
"text": "* You need to develop the game Snake. What data structures will you use? Code your solution."
},
{
"code": null,
"e": 1993,
"s": 1952,
"text": "Some additional hints for the interview:"
},
{
"code": null,
"e": 2053,
"s": 1993,
"text": "Clarify the question – make sure you understand everything."
},
{
"code": null,
"e": 2094,
"s": 2053,
"text": "Try to find the most efficient solution."
},
{
"code": null,
"e": 2210,
"s": 2094,
"text": "Come up with solutions quickly: even if its a brute force solution. Always iterate away from the original solution."
},
{
"code": null,
"e": 2355,
"s": 2210,
"text": "Before you start coding explain why you’re approaching it that way ,its ok to start off with a naive solution and try to make it more efficient."
},
{
"code": null,
"e": 2409,
"s": 2355,
"text": "Explain the rationale behind the steps you are doing."
},
{
"code": null,
"e": 2524,
"s": 2409,
"text": "Think out loud, keep things technical. The engineers will give you hints: take a hint! They are there to help you!"
},
{
"code": null,
"e": 2556,
"s": 2524,
"text": "Always write “compilable” code."
},
{
"code": null,
"e": 2597,
"s": 2556,
"text": "Mind edge cases. Find bugs in your code."
},
{
"code": null,
"e": 2820,
"s": 2599,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2827,
"s": 2820,
"text": "Google"
},
{
"code": null,
"e": 2849,
"s": 2827,
"text": "Interview Experiences"
},
{
"code": null,
"e": 2856,
"s": 2849,
"text": "Google"
}
] |
How to insert an item at the beginning of an array in PHP ?
|
06 Jun, 2021
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. There are two methods to insert an item at the beginning of an array which are discussed below:Using array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.
Create an array containing array elements.
Create another array containing one element which needs to insert at the beginning of another array.
Use array_merge() function to merge both arrays to create a single array.
Example:
php
<?php // Declare an array$arr1 = array( "GeeksforGeeks", "Computer", "Science", "Portal"); // Declare another array containing// element which need to insert at// the beginning of $arr1$arr2 = array( "Welcome"); // User array_merge() function to// merge both array$mergeArr = array_merge( $arr1, $arr2 ); print_r($mergeArr); ?>
Array
(
[0] => GeeksforGeeks
[1] => Computer
[2] => Science
[3] => Portal
[4] => Welcome
)
Using array_unshift() function: The array_unshift() function is used to add on or more elements at the beginning of the array. Example 1:
php
<?php // Declare an array$array = array( "GeeksforGeeks", "Computer", "Science", "Portal"); // Declare a variable containing element$element = "Welcome"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>
Array
(
[0] => Welcome
[1] => GeeksforGeeks
[2] => Computer
[3] => Science
[4] => Portal
)
Example 2:
php
<?php // Declare an associative array$array = array( "p" => "GeeksforGeeks", "q" => "Computer", "r" => "Science", "s" => "Portal"); // Declare a variable containing element$element = "Welcome"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>
Array
(
[0] => Welcome
[p] => GeeksforGeeks
[q] => Computer
[r] => Science
[s] => Portal
)
arorakashish0911
PHP-array
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 670,
"s": 28,
"text": "Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. There are two methods to insert an item at the beginning of an array which are discussed below:Using array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. "
},
{
"code": null,
"e": 713,
"s": 670,
"text": "Create an array containing array elements."
},
{
"code": null,
"e": 814,
"s": 713,
"text": "Create another array containing one element which needs to insert at the beginning of another array."
},
{
"code": null,
"e": 888,
"s": 814,
"text": "Use array_merge() function to merge both arrays to create a single array."
},
{
"code": null,
"e": 899,
"s": 888,
"text": "Example: "
},
{
"code": null,
"e": 903,
"s": 899,
"text": "php"
},
{
"code": "<?php // Declare an array$arr1 = array( \"GeeksforGeeks\", \"Computer\", \"Science\", \"Portal\"); // Declare another array containing// element which need to insert at// the beginning of $arr1$arr2 = array( \"Welcome\"); // User array_merge() function to// merge both array$mergeArr = array_merge( $arr1, $arr2 ); print_r($mergeArr); ?>",
"e": 1246,
"s": 903,
"text": null
},
{
"code": null,
"e": 1357,
"s": 1246,
"text": "Array\n(\n [0] => GeeksforGeeks\n [1] => Computer\n [2] => Science\n [3] => Portal\n [4] => Welcome\n)"
},
{
"code": null,
"e": 1499,
"s": 1359,
"text": "Using array_unshift() function: The array_unshift() function is used to add on or more elements at the beginning of the array. Example 1: "
},
{
"code": null,
"e": 1503,
"s": 1499,
"text": "php"
},
{
"code": "<?php // Declare an array$array = array( \"GeeksforGeeks\", \"Computer\", \"Science\", \"Portal\"); // Declare a variable containing element$element = \"Welcome\"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>",
"e": 1798,
"s": 1503,
"text": null
},
{
"code": null,
"e": 1909,
"s": 1798,
"text": "Array\n(\n [0] => Welcome\n [1] => GeeksforGeeks\n [2] => Computer\n [3] => Science\n [4] => Portal\n)"
},
{
"code": null,
"e": 1924,
"s": 1911,
"text": "Example 2: "
},
{
"code": null,
"e": 1928,
"s": 1924,
"text": "php"
},
{
"code": "<?php // Declare an associative array$array = array( \"p\" => \"GeeksforGeeks\", \"q\" => \"Computer\", \"r\" => \"Science\", \"s\" => \"Portal\"); // Declare a variable containing element$element = \"Welcome\"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>",
"e": 2263,
"s": 1928,
"text": null
},
{
"code": null,
"e": 2374,
"s": 2263,
"text": "Array\n(\n [0] => Welcome\n [p] => GeeksforGeeks\n [q] => Computer\n [r] => Science\n [s] => Portal\n)"
},
{
"code": null,
"e": 2393,
"s": 2376,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2403,
"s": 2393,
"text": "PHP-array"
},
{
"code": null,
"e": 2410,
"s": 2403,
"text": "Picked"
},
{
"code": null,
"e": 2414,
"s": 2410,
"text": "PHP"
},
{
"code": null,
"e": 2427,
"s": 2414,
"text": "PHP Programs"
},
{
"code": null,
"e": 2444,
"s": 2427,
"text": "Web Technologies"
},
{
"code": null,
"e": 2471,
"s": 2444,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2475,
"s": 2471,
"text": "PHP"
}
] |
Python | Check if all elements in a List are same
|
08 Dec, 2018
Given a list, write a Python program to check if all the elements in given list are same.
Example:
Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
Output: Yes
Input: ['Geeks', 'Is', 'all', 'Same', ]
Output: No
There are various ways we can do this task. Let’s see different ways we can check if all elements in a List are same.
Method #1: Comparing each element.
# Python program to check if all # ments in a List are same def ckeckList(lst): ele = lst[0] chk = True # Comparing each element with first item for item in lst: if ele != item: chk = False break; if (chk == True): print("Equal") else: print("Not equal") # Driver Codelst = ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]ckeckList(lst)
Output:
Equal
But In Python, we can do the same task in much interesting ways.
Method #2: Using all() method
# Python program to check if all # elements in a List are same res = False def chkList(lst): if len(lst) < 0 : res = True res = all(ele == lst[0] for ele in lst) if(res): print("Equal") else: print("Not equal") # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)
Output:
Equal
Method #3: Using count() method
# Python program to check if all # elements in a List are same res = False def chkList(lst): if len(lst) < 0 : res = True res = lst.count(lst[0]) == len(lst) if(res): print("Equal") else: print("Not equal") # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)
Output:
Equal
Method #4: Using set data structureSince we know there cannot be duplicate elements in a set, we can use this property to check whether all the elements are same or not.
# Python program to check if all # elements in a List are same def chkList(lst): return len(set(lst)) == 1 # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks'] if chkList(lst) == True: print("Equal")else: print("Not Equal")
Output:
Equal
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Dec, 2018"
},
{
"code": null,
"e": 143,
"s": 53,
"text": "Given a list, write a Python program to check if all the elements in given list are same."
},
{
"code": null,
"e": 152,
"s": 143,
"text": "Example:"
},
{
"code": null,
"e": 262,
"s": 152,
"text": "Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]\nOutput: Yes\n\nInput: ['Geeks', 'Is', 'all', 'Same', ]\nOutput: No"
},
{
"code": null,
"e": 380,
"s": 262,
"text": "There are various ways we can do this task. Let’s see different ways we can check if all elements in a List are same."
},
{
"code": null,
"e": 415,
"s": 380,
"text": "Method #1: Comparing each element."
},
{
"code": "# Python program to check if all # ments in a List are same def ckeckList(lst): ele = lst[0] chk = True # Comparing each element with first item for item in lst: if ele != item: chk = False break; if (chk == True): print(\"Equal\") else: print(\"Not equal\") # Driver Codelst = ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]ckeckList(lst)",
"e": 827,
"s": 415,
"text": null
},
{
"code": null,
"e": 835,
"s": 827,
"text": "Output:"
},
{
"code": null,
"e": 841,
"s": 835,
"text": "Equal"
},
{
"code": null,
"e": 907,
"s": 841,
"text": " But In Python, we can do the same task in much interesting ways."
},
{
"code": null,
"e": 937,
"s": 907,
"text": "Method #2: Using all() method"
},
{
"code": "# Python program to check if all # elements in a List are same res = False def chkList(lst): if len(lst) < 0 : res = True res = all(ele == lst[0] for ele in lst) if(res): print(\"Equal\") else: print(\"Not equal\") # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)",
"e": 1265,
"s": 937,
"text": null
},
{
"code": null,
"e": 1273,
"s": 1265,
"text": "Output:"
},
{
"code": null,
"e": 1279,
"s": 1273,
"text": "Equal"
},
{
"code": null,
"e": 1312,
"s": 1279,
"text": " Method #3: Using count() method"
},
{
"code": "# Python program to check if all # elements in a List are same res = False def chkList(lst): if len(lst) < 0 : res = True res = lst.count(lst[0]) == len(lst) if(res): print(\"Equal\") else: print(\"Not equal\") # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)",
"e": 1636,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1644,
"s": 1636,
"text": "Output:"
},
{
"code": null,
"e": 1650,
"s": 1644,
"text": "Equal"
},
{
"code": null,
"e": 1821,
"s": 1650,
"text": " Method #4: Using set data structureSince we know there cannot be duplicate elements in a set, we can use this property to check whether all the elements are same or not."
},
{
"code": "# Python program to check if all # elements in a List are same def chkList(lst): return len(set(lst)) == 1 # Driver Code lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks'] if chkList(lst) == True: print(\"Equal\")else: print(\"Not Equal\")",
"e": 2065,
"s": 1821,
"text": null
},
{
"code": null,
"e": 2073,
"s": 2065,
"text": "Output:"
},
{
"code": null,
"e": 2079,
"s": 2073,
"text": "Equal"
},
{
"code": null,
"e": 2100,
"s": 2079,
"text": "Python list-programs"
},
{
"code": null,
"e": 2112,
"s": 2100,
"text": "python-list"
},
{
"code": null,
"e": 2119,
"s": 2112,
"text": "Python"
},
{
"code": null,
"e": 2135,
"s": 2119,
"text": "Python Programs"
},
{
"code": null,
"e": 2147,
"s": 2135,
"text": "python-list"
}
] |
What is Python's Sys Module
|
The sys module in Python provides valuable information about the Python interpreter. You can also use it to obtain details about the constants, functions and methods of the Python interpreter.
The sys module comes packaged with Python, which means you do not need to download and install it separately using the PIP package manager.
In order to start using the sys module and its various functions, you need to import it. You can do that using the below line of code,
import sys
In python, we can execute the script directly from our terminal using various arguments. Sometimes it is nice to display the user the different arguments they’ve used while executing the script or to store it for other purposes.
We can achieve this with ease using the argv function present in the sys module.
# Creating a Python script named example.py
import sys
print("You entered: ", sys.argv[1], sys.argv[2])
Now, if you run the above program through a terminal with arguments, we first change the directory to the one where the script is present and then use,
python example.py Hello World
Typing the above line in the terminal will then execute the program which will then in turn print out the arguments we’ve entered.
Hello World
Note − In the above example we started with sys.argv[1] and not sys.argv[0], because sys.argv[0] prints the name of script we are currently executing and not the argument provided.
If you want to force quit the application or stop it from executing at any point, we can use the exit() function within the sys module.
import sys
print(“Hello there!”)
sys.exit()
print(“This line is not even executed because the program exited in the last line”)
Hello there!
In the above example, we use the sys.exit() function to stop the execution of the program, thus not printing the last line.
Wondered what version of python you are working on? Or just wanted the user to know what version of Python they are using to execute your script?
You can use the sys.version method to do so.
import sys
print(“You are currently using Python version”, sys.version)
You are currently using Python version 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)]
If you want to know where all your Python modules are downloaded and installed, you can use the sys.path folder.
import sys
sys.path
Input() is not the only way to read user input. You can use the sys module’s stdin function to read input as well.
import sys
data = sys.stdin.readline()
print(“You have entered −> ” + data)
The above line of code will read in the data entered until the user hits Enter and then print it back.
You now have a basic understanding of how and where we use the sys module in python.
There are a lot more functions in the sys module with more features and functionalities. To explore and read more about each of them, you can go through its official documentation at https://docs.python.org/3/library/sys.html.
|
[
{
"code": null,
"e": 1380,
"s": 1187,
"text": "The sys module in Python provides valuable information about the Python interpreter. You can also use it to obtain details about the constants, functions and methods of the Python interpreter."
},
{
"code": null,
"e": 1520,
"s": 1380,
"text": "The sys module comes packaged with Python, which means you do not need to download and install it separately using the PIP package manager."
},
{
"code": null,
"e": 1655,
"s": 1520,
"text": "In order to start using the sys module and its various functions, you need to import it. You can do that using the below line of code,"
},
{
"code": null,
"e": 1666,
"s": 1655,
"text": "import sys"
},
{
"code": null,
"e": 1895,
"s": 1666,
"text": "In python, we can execute the script directly from our terminal using various arguments. Sometimes it is nice to display the user the different arguments they’ve used while executing the script or to store it for other purposes."
},
{
"code": null,
"e": 1976,
"s": 1895,
"text": "We can achieve this with ease using the argv function present in the sys module."
},
{
"code": null,
"e": 2080,
"s": 1976,
"text": "# Creating a Python script named example.py\nimport sys\nprint(\"You entered: \", sys.argv[1], sys.argv[2])"
},
{
"code": null,
"e": 2232,
"s": 2080,
"text": "Now, if you run the above program through a terminal with arguments, we first change the directory to the one where the script is present and then use,"
},
{
"code": null,
"e": 2262,
"s": 2232,
"text": "python example.py Hello World"
},
{
"code": null,
"e": 2393,
"s": 2262,
"text": "Typing the above line in the terminal will then execute the program which will then in turn print out the arguments we’ve entered."
},
{
"code": null,
"e": 2405,
"s": 2393,
"text": "Hello World"
},
{
"code": null,
"e": 2586,
"s": 2405,
"text": "Note − In the above example we started with sys.argv[1] and not sys.argv[0], because sys.argv[0] prints the name of script we are currently executing and not the argument provided."
},
{
"code": null,
"e": 2722,
"s": 2586,
"text": "If you want to force quit the application or stop it from executing at any point, we can use the exit() function within the sys module."
},
{
"code": null,
"e": 2850,
"s": 2722,
"text": "import sys\nprint(“Hello there!”)\nsys.exit()\nprint(“This line is not even executed because the program exited in the last line”)"
},
{
"code": null,
"e": 2863,
"s": 2850,
"text": "Hello there!"
},
{
"code": null,
"e": 2987,
"s": 2863,
"text": "In the above example, we use the sys.exit() function to stop the execution of the program, thus not printing the last line."
},
{
"code": null,
"e": 3133,
"s": 2987,
"text": "Wondered what version of python you are working on? Or just wanted the user to know what version of Python they are using to execute your script?"
},
{
"code": null,
"e": 3178,
"s": 3133,
"text": "You can use the sys.version method to do so."
},
{
"code": null,
"e": 3250,
"s": 3178,
"text": "import sys\nprint(“You are currently using Python version”, sys.version)"
},
{
"code": null,
"e": 3371,
"s": 3250,
"text": "You are currently using Python version 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)]"
},
{
"code": null,
"e": 3484,
"s": 3371,
"text": "If you want to know where all your Python modules are downloaded and installed, you can use the sys.path folder."
},
{
"code": null,
"e": 3504,
"s": 3484,
"text": "import sys\nsys.path"
},
{
"code": null,
"e": 3619,
"s": 3504,
"text": "Input() is not the only way to read user input. You can use the sys module’s stdin function to read input as well."
},
{
"code": null,
"e": 3695,
"s": 3619,
"text": "import sys\ndata = sys.stdin.readline()\nprint(“You have entered −> ” + data)"
},
{
"code": null,
"e": 3798,
"s": 3695,
"text": "The above line of code will read in the data entered until the user hits Enter and then print it back."
},
{
"code": null,
"e": 3883,
"s": 3798,
"text": "You now have a basic understanding of how and where we use the sys module in python."
},
{
"code": null,
"e": 4110,
"s": 3883,
"text": "There are a lot more functions in the sys module with more features and functionalities. To explore and read more about each of them, you can go through its official documentation at https://docs.python.org/3/library/sys.html."
}
] |
How to make graphics with transparent background in R using ggplot2?
|
14 Sep, 2021
In this article, we will discuss how to create graphs with transparent background in R programming language.
The required task will be achieved by using theme() function with appropriate parameters. theme() function used to modify theme settings. To actually visualize a transparent background the image has to be stored as a PNG image, this can be done ggsave() function.
Syntax: ggsave(plot, filename, bg)
Parameter:
plot: plot to be saved
filename: path of the file
bg: background
Create a simple plot for demonstration:
R
library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line() ggsave(plt, filename = "output1.png")
Output:
In this approach, after the plot has been created normally, theme() function is added to it with rect parameter. To rect, element_rect() function is passed with parameter fill set to transparent.
Syntax: theme(rect = element_rect(fill=”transparent”))
Example: Plot with transparent background
R
library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line()+ theme(rect = element_rect(fill = "transparent")) ggsave(plt, filename = "output.png", bg = "transparent")
Output:
By setting, background elements to transparent the background of a plot can be made transparent.
Example: Plot with transparent background
R
library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c("function1","function2", "function3","function4"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line()+ theme(legend.background = element_rect(fill = "transparent"), legend.box.background = element_rect(fill = "transparent"), panel.background = element_rect(fill = "transparent"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_rect(fill = "transparent", color = NA)) ggsave(plt, filename = "output1.png", bg = "transparent")
Output:
Blogathon-2021
Picked
R-ggplot
Blogathon
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "In this article, we will discuss how to create graphs with transparent background in R programming language. "
},
{
"code": null,
"e": 402,
"s": 138,
"text": "The required task will be achieved by using theme() function with appropriate parameters. theme() function used to modify theme settings. To actually visualize a transparent background the image has to be stored as a PNG image, this can be done ggsave() function."
},
{
"code": null,
"e": 437,
"s": 402,
"text": "Syntax: ggsave(plot, filename, bg)"
},
{
"code": null,
"e": 448,
"s": 437,
"text": "Parameter:"
},
{
"code": null,
"e": 471,
"s": 448,
"text": "plot: plot to be saved"
},
{
"code": null,
"e": 498,
"s": 471,
"text": "filename: path of the file"
},
{
"code": null,
"e": 514,
"s": 498,
"text": "bg: background "
},
{
"code": null,
"e": 554,
"s": 514,
"text": "Create a simple plot for demonstration:"
},
{
"code": null,
"e": 556,
"s": 554,
"text": "R"
},
{
"code": "library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line() ggsave(plt, filename = \"output1.png\")",
"e": 1072,
"s": 556,
"text": null
},
{
"code": null,
"e": 1080,
"s": 1072,
"text": "Output:"
},
{
"code": null,
"e": 1276,
"s": 1080,
"text": "In this approach, after the plot has been created normally, theme() function is added to it with rect parameter. To rect, element_rect() function is passed with parameter fill set to transparent."
},
{
"code": null,
"e": 1331,
"s": 1276,
"text": "Syntax: theme(rect = element_rect(fill=”transparent”))"
},
{
"code": null,
"e": 1373,
"s": 1331,
"text": "Example: Plot with transparent background"
},
{
"code": null,
"e": 1375,
"s": 1373,
"text": "R"
},
{
"code": "library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line()+ theme(rect = element_rect(fill = \"transparent\")) ggsave(plt, filename = \"output.png\", bg = \"transparent\")",
"e": 1961,
"s": 1375,
"text": null
},
{
"code": null,
"e": 1969,
"s": 1961,
"text": "Output:"
},
{
"code": null,
"e": 2066,
"s": 1969,
"text": "By setting, background elements to transparent the background of a plot can be made transparent."
},
{
"code": null,
"e": 2108,
"s": 2066,
"text": "Example: Plot with transparent background"
},
{
"code": null,
"e": 2110,
"s": 2108,
"text": "R"
},
{
"code": "library(ggplot2) function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)} df=data.frame(x=-2:2, values=c(function1(-2:2), function2(-2:2), function3(-2:2), function4(-2:2)), fun=rep(c(\"function1\",\"function2\", \"function3\",\"function4\"))) plt<-ggplot(df,aes(x,values,col=fun))+geom_line()+ theme(legend.background = element_rect(fill = \"transparent\"), legend.box.background = element_rect(fill = \"transparent\"), panel.background = element_rect(fill = \"transparent\"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_rect(fill = \"transparent\", color = NA)) ggsave(plt, filename = \"output1.png\", bg = \"transparent\")",
"e": 3036,
"s": 2110,
"text": null
},
{
"code": null,
"e": 3044,
"s": 3036,
"text": "Output:"
},
{
"code": null,
"e": 3059,
"s": 3044,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 3066,
"s": 3059,
"text": "Picked"
},
{
"code": null,
"e": 3075,
"s": 3066,
"text": "R-ggplot"
},
{
"code": null,
"e": 3085,
"s": 3075,
"text": "Blogathon"
},
{
"code": null,
"e": 3096,
"s": 3085,
"text": "R Language"
}
] |
Python | Pandas dataframe.idxmax()
|
19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.idxmax() function returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded.
Syntax: DataFrame.idxmax(axis=0, skipna=True)
Parameters :axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiseskipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns : idxmax : Series
Example #1: Use idxmax() function to function to find the index of the maximum value along the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, 6], "B":[11, 2, 5, 8], "C":[1, 8, 66, 4]}) # Print the dataframedf
Now apply the idxmax() function along the index axis.
# applying idxmax() function.df.idxmax(axis = 0)
Output :
If we look at the values in the dataframe, we can verify the result returned by the function. The function returned a pandas series object containing the index of maximum value in each column.
Example #2: Use idxmax() function to find the index of the maximum value along the column axis. The dataframe contains NA values.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, None], "B":[11, 2, None, 8], "C":[1, 8, 66, 4]}) # Skipna = True will skip all the Na values# find maximum along column axisdf.idxmax(axis = 1, skipna = True)
Output :
The output is a pandas series containing the column label for each row which has the maximum value.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 439,
"s": 242,
"text": "Pandas dataframe.idxmax() function returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded."
},
{
"code": null,
"e": 485,
"s": 439,
"text": "Syntax: DataFrame.idxmax(axis=0, skipna=True)"
},
{
"code": null,
"e": 647,
"s": 485,
"text": "Parameters :axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiseskipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA"
},
{
"code": null,
"e": 673,
"s": 647,
"text": "Returns : idxmax : Series"
},
{
"code": null,
"e": 780,
"s": 673,
"text": "Example #1: Use idxmax() function to function to find the index of the maximum value along the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[4, 5, 2, 6], \"B\":[11, 2, 5, 8], \"C\":[1, 8, 66, 4]}) # Print the dataframedf",
"e": 988,
"s": 780,
"text": null
},
{
"code": null,
"e": 1042,
"s": 988,
"text": "Now apply the idxmax() function along the index axis."
},
{
"code": "# applying idxmax() function.df.idxmax(axis = 0)",
"e": 1091,
"s": 1042,
"text": null
},
{
"code": null,
"e": 1100,
"s": 1091,
"text": "Output :"
},
{
"code": null,
"e": 1294,
"s": 1100,
"text": "If we look at the values in the dataframe, we can verify the result returned by the function. The function returned a pandas series object containing the index of maximum value in each column. "
},
{
"code": null,
"e": 1424,
"s": 1294,
"text": "Example #2: Use idxmax() function to find the index of the maximum value along the column axis. The dataframe contains NA values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[4, 5, 2, None], \"B\":[11, 2, None, 8], \"C\":[1, 8, 66, 4]}) # Skipna = True will skip all the Na values# find maximum along column axisdf.idxmax(axis = 1, skipna = True)",
"e": 1724,
"s": 1424,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1724,
"text": "Output :"
},
{
"code": null,
"e": 1833,
"s": 1733,
"text": "The output is a pandas series containing the column label for each row which has the maximum value."
},
{
"code": null,
"e": 1857,
"s": 1833,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1889,
"s": 1857,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 1903,
"s": 1889,
"text": "Python-pandas"
},
{
"code": null,
"e": 1910,
"s": 1903,
"text": "Python"
}
] |
TypeScript | String search() Method
|
17 Feb, 2021
The search() is an inbuilt function in TypeScript that is used to search for a match between a regular expression and this String object. Syntax:
string.search(regexp);
Parameter: This methods accept a single parameter as mentioned above and described below:
regexp: This parameter is a RegExp object.
Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. Below example illustrate the String search() method in TypeScriptJS:
Example 1:
Javascript
// This is TypeScript// Original stringsvar str = "Geeksforgeeks - Best Platform"; var re = /Best/gi; // use of String search() Methodif (str.search(re) == -1 ) { console.log("Not Found" );} else { console.log("Found" );}
Output:
Found
Example 2:
JavaScript
// This is TypeScript// Original stringsvar str = "Geeksforgeeks - Best Platform"; var re = /geeek/gi; // use of String search() Methodif (str.search(re) == -1 ) { console.log("Not Found" );} else { console.log("Found" );}
Output:
Not Found
pratikraut0000
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
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": "\n17 Feb, 2021"
},
{
"code": null,
"e": 174,
"s": 28,
"text": "The search() is an inbuilt function in TypeScript that is used to search for a match between a regular expression and this String object. Syntax:"
},
{
"code": null,
"e": 197,
"s": 174,
"text": "string.search(regexp);"
},
{
"code": null,
"e": 288,
"s": 197,
"text": "Parameter: This methods accept a single parameter as mentioned above and described below: "
},
{
"code": null,
"e": 331,
"s": 288,
"text": "regexp: This parameter is a RegExp object."
},
{
"code": null,
"e": 516,
"s": 331,
"text": "Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. Below example illustrate the String search() method in TypeScriptJS:"
},
{
"code": null,
"e": 527,
"s": 516,
"text": "Example 1:"
},
{
"code": null,
"e": 538,
"s": 527,
"text": "Javascript"
},
{
"code": "// This is TypeScript// Original stringsvar str = \"Geeksforgeeks - Best Platform\"; var re = /Best/gi; // use of String search() Methodif (str.search(re) == -1 ) { console.log(\"Not Found\" );} else { console.log(\"Found\" );}",
"e": 762,
"s": 538,
"text": null
},
{
"code": null,
"e": 771,
"s": 762,
"text": "Output: "
},
{
"code": null,
"e": 777,
"s": 771,
"text": "Found"
},
{
"code": null,
"e": 788,
"s": 777,
"text": "Example 2:"
},
{
"code": null,
"e": 799,
"s": 788,
"text": "JavaScript"
},
{
"code": "// This is TypeScript// Original stringsvar str = \"Geeksforgeeks - Best Platform\"; var re = /geeek/gi; // use of String search() Methodif (str.search(re) == -1 ) { console.log(\"Not Found\" );} else { console.log(\"Found\" );}",
"e": 1028,
"s": 799,
"text": null
},
{
"code": null,
"e": 1036,
"s": 1028,
"text": "Output:"
},
{
"code": null,
"e": 1047,
"s": 1036,
"text": "Not Found "
},
{
"code": null,
"e": 1062,
"s": 1047,
"text": "pratikraut0000"
},
{
"code": null,
"e": 1073,
"s": 1062,
"text": "TypeScript"
},
{
"code": null,
"e": 1084,
"s": 1073,
"text": "JavaScript"
},
{
"code": null,
"e": 1101,
"s": 1084,
"text": "Web Technologies"
},
{
"code": null,
"e": 1199,
"s": 1101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1260,
"s": 1199,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1332,
"s": 1260,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1372,
"s": 1332,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1414,
"s": 1372,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1455,
"s": 1414,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1488,
"s": 1455,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1550,
"s": 1488,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1611,
"s": 1550,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1661,
"s": 1611,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
vi Editor in UNIX
|
16 May, 2020
The default editor that comes with the UNIX operating system is called vi (visual editor). Using vi editor, we can edit an existing file or create a new file from scratch. we can also use this editor to just read a text file.Syntax:
vi filename
Input:Output:
Modes of Operation in vi editor There are three modes of operation in vi:
Command Mode: When vi starts up, it is in Command Mode. This mode is where vi interprets any characters we type as commands and thus does not display them in the window. This mode allows us to move through a file, and to delete, copy, or paste a piece of text.To enter into Command Mode from any other mode, it requires pressing the [Esc] key. If we press [Esc] when we are already in Command Mode, then vi will beep or flash the screen.
Insert mode: This mode enables you to insert text into the file. Everything that’s typed in this mode is interpreted as input and finally, it is put in the file. The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode you simply type i. To get out of insert mode, press the Esc key, which will put you back into command mode.
Last Line Mode(Escape Mode): Line Mode is invoked by typing a colon [:], while vi is in Command Mode. The cursor will jump to the last line of the screen and vi will wait for a command. This mode enables you to perform tasks such as saving files, executing commands.
There are following way you can start using vi editor :
Commands and their Description
vi filename: Creates a new file if it already not exist, otherwise opens existing file.
vi -R filename : Opens an existing file in read only mode.
view filename : Opens an existing file in read only mode.
Moving within a File(Navigation):To move around within a file without affecting text must be in command mode (press Esc twice). Here are some of the commands can be used to move around one character at a time.
Commands and their Description
k : Moves the cursor up one line.
j : Moves the cursor down one line.
h : Moves the cursor to the left one character position.
l : Moves the cursor to the right one character position.
0 or | : Positions cursor at beginning of line.
$ : Positions cursor at end of line.
W : Positions cursor to the next word.
B : Positions cursor to previous word.
( : Positions cursor to beginning of current sentence.
) : Positions cursor to beginning of next sentence.
H : Move to top of screen.
nH : Moves to nth line from the top of the screen.
M : Move to middle of screen.
L : Move to bottom of screen.
nL : Moves to nth line from the bottom of the screen.
colon along with x : Colon followed by a number would position the cursor on line number represented by x.
Control Commands(Scrolling): There are following useful commands which can used along with Control Key:
Commands and their Description:
CTRL+d : Move forward 1/2 screen.
CTRL+f : Move forward one full screen.
CTRL+u : Move backward 1/2 screen.
CTRL+b : Move backward one full screen.
CTRL+e : Moves screen up one line.
CTRL+y : Moves screen down one line.
CTRL+u : Moves screen up 1/2 page.
CTRL+d : Moves screen down 1/2 page.
CTRL+b : Moves screen up one page.
CTRL+f : Moves screen down one page.
CTRL+I : Redraws screen.
Editing and inserting in Files(Entering and Replacing Text): To edit the file, we need to be in the insert mode. There are many ways to enter insert mode from the command mode.
i : Inserts text before current cursor location.
I : Inserts text at beginning of current line.
a : Inserts text after current cursor location.
A : Inserts text at end of current line.
o : Creates a new line for text entry below cursor location.
O : Creates a new line for text entry above cursor location.
r : Replace single character under the cursor with the next character typed.
R : Replaces text from the cursor to right.
s : Replaces single character under the cursor with any number of characters.
S :Replaces entire line.
Deleting Characters: Here is the list of important commands which can be used to delete characters and lines in an opened file.
X Uppercase: Deletes the character before the cursor location.
x Lowercase : Deletes the character at the cursor location.
Dw : Deletes from the current cursor location to the next word.
d^ : Deletes from current cursor position to the beginning of the line.
d$ : Deletes from current cursor position to the end of the line.
Dd : Deletes the line the cursor is on.
Copy and Past Commands: Copy lines or words from one place and paste them on another place by using the following commands.
Yy : Copies the current line.
9yy : Yank current line and 9 lines below.
p : Puts the copied text after the cursor.
P : Puts the yanked text before the cursor.
Save and Exit Commands of the ex Mode : Need to press [Esc] key followed by the colon (:) before typing the following commands:
q : Quit
q! : Quit without saving changes i.e. discard changes.
r fileName : Read data from file called fileName.
wq : Write and quit (save and exit).
w fileName : Write to file called fileName (save as).
w! fileName : Overwrite to file called fileName (save as forcefully).
!cmd : Runs shell commands and returns to Command mode.
Searching and Replacing in (ex Mode): vi also has powerful search and replace capabilities. The formal syntax for searching is:
:s/string
For example, suppose we want to search some text for the string “geeksforgeeks” Type the following and press ENTER:
:s/geeksforgeeks
Input:Output: finding the first match for “geeksforgeeks” in text will then be highlighted.The syntax for replacing one string with another string in the current line is:
:s/pattern/replace/
Here “pattern” represents the old string and “replace” represents the new string. For example, to replace each occurrence of the word “geeks” in a line with “geeksforgeeks” type:
:s/geeksforgeeks/gfg/
Input:Output:The syntax for replacing every occurrence of a string in the entire text is similar. The only difference is the addition of a “%” in front of the “s”:
:%s/pattern/replace/
Thus repeating the previous example for the entire text instead of just for a single line would be:
:%s/gfg/geeksforgeeks/
Reference: http://www.linfo.org/vi/
AbhinavKinagi
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
chown command in Linux with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 May, 2020"
},
{
"code": null,
"e": 287,
"s": 54,
"text": "The default editor that comes with the UNIX operating system is called vi (visual editor). Using vi editor, we can edit an existing file or create a new file from scratch. we can also use this editor to just read a text file.Syntax:"
},
{
"code": null,
"e": 300,
"s": 287,
"text": "vi filename\n"
},
{
"code": null,
"e": 314,
"s": 300,
"text": "Input:Output:"
},
{
"code": null,
"e": 388,
"s": 314,
"text": "Modes of Operation in vi editor There are three modes of operation in vi:"
},
{
"code": null,
"e": 826,
"s": 388,
"text": "Command Mode: When vi starts up, it is in Command Mode. This mode is where vi interprets any characters we type as commands and thus does not display them in the window. This mode allows us to move through a file, and to delete, copy, or paste a piece of text.To enter into Command Mode from any other mode, it requires pressing the [Esc] key. If we press [Esc] when we are already in Command Mode, then vi will beep or flash the screen."
},
{
"code": null,
"e": 1200,
"s": 826,
"text": "Insert mode: This mode enables you to insert text into the file. Everything that’s typed in this mode is interpreted as input and finally, it is put in the file. The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode you simply type i. To get out of insert mode, press the Esc key, which will put you back into command mode."
},
{
"code": null,
"e": 1467,
"s": 1200,
"text": "Last Line Mode(Escape Mode): Line Mode is invoked by typing a colon [:], while vi is in Command Mode. The cursor will jump to the last line of the screen and vi will wait for a command. This mode enables you to perform tasks such as saving files, executing commands."
},
{
"code": null,
"e": 1523,
"s": 1467,
"text": "There are following way you can start using vi editor :"
},
{
"code": null,
"e": 1554,
"s": 1523,
"text": "Commands and their Description"
},
{
"code": null,
"e": 1642,
"s": 1554,
"text": "vi filename: Creates a new file if it already not exist, otherwise opens existing file."
},
{
"code": null,
"e": 1701,
"s": 1642,
"text": "vi -R filename : Opens an existing file in read only mode."
},
{
"code": null,
"e": 1759,
"s": 1701,
"text": "view filename : Opens an existing file in read only mode."
},
{
"code": null,
"e": 1969,
"s": 1759,
"text": "Moving within a File(Navigation):To move around within a file without affecting text must be in command mode (press Esc twice). Here are some of the commands can be used to move around one character at a time."
},
{
"code": null,
"e": 2000,
"s": 1969,
"text": "Commands and their Description"
},
{
"code": null,
"e": 2034,
"s": 2000,
"text": "k : Moves the cursor up one line."
},
{
"code": null,
"e": 2070,
"s": 2034,
"text": "j : Moves the cursor down one line."
},
{
"code": null,
"e": 2127,
"s": 2070,
"text": "h : Moves the cursor to the left one character position."
},
{
"code": null,
"e": 2185,
"s": 2127,
"text": "l : Moves the cursor to the right one character position."
},
{
"code": null,
"e": 2233,
"s": 2185,
"text": "0 or | : Positions cursor at beginning of line."
},
{
"code": null,
"e": 2270,
"s": 2233,
"text": "$ : Positions cursor at end of line."
},
{
"code": null,
"e": 2309,
"s": 2270,
"text": "W : Positions cursor to the next word."
},
{
"code": null,
"e": 2348,
"s": 2309,
"text": "B : Positions cursor to previous word."
},
{
"code": null,
"e": 2403,
"s": 2348,
"text": "( : Positions cursor to beginning of current sentence."
},
{
"code": null,
"e": 2455,
"s": 2403,
"text": ") : Positions cursor to beginning of next sentence."
},
{
"code": null,
"e": 2482,
"s": 2455,
"text": "H : Move to top of screen."
},
{
"code": null,
"e": 2533,
"s": 2482,
"text": "nH : Moves to nth line from the top of the screen."
},
{
"code": null,
"e": 2563,
"s": 2533,
"text": "M : Move to middle of screen."
},
{
"code": null,
"e": 2593,
"s": 2563,
"text": "L : Move to bottom of screen."
},
{
"code": null,
"e": 2647,
"s": 2593,
"text": "nL : Moves to nth line from the bottom of the screen."
},
{
"code": null,
"e": 2754,
"s": 2647,
"text": "colon along with x : Colon followed by a number would position the cursor on line number represented by x."
},
{
"code": null,
"e": 2858,
"s": 2754,
"text": "Control Commands(Scrolling): There are following useful commands which can used along with Control Key:"
},
{
"code": null,
"e": 2890,
"s": 2858,
"text": "Commands and their Description:"
},
{
"code": null,
"e": 2924,
"s": 2890,
"text": "CTRL+d : Move forward 1/2 screen."
},
{
"code": null,
"e": 2963,
"s": 2924,
"text": "CTRL+f : Move forward one full screen."
},
{
"code": null,
"e": 2998,
"s": 2963,
"text": "CTRL+u : Move backward 1/2 screen."
},
{
"code": null,
"e": 3038,
"s": 2998,
"text": "CTRL+b : Move backward one full screen."
},
{
"code": null,
"e": 3073,
"s": 3038,
"text": "CTRL+e : Moves screen up one line."
},
{
"code": null,
"e": 3110,
"s": 3073,
"text": "CTRL+y : Moves screen down one line."
},
{
"code": null,
"e": 3145,
"s": 3110,
"text": "CTRL+u : Moves screen up 1/2 page."
},
{
"code": null,
"e": 3182,
"s": 3145,
"text": "CTRL+d : Moves screen down 1/2 page."
},
{
"code": null,
"e": 3217,
"s": 3182,
"text": "CTRL+b : Moves screen up one page."
},
{
"code": null,
"e": 3254,
"s": 3217,
"text": "CTRL+f : Moves screen down one page."
},
{
"code": null,
"e": 3279,
"s": 3254,
"text": "CTRL+I : Redraws screen."
},
{
"code": null,
"e": 3456,
"s": 3279,
"text": "Editing and inserting in Files(Entering and Replacing Text): To edit the file, we need to be in the insert mode. There are many ways to enter insert mode from the command mode."
},
{
"code": null,
"e": 3505,
"s": 3456,
"text": "i : Inserts text before current cursor location."
},
{
"code": null,
"e": 3552,
"s": 3505,
"text": "I : Inserts text at beginning of current line."
},
{
"code": null,
"e": 3600,
"s": 3552,
"text": "a : Inserts text after current cursor location."
},
{
"code": null,
"e": 3641,
"s": 3600,
"text": "A : Inserts text at end of current line."
},
{
"code": null,
"e": 3702,
"s": 3641,
"text": "o : Creates a new line for text entry below cursor location."
},
{
"code": null,
"e": 3763,
"s": 3702,
"text": "O : Creates a new line for text entry above cursor location."
},
{
"code": null,
"e": 3840,
"s": 3763,
"text": "r : Replace single character under the cursor with the next character typed."
},
{
"code": null,
"e": 3884,
"s": 3840,
"text": "R : Replaces text from the cursor to right."
},
{
"code": null,
"e": 3962,
"s": 3884,
"text": "s : Replaces single character under the cursor with any number of characters."
},
{
"code": null,
"e": 3987,
"s": 3962,
"text": "S :Replaces entire line."
},
{
"code": null,
"e": 4115,
"s": 3987,
"text": "Deleting Characters: Here is the list of important commands which can be used to delete characters and lines in an opened file."
},
{
"code": null,
"e": 4178,
"s": 4115,
"text": "X Uppercase: Deletes the character before the cursor location."
},
{
"code": null,
"e": 4238,
"s": 4178,
"text": "x Lowercase : Deletes the character at the cursor location."
},
{
"code": null,
"e": 4302,
"s": 4238,
"text": "Dw : Deletes from the current cursor location to the next word."
},
{
"code": null,
"e": 4374,
"s": 4302,
"text": "d^ : Deletes from current cursor position to the beginning of the line."
},
{
"code": null,
"e": 4440,
"s": 4374,
"text": "d$ : Deletes from current cursor position to the end of the line."
},
{
"code": null,
"e": 4480,
"s": 4440,
"text": "Dd : Deletes the line the cursor is on."
},
{
"code": null,
"e": 4604,
"s": 4480,
"text": "Copy and Past Commands: Copy lines or words from one place and paste them on another place by using the following commands."
},
{
"code": null,
"e": 4634,
"s": 4604,
"text": "Yy : Copies the current line."
},
{
"code": null,
"e": 4677,
"s": 4634,
"text": "9yy : Yank current line and 9 lines below."
},
{
"code": null,
"e": 4720,
"s": 4677,
"text": "p : Puts the copied text after the cursor."
},
{
"code": null,
"e": 4764,
"s": 4720,
"text": "P : Puts the yanked text before the cursor."
},
{
"code": null,
"e": 4892,
"s": 4764,
"text": "Save and Exit Commands of the ex Mode : Need to press [Esc] key followed by the colon (:) before typing the following commands:"
},
{
"code": null,
"e": 4901,
"s": 4892,
"text": "q : Quit"
},
{
"code": null,
"e": 4956,
"s": 4901,
"text": "q! : Quit without saving changes i.e. discard changes."
},
{
"code": null,
"e": 5006,
"s": 4956,
"text": "r fileName : Read data from file called fileName."
},
{
"code": null,
"e": 5043,
"s": 5006,
"text": "wq : Write and quit (save and exit)."
},
{
"code": null,
"e": 5097,
"s": 5043,
"text": "w fileName : Write to file called fileName (save as)."
},
{
"code": null,
"e": 5167,
"s": 5097,
"text": "w! fileName : Overwrite to file called fileName (save as forcefully)."
},
{
"code": null,
"e": 5223,
"s": 5167,
"text": "!cmd : Runs shell commands and returns to Command mode."
},
{
"code": null,
"e": 5351,
"s": 5223,
"text": "Searching and Replacing in (ex Mode): vi also has powerful search and replace capabilities. The formal syntax for searching is:"
},
{
"code": null,
"e": 5363,
"s": 5351,
"text": ":s/string \n"
},
{
"code": null,
"e": 5479,
"s": 5363,
"text": "For example, suppose we want to search some text for the string “geeksforgeeks” Type the following and press ENTER:"
},
{
"code": null,
"e": 5497,
"s": 5479,
"text": ":s/geeksforgeeks\n"
},
{
"code": null,
"e": 5668,
"s": 5497,
"text": "Input:Output: finding the first match for “geeksforgeeks” in text will then be highlighted.The syntax for replacing one string with another string in the current line is:"
},
{
"code": null,
"e": 5690,
"s": 5668,
"text": ":s/pattern/replace/ \n"
},
{
"code": null,
"e": 5869,
"s": 5690,
"text": "Here “pattern” represents the old string and “replace” represents the new string. For example, to replace each occurrence of the word “geeks” in a line with “geeksforgeeks” type:"
},
{
"code": null,
"e": 5893,
"s": 5869,
"text": ":s/geeksforgeeks/gfg/ \n"
},
{
"code": null,
"e": 6057,
"s": 5893,
"text": "Input:Output:The syntax for replacing every occurrence of a string in the entire text is similar. The only difference is the addition of a “%” in front of the “s”:"
},
{
"code": null,
"e": 6080,
"s": 6057,
"text": ":%s/pattern/replace/ \n"
},
{
"code": null,
"e": 6180,
"s": 6080,
"text": "Thus repeating the previous example for the entire text instead of just for a single line would be:"
},
{
"code": null,
"e": 6205,
"s": 6180,
"text": ":%s/gfg/geeksforgeeks/ \n"
},
{
"code": null,
"e": 6241,
"s": 6205,
"text": "Reference: http://www.linfo.org/vi/"
},
{
"code": null,
"e": 6255,
"s": 6241,
"text": "AbhinavKinagi"
},
{
"code": null,
"e": 6269,
"s": 6255,
"text": "linux-command"
},
{
"code": null,
"e": 6300,
"s": 6269,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 6311,
"s": 6300,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6409,
"s": 6311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6444,
"s": 6409,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 6482,
"s": 6444,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 6518,
"s": 6482,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 6544,
"s": 6518,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 6582,
"s": 6544,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 6617,
"s": 6582,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 6653,
"s": 6617,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 6688,
"s": 6653,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 6725,
"s": 6688,
"text": "touch command in Linux with Examples"
}
] |
How to convert the hamburger icon of navigation menu to X on click ? - GeeksforGeeks
|
25 Jun, 2021
The navigation menu is the most important section of a website. It helps in navigating through the website. Having a proper animation not only makes the website look good but also provides a user-friendly interface to the customer. Hence, this animation will make it possible to convert the three lines or the hamburger icon as it is frequently called, into an X upon click and vice versa. The code will contain 3 different structures which will make it possible to apply this animation. The HTML body, CSS body, and JavaScript body.Creating the structure: In this section, we will create a basic structure with the help of HTML. We will also add the font-awesome link to generate the lines to create the hamburger icon.
HTML
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <title> Converting the hamburger icon to X and vice versa </title></head> <body id="bg-img"> <header> <div class="menu-btn"> <div class="btn-line"></div> <div class="btn-line"></div> <div class="btn-line"></div> </div> <nav class="menu"> <div class="menu-branding"> <div class="portrait"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png" alt="" /> </div> </div> <ul class="menu-nav"> <li class="nav-item current"> <a href="#" class="nav-link"> HOME</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> ABOUT ME</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> MY WORK</a> </li> <li class="nav-item"> <a href="#" class="nav-link"> CONTACT ME</a> </li> </ul> </nav> </header></body> </html>
Designing the structure: In the previous section, we have created the basic structure of the hamburger icon. In this section, we will design the structure with the help of CSS.
css
<style> /* Styling the menu button */ .menu-btn { position: absolute; z-index: 3; right: 35px; top: 35px; cursor: pointer; transition: all 0.5s ease-out; } /* Styling the hamburger lines */ .menu-btn .btn-line { width: 28px; height: 3px; margin: 0 0 5px 0; background: black; transition: all 0.5s ease-out; } /* Adding transform to the X */ .menu-btn.close { transform: rotate(180deg); } /* Styling the three lines to make it an X */ .menu-btn.close .btn-line:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); } .menu-btn.close .btn-line:nth-child(2) { opacity: 0; } .menu-btn.close .btn-line:nth-child(3) { transform: rotate(-45deg) translate(7px, -6px); } /* Styling the position of the menu icon */ .menu { position: fixed; top: 0; width: 100%; opacity: 0.9; visibility: hidden; } .menu.show { visibility: visible; } /* Adding a transition delay to the 4 items in the navigation menu */ .nav-item:nth-child(1) { transition-delay: 0.1s; } .nav-item:nth-child(2) { transition-delay: 0.2s; } .nav-item:nth-child(3) { transition-delay: 0.3s; } .nav-item:nth-child(4) { transition-delay: 0.4s; }</style>
Adding JavaScript: In this section, we will add the javascript which is necessary for us to animate all the three lines of the hamburger icon. It adds an EventListener to the icon. This EventListener toggles the menu that is to be displayed upon click and needs to be hidden upon click. It determines the state of the menu button, whether it is X state or the hamburger state.
javascript
<script> // select dom items const menuBtn = document.querySelector(".menu-btn"); const menu = document.querySelector(".menu"); const menuNav = document.querySelector(".menu-nav"); const menuBranding = document.querySelector(".menu-branding"); const navItems = document.querySelectorAll(".nav-item"); // Set the initial state of the menu let showMenu = false; menuBtn.addEventListener("click", toggleMenu); function toggleMenu() { if (!showMenu) { menuBtn.classList.add("close"); menu.classList.add("show"); menuNav.classList.add("show"); menuBranding.classList.add("show"); navItems.forEach((item) => item.classList.add("show")); // Reset the menu state showMenu = true; } else { menuBtn.classList.remove("close"); menu.classList.remove("show"); menuNav.classList.remove("show"); menuBranding.classList.remove("show"); navItems.forEach((item) => item.classList.remove("show")); // Reset the menu state showMenu = false; } }</script>
Final solution: The final solution is the combination of the HTML, CSS, and the JavaScript codes to get the desired animation result.
html
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <title> Converting the hamburger icon to X and vice versa </title> <style> /* Styling the menu button */ .menu-btn { position: absolute; z-index: 3; right: 35px; top: 35px; cursor: pointer; transition: all 0.5s ease-out; } /* Styling the hamburger lines */ .menu-btn .btn-line { width: 28px; height: 3px; margin: 0 0 5px 0; background: black; transition: all 0.5s ease-out; } /* Adding transform to the X */ .menu-btn.close { transform: rotate(180deg); } /* Styling the three lines to make it an X */ .menu-btn.close .btn-line:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); } .menu-btn.close .btn-line:nth-child(2) { opacity: 0; } .menu-btn.close .btn-line:nth-child(3) { transform: rotate(-45deg) translate(7px, -6px); } /* Styling the position of the menu icon */ .menu { position: fixed; top: 0; width: 100%; opacity: 0.9; visibility: hidden; } .menu.show { visibility: visible; } /* Adding a transition delay to the 4 items in the navigation menu */ .nav-item:nth-child(1) { transition-delay: 0.1s; } .nav-item:nth-child(2) { transition-delay: 0.2s; } .nav-item:nth-child(3) { transition-delay: 0.3s; } .nav-item:nth-child(4) { transition-delay: 0.4s; } </style></head> <body id="bg-img"> <header> <div class="menu-btn"> <div class="btn-line"></div> <div class="btn-line"></div> <div class="btn-line"></div> </div> <nav class="menu"> <div class="menu-branding"> <div class="portrait"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png" alt="" /> </div> </div> <ul class="menu-nav"> <li class="nav-item current"> <a href="#" class="nav-link"> HOME </a> </li> <li class="nav-item"> <a href="#" class="nav-link"> ABOUT ME </a> </li> <li class="nav-item"> <a href="#" class="nav-link"> MY WORK </a> </li> <li class="nav-item"> <a href="#" class="nav-link"> CONTACT ME </a> </li> </ul> </nav> </header> <script> // Select dom items const menuBtn = document.querySelector(".menu-btn"); const menu = document.querySelector(".menu"); const menuNav = document.querySelector(".menu-nav"); const menuBranding = document.querySelector(".menu-branding"); const navItems = document.querySelectorAll(".nav-item"); // Set the initial state of the menu let showMenu = false; menuBtn.addEventListener("click", toggleMenu); function toggleMenu() { if (!showMenu) { menuBtn.classList.add("close"); menu.classList.add("show"); menuNav.classList.add("show"); menuBranding.classList.add("show"); navItems.forEach((item) => item.classList.add("show")); // Reset the menu state showMenu = true; } else { menuBtn.classList.remove("close"); menu.classList.remove("show"); menuNav.classList.remove("show"); menuBranding.classList.remove("show"); navItems.forEach((item) => item.classList.remove("show")); // Reset the menu state showMenu = false; } } </script></body> </html>
Output:
rajeev0719singh
CSS-Misc
HTML-Misc
JavaScript-Misc
Bootstrap
CSS
HTML
JavaScript
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
Difference between Bootstrap 4 and Bootstrap 5
How to Use Bootstrap with React?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 24465,
"s": 24437,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 25187,
"s": 24465,
"text": "The navigation menu is the most important section of a website. It helps in navigating through the website. Having a proper animation not only makes the website look good but also provides a user-friendly interface to the customer. Hence, this animation will make it possible to convert the three lines or the hamburger icon as it is frequently called, into an X upon click and vice versa. The code will contain 3 different structures which will make it possible to apply this animation. The HTML body, CSS body, and JavaScript body.Creating the structure: In this section, we will create a basic structure with the help of HTML. We will also add the font-awesome link to generate the lines to create the hamburger icon. "
},
{
"code": null,
"e": 25192,
"s": 25187,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <title> Converting the hamburger icon to X and vice versa </title></head> <body id=\"bg-img\"> <header> <div class=\"menu-btn\"> <div class=\"btn-line\"></div> <div class=\"btn-line\"></div> <div class=\"btn-line\"></div> </div> <nav class=\"menu\"> <div class=\"menu-branding\"> <div class=\"portrait\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png\" alt=\"\" /> </div> </div> <ul class=\"menu-nav\"> <li class=\"nav-item current\"> <a href=\"#\" class=\"nav-link\"> HOME</a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> ABOUT ME</a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> MY WORK</a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> CONTACT ME</a> </li> </ul> </nav> </header></body> </html>",
"e": 26753,
"s": 25192,
"text": null
},
{
"code": null,
"e": 26931,
"s": 26753,
"text": "Designing the structure: In the previous section, we have created the basic structure of the hamburger icon. In this section, we will design the structure with the help of CSS. "
},
{
"code": null,
"e": 26935,
"s": 26931,
"text": "css"
},
{
"code": "<style> /* Styling the menu button */ .menu-btn { position: absolute; z-index: 3; right: 35px; top: 35px; cursor: pointer; transition: all 0.5s ease-out; } /* Styling the hamburger lines */ .menu-btn .btn-line { width: 28px; height: 3px; margin: 0 0 5px 0; background: black; transition: all 0.5s ease-out; } /* Adding transform to the X */ .menu-btn.close { transform: rotate(180deg); } /* Styling the three lines to make it an X */ .menu-btn.close .btn-line:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); } .menu-btn.close .btn-line:nth-child(2) { opacity: 0; } .menu-btn.close .btn-line:nth-child(3) { transform: rotate(-45deg) translate(7px, -6px); } /* Styling the position of the menu icon */ .menu { position: fixed; top: 0; width: 100%; opacity: 0.9; visibility: hidden; } .menu.show { visibility: visible; } /* Adding a transition delay to the 4 items in the navigation menu */ .nav-item:nth-child(1) { transition-delay: 0.1s; } .nav-item:nth-child(2) { transition-delay: 0.2s; } .nav-item:nth-child(3) { transition-delay: 0.3s; } .nav-item:nth-child(4) { transition-delay: 0.4s; }</style>",
"e": 28337,
"s": 26935,
"text": null
},
{
"code": null,
"e": 28715,
"s": 28337,
"text": "Adding JavaScript: In this section, we will add the javascript which is necessary for us to animate all the three lines of the hamburger icon. It adds an EventListener to the icon. This EventListener toggles the menu that is to be displayed upon click and needs to be hidden upon click. It determines the state of the menu button, whether it is X state or the hamburger state. "
},
{
"code": null,
"e": 28726,
"s": 28715,
"text": "javascript"
},
{
"code": "<script> // select dom items const menuBtn = document.querySelector(\".menu-btn\"); const menu = document.querySelector(\".menu\"); const menuNav = document.querySelector(\".menu-nav\"); const menuBranding = document.querySelector(\".menu-branding\"); const navItems = document.querySelectorAll(\".nav-item\"); // Set the initial state of the menu let showMenu = false; menuBtn.addEventListener(\"click\", toggleMenu); function toggleMenu() { if (!showMenu) { menuBtn.classList.add(\"close\"); menu.classList.add(\"show\"); menuNav.classList.add(\"show\"); menuBranding.classList.add(\"show\"); navItems.forEach((item) => item.classList.add(\"show\")); // Reset the menu state showMenu = true; } else { menuBtn.classList.remove(\"close\"); menu.classList.remove(\"show\"); menuNav.classList.remove(\"show\"); menuBranding.classList.remove(\"show\"); navItems.forEach((item) => item.classList.remove(\"show\")); // Reset the menu state showMenu = false; } }</script>",
"e": 29942,
"s": 28726,
"text": null
},
{
"code": null,
"e": 30077,
"s": 29942,
"text": "Final solution: The final solution is the combination of the HTML, CSS, and the JavaScript codes to get the desired animation result. "
},
{
"code": null,
"e": 30082,
"s": 30077,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <title> Converting the hamburger icon to X and vice versa </title> <style> /* Styling the menu button */ .menu-btn { position: absolute; z-index: 3; right: 35px; top: 35px; cursor: pointer; transition: all 0.5s ease-out; } /* Styling the hamburger lines */ .menu-btn .btn-line { width: 28px; height: 3px; margin: 0 0 5px 0; background: black; transition: all 0.5s ease-out; } /* Adding transform to the X */ .menu-btn.close { transform: rotate(180deg); } /* Styling the three lines to make it an X */ .menu-btn.close .btn-line:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); } .menu-btn.close .btn-line:nth-child(2) { opacity: 0; } .menu-btn.close .btn-line:nth-child(3) { transform: rotate(-45deg) translate(7px, -6px); } /* Styling the position of the menu icon */ .menu { position: fixed; top: 0; width: 100%; opacity: 0.9; visibility: hidden; } .menu.show { visibility: visible; } /* Adding a transition delay to the 4 items in the navigation menu */ .nav-item:nth-child(1) { transition-delay: 0.1s; } .nav-item:nth-child(2) { transition-delay: 0.2s; } .nav-item:nth-child(3) { transition-delay: 0.3s; } .nav-item:nth-child(4) { transition-delay: 0.4s; } </style></head> <body id=\"bg-img\"> <header> <div class=\"menu-btn\"> <div class=\"btn-line\"></div> <div class=\"btn-line\"></div> <div class=\"btn-line\"></div> </div> <nav class=\"menu\"> <div class=\"menu-branding\"> <div class=\"portrait\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200326201748/download312.png\" alt=\"\" /> </div> </div> <ul class=\"menu-nav\"> <li class=\"nav-item current\"> <a href=\"#\" class=\"nav-link\"> HOME </a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> ABOUT ME </a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> MY WORK </a> </li> <li class=\"nav-item\"> <a href=\"#\" class=\"nav-link\"> CONTACT ME </a> </li> </ul> </nav> </header> <script> // Select dom items const menuBtn = document.querySelector(\".menu-btn\"); const menu = document.querySelector(\".menu\"); const menuNav = document.querySelector(\".menu-nav\"); const menuBranding = document.querySelector(\".menu-branding\"); const navItems = document.querySelectorAll(\".nav-item\"); // Set the initial state of the menu let showMenu = false; menuBtn.addEventListener(\"click\", toggleMenu); function toggleMenu() { if (!showMenu) { menuBtn.classList.add(\"close\"); menu.classList.add(\"show\"); menuNav.classList.add(\"show\"); menuBranding.classList.add(\"show\"); navItems.forEach((item) => item.classList.add(\"show\")); // Reset the menu state showMenu = true; } else { menuBtn.classList.remove(\"close\"); menu.classList.remove(\"show\"); menuNav.classList.remove(\"show\"); menuBranding.classList.remove(\"show\"); navItems.forEach((item) => item.classList.remove(\"show\")); // Reset the menu state showMenu = false; } } </script></body> </html>",
"e": 34730,
"s": 30082,
"text": null
},
{
"code": null,
"e": 34740,
"s": 34730,
"text": "Output: "
},
{
"code": null,
"e": 34758,
"s": 34742,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 34767,
"s": 34758,
"text": "CSS-Misc"
},
{
"code": null,
"e": 34777,
"s": 34767,
"text": "HTML-Misc"
},
{
"code": null,
"e": 34793,
"s": 34777,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 34803,
"s": 34793,
"text": "Bootstrap"
},
{
"code": null,
"e": 34807,
"s": 34803,
"text": "CSS"
},
{
"code": null,
"e": 34812,
"s": 34807,
"text": "HTML"
},
{
"code": null,
"e": 34823,
"s": 34812,
"text": "JavaScript"
},
{
"code": null,
"e": 34850,
"s": 34823,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34855,
"s": 34850,
"text": "HTML"
},
{
"code": null,
"e": 34953,
"s": 34855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34962,
"s": 34953,
"text": "Comments"
},
{
"code": null,
"e": 34975,
"s": 34962,
"text": "Old Comments"
},
{
"code": null,
"e": 35016,
"s": 34975,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 35057,
"s": 35016,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 35120,
"s": 35057,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 35167,
"s": 35120,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 35200,
"s": 35167,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 35262,
"s": 35200,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35312,
"s": 35262,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35370,
"s": 35312,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35418,
"s": 35370,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Set equal_range() function in C++ STL
|
In this article we are going to discuss the set::equal_range() function in C++ STL, their syntax, working and their return values.
Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.
equal_range() function is an inbuilt function in C++ STL, which is defined in header file. This function returns the range of the set container which contains value passed as the argument of the function. The set contain all the unique values so the equivalent value in the found range will be single. If the value is not present in the container the range will be zero, with both iterators pointing to the first position.
Set1.equal_range(const type_t& value);
This function accepts one parameter, i.e., element which is to be found.
This function returns the pair or we can say iterator range starting from the lower bound of the container till the element which is to be found in the container.
Input: set<int> myset = {10, 20, 30, 40};
Output: lower bound of 30 is 30
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(40);
mySet.insert(50);
cout<<"Elements before applying range() Function : ";
for (auto i = mySet.begin(); i != mySet.end(); i++)
cout << *i << " ";
auto i = mySet.equal_range(30);
cout<<"\nlower bound of 30 is "<< *i.first;
cout<<"\nupper bound of 30 is "<< *i.second;
i = mySet.equal_range(40);
cout<<"\nlower bound of 40 is " << *i.first;
cout<<"\nupper bound of 40 is " << *i.second;
i = mySet.equal_range(10);
cout<<"\nlower bound of 10 is " << *i.first;
cout<<"\nupper bound of 10 is " << *i.second;
return 0;
}
If we run the above code then it will generate the following output −
Elements before applying range() Function : 10 20 30 40 50
lower bound of 30 is 30
upper bound of 30 is 40
lower bound of 40 is 40
upper bound of 40 is 50
lower bound of 10 is 10
upper bound of 10 is 20
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "In this article we are going to discuss the set::equal_range() function in C++ STL, their syntax, working and their return values."
},
{
"code": null,
"e": 1528,
"s": 1193,
"text": "Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees."
},
{
"code": null,
"e": 1951,
"s": 1528,
"text": "equal_range() function is an inbuilt function in C++ STL, which is defined in header file. This function returns the range of the set container which contains value passed as the argument of the function. The set contain all the unique values so the equivalent value in the found range will be single. If the value is not present in the container the range will be zero, with both iterators pointing to the first position."
},
{
"code": null,
"e": 1990,
"s": 1951,
"text": "Set1.equal_range(const type_t& value);"
},
{
"code": null,
"e": 2063,
"s": 1990,
"text": "This function accepts one parameter, i.e., element which is to be found."
},
{
"code": null,
"e": 2226,
"s": 2063,
"text": "This function returns the pair or we can say iterator range starting from the lower bound of the container till the element which is to be found in the container."
},
{
"code": null,
"e": 2300,
"s": 2226,
"text": "Input: set<int> myset = {10, 20, 30, 40};\nOutput: lower bound of 30 is 30"
},
{
"code": null,
"e": 2311,
"s": 2300,
"text": " Live Demo"
},
{
"code": null,
"e": 3029,
"s": 2311,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n set<int> mySet;\n mySet.insert(10);\n mySet.insert(20);\n mySet.insert(30);\n mySet.insert(40);\n mySet.insert(50);\n cout<<\"Elements before applying range() Function : \";\n for (auto i = mySet.begin(); i != mySet.end(); i++)\n cout << *i << \" \";\n auto i = mySet.equal_range(30);\n cout<<\"\\nlower bound of 30 is \"<< *i.first;\n cout<<\"\\nupper bound of 30 is \"<< *i.second;\n i = mySet.equal_range(40);\n cout<<\"\\nlower bound of 40 is \" << *i.first;\n cout<<\"\\nupper bound of 40 is \" << *i.second;\n i = mySet.equal_range(10);\n cout<<\"\\nlower bound of 10 is \" << *i.first;\n cout<<\"\\nupper bound of 10 is \" << *i.second;\n return 0;\n}"
},
{
"code": null,
"e": 3099,
"s": 3029,
"text": "If we run the above code then it will generate the following output −"
},
{
"code": null,
"e": 3302,
"s": 3099,
"text": "Elements before applying range() Function : 10 20 30 40 50\nlower bound of 30 is 30\nupper bound of 30 is 40\nlower bound of 40 is 40\nupper bound of 40 is 50\nlower bound of 10 is 10\nupper bound of 10 is 20"
}
] |
Apply changes to all the images in given folder - Using Python PIL - GeeksforGeeks
|
21 Nov, 2019
Given a dataset of raw images, which usually need some pre-processing, which one person has to do physically. It is generally a task that requires some repetitive operation to perform for each image. Well, we can easily automate this process using some simple Python code and some libraries with it. So without further adieu, let’s see how to apply changes to all the images in given folder and save it to some destination folder using Python PIL.
Let’s install all the required modules –
pip3 install pillow
pip3 install os-sys
We will be parsing all the images in the folder to apply changes/operations to all of them simultaneously.
# Code to apply operations on all the images# present in a folder one by one# operations such as rotating, cropping, from PIL import Imagefrom PIL import ImageFilterimport os def main(): # path of the folder containing the raw images inPath ="E:\\GeeksforGeeks\\images" # path of the folder that will contain the modified image outPath ="E:\\GeeksforGeeks\\images_rotated" for imagePath in os.listdir(inPath): # imagePath contains name of the image inputPath = os.path.join(inPath, imagePath) # inputPath contains the full directory name img = Image.open(inputPath) fullOutPath = os.path.join(outPath, 'invert_'+imagePath) # fullOutPath contains the path of the output # image that needs to be generated img.rotate(90).save(fullOutPath) print(fullOutPath) # Driver Functionif __name__ == '__main__': main()
Sample images from the folder –
Input :
image_sample1
invert_image_sample1
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24474,
"s": 24446,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 24922,
"s": 24474,
"text": "Given a dataset of raw images, which usually need some pre-processing, which one person has to do physically. It is generally a task that requires some repetitive operation to perform for each image. Well, we can easily automate this process using some simple Python code and some libraries with it. So without further adieu, let’s see how to apply changes to all the images in given folder and save it to some destination folder using Python PIL."
},
{
"code": null,
"e": 24963,
"s": 24922,
"text": "Let’s install all the required modules –"
},
{
"code": null,
"e": 25003,
"s": 24963,
"text": "pip3 install pillow\npip3 install os-sys"
},
{
"code": null,
"e": 25110,
"s": 25003,
"text": "We will be parsing all the images in the folder to apply changes/operations to all of them simultaneously."
},
{
"code": "# Code to apply operations on all the images# present in a folder one by one# operations such as rotating, cropping, from PIL import Imagefrom PIL import ImageFilterimport os def main(): # path of the folder containing the raw images inPath =\"E:\\\\GeeksforGeeks\\\\images\" # path of the folder that will contain the modified image outPath =\"E:\\\\GeeksforGeeks\\\\images_rotated\" for imagePath in os.listdir(inPath): # imagePath contains name of the image inputPath = os.path.join(inPath, imagePath) # inputPath contains the full directory name img = Image.open(inputPath) fullOutPath = os.path.join(outPath, 'invert_'+imagePath) # fullOutPath contains the path of the output # image that needs to be generated img.rotate(90).save(fullOutPath) print(fullOutPath) # Driver Functionif __name__ == '__main__': main()",
"e": 26011,
"s": 25110,
"text": null
},
{
"code": null,
"e": 26043,
"s": 26011,
"text": "Sample images from the folder –"
},
{
"code": null,
"e": 26051,
"s": 26043,
"text": "Input :"
},
{
"code": null,
"e": 26065,
"s": 26051,
"text": "image_sample1"
},
{
"code": null,
"e": 26086,
"s": 26065,
"text": "invert_image_sample1"
},
{
"code": null,
"e": 26103,
"s": 26086,
"text": "Image-Processing"
},
{
"code": null,
"e": 26114,
"s": 26103,
"text": "Python-pil"
},
{
"code": null,
"e": 26121,
"s": 26114,
"text": "Python"
},
{
"code": null,
"e": 26219,
"s": 26121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26237,
"s": 26219,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26272,
"s": 26237,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26294,
"s": 26272,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26326,
"s": 26294,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26356,
"s": 26326,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26398,
"s": 26356,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26424,
"s": 26398,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26461,
"s": 26424,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26504,
"s": 26461,
"text": "Python program to convert a list to string"
}
] |
BigDecimal signum() Method in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.signum() is an inbuilt method in Java that returns the signum function of this BigDecimal. The sign function or signum function is an odd mathematical function that extracts the sign of a real number. In mathematical expressions, the sign function is often represented as sgn.
Syntax:
public int signum()
Parameters: This method does not accepts any parameter.
Return value: This method can return three types of values:
-1 if this BigDecimal < 0
0 if this BigDecimal = 0
1 if this BigDecimal is > 0
Below program illustrates the working of the above mentioned method:
Program 1:
// Program to demonstrate signum() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("12743"); BigDecimal b2 = new BigDecimal("0"); BigDecimal b3 = new BigDecimal("-4512"); // Assigning the signum values of BigDecimal objects b1, b2, b3 // to int objects i1, i2, i3 respectively int i1 = b1.signum(); int i2 = b2.signum(); int i3 = b3.signum(); // Printing i1, i2, i3 values System.out.println("Signum function on " + b1 + " is " + i1); System.out.println("Signum function on " + b2 + " is " + i2); System.out.println("Signum function on " + b3 + " is " + i3); }}
Signum function on 12743 is 1
Signum function on 0 is 0
Signum function on -4512 is -1
Program 2:
// Program to demonstrate signum() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal("17845452743"); BigDecimal b2 = new BigDecimal("000"); BigDecimal b3 = new BigDecimal("-444512"); // Assigning the signum values of BigDecimal objects b1, b2, b3 // to int objects i1, i2, i3 respectively int i1 = b1.signum(); int i2 = b2.signum(); int i3 = b3.signum(); // Printing i1, i2, i3 values System.out.println("Signum function on " + b1 + " is " + i1); System.out.println("Signum function on " + b2 + " is " + i2); System.out.println("Signum function on " + b3 + " is " + i3); }}
Signum function on 17845452743 is 1
Signum function on 0 is 0
Signum function on -444512 is -1
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#signum()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
|
[
{
"code": null,
"e": 24816,
"s": 24788,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25118,
"s": 24816,
"text": "The java.math.BigDecimal.signum() is an inbuilt method in Java that returns the signum function of this BigDecimal. The sign function or signum function is an odd mathematical function that extracts the sign of a real number. In mathematical expressions, the sign function is often represented as sgn."
},
{
"code": null,
"e": 25126,
"s": 25118,
"text": "Syntax:"
},
{
"code": null,
"e": 25147,
"s": 25126,
"text": "public int signum()\n"
},
{
"code": null,
"e": 25203,
"s": 25147,
"text": "Parameters: This method does not accepts any parameter."
},
{
"code": null,
"e": 25263,
"s": 25203,
"text": "Return value: This method can return three types of values:"
},
{
"code": null,
"e": 25289,
"s": 25263,
"text": "-1 if this BigDecimal < 0"
},
{
"code": null,
"e": 25314,
"s": 25289,
"text": "0 if this BigDecimal = 0"
},
{
"code": null,
"e": 25342,
"s": 25314,
"text": "1 if this BigDecimal is > 0"
},
{
"code": null,
"e": 25411,
"s": 25342,
"text": "Below program illustrates the working of the above mentioned method:"
},
{
"code": null,
"e": 25422,
"s": 25411,
"text": "Program 1:"
},
{
"code": "// Program to demonstrate signum() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"12743\"); BigDecimal b2 = new BigDecimal(\"0\"); BigDecimal b3 = new BigDecimal(\"-4512\"); // Assigning the signum values of BigDecimal objects b1, b2, b3 // to int objects i1, i2, i3 respectively int i1 = b1.signum(); int i2 = b2.signum(); int i3 = b3.signum(); // Printing i1, i2, i3 values System.out.println(\"Signum function on \" + b1 + \" is \" + i1); System.out.println(\"Signum function on \" + b2 + \" is \" + i2); System.out.println(\"Signum function on \" + b3 + \" is \" + i3); }}",
"e": 26174,
"s": 25422,
"text": null
},
{
"code": null,
"e": 26262,
"s": 26174,
"text": "Signum function on 12743 is 1\nSignum function on 0 is 0\nSignum function on -4512 is -1\n"
},
{
"code": null,
"e": 26273,
"s": 26262,
"text": "Program 2:"
},
{
"code": "// Program to demonstrate signum() method of BigDecimal import java.math.*; public class Gfg { public static void main(String[] args) { BigDecimal b1 = new BigDecimal(\"17845452743\"); BigDecimal b2 = new BigDecimal(\"000\"); BigDecimal b3 = new BigDecimal(\"-444512\"); // Assigning the signum values of BigDecimal objects b1, b2, b3 // to int objects i1, i2, i3 respectively int i1 = b1.signum(); int i2 = b2.signum(); int i3 = b3.signum(); // Printing i1, i2, i3 values System.out.println(\"Signum function on \" + b1 + \" is \" + i1); System.out.println(\"Signum function on \" + b2 + \" is \" + i2); System.out.println(\"Signum function on \" + b3 + \" is \" + i3); }}",
"e": 27035,
"s": 26273,
"text": null
},
{
"code": null,
"e": 27131,
"s": 27035,
"text": "Signum function on 17845452743 is 1\nSignum function on 0 is 0\nSignum function on -444512 is -1\n"
},
{
"code": null,
"e": 27219,
"s": 27131,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#signum()"
},
{
"code": null,
"e": 27235,
"s": 27219,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 27250,
"s": 27235,
"text": "Java-Functions"
},
{
"code": null,
"e": 27260,
"s": 27250,
"text": "java-math"
},
{
"code": null,
"e": 27278,
"s": 27260,
"text": "Java-math-package"
},
{
"code": null,
"e": 27283,
"s": 27278,
"text": "Java"
},
{
"code": null,
"e": 27288,
"s": 27283,
"text": "Java"
},
{
"code": null,
"e": 27386,
"s": 27288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27418,
"s": 27386,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27469,
"s": 27418,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27499,
"s": 27469,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27518,
"s": 27499,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27536,
"s": 27518,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27567,
"s": 27536,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27599,
"s": 27567,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27619,
"s": 27599,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27634,
"s": 27619,
"text": "Stream In Java"
}
] |
JavaScript Date getMonth() Method - GeeksforGeeks
|
12 Oct, 2021
Below is the example of Date getMonth() method.
Example:
javascript
<script type="text/javascript"> // Creating a Date Object var DateObj = new Date('October 15, 1996 05:35:32'); // Month from above Date Object is // Being extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>
Output:
9
The date.getMonth() method is used to fetch the month(0 to 11) from given Date object.Syntax:
DateObj.getMonth()
Parameter: This function does not accept any parameter. Return Value: It returns the Month for the given Date object. The month is an integer value ranging from 0 to 11. Zero (0) means January, 1 means February, and so on till 11 means December.More codes for the above method are as follows:Program 1: Here the date of the month should lie in between 1 to 31 because no date can have month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31.
javascript
<script type="text/javascript"> // Creating a Date Object var DateObj = new Date('October 33, 1996 05:35:32'); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>
Output:
NaN
Program 2: If month is not given, it returns zero (0).
javascript
<script type="text/javascript"> // Creating a Date Object var DateObj = new Date('1996 05:35:32'); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>
Output:
0
Program 3: If nothing as parameter is given, it returns current month.
javascript
<script type="text/javascript"> // Creating a Date Object var DateObj = new Date(); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>
Output:
2
Supported Browsers: The browsers supported by JavaScript Date getMonth() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 3 and above
Safari 1 and above
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24798,
"s": 24770,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 24848,
"s": 24798,
"text": "Below is the example of Date getMonth() method. "
},
{
"code": null,
"e": 24859,
"s": 24848,
"text": "Example: "
},
{
"code": null,
"e": 24870,
"s": 24859,
"text": "javascript"
},
{
"code": "<script type=\"text/javascript\"> // Creating a Date Object var DateObj = new Date('October 15, 1996 05:35:32'); // Month from above Date Object is // Being extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>",
"e": 25153,
"s": 24870,
"text": null
},
{
"code": null,
"e": 25163,
"s": 25153,
"text": "Output: "
},
{
"code": null,
"e": 25165,
"s": 25163,
"text": "9"
},
{
"code": null,
"e": 25261,
"s": 25165,
"text": "The date.getMonth() method is used to fetch the month(0 to 11) from given Date object.Syntax: "
},
{
"code": null,
"e": 25280,
"s": 25261,
"text": "DateObj.getMonth()"
},
{
"code": null,
"e": 25787,
"s": 25280,
"text": "Parameter: This function does not accept any parameter. Return Value: It returns the Month for the given Date object. The month is an integer value ranging from 0 to 11. Zero (0) means January, 1 means February, and so on till 11 means December.More codes for the above method are as follows:Program 1: Here the date of the month should lie in between 1 to 31 because no date can have month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31. "
},
{
"code": null,
"e": 25798,
"s": 25787,
"text": "javascript"
},
{
"code": "<script type=\"text/javascript\"> // Creating a Date Object var DateObj = new Date('October 33, 1996 05:35:32'); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>",
"e": 26081,
"s": 25798,
"text": null
},
{
"code": null,
"e": 26091,
"s": 26081,
"text": "Output: "
},
{
"code": null,
"e": 26095,
"s": 26091,
"text": "NaN"
},
{
"code": null,
"e": 26152,
"s": 26095,
"text": "Program 2: If month is not given, it returns zero (0). "
},
{
"code": null,
"e": 26163,
"s": 26152,
"text": "javascript"
},
{
"code": "<script type=\"text/javascript\"> // Creating a Date Object var DateObj = new Date('1996 05:35:32'); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>",
"e": 26434,
"s": 26163,
"text": null
},
{
"code": null,
"e": 26444,
"s": 26434,
"text": "Output: "
},
{
"code": null,
"e": 26446,
"s": 26444,
"text": "0"
},
{
"code": null,
"e": 26519,
"s": 26446,
"text": "Program 3: If nothing as parameter is given, it returns current month. "
},
{
"code": null,
"e": 26530,
"s": 26519,
"text": "javascript"
},
{
"code": "<script type=\"text/javascript\"> // Creating a Date Object var DateObj = new Date(); // Month from above Date Object is being // Extracted using getMonth() var months = DateObj.getMonth(); // Printing month. document.write(months);</script>",
"e": 26785,
"s": 26530,
"text": null
},
{
"code": null,
"e": 26795,
"s": 26785,
"text": "Output: "
},
{
"code": null,
"e": 26797,
"s": 26795,
"text": "2"
},
{
"code": null,
"e": 26897,
"s": 26797,
"text": "Supported Browsers: The browsers supported by JavaScript Date getMonth() method are listed below: "
},
{
"code": null,
"e": 26923,
"s": 26897,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 26941,
"s": 26923,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 26961,
"s": 26941,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 26991,
"s": 26961,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 27009,
"s": 26991,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 27028,
"s": 27009,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 27042,
"s": 27030,
"text": "ysachin2314"
},
{
"code": null,
"e": 27058,
"s": 27042,
"text": "javascript-date"
},
{
"code": null,
"e": 27077,
"s": 27058,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 27088,
"s": 27077,
"text": "JavaScript"
},
{
"code": null,
"e": 27105,
"s": 27088,
"text": "Web Technologies"
},
{
"code": null,
"e": 27203,
"s": 27105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27212,
"s": 27203,
"text": "Comments"
},
{
"code": null,
"e": 27225,
"s": 27212,
"text": "Old Comments"
},
{
"code": null,
"e": 27270,
"s": 27225,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27331,
"s": 27270,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27403,
"s": 27331,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27455,
"s": 27403,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27501,
"s": 27455,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27543,
"s": 27501,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27576,
"s": 27543,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27619,
"s": 27576,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27681,
"s": 27619,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Training Neural Network from Scratch using PyTorch in just 7 cells | by Khush Patel | Towards Data Science
|
Content of the blog:
Installation and import modulesre-processing and loading the datasetDesigning the modelTraining the modelVisualizing the Output
Installation and import modules
re-processing and loading the dataset
Designing the model
Training the model
Visualizing the Output
First thing first. Regardless of the operating system just run below command which will install all the required modules to run the below code snippets. If you use anaconda then also you can install it with conda command.
pip install torch torchvision numpy matplotlibconda install torch torchvision numpy matplotlib
import torch is used to add all the essential modules to build the neural network and torchvision is used to add other functionalities like pre-processing and transformation of the data. numpy is used to work with image arrays and matplotlib is to display the image.
import torchimport torchvisionimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision import datasets, transformsimport matplotlib.pyplot as pltfrom torch import optimimport numpy as np%matplotlib inline
PyTorch has transform module to convert images to tensors and pre-process every image to normalize with a standard deviation 1. torchvison has build-in dataset MNIST hand digits which I am going to use for further explanation for all below code snippets. DataLoader is the PyTorch module to combine the image and its corresponding label in a package. So we can easily access both the things simultaneously. Just note that we are adding batch_size as 64 to create a batch of 64 images in one iteration.
transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.MNIST('~/.pytorch/MNIST_data/', train=True, transform=transform, download=True)trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
To train any neural network first we have to understand the input size of the images, # of output classes and hidden layers of the neural networks. Hereby checking trainloader.dataset.train_data.shape we will get 64,1,28,28 which denotes 64 images with height and width 28 and channel 1 as greyscale images.
Input Size: So the input size is 784 which is the product of height(28) and width(28) of the image. The image has only 1 channel so no need to add it in the input size.
Output Size: We have digits from 0–9 so a total of 10 possible class options. Therefor output size is 10
Hidden Layers: Layers are between the input layer and output layers are basically known as hidden layers. In our case, we have an input image of 784 nodes and the output size is 10 so in between, we are adding layers of 128 and 64. Thus our network will scale from 784 to 128 to 64 to 10.
input_size = trainloader.dataset.train_data.shape[1] * trainloader.dataset.train_data.shape[2]hidden_layers = [128,64]output_size = 10
torchvision has nn module which has all the functionalities to build a neural network. Initially, adding input size to the first hidden layer which is 784 to 128 followed by ReLU (Activation function). From 128 to 64 with the same ReLU activation function and 64 to 10 in the very last layer. To getting probabilities distribution we are adding the final layer of LogSoftmax and dimension = 1 because we have 64 image batch so it will give 64x10 results in the output.
To compute the errors and mistakes of the neural network we are adding NLLLoss cross-entropy loss (Negative log-likelihood loss) as a criterion (error function) and optimizer as SGD (stochastic gradient descent) with a learning rate of 0.003.
Read more about Cross-Entropy Loss here and Stochastic gradient descent here
model = nn.Sequential( nn.Linear(input_size, hidden_layers[0]), nn.ReLU(), nn.Linear(hidden_layers[0], hidden_layers[1]), nn.ReLU(), nn.Linear(hidden_layers[1], output_size), nn.LogSoftmax(dim=1))print(model)criterion = nn.NLLLoss()optimizer = optim.SGD(model.parameters(), lr=0.003)
Training:
Now, we successfully defined the model and its time to train the model by passing the images and corresponding labels. But before that, we are flattening our images from 28x28 to 784x1 and setting all the gradient to zero to train the weights and bias for models.
Finally model(images) will train the model and criterion will calculate the loss. loss.backward() is used to backpropagation and optimizer.step() will update the weights as per backpropagated weights and bias.
We are printing loss as every epoch of training. Just make sure your training loss will decrease as epochs are increasing. If you are not getting less loss with every epoch, you made some mistakes in the code.
epochs = 5for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten the Image from 28*28 to 784 column vector images = images.view(images.shape[0], -1) # setting gradient to zeros optimizer.zero_grad() output = model(images) loss = criterion(output, labels) # backward propagation loss.backward() # update the gradient to new gradients optimizer.step() running_loss += loss.item() else: print("Training loss: ",(running_loss/len(trainloader)))
Visualization:
In the prediction phase of the neural network, we are passing images and their probability distribution to visualizing the image. ax1 is the original image of any digit and ax2 is a probability distribution. Just setting xlabel and ylabel between 0–9 and title of the plot.
def view_classify(img, ps): ps = ps.data.numpy().squeeze() fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2) ax1.imshow(img.resize_(1, 28, 28).numpy().squeeze()) ax1.axis('off') ax2.barh(np.arange(10), ps) ax2.set_aspect(0.1) ax2.set_yticks(np.arange(10)) ax2.set_yticklabels(np.arange(10)) ax2.set_title('Class Probability') ax2.set_xlim(0, 1.1) plt.tight_layout()
Prediction:
Turn of the gradient as we are using the same model which will start training so we are turning off all the gradient and getting the probability distribution of the testing image. All probability in logarithm so we are converting it to 0–1 and visualizing image using the function.
# Getting the image to testimages, labels = next(iter(trainloader))# Flatten the image to pass in the modelimg = images[0].view(1, 784)# Turn off gradients to speed up this partwith torch.no_grad(): logps = model(img)# Output of the network are log-probabilities, need to take exponential for probabilitiesps = torch.exp(logps)view_classify(img, ps)
And you are done with training a neural network on the MNIST Hand digit recognition dataset from very scratch using PyTorch.
Now, Its time for celebration, because you achieved it!!!
Thank you for reading the blog and appreciating my efforts. Feel free to comment and ask questions with your suggestions. You can connect with me on LinkedIn, Twitter and my check out my Website for more Deep Learning projects. Happy Learning!!!
|
[
{
"code": null,
"e": 193,
"s": 172,
"text": "Content of the blog:"
},
{
"code": null,
"e": 321,
"s": 193,
"text": "Installation and import modulesre-processing and loading the datasetDesigning the modelTraining the modelVisualizing the Output"
},
{
"code": null,
"e": 353,
"s": 321,
"text": "Installation and import modules"
},
{
"code": null,
"e": 391,
"s": 353,
"text": "re-processing and loading the dataset"
},
{
"code": null,
"e": 411,
"s": 391,
"text": "Designing the model"
},
{
"code": null,
"e": 430,
"s": 411,
"text": "Training the model"
},
{
"code": null,
"e": 453,
"s": 430,
"text": "Visualizing the Output"
},
{
"code": null,
"e": 675,
"s": 453,
"text": "First thing first. Regardless of the operating system just run below command which will install all the required modules to run the below code snippets. If you use anaconda then also you can install it with conda command."
},
{
"code": null,
"e": 770,
"s": 675,
"text": "pip install torch torchvision numpy matplotlibconda install torch torchvision numpy matplotlib"
},
{
"code": null,
"e": 1037,
"s": 770,
"text": "import torch is used to add all the essential modules to build the neural network and torchvision is used to add other functionalities like pre-processing and transformation of the data. numpy is used to work with image arrays and matplotlib is to display the image."
},
{
"code": null,
"e": 1254,
"s": 1037,
"text": "import torchimport torchvisionimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision import datasets, transformsimport matplotlib.pyplot as pltfrom torch import optimimport numpy as np%matplotlib inline"
},
{
"code": null,
"e": 1756,
"s": 1254,
"text": "PyTorch has transform module to convert images to tensors and pre-process every image to normalize with a standard deviation 1. torchvison has build-in dataset MNIST hand digits which I am going to use for further explanation for all below code snippets. DataLoader is the PyTorch module to combine the image and its corresponding label in a package. So we can easily access both the things simultaneously. Just note that we are adding batch_size as 64 to create a batch of 64 images in one iteration."
},
{
"code": null,
"e": 2066,
"s": 1756,
"text": "transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.MNIST('~/.pytorch/MNIST_data/', train=True, transform=transform, download=True)trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)"
},
{
"code": null,
"e": 2374,
"s": 2066,
"text": "To train any neural network first we have to understand the input size of the images, # of output classes and hidden layers of the neural networks. Hereby checking trainloader.dataset.train_data.shape we will get 64,1,28,28 which denotes 64 images with height and width 28 and channel 1 as greyscale images."
},
{
"code": null,
"e": 2543,
"s": 2374,
"text": "Input Size: So the input size is 784 which is the product of height(28) and width(28) of the image. The image has only 1 channel so no need to add it in the input size."
},
{
"code": null,
"e": 2648,
"s": 2543,
"text": "Output Size: We have digits from 0–9 so a total of 10 possible class options. Therefor output size is 10"
},
{
"code": null,
"e": 2937,
"s": 2648,
"text": "Hidden Layers: Layers are between the input layer and output layers are basically known as hidden layers. In our case, we have an input image of 784 nodes and the output size is 10 so in between, we are adding layers of 128 and 64. Thus our network will scale from 784 to 128 to 64 to 10."
},
{
"code": null,
"e": 3072,
"s": 2937,
"text": "input_size = trainloader.dataset.train_data.shape[1] * trainloader.dataset.train_data.shape[2]hidden_layers = [128,64]output_size = 10"
},
{
"code": null,
"e": 3541,
"s": 3072,
"text": "torchvision has nn module which has all the functionalities to build a neural network. Initially, adding input size to the first hidden layer which is 784 to 128 followed by ReLU (Activation function). From 128 to 64 with the same ReLU activation function and 64 to 10 in the very last layer. To getting probabilities distribution we are adding the final layer of LogSoftmax and dimension = 1 because we have 64 image batch so it will give 64x10 results in the output."
},
{
"code": null,
"e": 3784,
"s": 3541,
"text": "To compute the errors and mistakes of the neural network we are adding NLLLoss cross-entropy loss (Negative log-likelihood loss) as a criterion (error function) and optimizer as SGD (stochastic gradient descent) with a learning rate of 0.003."
},
{
"code": null,
"e": 3861,
"s": 3784,
"text": "Read more about Cross-Entropy Loss here and Stochastic gradient descent here"
},
{
"code": null,
"e": 4163,
"s": 3861,
"text": "model = nn.Sequential( nn.Linear(input_size, hidden_layers[0]), nn.ReLU(), nn.Linear(hidden_layers[0], hidden_layers[1]), nn.ReLU(), nn.Linear(hidden_layers[1], output_size), nn.LogSoftmax(dim=1))print(model)criterion = nn.NLLLoss()optimizer = optim.SGD(model.parameters(), lr=0.003)"
},
{
"code": null,
"e": 4173,
"s": 4163,
"text": "Training:"
},
{
"code": null,
"e": 4437,
"s": 4173,
"text": "Now, we successfully defined the model and its time to train the model by passing the images and corresponding labels. But before that, we are flattening our images from 28x28 to 784x1 and setting all the gradient to zero to train the weights and bias for models."
},
{
"code": null,
"e": 4647,
"s": 4437,
"text": "Finally model(images) will train the model and criterion will calculate the loss. loss.backward() is used to backpropagation and optimizer.step() will update the weights as per backpropagated weights and bias."
},
{
"code": null,
"e": 4857,
"s": 4647,
"text": "We are printing loss as every epoch of training. Just make sure your training loss will decrease as epochs are increasing. If you are not getting less loss with every epoch, you made some mistakes in the code."
},
{
"code": null,
"e": 5454,
"s": 4857,
"text": "epochs = 5for e in range(epochs): running_loss = 0 for images, labels in trainloader: # Flatten the Image from 28*28 to 784 column vector images = images.view(images.shape[0], -1) # setting gradient to zeros optimizer.zero_grad() output = model(images) loss = criterion(output, labels) # backward propagation loss.backward() # update the gradient to new gradients optimizer.step() running_loss += loss.item() else: print(\"Training loss: \",(running_loss/len(trainloader)))"
},
{
"code": null,
"e": 5469,
"s": 5454,
"text": "Visualization:"
},
{
"code": null,
"e": 5743,
"s": 5469,
"text": "In the prediction phase of the neural network, we are passing images and their probability distribution to visualizing the image. ax1 is the original image of any digit and ax2 is a probability distribution. Just setting xlabel and ylabel between 0–9 and title of the plot."
},
{
"code": null,
"e": 6147,
"s": 5743,
"text": "def view_classify(img, ps): ps = ps.data.numpy().squeeze() fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2) ax1.imshow(img.resize_(1, 28, 28).numpy().squeeze()) ax1.axis('off') ax2.barh(np.arange(10), ps) ax2.set_aspect(0.1) ax2.set_yticks(np.arange(10)) ax2.set_yticklabels(np.arange(10)) ax2.set_title('Class Probability') ax2.set_xlim(0, 1.1) plt.tight_layout()"
},
{
"code": null,
"e": 6159,
"s": 6147,
"text": "Prediction:"
},
{
"code": null,
"e": 6441,
"s": 6159,
"text": "Turn of the gradient as we are using the same model which will start training so we are turning off all the gradient and getting the probability distribution of the testing image. All probability in logarithm so we are converting it to 0–1 and visualizing image using the function."
},
{
"code": null,
"e": 6794,
"s": 6441,
"text": "# Getting the image to testimages, labels = next(iter(trainloader))# Flatten the image to pass in the modelimg = images[0].view(1, 784)# Turn off gradients to speed up this partwith torch.no_grad(): logps = model(img)# Output of the network are log-probabilities, need to take exponential for probabilitiesps = torch.exp(logps)view_classify(img, ps)"
},
{
"code": null,
"e": 6919,
"s": 6794,
"text": "And you are done with training a neural network on the MNIST Hand digit recognition dataset from very scratch using PyTorch."
},
{
"code": null,
"e": 6977,
"s": 6919,
"text": "Now, Its time for celebration, because you achieved it!!!"
}
] |
Int64.MaxValue Field in C# with Examples - GeeksforGeeks
|
08 Apr, 2019
The MaxValue field or property of Int64 Struct is used to represent the maximum value of Int64. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 9223372036854775807. Its hexadecimal value is 0x7FFFFFFFFFFFFFFF.
Syntax:
public const long MaxValue = 9223372036854775807;
Return Value: This field always returns 9223372036854775807.
Example:
// C# program to illustrate the// Int64.MaxValue Fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum // value of Int64 struct Console.WriteLine("Maximum Value is: "+ Int64.MaxValue); // taking a variable long var1 = 93422337368375807; if(var1.Equals(Int64.MaxValue)) { Console.WriteLine("Equal..!!"); Console.WriteLine("Type of var1 is: {0}", var1.GetTypeCode()); } else { Console.WriteLine("Not equal..!!"); Console.WriteLine("Type of var1 is: {0}", var1.GetTypeCode()); } }}
Maximum Value is: 9223372036854775807
Not equal..!!
Type of var1 is: Int64
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int64.maxvalue?view=netframework-4.7.2
CSharp-Int64-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
C# | Data Types
C# | Encapsulation
|
[
{
"code": null,
"e": 24264,
"s": 24236,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 24548,
"s": 24264,
"text": "The MaxValue field or property of Int64 Struct is used to represent the maximum value of Int64. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 9223372036854775807. Its hexadecimal value is 0x7FFFFFFFFFFFFFFF."
},
{
"code": null,
"e": 24556,
"s": 24548,
"text": "Syntax:"
},
{
"code": null,
"e": 24606,
"s": 24556,
"text": "public const long MaxValue = 9223372036854775807;"
},
{
"code": null,
"e": 24667,
"s": 24606,
"text": "Return Value: This field always returns 9223372036854775807."
},
{
"code": null,
"e": 24676,
"s": 24667,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Int64.MaxValue Fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum // value of Int64 struct Console.WriteLine(\"Maximum Value is: \"+ Int64.MaxValue); // taking a variable long var1 = 93422337368375807; if(var1.Equals(Int64.MaxValue)) { Console.WriteLine(\"Equal..!!\"); Console.WriteLine(\"Type of var1 is: {0}\", var1.GetTypeCode()); } else { Console.WriteLine(\"Not equal..!!\"); Console.WriteLine(\"Type of var1 is: {0}\", var1.GetTypeCode()); } }}",
"e": 25464,
"s": 24676,
"text": null
},
{
"code": null,
"e": 25540,
"s": 25464,
"text": "Maximum Value is: 9223372036854775807\nNot equal..!!\nType of var1 is: Int64\n"
},
{
"code": null,
"e": 25551,
"s": 25540,
"text": "Reference:"
},
{
"code": null,
"e": 25641,
"s": 25551,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int64.maxvalue?view=netframework-4.7.2"
},
{
"code": null,
"e": 25661,
"s": 25641,
"text": "CSharp-Int64-Struct"
},
{
"code": null,
"e": 25664,
"s": 25661,
"text": "C#"
},
{
"code": null,
"e": 25762,
"s": 25664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25808,
"s": 25762,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 25826,
"s": 25808,
"text": "C# | Constructors"
},
{
"code": null,
"e": 25848,
"s": 25826,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 25879,
"s": 25848,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 25894,
"s": 25879,
"text": "C# | Delegates"
},
{
"code": null,
"e": 25934,
"s": 25894,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 25956,
"s": 25934,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 25979,
"s": 25956,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25995,
"s": 25979,
"text": "C# | Data Types"
}
] |
Breaking Down Goodreads Dataset using Python | by Shivangi Sareen | Towards Data Science
|
I love reading books and am always looking out for the next one to read, even before I start the one recently bought. So, I decided to mess around with this Goodreads dataset I happened to stumble upon on Kaggle and see what book recommendations I would end up with.
It was super fun and packed with learning!
Like always, I used Jupyter notebook and set up a virtual environment using virtualenv. Check out this post for all the steps.
import syssys.path.append('./lib/python3.7/site-packages')import pandas as pdimport reimport mathdata = pd.read_csv("books.csv")
When reading the csv, we get the following error:
ParserError: Error tokenizing data. C error: Expected 10 fields in line 4012, saw 11
This is happening because, in certain rows, there are commas that lead to all the values being shifted one place to the right and hence an extra column being added.
Possible things to do:
Skip those rows entirely. But we do not know beforehand what those rows are. The Kaggle discussion area for this dataset lists those rows, however, doing away with them will end in a loss of data.
Using a text editor, replace all commas with another delimiter like ; or | and then manually go to the rows with more than one author and put commas there. This is a cumbersome process and one which involves too much manual effort. If the number of rows corrupted are too many, this solution is not feasible.
What I ended up doing — using a text editor and adding a column in the end to avoid the ParseError. I named the column extra and read the csv file using pandas.
Now we can view and data.
data.describe(include = "all")
bookID: unique identification number for each book;title: the name of the book;authors: names of the authors of the book. Multiple authors are delimited with -;average_rating: the average rating of the book;isbn: unique number to identify the book, the International Standard Book Number;isbn13: a 13-digit ISBN to identify the book, instead of the standard 11-digit ISBN;language_code: the primary language of the book;# num_pages: number of pages of the book;ratings_count: total number of ratings the book received;text_reviews_count: total number of written text reviews the book received.
5 rows out of 13719 are corrupted, i.e., they have a value in the extra field.
To find out these rows, we check which do not have value NaN in that field, i.e., have an integer value. So, I stored the index of those rows that had an integer value in the field extra.
corrupted_rows = []for index, i in data.iterrows(): if -math.inf <= i['extra'] <= math.inf: print("index number:", index) print("field value:", i['extra']) print("...")corrupted_rows.append(index)
data.loc[corrupted_rows, :]
Let’s combine the multiple authors into a single field. I join them using a ; in the authors field:
data['authors'] = data['authors']+ ";" +data['average_rating']
We get a warning: SettingWithCopyWarning. This isn't an error so nothing is broken. However, it's always good to know what the warning is trying to tell us instead of brushing it off. Here's an explanation.
The authors have been combined in one column. What’s left to do now is to shift the column values, from the third column onwards (including third since we start from index 0), one space to the left. This is achieved using the shift operator where we specify how many spaces to the left (or right) need to be shifted and whether along the row or column axis.
#-1 indicates one space to the left and axis=1 specifies column axisdata.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].shift(-1, axis = 1)
The result of this shift is missing values from two columns: # num_pages and text_reviews_count. This is because the data types of the columns do not match those of the final shifted values.
The solution is to temporarily convert the data type of all columns to str, perform the shift and then convert them back to their original data types.
data.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].astype(str) #convert to strdata.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].shift(-1, axis = 1) #the shiftdata.describe(include="all")
We can now delete the last column.
del data['extra']
We now have to convert the data types of the columns back to their original types.
pd.to_numeric automatically configures float or int data types.
data["average_rating"] = pd.to_numeric(data.average_rating) data["ratings_count"] = pd.to_numeric(data.ratings_count) data["# num_pages"] = pd.to_numeric(data.["# num_pages"])data["text_reviews_count"] = pd.to_numeric(data.["text_reviews_count"])
I want to only keep those books that are in English. First, we need a list of distinct language codes that are being used.
language_code_unique = data.language_code.unique()
When we print the list, we see that the English language codes start with en. So, simple use of regex will help us filter the data.
#list to store the different English language codesenglish_lang_code = [] language_code_regex = re.compile(r'^en')for code in language_code_unique: mo2 = language_code_regex.search(code) if mo2 != None: english_lang_code.append(code)
The output is 5 language codes that correspond to English. We then use define a function to be used directly on the dataframe.
def check_lang_code(row): if row.language_code in english_lang_code: return rowdata = data[data.language_code.isin(english_lang_code)]
This leaves us with books in English and reduces the number of rows to 12651. To further decrease the data size, we extract only relevant columns: title, authors, average_rating, ratings_count.
data_filtered = data.iloc[:, [1, 2, 3, 8]]
To get a higher quality list of books, we need to set a threshold of average_rating and ratings_count. I decided to use the mean for both.
ratings_count_mean = data_filtered["ratings_count"].mean()average_rating_mean = data_filtered["average_rating"].mean()data_filtered = data_filtered[(data_filtered.average_rating > average_rating_mean)]data_filtered = data_filtered[(data_filtered.ratings_count > ratings_count_mean)]
This leaves us with a dataset of 1013 rows × 4 columns.
Using average_rating as the only factor to get a list of top rated books isn’t enough.
data_filtered.sort_values(by=['average_rating'], ascending=False)
The list below is not right.
We need to factor in ratings_count. I created a new column weighted_rating as the multiplication of ratings_count and average_rating.
data_filtered['weighted_rating'] = data_filtered['average_rating'] * data_filtered['ratings_count']#sort in descending order of 'weighted_rating'data_filtered = data_filtered.sort_values(by='weighted_rating', ascending=False)
Looking much better!
Clearly, Harry Potter takes the lead. Now, I’ve read the entire series and so I don’t want to include any Harry Potter books. This is an easy case of regex.
match_regex = re.compile(r’Harry Potter’)#list to store all 'Harry Potter' titlesmatched_titles = []for index, row in data_filtered.iterrows(): mo1 = match_regex.search(row.title) if mo1 != None: matched_titles.append(row.title)
data_without_hp = data_filtered[~data_filtered.title.isin(matched_titles)]
The top 20 books in the list:
There are books in the list that I’ve read and can easily filter out by adding to match_regex but I decided to leave it at that. The book that stood out was “The Secret Life of Bees”. I hadn’t heard of the book before and one I’m surely going to give a read!
Unfortunately, this dataset doesn’t have a genre category (horror/crime/funny/...) and a fiction/non-fiction category, which would’ve made the list far more curated and personalised (thinking about creating such a list makes me squeal with excitement)!
→ Dealing with “corrupted rows”→ Filtering out data as much as possible to get desired results and increase performance→ A major lesson is to reduce the number of for loops as much as possible, since they are slower than other methods:
defining a function and then applying it on the dataframe
filtering data within dataframe brackets
calculating function values directly
Hope you enjoyed took away some valuable insights!
|
[
{
"code": null,
"e": 438,
"s": 171,
"text": "I love reading books and am always looking out for the next one to read, even before I start the one recently bought. So, I decided to mess around with this Goodreads dataset I happened to stumble upon on Kaggle and see what book recommendations I would end up with."
},
{
"code": null,
"e": 481,
"s": 438,
"text": "It was super fun and packed with learning!"
},
{
"code": null,
"e": 608,
"s": 481,
"text": "Like always, I used Jupyter notebook and set up a virtual environment using virtualenv. Check out this post for all the steps."
},
{
"code": null,
"e": 737,
"s": 608,
"text": "import syssys.path.append('./lib/python3.7/site-packages')import pandas as pdimport reimport mathdata = pd.read_csv(\"books.csv\")"
},
{
"code": null,
"e": 787,
"s": 737,
"text": "When reading the csv, we get the following error:"
},
{
"code": null,
"e": 872,
"s": 787,
"text": "ParserError: Error tokenizing data. C error: Expected 10 fields in line 4012, saw 11"
},
{
"code": null,
"e": 1037,
"s": 872,
"text": "This is happening because, in certain rows, there are commas that lead to all the values being shifted one place to the right and hence an extra column being added."
},
{
"code": null,
"e": 1060,
"s": 1037,
"text": "Possible things to do:"
},
{
"code": null,
"e": 1257,
"s": 1060,
"text": "Skip those rows entirely. But we do not know beforehand what those rows are. The Kaggle discussion area for this dataset lists those rows, however, doing away with them will end in a loss of data."
},
{
"code": null,
"e": 1566,
"s": 1257,
"text": "Using a text editor, replace all commas with another delimiter like ; or | and then manually go to the rows with more than one author and put commas there. This is a cumbersome process and one which involves too much manual effort. If the number of rows corrupted are too many, this solution is not feasible."
},
{
"code": null,
"e": 1727,
"s": 1566,
"text": "What I ended up doing — using a text editor and adding a column in the end to avoid the ParseError. I named the column extra and read the csv file using pandas."
},
{
"code": null,
"e": 1753,
"s": 1727,
"text": "Now we can view and data."
},
{
"code": null,
"e": 1784,
"s": 1753,
"text": "data.describe(include = \"all\")"
},
{
"code": null,
"e": 2378,
"s": 1784,
"text": "bookID: unique identification number for each book;title: the name of the book;authors: names of the authors of the book. Multiple authors are delimited with -;average_rating: the average rating of the book;isbn: unique number to identify the book, the International Standard Book Number;isbn13: a 13-digit ISBN to identify the book, instead of the standard 11-digit ISBN;language_code: the primary language of the book;# num_pages: number of pages of the book;ratings_count: total number of ratings the book received;text_reviews_count: total number of written text reviews the book received."
},
{
"code": null,
"e": 2457,
"s": 2378,
"text": "5 rows out of 13719 are corrupted, i.e., they have a value in the extra field."
},
{
"code": null,
"e": 2645,
"s": 2457,
"text": "To find out these rows, we check which do not have value NaN in that field, i.e., have an integer value. So, I stored the index of those rows that had an integer value in the field extra."
},
{
"code": null,
"e": 2870,
"s": 2645,
"text": "corrupted_rows = []for index, i in data.iterrows(): if -math.inf <= i['extra'] <= math.inf: print(\"index number:\", index) print(\"field value:\", i['extra']) print(\"...\")corrupted_rows.append(index)"
},
{
"code": null,
"e": 2898,
"s": 2870,
"text": "data.loc[corrupted_rows, :]"
},
{
"code": null,
"e": 2998,
"s": 2898,
"text": "Let’s combine the multiple authors into a single field. I join them using a ; in the authors field:"
},
{
"code": null,
"e": 3061,
"s": 2998,
"text": "data['authors'] = data['authors']+ \";\" +data['average_rating']"
},
{
"code": null,
"e": 3268,
"s": 3061,
"text": "We get a warning: SettingWithCopyWarning. This isn't an error so nothing is broken. However, it's always good to know what the warning is trying to tell us instead of brushing it off. Here's an explanation."
},
{
"code": null,
"e": 3626,
"s": 3268,
"text": "The authors have been combined in one column. What’s left to do now is to shift the column values, from the third column onwards (including third since we start from index 0), one space to the left. This is achieved using the shift operator where we specify how many spaces to the left (or right) need to be shifted and whether along the row or column axis."
},
{
"code": null,
"e": 3777,
"s": 3626,
"text": "#-1 indicates one space to the left and axis=1 specifies column axisdata.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].shift(-1, axis = 1) "
},
{
"code": null,
"e": 3968,
"s": 3777,
"text": "The result of this shift is missing values from two columns: # num_pages and text_reviews_count. This is because the data types of the columns do not match those of the final shifted values."
},
{
"code": null,
"e": 4119,
"s": 3968,
"text": "The solution is to temporarily convert the data type of all columns to str, perform the shift and then convert them back to their original data types."
},
{
"code": null,
"e": 4329,
"s": 4119,
"text": "data.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].astype(str) #convert to strdata.iloc[corrupted_rows, 3:] = data.iloc[corrupted_rows, 3:].shift(-1, axis = 1) #the shiftdata.describe(include=\"all\")"
},
{
"code": null,
"e": 4364,
"s": 4329,
"text": "We can now delete the last column."
},
{
"code": null,
"e": 4383,
"s": 4364,
"text": " del data['extra']"
},
{
"code": null,
"e": 4466,
"s": 4383,
"text": "We now have to convert the data types of the columns back to their original types."
},
{
"code": null,
"e": 4530,
"s": 4466,
"text": "pd.to_numeric automatically configures float or int data types."
},
{
"code": null,
"e": 4777,
"s": 4530,
"text": "data[\"average_rating\"] = pd.to_numeric(data.average_rating) data[\"ratings_count\"] = pd.to_numeric(data.ratings_count) data[\"# num_pages\"] = pd.to_numeric(data.[\"# num_pages\"])data[\"text_reviews_count\"] = pd.to_numeric(data.[\"text_reviews_count\"])"
},
{
"code": null,
"e": 4900,
"s": 4777,
"text": "I want to only keep those books that are in English. First, we need a list of distinct language codes that are being used."
},
{
"code": null,
"e": 4952,
"s": 4900,
"text": "language_code_unique = data.language_code.unique() "
},
{
"code": null,
"e": 5084,
"s": 4952,
"text": "When we print the list, we see that the English language codes start with en. So, simple use of regex will help us filter the data."
},
{
"code": null,
"e": 5331,
"s": 5084,
"text": "#list to store the different English language codesenglish_lang_code = [] language_code_regex = re.compile(r'^en')for code in language_code_unique: mo2 = language_code_regex.search(code) if mo2 != None: english_lang_code.append(code)"
},
{
"code": null,
"e": 5458,
"s": 5331,
"text": "The output is 5 language codes that correspond to English. We then use define a function to be used directly on the dataframe."
},
{
"code": null,
"e": 5605,
"s": 5458,
"text": "def check_lang_code(row): if row.language_code in english_lang_code: return rowdata = data[data.language_code.isin(english_lang_code)]"
},
{
"code": null,
"e": 5799,
"s": 5605,
"text": "This leaves us with books in English and reduces the number of rows to 12651. To further decrease the data size, we extract only relevant columns: title, authors, average_rating, ratings_count."
},
{
"code": null,
"e": 5843,
"s": 5799,
"text": "data_filtered = data.iloc[:, [1, 2, 3, 8]] "
},
{
"code": null,
"e": 5982,
"s": 5843,
"text": "To get a higher quality list of books, we need to set a threshold of average_rating and ratings_count. I decided to use the mean for both."
},
{
"code": null,
"e": 6265,
"s": 5982,
"text": "ratings_count_mean = data_filtered[\"ratings_count\"].mean()average_rating_mean = data_filtered[\"average_rating\"].mean()data_filtered = data_filtered[(data_filtered.average_rating > average_rating_mean)]data_filtered = data_filtered[(data_filtered.ratings_count > ratings_count_mean)]"
},
{
"code": null,
"e": 6321,
"s": 6265,
"text": "This leaves us with a dataset of 1013 rows × 4 columns."
},
{
"code": null,
"e": 6408,
"s": 6321,
"text": "Using average_rating as the only factor to get a list of top rated books isn’t enough."
},
{
"code": null,
"e": 6475,
"s": 6408,
"text": "data_filtered.sort_values(by=['average_rating'], ascending=False) "
},
{
"code": null,
"e": 6504,
"s": 6475,
"text": "The list below is not right."
},
{
"code": null,
"e": 6638,
"s": 6504,
"text": "We need to factor in ratings_count. I created a new column weighted_rating as the multiplication of ratings_count and average_rating."
},
{
"code": null,
"e": 6865,
"s": 6638,
"text": "data_filtered['weighted_rating'] = data_filtered['average_rating'] * data_filtered['ratings_count']#sort in descending order of 'weighted_rating'data_filtered = data_filtered.sort_values(by='weighted_rating', ascending=False) "
},
{
"code": null,
"e": 6886,
"s": 6865,
"text": "Looking much better!"
},
{
"code": null,
"e": 7043,
"s": 6886,
"text": "Clearly, Harry Potter takes the lead. Now, I’ve read the entire series and so I don’t want to include any Harry Potter books. This is an easy case of regex."
},
{
"code": null,
"e": 7285,
"s": 7043,
"text": "match_regex = re.compile(r’Harry Potter’)#list to store all 'Harry Potter' titlesmatched_titles = []for index, row in data_filtered.iterrows(): mo1 = match_regex.search(row.title) if mo1 != None: matched_titles.append(row.title)"
},
{
"code": null,
"e": 7360,
"s": 7285,
"text": "data_without_hp = data_filtered[~data_filtered.title.isin(matched_titles)]"
},
{
"code": null,
"e": 7390,
"s": 7360,
"text": "The top 20 books in the list:"
},
{
"code": null,
"e": 7649,
"s": 7390,
"text": "There are books in the list that I’ve read and can easily filter out by adding to match_regex but I decided to leave it at that. The book that stood out was “The Secret Life of Bees”. I hadn’t heard of the book before and one I’m surely going to give a read!"
},
{
"code": null,
"e": 7902,
"s": 7649,
"text": "Unfortunately, this dataset doesn’t have a genre category (horror/crime/funny/...) and a fiction/non-fiction category, which would’ve made the list far more curated and personalised (thinking about creating such a list makes me squeal with excitement)!"
},
{
"code": null,
"e": 8138,
"s": 7902,
"text": "→ Dealing with “corrupted rows”→ Filtering out data as much as possible to get desired results and increase performance→ A major lesson is to reduce the number of for loops as much as possible, since they are slower than other methods:"
},
{
"code": null,
"e": 8196,
"s": 8138,
"text": "defining a function and then applying it on the dataframe"
},
{
"code": null,
"e": 8237,
"s": 8196,
"text": "filtering data within dataframe brackets"
},
{
"code": null,
"e": 8274,
"s": 8237,
"text": "calculating function values directly"
}
] |
You Should Use CatBoost. Here’s Why. | Towards Data Science
|
IntroductionCatBoostShort TutorialSummaryReferences
Introduction
CatBoost
Short Tutorial
Summary
References
With Data Science competitions becoming more and more popular, especially on the site, Kaggle, so are new Machine Learning algorithms. Whereas XGBoost was the most competitive and accurate algorithm most of the time, a new leader has emerged, named CatBoost. There has been an open-source library that is based on gradient boosting decision trees from the company Yandex [2]. In their documentation, they include GitHub references and examples, news, benchmarks, feedback, contacts, tutorial, and installation. If you are using XGBoost, LightGBM, or H2O, CatBoost documentation has benchmarked and proved that they are the best with both tuned and default results. Of course, if you have more categorical variables, then CatBoost is the way to go. Keep on reading below if you would like to learn more about this awesome library from Yandex.
The main reason I use CatBoost is that it is easy to use, efficient, and works especially well with categorical variables. As the name implies, CatBoost means ‘categorical’ boosting. It is quicker to use than, say, XGBoost, because it does not require the use of pre-processing your data, which can take the most amount of time in a typical Data Science model building process. Another problem that other algorithms have is when using categorical variables like ID’s, they create an impossible to compute matrix composed of thousands of columns made from dummy variables or one-hot-encoding. CatBoost fixes this problem in the way that it transforms its categorical variables, as you will see below.
Training
CatBoost builds upon gradient boosted decision trees including a training dataset, with accuracy determined on a validation dataset. In training, those decision trees are built consecutively with each tree having its loss reduced.
Split Calculation
Based on the starting parameters of CatBoost, quantization is used for the numerical features when determining the best ways for splitting data into buckets.
Categorical Feature Transformation
The main benefit, I think, of this algorithm is that it treats categorical feature transformation in the best way when compared to other Machine Learning algorithms.
For example, in classification, a permutation is performed randomly, then a calculation is performed from a standard formula unique to CatBoost (ordered target encoding):
target_average = countInClass + prior / totalCount + 1
Feature Importance
This library allows for some awesome visualizations, including the model training and testing process and a print out of feature importance to name a few. You can access ShapValues as well, which is becoming more popular in distinguishing more explainability for your model features. There are plenty of examples in the docs. Here [4] is a particularly useful link they have provided for visualizations:
catboost.ai
There is both the CatBoostClassifier and the CatBoostRegressor, I will be discussing the CatBoostRegressor, while the classifier code is not too much different, other than the main type of algorithm you are using based on your target variable.
Here is some code you can use to build your initial CatBoost model — of course, you can tune your parameters as well:
from catboost import CatBoostRegressor# read in your specific datatraining_data = pd.read_csv('file_to_training_data.csv')evaluation_data = pd.read_csv('file_to_evaluation_data.csv')training_labels = [y,y2,y3, etc.]# establish, fit, and predict using CatBoostRegressorcat_features = ['person_type', 'cat_example_2', etx]model = CatBoostRegressor()model.fit(training_data, training_labels, cat_features)preds = model.predict(evaluation_data)
As you can see, in just a few lines of code, you can create your first base-line CatBoost regression model. It is similar to most other Machine Learning algorithms, with the most important part of code to include being the cat_features parameter. You will have to distinguish your list of categorical features in cat_features.
Here are some of the many useful methods that are a part of this algorithm:
* get_all_params* get_feature_importance* load_model* randomized_search* save_model
There are a ton more of course, but these ones I have personally used the model, especially get_feature_importance as it returns a nice summary of your important features.
As you can see, CatBoost has some useful benefits, with easy implementation. Some of the main features of this competitive library are that even without parameter tuning the default parameters provide for great results, categorical features do not need preprocessing, quick computation, increase in accuracy with less overfitting, and lastly, efficient predictions. Yandex researchers have provided an extremely useful library that can be utilized for several competition use cases, as well as career and production use cases. They have also proved that on many popular datasets that their benchmark quality is the best when compared to LightGBM, XGBoost, and H2O.
Overall, CatBoost is great at the following:
fast
easy to use
accurate
use of categorical variables in your feature set
provides several useful methods
provides several useful visualizations
has been proven to be better than the previous leading Machine Learning algorithms
I hope you found this article both interesting and useful. Please feel free to comment down below if you have used CatBoost before or prefer something else. Do you agree that it is better and why or why not? I want to thank Yandex for an amazing library and documentation. Thank you for reading, I appreciate it!
If you would like to learn more in-depth about the CatBoost library, there is another article [6] that uncovers all of the parameters, what they mean, and how to tune them from Mariia Garkavenko.
towardsdatascience.com
[1] Photo by Pacto Visual on Unsplash, (2016)
[2] Photo by Fachry Zella Devandra on Unsplash, (2017)
[3] Yandex, CatBoost documentation, (2020)
[4] Yandex, CatBoost visualization, (2020)
[5] Photo by Joshua Aragon on Unsplash, (2019)
[6] Mariia Garkavenko, Categorical features parameters in CatBoost, (2020)
|
[
{
"code": null,
"e": 224,
"s": 172,
"text": "IntroductionCatBoostShort TutorialSummaryReferences"
},
{
"code": null,
"e": 237,
"s": 224,
"text": "Introduction"
},
{
"code": null,
"e": 246,
"s": 237,
"text": "CatBoost"
},
{
"code": null,
"e": 261,
"s": 246,
"text": "Short Tutorial"
},
{
"code": null,
"e": 269,
"s": 261,
"text": "Summary"
},
{
"code": null,
"e": 280,
"s": 269,
"text": "References"
},
{
"code": null,
"e": 1122,
"s": 280,
"text": "With Data Science competitions becoming more and more popular, especially on the site, Kaggle, so are new Machine Learning algorithms. Whereas XGBoost was the most competitive and accurate algorithm most of the time, a new leader has emerged, named CatBoost. There has been an open-source library that is based on gradient boosting decision trees from the company Yandex [2]. In their documentation, they include GitHub references and examples, news, benchmarks, feedback, contacts, tutorial, and installation. If you are using XGBoost, LightGBM, or H2O, CatBoost documentation has benchmarked and proved that they are the best with both tuned and default results. Of course, if you have more categorical variables, then CatBoost is the way to go. Keep on reading below if you would like to learn more about this awesome library from Yandex."
},
{
"code": null,
"e": 1822,
"s": 1122,
"text": "The main reason I use CatBoost is that it is easy to use, efficient, and works especially well with categorical variables. As the name implies, CatBoost means ‘categorical’ boosting. It is quicker to use than, say, XGBoost, because it does not require the use of pre-processing your data, which can take the most amount of time in a typical Data Science model building process. Another problem that other algorithms have is when using categorical variables like ID’s, they create an impossible to compute matrix composed of thousands of columns made from dummy variables or one-hot-encoding. CatBoost fixes this problem in the way that it transforms its categorical variables, as you will see below."
},
{
"code": null,
"e": 1831,
"s": 1822,
"text": "Training"
},
{
"code": null,
"e": 2062,
"s": 1831,
"text": "CatBoost builds upon gradient boosted decision trees including a training dataset, with accuracy determined on a validation dataset. In training, those decision trees are built consecutively with each tree having its loss reduced."
},
{
"code": null,
"e": 2080,
"s": 2062,
"text": "Split Calculation"
},
{
"code": null,
"e": 2238,
"s": 2080,
"text": "Based on the starting parameters of CatBoost, quantization is used for the numerical features when determining the best ways for splitting data into buckets."
},
{
"code": null,
"e": 2273,
"s": 2238,
"text": "Categorical Feature Transformation"
},
{
"code": null,
"e": 2439,
"s": 2273,
"text": "The main benefit, I think, of this algorithm is that it treats categorical feature transformation in the best way when compared to other Machine Learning algorithms."
},
{
"code": null,
"e": 2610,
"s": 2439,
"text": "For example, in classification, a permutation is performed randomly, then a calculation is performed from a standard formula unique to CatBoost (ordered target encoding):"
},
{
"code": null,
"e": 2665,
"s": 2610,
"text": "target_average = countInClass + prior / totalCount + 1"
},
{
"code": null,
"e": 2684,
"s": 2665,
"text": "Feature Importance"
},
{
"code": null,
"e": 3088,
"s": 2684,
"text": "This library allows for some awesome visualizations, including the model training and testing process and a print out of feature importance to name a few. You can access ShapValues as well, which is becoming more popular in distinguishing more explainability for your model features. There are plenty of examples in the docs. Here [4] is a particularly useful link they have provided for visualizations:"
},
{
"code": null,
"e": 3100,
"s": 3088,
"text": "catboost.ai"
},
{
"code": null,
"e": 3344,
"s": 3100,
"text": "There is both the CatBoostClassifier and the CatBoostRegressor, I will be discussing the CatBoostRegressor, while the classifier code is not too much different, other than the main type of algorithm you are using based on your target variable."
},
{
"code": null,
"e": 3462,
"s": 3344,
"text": "Here is some code you can use to build your initial CatBoost model — of course, you can tune your parameters as well:"
},
{
"code": null,
"e": 3903,
"s": 3462,
"text": "from catboost import CatBoostRegressor# read in your specific datatraining_data = pd.read_csv('file_to_training_data.csv')evaluation_data = pd.read_csv('file_to_evaluation_data.csv')training_labels = [y,y2,y3, etc.]# establish, fit, and predict using CatBoostRegressorcat_features = ['person_type', 'cat_example_2', etx]model = CatBoostRegressor()model.fit(training_data, training_labels, cat_features)preds = model.predict(evaluation_data)"
},
{
"code": null,
"e": 4230,
"s": 3903,
"text": "As you can see, in just a few lines of code, you can create your first base-line CatBoost regression model. It is similar to most other Machine Learning algorithms, with the most important part of code to include being the cat_features parameter. You will have to distinguish your list of categorical features in cat_features."
},
{
"code": null,
"e": 4306,
"s": 4230,
"text": "Here are some of the many useful methods that are a part of this algorithm:"
},
{
"code": null,
"e": 4390,
"s": 4306,
"text": "* get_all_params* get_feature_importance* load_model* randomized_search* save_model"
},
{
"code": null,
"e": 4562,
"s": 4390,
"text": "There are a ton more of course, but these ones I have personally used the model, especially get_feature_importance as it returns a nice summary of your important features."
},
{
"code": null,
"e": 5227,
"s": 4562,
"text": "As you can see, CatBoost has some useful benefits, with easy implementation. Some of the main features of this competitive library are that even without parameter tuning the default parameters provide for great results, categorical features do not need preprocessing, quick computation, increase in accuracy with less overfitting, and lastly, efficient predictions. Yandex researchers have provided an extremely useful library that can be utilized for several competition use cases, as well as career and production use cases. They have also proved that on many popular datasets that their benchmark quality is the best when compared to LightGBM, XGBoost, and H2O."
},
{
"code": null,
"e": 5272,
"s": 5227,
"text": "Overall, CatBoost is great at the following:"
},
{
"code": null,
"e": 5277,
"s": 5272,
"text": "fast"
},
{
"code": null,
"e": 5289,
"s": 5277,
"text": "easy to use"
},
{
"code": null,
"e": 5298,
"s": 5289,
"text": "accurate"
},
{
"code": null,
"e": 5347,
"s": 5298,
"text": "use of categorical variables in your feature set"
},
{
"code": null,
"e": 5379,
"s": 5347,
"text": "provides several useful methods"
},
{
"code": null,
"e": 5418,
"s": 5379,
"text": "provides several useful visualizations"
},
{
"code": null,
"e": 5501,
"s": 5418,
"text": "has been proven to be better than the previous leading Machine Learning algorithms"
},
{
"code": null,
"e": 5814,
"s": 5501,
"text": "I hope you found this article both interesting and useful. Please feel free to comment down below if you have used CatBoost before or prefer something else. Do you agree that it is better and why or why not? I want to thank Yandex for an amazing library and documentation. Thank you for reading, I appreciate it!"
},
{
"code": null,
"e": 6010,
"s": 5814,
"text": "If you would like to learn more in-depth about the CatBoost library, there is another article [6] that uncovers all of the parameters, what they mean, and how to tune them from Mariia Garkavenko."
},
{
"code": null,
"e": 6033,
"s": 6010,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6079,
"s": 6033,
"text": "[1] Photo by Pacto Visual on Unsplash, (2016)"
},
{
"code": null,
"e": 6134,
"s": 6079,
"text": "[2] Photo by Fachry Zella Devandra on Unsplash, (2017)"
},
{
"code": null,
"e": 6177,
"s": 6134,
"text": "[3] Yandex, CatBoost documentation, (2020)"
},
{
"code": null,
"e": 6220,
"s": 6177,
"text": "[4] Yandex, CatBoost visualization, (2020)"
},
{
"code": null,
"e": 6267,
"s": 6220,
"text": "[5] Photo by Joshua Aragon on Unsplash, (2019)"
}
] |
How to install python modules without root access?
|
If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given directory:
>>> import os, sys
>>> file_path = 'AdditionalModules/'
>>> sys.path.append(os.path.dirname(file_path))
>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH.
You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/
|
[
{
"code": null,
"e": 1320,
"s": 1062,
"text": "If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given directory:"
},
{
"code": null,
"e": 1539,
"s": 1320,
"text": ">>> import os, sys\n>>> file_path = 'AdditionalModules/'\n>>> sys.path.append(os.path.dirname(file_path))\n>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH."
},
{
"code": null,
"e": 2296,
"s": 1539,
"text": "You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/"
}
] |
Bootstrap 4 | Toast - GeeksforGeeks
|
04 May, 2022
Toast is used to create something like an alert box which is shown for a short time like a couple of seconds when something happens. Like when the user clicks on a button or submits a form and many other actions.
.toast: It helps to create a toast
.toast-header : It helps to create the toast header
.toast-body : It helps to create toast body
Toast Methods:
.toast(options): It helps to activate the toast with a parameter of option. In the below implementation we remove the fading transition effect from the toast, and we delay the hiding of the toast to 8000 milliseconds when it is shown. It has three options animation, autohide, delay. Refer this link for more information on these options.Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body style="text-align: center"> <h1 style="color:green">GeeksforGeeks</h1> <div class="container mt-3"> <h3>.toast(options)</h3> <p> When we click the button below there would be delay of the toast to 8000 milliseconds. </p> <button type="button" class="btn btn-primary" id="myBtn">Show Toast</button> <div class="toast mt-3"> <div class="toast-header"> Toast Header </div> <div class="toast-body"> Some text inside the toast body </div> </div> </div> <script> $(document).ready(function () { $('#myBtn').click(function () { $('.toast').toast({ animation: false, delay: 2000 }); $('.toast').toast('show'); }); }); </script></body></html>
Output:
.toast(“show”): It shows the toast
.toast(“hide”): It hides the toast
.toast(“dispose”): It disposes the toast
Toast Events: Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <div class="container mt-3"> <h3>Toast Events</h3> <strong>show.bs.toast, </strong> <strong>shown.bs.toast, </strong> <strong>hide.bs.toast, </strong> <strong>hidden.bs.toast </strong> <p>Click on the button below to perform toast.</p> <button type="button" class="btn btn-primary" id="myShowBtn"> Show Toast </button> <div class="toast mt-3"> <div class="toast-header"> Toast Header </div> <div class="toast-body"> Some text inside the toast body </div> </div> </div> <script> $(document).ready(function () { $("#myShowBtn").click(function () { $('.toast').toast('show'); }); $('.toast').on('show.bs.toast', function () { alert('The toast is about to be shown.'); }); $('.toast').on('shown.bs.toast', function () { alert('The toast is now fully shown.'); }); $('.toast').on('hide.bs.toast', function () { alert('The toast is about to be hidden.'); }); $('.toast').on('hidden.bs.toast', function () { alert('The toast is now hidden.'); }); }); </script></body></html>
Output:
show.bs.toast : It happens when the toast is about to be shown.
shown.bs.toast : It happens when the toast is shown.
hide.bs.toast : It happens when the toast is about to be hidden.
hidden.bs.toast : It happens when the toast is fully hidden.
Supported Browser:
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.
ysachin2314
sahilintern
Bootstrap-4
Bootstrap
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 29793,
"s": 29765,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 30006,
"s": 29793,
"text": "Toast is used to create something like an alert box which is shown for a short time like a couple of seconds when something happens. Like when the user clicks on a button or submits a form and many other actions."
},
{
"code": null,
"e": 30041,
"s": 30006,
"text": ".toast: It helps to create a toast"
},
{
"code": null,
"e": 30093,
"s": 30041,
"text": ".toast-header : It helps to create the toast header"
},
{
"code": null,
"e": 30137,
"s": 30093,
"text": ".toast-body : It helps to create toast body"
},
{
"code": null,
"e": 30152,
"s": 30137,
"text": "Toast Methods:"
},
{
"code": null,
"e": 30501,
"s": 30152,
"text": ".toast(options): It helps to activate the toast with a parameter of option. In the below implementation we remove the fading transition effect from the toast, and we delay the hiding of the toast to 8000 milliseconds when it is shown. It has three options animation, autohide, delay. Refer this link for more information on these options.Example: "
},
{
"code": null,
"e": 30506,
"s": 30501,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body style=\"text-align: center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <div class=\"container mt-3\"> <h3>.toast(options)</h3> <p> When we click the button below there would be delay of the toast to 8000 milliseconds. </p> <button type=\"button\" class=\"btn btn-primary\" id=\"myBtn\">Show Toast</button> <div class=\"toast mt-3\"> <div class=\"toast-header\"> Toast Header </div> <div class=\"toast-body\"> Some text inside the toast body </div> </div> </div> <script> $(document).ready(function () { $('#myBtn').click(function () { $('.toast').toast({ animation: false, delay: 2000 }); $('.toast').toast('show'); }); }); </script></body></html>",
"e": 32031,
"s": 30506,
"text": null
},
{
"code": null,
"e": 32041,
"s": 32031,
"text": "Output: "
},
{
"code": null,
"e": 32078,
"s": 32043,
"text": ".toast(“show”): It shows the toast"
},
{
"code": null,
"e": 32113,
"s": 32078,
"text": ".toast(“hide”): It hides the toast"
},
{
"code": null,
"e": 32154,
"s": 32113,
"text": ".toast(“dispose”): It disposes the toast"
},
{
"code": null,
"e": 32179,
"s": 32154,
"text": "Toast Events: Example: "
},
{
"code": null,
"e": 32184,
"s": 32179,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <div class=\"container mt-3\"> <h3>Toast Events</h3> <strong>show.bs.toast, </strong> <strong>shown.bs.toast, </strong> <strong>hide.bs.toast, </strong> <strong>hidden.bs.toast </strong> <p>Click on the button below to perform toast.</p> <button type=\"button\" class=\"btn btn-primary\" id=\"myShowBtn\"> Show Toast </button> <div class=\"toast mt-3\"> <div class=\"toast-header\"> Toast Header </div> <div class=\"toast-body\"> Some text inside the toast body </div> </div> </div> <script> $(document).ready(function () { $(\"#myShowBtn\").click(function () { $('.toast').toast('show'); }); $('.toast').on('show.bs.toast', function () { alert('The toast is about to be shown.'); }); $('.toast').on('shown.bs.toast', function () { alert('The toast is now fully shown.'); }); $('.toast').on('hide.bs.toast', function () { alert('The toast is about to be hidden.'); }); $('.toast').on('hidden.bs.toast', function () { alert('The toast is now hidden.'); }); }); </script></body></html>",
"e": 34199,
"s": 32184,
"text": null
},
{
"code": null,
"e": 34209,
"s": 34199,
"text": "Output: "
},
{
"code": null,
"e": 34275,
"s": 34209,
"text": "show.bs.toast : It happens when the toast is about to be shown. "
},
{
"code": null,
"e": 34330,
"s": 34275,
"text": "shown.bs.toast : It happens when the toast is shown. "
},
{
"code": null,
"e": 34397,
"s": 34330,
"text": "hide.bs.toast : It happens when the toast is about to be hidden. "
},
{
"code": null,
"e": 34460,
"s": 34397,
"text": "hidden.bs.toast : It happens when the toast is fully hidden. "
},
{
"code": null,
"e": 34479,
"s": 34460,
"text": "Supported Browser:"
},
{
"code": null,
"e": 34493,
"s": 34479,
"text": "Google Chrome"
},
{
"code": null,
"e": 34511,
"s": 34493,
"text": "Internet Explorer"
},
{
"code": null,
"e": 34519,
"s": 34511,
"text": "Firefox"
},
{
"code": null,
"e": 34525,
"s": 34519,
"text": "Opera"
},
{
"code": null,
"e": 34532,
"s": 34525,
"text": "Safari"
},
{
"code": null,
"e": 34669,
"s": 34532,
"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": 34681,
"s": 34669,
"text": "ysachin2314"
},
{
"code": null,
"e": 34693,
"s": 34681,
"text": "sahilintern"
},
{
"code": null,
"e": 34705,
"s": 34693,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 34715,
"s": 34705,
"text": "Bootstrap"
},
{
"code": null,
"e": 34720,
"s": 34715,
"text": "HTML"
},
{
"code": null,
"e": 34725,
"s": 34720,
"text": "HTML"
},
{
"code": null,
"e": 34823,
"s": 34725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34873,
"s": 34823,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 34902,
"s": 34873,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 34943,
"s": 34902,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 34999,
"s": 34943,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 35040,
"s": 34999,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 35090,
"s": 35040,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35152,
"s": 35090,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35200,
"s": 35152,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35260,
"s": 35200,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Binary number to decimal number | Practice | GeeksforGeeks
|
Given a Binary Number B, find its decimal equivalent.
Example 1:
Input: B = 10001000
Output: 136
Example 2:
Input: B = 101100
Output: 44
Your Task:
You don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.
Expected Time Complexity: O(K * Log(K)) where K is number of bits in binary number.
Expected Space Complexity: O(1)
Constraints:
1 <= number of bits in binary number <= 16
0
bucephalus370Premium1 week ago
public int binary_to_decimal(String str) { // Code here int sum = 0; int j = 0; for (int i = str.length()-1; i>=0; i--){ int a = Character.getNumericValue(str.charAt(i)); sum += a*Math.pow(2,j); j++; } return sum; }
0
moonchild3263 weeks ago
def binary_to_decimal(self, str): # Code here return int(str,2)
0
siddharthkumar08071 month ago
int binary_to_decimal(string str) { int base = 1; int ans = 0; int size = str.length()-1; for(int i = size; i >= 0; i--) { ans += ((int)(str[i]-'0')*base); base = base * 2; } return ans; }
0
soham0071 month ago
int binary_to_decimal(string str)
{
// Code here.
int dec =0;
int len = str.length();
for(int i=0;i<len;i++){
if(str[i]=='1') {
dec += pow(2,len-i-1);
}
}
return dec;
}
0
dell94591 month ago
Java: public int binary_to_decimal(String str) { // Code here return Integer.parseInt(str,2); }
0
anushavennapoosa20022 months ago
class Solution{ public int binary_to_decimal(String str) { // Code here int t=Integer.parseInt(str,2); return t; }}
0
bhanujggandhi2 months ago
// Idea is to iterate the string char one by one and check if it is 1 then we have to add appropriate power of 2 in the answer.
/*
1. Iterate over the string from any side, lets say from left until we reach the end.
2. If char at i is 1 then add 2^len-i-1 to the ans
3. Increment i;
4. Go to step 2.
*/
int binary_to_decimal(string str)
{
int len = str.length();
int decimal = 0;
for(int i=0; i<len;i++) {
if(str[i]=='1')
decimal = decimal + pow(2, len - i - 1);
}
return decimal;
}
+1
ashmeetsingh78012 months ago
int binary_to_decimal(string str) { int n=str.length(); int m=n-1; int ans=0; for(int i=0;i<str.length();i++) { if(str[i]=='1') { ans=ans+ pow(2,m); } m--; } return ans; }
+1
sana119038632 months ago
JAVA
class Solution
{
public int binary_to_decimal(String str)
{
// Code here
int sum =0,power=0;
StringBuilder x = new StringBuilder(str);
StringBuilder y = x.reverse();
for(int i=0;i<y.length();i++){
if(y.charAt(i)=='1'){
power = (int) Math.pow(2,i);
sum = sum + power;
}
}
return sum;
}
}
+1
dwarampudi119049212 months ago
JAVA
class Solution
{
public int binary_to_decimal(String str)
{
int z=0;
int i=0;
int x = str.length()-1;
while(x>=0) {
char s = str.charAt(x);
z+=Integer.parseInt(Character.toString(s))*(int)Math.pow(2,i);
x--;
i++;
}
return z;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 294,
"s": 238,
"text": "Given a Binary Number B, find its decimal equivalent.\n "
},
{
"code": null,
"e": 305,
"s": 294,
"text": "Example 1:"
},
{
"code": null,
"e": 338,
"s": 305,
"text": "Input: B = 10001000\nOutput: 136\n"
},
{
"code": null,
"e": 349,
"s": 338,
"text": "Example 2:"
},
{
"code": null,
"e": 379,
"s": 349,
"text": "Input: B = 101100\nOutput: 44\n"
},
{
"code": null,
"e": 586,
"s": 381,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function binary_to_decimal() which takes the binary number as string input parameter and returns its decimal equivalent.\n "
},
{
"code": null,
"e": 704,
"s": 586,
"text": "Expected Time Complexity: O(K * Log(K)) where K is number of bits in binary number.\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 761,
"s": 704,
"text": "Constraints:\n1 <= number of bits in binary number <= 16"
},
{
"code": null,
"e": 763,
"s": 761,
"text": "0"
},
{
"code": null,
"e": 794,
"s": 763,
"text": "bucephalus370Premium1 week ago"
},
{
"code": null,
"e": 1080,
"s": 794,
"text": "public int binary_to_decimal(String str) { // Code here int sum = 0; int j = 0; for (int i = str.length()-1; i>=0; i--){ int a = Character.getNumericValue(str.charAt(i)); sum += a*Math.pow(2,j); j++; } return sum; }"
},
{
"code": null,
"e": 1082,
"s": 1080,
"text": "0"
},
{
"code": null,
"e": 1106,
"s": 1082,
"text": "moonchild3263 weeks ago"
},
{
"code": null,
"e": 1170,
"s": 1106,
"text": "def binary_to_decimal(self, str): # Code here return int(str,2)"
},
{
"code": null,
"e": 1172,
"s": 1170,
"text": "0"
},
{
"code": null,
"e": 1202,
"s": 1172,
"text": "siddharthkumar08071 month ago"
},
{
"code": null,
"e": 1435,
"s": 1202,
"text": "int binary_to_decimal(string str) { int base = 1; int ans = 0; int size = str.length()-1; for(int i = size; i >= 0; i--) { ans += ((int)(str[i]-'0')*base); base = base * 2; } return ans; }"
},
{
"code": null,
"e": 1437,
"s": 1435,
"text": "0"
},
{
"code": null,
"e": 1457,
"s": 1437,
"text": "soham0071 month ago"
},
{
"code": null,
"e": 1708,
"s": 1457,
"text": "\tint binary_to_decimal(string str)\n\t\t{\n\t\t // Code here.\n\t\t int dec =0;\n\t\t int len = str.length();\n\t\t for(int i=0;i<len;i++){\n\t\t if(str[i]=='1') {\n\t\t dec += pow(2,len-i-1);\n\t\t }\n\t\t }\n\t\t \n\t\t return dec;\n\t\t}"
},
{
"code": null,
"e": 1710,
"s": 1708,
"text": "0"
},
{
"code": null,
"e": 1730,
"s": 1710,
"text": "dell94591 month ago"
},
{
"code": null,
"e": 1845,
"s": 1730,
"text": "Java: public int binary_to_decimal(String str) { // Code here return Integer.parseInt(str,2); }"
},
{
"code": null,
"e": 1847,
"s": 1845,
"text": "0"
},
{
"code": null,
"e": 1880,
"s": 1847,
"text": "anushavennapoosa20022 months ago"
},
{
"code": null,
"e": 2020,
"s": 1880,
"text": "class Solution{ public int binary_to_decimal(String str) { // Code here int t=Integer.parseInt(str,2); return t; }}"
},
{
"code": null,
"e": 2022,
"s": 2020,
"text": "0"
},
{
"code": null,
"e": 2048,
"s": 2022,
"text": "bhanujggandhi2 months ago"
},
{
"code": null,
"e": 2597,
"s": 2048,
"text": "// Idea is to iterate the string char one by one and check if it is 1 then we have to add appropriate power of 2 in the answer.\n/*\n1. Iterate over the string from any side, lets say from left until we reach the end.\n2. If char at i is 1 then add 2^len-i-1 to the ans\n3. Increment i;\n4. Go to step 2.\n*/\n\nint binary_to_decimal(string str)\n\t{\n\t\t int len = str.length();\n\t\t int decimal = 0;\n\t\t \n\t\t for(int i=0; i<len;i++) {\n\t\t if(str[i]=='1') \n\t\t decimal = decimal + pow(2, len - i - 1);\n\t\t }\n\t\t return decimal;\n\t}\n"
},
{
"code": null,
"e": 2600,
"s": 2597,
"text": "+1"
},
{
"code": null,
"e": 2629,
"s": 2600,
"text": "ashmeetsingh78012 months ago"
},
{
"code": null,
"e": 2941,
"s": 2629,
"text": "int binary_to_decimal(string str) { int n=str.length(); int m=n-1; int ans=0; for(int i=0;i<str.length();i++) { if(str[i]=='1') { ans=ans+ pow(2,m); } m--; } return ans; }"
},
{
"code": null,
"e": 2944,
"s": 2941,
"text": "+1"
},
{
"code": null,
"e": 2969,
"s": 2944,
"text": "sana119038632 months ago"
},
{
"code": null,
"e": 2974,
"s": 2969,
"text": "JAVA"
},
{
"code": null,
"e": 3398,
"s": 2976,
"text": "class Solution\n{\n public int binary_to_decimal(String str)\n {\n // Code here\n int sum =0,power=0;\n StringBuilder x = new StringBuilder(str);\n StringBuilder y = x.reverse();\n for(int i=0;i<y.length();i++){\n if(y.charAt(i)=='1'){\n power = (int) Math.pow(2,i); \n sum = sum + power;\n }\n }\n \n return sum;\n }\n}"
},
{
"code": null,
"e": 3403,
"s": 3400,
"text": "+1"
},
{
"code": null,
"e": 3434,
"s": 3403,
"text": "dwarampudi119049212 months ago"
},
{
"code": null,
"e": 3439,
"s": 3434,
"text": "JAVA"
},
{
"code": null,
"e": 3695,
"s": 3439,
"text": "class Solution\n{\n public int binary_to_decimal(String str)\n {\n int z=0;\n int i=0;\n int x = str.length()-1;\n while(x>=0) {\n char s = str.charAt(x);\n z+=Integer.parseInt(Character.toString(s))*(int)Math.pow(2,i);\n x--;\n i++;\n }\n return z;\n }\n}"
},
{
"code": null,
"e": 3841,
"s": 3695,
"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": 3877,
"s": 3841,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3887,
"s": 3877,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3897,
"s": 3887,
"text": "\nContest\n"
},
{
"code": null,
"e": 3960,
"s": 3897,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4108,
"s": 3960,
"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": 4316,
"s": 4108,
"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": 4422,
"s": 4316,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Find All Duplicate Subtrees - GeeksforGeeks
|
20 Nov, 2021
Given a binary tree, find all duplicate subtrees. For each duplicate subtree, we only need to return the root node of any one of them. Two trees are duplicates if they have the same structure with the same node values.Examples:
Input :
1
/ \
2 3
/ / \
4 2 4
/
4
Output :
2
/ and 4
4
Explanation: Above Trees are two duplicate subtrees.
Therefore, you need to return above trees root in the
form of a list.
The idea is to use hashing. We store inorder traversals of subtrees in a hash. Since simple inorder traversal cannot uniquely identify a tree, we use symbols like ‘(‘ and ‘)’ to represent NULL nodes. We pass an Unordered Map in C++ as an argument to the helper function which recursively calculates inorder string and increases its count in map. If any string gets repeated, then it will imply duplication of the subtree rooted at that node so push that node in the Final result and return the vector of these nodes.
C++
Java
Python3
C#
Javascript
// C++ program to find averages of all levels// in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int data; struct Node* left, *right;}; string inorder(Node* node, unordered_map<string, int>& m){ if (!node) return ""; string str = "("; str += inorder(node->left, m); str += to_string(node->data); str += inorder(node->right, m); str += ")"; // Subtree already present (Note that we use // unordered_map instead of unordered_set // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m[str] == 1) cout << node->data << " "; m[str]++; return str;} // Wrapper over inorder()void printAllDups(Node* root){ unordered_map<string, int> m; inorder(root, m);} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(2); root->right->left->left = newNode(4); root->right->right = newNode(4); printAllDups(root); return 0;}
// A java program to find all duplicate subtrees// in a binary tree.import java.util.HashMap;public class Duplicate_subtress { /* A binary tree node has data, pointer to left child and a pointer to right child */ static HashMap<String, Integer> m; static class Node { int data; Node left; Node right; Node(int data){ this.data = data; left = null; right = null; } } static String inorder(Node node) { if (node == null) return ""; String str = "("; str += inorder(node.left); str += Integer.toString(node.data); str += inorder(node.right); str += ")"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.get(str) != null && m.get(str)==1 ) System.out.print( node.data + " "); if (m.containsKey(str)) m.put(str, m.get(str) + 1); else m.put(str, 1); return str; } // Wrapper over inorder() static void printAllDups(Node root) { m = new HashMap<>(); inorder(root); } // Driver code public static void main(String args[]) { Node root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); }}// This code is contributed by Sumit Ghosh
# Python3 program to find averages of# all levels in a binary tree. # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None def inorder(node, m): if (not node): return "" Str = "(" Str += inorder(node.left, m) Str += str(node.data) Str += inorder(node.right, m) Str += ")" # Subtree already present (Note that # we use unordered_map instead of # unordered_set because we want to print # multiple duplicates only once, consider # example of 4 in above subtree, it # should be printed only once. if (Str in m and m[Str] == 1): print(node.data, end = " ") if Str in m: m[Str] += 1 else: m[Str] = 1 return Str # Wrapper over inorder()def printAllDups(root): m = {} inorder(root, m) # Driver codeif __name__ == '__main__': root = None root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(2) root.right.left.left = newNode(4) root.right.right = newNode(4) printAllDups(root) # This code is contributed by PranchalK
// A C# program to find all duplicate subtrees// in a binary tree.using System;using System.Collections.Generic; class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static Dictionary<String, int> m = new Dictionary<String, int>(); public class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; left = null; right = null; } } static String inorder(Node node) { if (node == null) return ""; String str = "("; str += inorder(node.left); str += (node.data).ToString(); str += inorder(node.right); str += ")"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.ContainsKey(str) && m[str] == 1 ) Console.Write(node.data + " "); if (m.ContainsKey(str)) m[str] = m[str] + 1; else m.Add(str, 1); return str; } // Wrapper over inorder() static void printAllDups(Node root) { m = new Dictionary<String, int>(); inorder(root); } // Driver code public static void Main(String []args) { Node root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); }} // This code is contributed by Princi Singh
<script> // A javascript program to find all duplicate subtrees // in a binary tree. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* A binary tree node has data, pointer to left child and a pointer to right child */ let m; function inorder(node) { if (node == null) return ""; let str = "("; str += inorder(node.left); str += toString(node.data); str += inorder(node.right); str += ")"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.get(str) != null && m.get(str)==1 ) document.write( node.data + " "); if (m.has(str)) m.set(str, m.get(str) + 1); else m.set(str, 1); return str; } // Wrapper over inorder() function printAllDups(root) { m = new Map(); inorder(root); } let root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); // This code is contributed by suresh07.</script>
Output:
4 2
Time Complexity: O(N^2) Since string copying takes O(n) extra time.
Auxiliary Space: O(N^2) Since we are hashing a string for each node and length of this string can be of the order N.If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
PranchalKatiyar
princi singh
rohitsingh07052
helloween123
suresh07
neminbshah
ankurk1947
cpp-unordered_map
Hash
Tree
Hash
Tree
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)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 37201,
"s": 37173,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 37430,
"s": 37201,
"text": "Given a binary tree, find all duplicate subtrees. For each duplicate subtree, we only need to return the root node of any one of them. Two trees are duplicates if they have the same structure with the same node values.Examples: "
},
{
"code": null,
"e": 37679,
"s": 37430,
"text": "Input :\n 1\n / \\\n 2 3\n / / \\\n 4 2 4\n /\n 4\n\nOutput : \n 2 \n / and 4\n 4\nExplanation: Above Trees are two duplicate subtrees. \nTherefore, you need to return above trees root in the \nform of a list."
},
{
"code": null,
"e": 38198,
"s": 37679,
"text": "The idea is to use hashing. We store inorder traversals of subtrees in a hash. Since simple inorder traversal cannot uniquely identify a tree, we use symbols like ‘(‘ and ‘)’ to represent NULL nodes. We pass an Unordered Map in C++ as an argument to the helper function which recursively calculates inorder string and increases its count in map. If any string gets repeated, then it will imply duplication of the subtree rooted at that node so push that node in the Final result and return the vector of these nodes. "
},
{
"code": null,
"e": 38202,
"s": 38198,
"text": "C++"
},
{
"code": null,
"e": 38207,
"s": 38202,
"text": "Java"
},
{
"code": null,
"e": 38215,
"s": 38207,
"text": "Python3"
},
{
"code": null,
"e": 38218,
"s": 38215,
"text": "C#"
},
{
"code": null,
"e": 38229,
"s": 38218,
"text": "Javascript"
},
{
"code": "// C++ program to find averages of all levels// in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int data; struct Node* left, *right;}; string inorder(Node* node, unordered_map<string, int>& m){ if (!node) return \"\"; string str = \"(\"; str += inorder(node->left, m); str += to_string(node->data); str += inorder(node->right, m); str += \")\"; // Subtree already present (Note that we use // unordered_map instead of unordered_set // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m[str] == 1) cout << node->data << \" \"; m[str]++; return str;} // Wrapper over inorder()void printAllDups(Node* root){ unordered_map<string, int> m; inorder(root, m);} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main(){ Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(2); root->right->left->left = newNode(4); root->right->right = newNode(4); printAllDups(root); return 0;}",
"e": 39683,
"s": 38229,
"text": null
},
{
"code": "// A java program to find all duplicate subtrees// in a binary tree.import java.util.HashMap;public class Duplicate_subtress { /* A binary tree node has data, pointer to left child and a pointer to right child */ static HashMap<String, Integer> m; static class Node { int data; Node left; Node right; Node(int data){ this.data = data; left = null; right = null; } } static String inorder(Node node) { if (node == null) return \"\"; String str = \"(\"; str += inorder(node.left); str += Integer.toString(node.data); str += inorder(node.right); str += \")\"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.get(str) != null && m.get(str)==1 ) System.out.print( node.data + \" \"); if (m.containsKey(str)) m.put(str, m.get(str) + 1); else m.put(str, 1); return str; } // Wrapper over inorder() static void printAllDups(Node root) { m = new HashMap<>(); inorder(root); } // Driver code public static void main(String args[]) { Node root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); }}// This code is contributed by Sumit Ghosh",
"e": 41441,
"s": 39683,
"text": null
},
{
"code": "# Python3 program to find averages of# all levels in a binary tree. # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None def inorder(node, m): if (not node): return \"\" Str = \"(\" Str += inorder(node.left, m) Str += str(node.data) Str += inorder(node.right, m) Str += \")\" # Subtree already present (Note that # we use unordered_map instead of # unordered_set because we want to print # multiple duplicates only once, consider # example of 4 in above subtree, it # should be printed only once. if (Str in m and m[Str] == 1): print(node.data, end = \" \") if Str in m: m[Str] += 1 else: m[Str] = 1 return Str # Wrapper over inorder()def printAllDups(root): m = {} inorder(root, m) # Driver codeif __name__ == '__main__': root = None root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(2) root.right.left.left = newNode(4) root.right.right = newNode(4) printAllDups(root) # This code is contributed by PranchalK",
"e": 42676,
"s": 41441,
"text": null
},
{
"code": "// A C# program to find all duplicate subtrees// in a binary tree.using System;using System.Collections.Generic; class GFG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static Dictionary<String, int> m = new Dictionary<String, int>(); public class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; left = null; right = null; } } static String inorder(Node node) { if (node == null) return \"\"; String str = \"(\"; str += inorder(node.left); str += (node.data).ToString(); str += inorder(node.right); str += \")\"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.ContainsKey(str) && m[str] == 1 ) Console.Write(node.data + \" \"); if (m.ContainsKey(str)) m[str] = m[str] + 1; else m.Add(str, 1); return str; } // Wrapper over inorder() static void printAllDups(Node root) { m = new Dictionary<String, int>(); inorder(root); } // Driver code public static void Main(String []args) { Node root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); }} // This code is contributed by Princi Singh",
"e": 44561,
"s": 42676,
"text": null
},
{
"code": "<script> // A javascript program to find all duplicate subtrees // in a binary tree. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* A binary tree node has data, pointer to left child and a pointer to right child */ let m; function inorder(node) { if (node == null) return \"\"; let str = \"(\"; str += inorder(node.left); str += toString(node.data); str += inorder(node.right); str += \")\"; // Subtree already present (Note that we use // HashMap instead of HashSet // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m.get(str) != null && m.get(str)==1 ) document.write( node.data + \" \"); if (m.has(str)) m.set(str, m.get(str) + 1); else m.set(str, 1); return str; } // Wrapper over inorder() function printAllDups(root) { m = new Map(); inorder(root); } let root = null; root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(2); root.right.left.left = new Node(4); root.right.right = new Node(4); printAllDups(root); // This code is contributed by suresh07.</script>",
"e": 46093,
"s": 44561,
"text": null
},
{
"code": null,
"e": 46102,
"s": 46093,
"text": "Output: "
},
{
"code": null,
"e": 46106,
"s": 46102,
"text": "4 2"
},
{
"code": null,
"e": 46175,
"s": 46106,
"text": "Time Complexity: O(N^2) Since string copying takes O(n) extra time."
},
{
"code": null,
"e": 46667,
"s": 46175,
"text": "Auxiliary Space: O(N^2) Since we are hashing a string for each node and length of this string can be of the order N.If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 46683,
"s": 46667,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 46696,
"s": 46683,
"text": "princi singh"
},
{
"code": null,
"e": 46712,
"s": 46696,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 46725,
"s": 46712,
"text": "helloween123"
},
{
"code": null,
"e": 46734,
"s": 46725,
"text": "suresh07"
},
{
"code": null,
"e": 46745,
"s": 46734,
"text": "neminbshah"
},
{
"code": null,
"e": 46756,
"s": 46745,
"text": "ankurk1947"
},
{
"code": null,
"e": 46774,
"s": 46756,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 46779,
"s": 46774,
"text": "Hash"
},
{
"code": null,
"e": 46784,
"s": 46779,
"text": "Tree"
},
{
"code": null,
"e": 46789,
"s": 46784,
"text": "Hash"
},
{
"code": null,
"e": 46794,
"s": 46789,
"text": "Tree"
},
{
"code": null,
"e": 46892,
"s": 46794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46977,
"s": 46892,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 47013,
"s": 46977,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 47044,
"s": 47013,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 47078,
"s": 47044,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 47114,
"s": 47078,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 47164,
"s": 47114,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 47193,
"s": 47164,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 47228,
"s": 47193,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 47262,
"s": 47228,
"text": "Level Order Binary Tree Traversal"
}
] |
C# | How to use strings in switch statement - GeeksforGeeks
|
23 Jan, 2019
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement.
Important points:
Switching on strings can be more costly in term of execution than switching on primitive data types. Therefore, it is good to switch on strings only in cases in which the controlling data is already in string form.
The comparison perform between String objects in switch statements is case sensitive.
You must use break statements in switch case.
Example 1:
// C# program to illustrate hwo to use// a string in switch statementusing System; class GFG { // Main Method static public void Main() { string str = "one"; // passing string "str" in // switch statement switch (str) { case "one": Console.WriteLine("It is 1"); break; case "two": Console.WriteLine("It is 2"); break; default: Console.WriteLine("Nothing"); break; } }}
Output:
It is 1
Example 2:
// C# program to illustrate hwo to use// a string in switch statementusing System; class GFG { // Main Method static public void Main() { string subject = "C#"; // passing string "subject" in // switch statement switch (subject) { case "Java": Console.WriteLine("Subject is Java"); break; case "C++": Console.WriteLine("Subject is C++"); break; default: Console.WriteLine("Subject is C#"); break; } }}
Output:
Subject is C#
CSharp-ControlFlow
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
Common Language Runtime (CLR) in C#
|
[
{
"code": null,
"e": 25435,
"s": 25407,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 25673,
"s": 25435,
"text": "The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement."
},
{
"code": null,
"e": 25691,
"s": 25673,
"text": "Important points:"
},
{
"code": null,
"e": 25906,
"s": 25691,
"text": "Switching on strings can be more costly in term of execution than switching on primitive data types. Therefore, it is good to switch on strings only in cases in which the controlling data is already in string form."
},
{
"code": null,
"e": 25992,
"s": 25906,
"text": "The comparison perform between String objects in switch statements is case sensitive."
},
{
"code": null,
"e": 26038,
"s": 25992,
"text": "You must use break statements in switch case."
},
{
"code": null,
"e": 26049,
"s": 26038,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate hwo to use// a string in switch statementusing System; class GFG { // Main Method static public void Main() { string str = \"one\"; // passing string \"str\" in // switch statement switch (str) { case \"one\": Console.WriteLine(\"It is 1\"); break; case \"two\": Console.WriteLine(\"It is 2\"); break; default: Console.WriteLine(\"Nothing\"); break; } }}",
"e": 26588,
"s": 26049,
"text": null
},
{
"code": null,
"e": 26596,
"s": 26588,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26596,
"text": "It is 1"
},
{
"code": null,
"e": 26615,
"s": 26604,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate hwo to use// a string in switch statementusing System; class GFG { // Main Method static public void Main() { string subject = \"C#\"; // passing string \"subject\" in // switch statement switch (subject) { case \"Java\": Console.WriteLine(\"Subject is Java\"); break; case \"C++\": Console.WriteLine(\"Subject is C++\"); break; default: Console.WriteLine(\"Subject is C#\"); break; } }}",
"e": 27187,
"s": 26615,
"text": null
},
{
"code": null,
"e": 27195,
"s": 27187,
"text": "Output:"
},
{
"code": null,
"e": 27210,
"s": 27195,
"text": "Subject is C#\n"
},
{
"code": null,
"e": 27229,
"s": 27210,
"text": "CSharp-ControlFlow"
},
{
"code": null,
"e": 27243,
"s": 27229,
"text": "CSharp-string"
},
{
"code": null,
"e": 27246,
"s": 27243,
"text": "C#"
},
{
"code": null,
"e": 27344,
"s": 27246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27359,
"s": 27344,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27381,
"s": 27359,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27404,
"s": 27381,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27426,
"s": 27404,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27466,
"s": 27426,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27497,
"s": 27466,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27513,
"s": 27497,
"text": "C# | Data Types"
},
{
"code": null,
"e": 27525,
"s": 27513,
"text": "C# | Arrays"
},
{
"code": null,
"e": 27553,
"s": 27525,
"text": "HashSet in C# with Examples"
}
] |
Difference between != and is not operator in Python - GeeksforGeeks
|
11 Dec, 2020
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If same, it returns False and if not same, it returns True. And is not operator returns True if operands on either side are not equal to each other, and returns false if they are equal.
Let us understand the concepts one by one:
Example 1:
Python3
a = 10b = 10 print(a is not b)print(id(a), id(b)) c = "Python"d = "Python"print(c is not d)print(id(c), id(d)) e = [1,2,3,4]f = [1,2,3,4]print(e is not f)print(id(e), id(f))
Output:
False
140733278626480 140733278626480
False
2693154698864 2693154698864
True
2693232342792 2693232342600
Explanation:
First with integer data the output was false because both the variables a, b are referring to same data 10.Second with string data the output was false because both the variables c, d are referring to same data “Python”.Third with list data the output was true because the variables e, f have different memory address.(Even though the both variable have the same data)
First with integer data the output was false because both the variables a, b are referring to same data 10.
Second with string data the output was false because both the variables c, d are referring to same data “Python”.
Third with list data the output was true because the variables e, f have different memory address.(Even though the both variable have the same data)
Example 2:
!= is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
Python3
# Python3 code to # illustrate the # difference between# != and is operator a = 10b = 10print(a != b)print(id(a), id(b)) c = "Python"d = "Python"print(c != d)print(id(c), id(d)) e = [ 1, 2, 3, 4]f=[ 1, 2, 3, 4]print(e != f)print(id(e), id(f))
Output:
False
140733278626480 140733278626480
False
2693154698864 2693154698864
False
2693232369224 2693232341064
Example 3:
The != operator compares the value or equality of two objects, whereas the Python is not operator checks whether two variables point to the same object in memory.
Python3
# Python3 code to # illustrate the # difference between# != and is not operator# [] is an empty listlist1 = []list2 = []list3 = list1 #First ifif (list1 != list2): print(" First if Condition True")else: print("First else Condition False") #Second ifif (list1 is not list2): print("Second if Condition True")else: print("Second else Condition False") #Third ifif (list1 is not list3): print("Third if Condition True")else: print("Third else Condition False") list3 = list3 + list2 #Fourth ifif (list1 is not list3): print("Fourth if Condition True")else: print("Fourth else Condition False")
Output:
First else Condition False
Second if Condition True
Third else Condition False
Fourth if Condition True
Explanation:
The output of the first if the condition is “False” as both list1 and list2 are empty lists.Second if the condition shows “True” because two empty lists are at different memory locations. Hence list1 and list2 refer to different objects. We can check it with id() function in python which returns the “identity” of an object.The output of the third if the condition is “False” as both list1 and list3 are pointing to the same object.The output of the fourth if the condition is “True” because the concatenation of two lists always produces a new list.
The output of the first if the condition is “False” as both list1 and list2 are empty lists.
Second if the condition shows “True” because two empty lists are at different memory locations. Hence list1 and list2 refer to different objects. We can check it with id() function in python which returns the “identity” of an object.
The output of the third if the condition is “False” as both list1 and list3 are pointing to the same object.
The output of the fourth if the condition is “True” because the concatenation of two lists always produces a new list.
Python-Operators
Difference Between
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Process and Thread
Difference Between Spark DataFrame and Pandas DataFrame
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24402,
"s": 24374,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24885,
"s": 24402,
"text": "In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If same, it returns False and if not same, it returns True. And is not operator returns True if operands on either side are not equal to each other, and returns false if they are equal."
},
{
"code": null,
"e": 24928,
"s": 24885,
"text": "Let us understand the concepts one by one:"
},
{
"code": null,
"e": 24939,
"s": 24928,
"text": "Example 1:"
},
{
"code": null,
"e": 24947,
"s": 24939,
"text": "Python3"
},
{
"code": "a = 10b = 10 print(a is not b)print(id(a), id(b)) c = \"Python\"d = \"Python\"print(c is not d)print(id(c), id(d)) e = [1,2,3,4]f = [1,2,3,4]print(e is not f)print(id(e), id(f))",
"e": 25124,
"s": 24947,
"text": null
},
{
"code": null,
"e": 25132,
"s": 25124,
"text": "Output:"
},
{
"code": null,
"e": 25237,
"s": 25132,
"text": "False\n140733278626480 140733278626480\nFalse\n2693154698864 2693154698864\nTrue\n2693232342792 2693232342600"
},
{
"code": null,
"e": 25250,
"s": 25237,
"text": "Explanation:"
},
{
"code": null,
"e": 25619,
"s": 25250,
"text": "First with integer data the output was false because both the variables a, b are referring to same data 10.Second with string data the output was false because both the variables c, d are referring to same data “Python”.Third with list data the output was true because the variables e, f have different memory address.(Even though the both variable have the same data)"
},
{
"code": null,
"e": 25727,
"s": 25619,
"text": "First with integer data the output was false because both the variables a, b are referring to same data 10."
},
{
"code": null,
"e": 25841,
"s": 25727,
"text": "Second with string data the output was false because both the variables c, d are referring to same data “Python”."
},
{
"code": null,
"e": 25990,
"s": 25841,
"text": "Third with list data the output was true because the variables e, f have different memory address.(Even though the both variable have the same data)"
},
{
"code": null,
"e": 26001,
"s": 25990,
"text": "Example 2:"
},
{
"code": null,
"e": 26152,
"s": 26001,
"text": " != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. "
},
{
"code": null,
"e": 26160,
"s": 26152,
"text": "Python3"
},
{
"code": "# Python3 code to # illustrate the # difference between# != and is operator a = 10b = 10print(a != b)print(id(a), id(b)) c = \"Python\"d = \"Python\"print(c != d)print(id(c), id(d)) e = [ 1, 2, 3, 4]f=[ 1, 2, 3, 4]print(e != f)print(id(e), id(f))",
"e": 26406,
"s": 26160,
"text": null
},
{
"code": null,
"e": 26414,
"s": 26406,
"text": "Output:"
},
{
"code": null,
"e": 26520,
"s": 26414,
"text": "False\n140733278626480 140733278626480\nFalse\n2693154698864 2693154698864\nFalse\n2693232369224 2693232341064"
},
{
"code": null,
"e": 26531,
"s": 26520,
"text": "Example 3:"
},
{
"code": null,
"e": 26694,
"s": 26531,
"text": "The != operator compares the value or equality of two objects, whereas the Python is not operator checks whether two variables point to the same object in memory."
},
{
"code": null,
"e": 26702,
"s": 26694,
"text": "Python3"
},
{
"code": "# Python3 code to # illustrate the # difference between# != and is not operator# [] is an empty listlist1 = []list2 = []list3 = list1 #First ifif (list1 != list2): print(\" First if Condition True\")else: print(\"First else Condition False\") #Second ifif (list1 is not list2): print(\"Second if Condition True\")else: print(\"Second else Condition False\") #Third ifif (list1 is not list3): print(\"Third if Condition True\")else: print(\"Third else Condition False\") list3 = list3 + list2 #Fourth ifif (list1 is not list3): print(\"Fourth if Condition True\")else: print(\"Fourth else Condition False\")",
"e": 27333,
"s": 26702,
"text": null
},
{
"code": null,
"e": 27341,
"s": 27333,
"text": "Output:"
},
{
"code": null,
"e": 27445,
"s": 27341,
"text": "First else Condition False\nSecond if Condition True\nThird else Condition False\nFourth if Condition True"
},
{
"code": null,
"e": 27458,
"s": 27445,
"text": "Explanation:"
},
{
"code": null,
"e": 28010,
"s": 27458,
"text": "The output of the first if the condition is “False” as both list1 and list2 are empty lists.Second if the condition shows “True” because two empty lists are at different memory locations. Hence list1 and list2 refer to different objects. We can check it with id() function in python which returns the “identity” of an object.The output of the third if the condition is “False” as both list1 and list3 are pointing to the same object.The output of the fourth if the condition is “True” because the concatenation of two lists always produces a new list."
},
{
"code": null,
"e": 28103,
"s": 28010,
"text": "The output of the first if the condition is “False” as both list1 and list2 are empty lists."
},
{
"code": null,
"e": 28337,
"s": 28103,
"text": "Second if the condition shows “True” because two empty lists are at different memory locations. Hence list1 and list2 refer to different objects. We can check it with id() function in python which returns the “identity” of an object."
},
{
"code": null,
"e": 28446,
"s": 28337,
"text": "The output of the third if the condition is “False” as both list1 and list3 are pointing to the same object."
},
{
"code": null,
"e": 28565,
"s": 28446,
"text": "The output of the fourth if the condition is “True” because the concatenation of two lists always produces a new list."
},
{
"code": null,
"e": 28582,
"s": 28565,
"text": "Python-Operators"
},
{
"code": null,
"e": 28601,
"s": 28582,
"text": "Difference Between"
},
{
"code": null,
"e": 28608,
"s": 28601,
"text": "Python"
},
{
"code": null,
"e": 28706,
"s": 28608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28715,
"s": 28706,
"text": "Comments"
},
{
"code": null,
"e": 28728,
"s": 28715,
"text": "Old Comments"
},
{
"code": null,
"e": 28766,
"s": 28728,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 28822,
"s": 28766,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 28883,
"s": 28822,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28951,
"s": 28883,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 29004,
"s": 28951,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 29032,
"s": 29004,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29082,
"s": 29032,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29104,
"s": 29082,
"text": "Python map() function"
}
] |
How to Close a Tkinter Window With a Button? - GeeksforGeeks
|
17 Dec, 2020
Prerequisites: Tkinter
Python’s Tkinter module offers the Button function to create a button in a Tkinter Window to execute any task once the button is clicked. The task can be assigned in the command parameter of Button() function. Given below are various methods by which this can be achieved.
Approach:
Import tkinter module.
Create a main window named root.
Add a button.
Assign root.destroy to the command attribute of that button.
Example: Using destroy() directly in command attribute
Python3
# Python program to create a close button# using destroy Non-Class methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry("200x100") # Button for closingexit_button = Button(root, text="Exit", command=root.destroy)exit_button.pack(pady=20) root.mainloop()
Example: Using destroy() in a function
Python3
# Python program to create a close button# using destroy Non-Class methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry("200x100") # Function for closing window def Close(): root.destroy() # Button for closingexit_button = Button(root, text="Exit", command=Close)exit_button.pack(pady=20) root.mainloop()
Output:
Approach:
Import tkinter module.
Create a tkinter window class.
Create a main window named root.
Add a button.
Assign root.destroy to the command attribute of that button.
Example: Using destroy() directly in command attribute
Python3
# Python program to create a close button# using destroy Class methodfrom tkinter import * # Class for tkinter window class Window(): def __init__(self): # Creating the tkinter Window self.root = Tk() self.root.geometry("200x100") # Button for closing exit_button = Button(self.root, text="Exit", command=self.root.destroy) exit_button.pack(pady=20) self.root.mainloop() # Running test windowtest = Window()
Example: Using destroy() in a function
Python3
# Python program to create a close button# using destroy Class methodfrom tkinter import * # Class for tkinter window class Window(): def __init__(self): # Creating the tkinter Window self.root = Tk() self.root.geometry("200x100") # Button for closing exit_button = Button(self.root, text="Exit", command=self.Close) exit_button.pack(pady=20) self.root.mainloop() # Function for closing window def Close(self): self.root.destroy() # Running test windowtest = Window()
Output:
This method doesn’t work properly if you’re calling your Tkinter app from IDLE as quit() will terminate the whole TCL interpreter and cause the mainloop to exit leaving all the widgets intact. So, it is better to use quit() if you’re using any other editor/interpreter other than IDLE. Or, you can use exit() function after mainloop to exit from the Python program.
It is not recommended to use quit() if your Tkinter application is executed from IDLE as it will close the interpreter leaving the program running with all its widgets. It is also mainly not recommended because it may fail in some interpreters.
Approach:
Import tkinter module.
Create a main window named root.
Add a button.
Assign root.quit to the command attribute of that button.
Add exit() function after calling the mainloop
Example:
Python3
# Python program to create a close button# using quit methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry("200x100") # Button for closingexit_button = Button(root, text="Exit", command=root.quit)exit_button.pack(pady=20) root.mainloop()exit(0)
Output:
Output in Normal Editor (VS Code)
Output in IDLE
Output in Jupyter Notebook
Picked
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25783,
"s": 25755,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 25806,
"s": 25783,
"text": "Prerequisites: Tkinter"
},
{
"code": null,
"e": 26079,
"s": 25806,
"text": "Python’s Tkinter module offers the Button function to create a button in a Tkinter Window to execute any task once the button is clicked. The task can be assigned in the command parameter of Button() function. Given below are various methods by which this can be achieved."
},
{
"code": null,
"e": 26089,
"s": 26079,
"text": "Approach:"
},
{
"code": null,
"e": 26112,
"s": 26089,
"text": "Import tkinter module."
},
{
"code": null,
"e": 26145,
"s": 26112,
"text": "Create a main window named root."
},
{
"code": null,
"e": 26159,
"s": 26145,
"text": "Add a button."
},
{
"code": null,
"e": 26220,
"s": 26159,
"text": "Assign root.destroy to the command attribute of that button."
},
{
"code": null,
"e": 26275,
"s": 26220,
"text": "Example: Using destroy() directly in command attribute"
},
{
"code": null,
"e": 26283,
"s": 26275,
"text": "Python3"
},
{
"code": "# Python program to create a close button# using destroy Non-Class methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry(\"200x100\") # Button for closingexit_button = Button(root, text=\"Exit\", command=root.destroy)exit_button.pack(pady=20) root.mainloop()",
"e": 26569,
"s": 26283,
"text": null
},
{
"code": null,
"e": 26608,
"s": 26569,
"text": "Example: Using destroy() in a function"
},
{
"code": null,
"e": 26616,
"s": 26608,
"text": "Python3"
},
{
"code": "# Python program to create a close button# using destroy Non-Class methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry(\"200x100\") # Function for closing window def Close(): root.destroy() # Button for closingexit_button = Button(root, text=\"Exit\", command=Close)exit_button.pack(pady=20) root.mainloop()",
"e": 26962,
"s": 26616,
"text": null
},
{
"code": null,
"e": 26970,
"s": 26962,
"text": "Output:"
},
{
"code": null,
"e": 26980,
"s": 26970,
"text": "Approach:"
},
{
"code": null,
"e": 27003,
"s": 26980,
"text": "Import tkinter module."
},
{
"code": null,
"e": 27034,
"s": 27003,
"text": "Create a tkinter window class."
},
{
"code": null,
"e": 27067,
"s": 27034,
"text": "Create a main window named root."
},
{
"code": null,
"e": 27081,
"s": 27067,
"text": "Add a button."
},
{
"code": null,
"e": 27142,
"s": 27081,
"text": "Assign root.destroy to the command attribute of that button."
},
{
"code": null,
"e": 27197,
"s": 27142,
"text": "Example: Using destroy() directly in command attribute"
},
{
"code": null,
"e": 27205,
"s": 27197,
"text": "Python3"
},
{
"code": "# Python program to create a close button# using destroy Class methodfrom tkinter import * # Class for tkinter window class Window(): def __init__(self): # Creating the tkinter Window self.root = Tk() self.root.geometry(\"200x100\") # Button for closing exit_button = Button(self.root, text=\"Exit\", command=self.root.destroy) exit_button.pack(pady=20) self.root.mainloop() # Running test windowtest = Window()",
"e": 27678,
"s": 27205,
"text": null
},
{
"code": null,
"e": 27717,
"s": 27678,
"text": "Example: Using destroy() in a function"
},
{
"code": null,
"e": 27725,
"s": 27717,
"text": "Python3"
},
{
"code": "# Python program to create a close button# using destroy Class methodfrom tkinter import * # Class for tkinter window class Window(): def __init__(self): # Creating the tkinter Window self.root = Tk() self.root.geometry(\"200x100\") # Button for closing exit_button = Button(self.root, text=\"Exit\", command=self.Close) exit_button.pack(pady=20) self.root.mainloop() # Function for closing window def Close(self): self.root.destroy() # Running test windowtest = Window()",
"e": 28273,
"s": 27725,
"text": null
},
{
"code": null,
"e": 28281,
"s": 28273,
"text": "Output:"
},
{
"code": null,
"e": 28647,
"s": 28281,
"text": "This method doesn’t work properly if you’re calling your Tkinter app from IDLE as quit() will terminate the whole TCL interpreter and cause the mainloop to exit leaving all the widgets intact. So, it is better to use quit() if you’re using any other editor/interpreter other than IDLE. Or, you can use exit() function after mainloop to exit from the Python program."
},
{
"code": null,
"e": 28893,
"s": 28647,
"text": "It is not recommended to use quit() if your Tkinter application is executed from IDLE as it will close the interpreter leaving the program running with all its widgets. It is also mainly not recommended because it may fail in some interpreters. "
},
{
"code": null,
"e": 28903,
"s": 28893,
"text": "Approach:"
},
{
"code": null,
"e": 28926,
"s": 28903,
"text": "Import tkinter module."
},
{
"code": null,
"e": 28959,
"s": 28926,
"text": "Create a main window named root."
},
{
"code": null,
"e": 28973,
"s": 28959,
"text": "Add a button."
},
{
"code": null,
"e": 29031,
"s": 28973,
"text": "Assign root.quit to the command attribute of that button."
},
{
"code": null,
"e": 29078,
"s": 29031,
"text": "Add exit() function after calling the mainloop"
},
{
"code": null,
"e": 29087,
"s": 29078,
"text": "Example:"
},
{
"code": null,
"e": 29095,
"s": 29087,
"text": "Python3"
},
{
"code": "# Python program to create a close button# using quit methodfrom tkinter import * # Creating the tkinter windowroot = Tk()root.geometry(\"200x100\") # Button for closingexit_button = Button(root, text=\"Exit\", command=root.quit)exit_button.pack(pady=20) root.mainloop()exit(0)",
"e": 29372,
"s": 29095,
"text": null
},
{
"code": null,
"e": 29380,
"s": 29372,
"text": "Output:"
},
{
"code": null,
"e": 29414,
"s": 29380,
"text": "Output in Normal Editor (VS Code)"
},
{
"code": null,
"e": 29429,
"s": 29414,
"text": "Output in IDLE"
},
{
"code": null,
"e": 29456,
"s": 29429,
"text": "Output in Jupyter Notebook"
},
{
"code": null,
"e": 29463,
"s": 29456,
"text": "Picked"
},
{
"code": null,
"e": 29478,
"s": 29463,
"text": "Python-tkinter"
},
{
"code": null,
"e": 29502,
"s": 29478,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29509,
"s": 29502,
"text": "Python"
},
{
"code": null,
"e": 29528,
"s": 29509,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29626,
"s": 29528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29644,
"s": 29626,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29679,
"s": 29644,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29711,
"s": 29679,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29733,
"s": 29711,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29775,
"s": 29733,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29805,
"s": 29775,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29831,
"s": 29805,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29860,
"s": 29831,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29904,
"s": 29860,
"text": "Reading and Writing to text files in Python"
}
] |
Top View of Binary Tree | Practice | GeeksforGeeks
|
Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
1
/ \
2 3
/ \ / \
4 5 6 7
Top view will be: 4 2 1 3 7
Note: Return nodes from leftmost node to rightmost node.
Example 1:
Input:
1
/ \
2 3
Output: 2 1 3
Example 2:
Input:
10
/ \
20 30
/ \ / \
40 60 90 100
Output: 40 20 10 30 100
Your Task:
Since this is a function problem. You don't have to take input. Just complete the function topView() that takes root node as parameter and returns a list of nodes visible from the top view from left to right.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 105
1 ≤ Node Data ≤ 105
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
rmn51243 days ago
vector<int> topView(Node *root)
{
queue<pair<Node*,int>>q; //node,level
map<int,int>m; //level,verticle
q.push({root,0});
while(!q.empty()){
auto f=q.front();
q.pop();
auto node=f.first;
int x=f.second;
if(m.find(x)==m.end())
m[x]=node->data; // only insert if its first vertical i.e only diff from bottom view
if(node->left) q.push({node->left,x-1});
if(node->right)
q.push({node->right,x+1});
}
vector<int>v;
for(auto i:m){
v.push_back(i.second); // insert value
}
return v;
}
+1
jeffprivate03136 days ago
Runs in 0.05, simple solution.
global: vector<pair<int,int>> a;
void tr(Node * n, int level,int pos) { if(n==NULL){ return; } if(a[pos].first==0){//initialize a[pos]=make_pair(n->data, level);//switch }else if(a[pos].first!=0){ if(level<a[pos].second){//higher, will cover the old node a[pos]=make_pair(n->data,level); } } tr(n->left, level+1, pos-1);//go to left node, level+1,position-1 tr(n->right, level+1, pos+1);//same } vector<int> topView(Node *root) { a.clear();//clear since global vector for(int g=0;g<20002;g++){ a.push_back({0,20000});//value and level, we initialize since we note all data are 1≤data≤10000. } tr(root,0,10000);//traverse with position 10000 since we don't want to die from negative numbers vector<int>final={};//just solution vector for(int i=0;i<20002;i++){//look from left to right if(a[i].first!=0){//if initialized final.push_back(a[i].first);//include } } return final; }
0
jainmuskan5651 week ago
vector<int> topView(Node *root) { // we are going to use queue and map // line traversal where root is zero, left is -1 and right is +1 // base case vector<int> res; if(root==NULL){ return res; } // first element of each line level is appended in map // queue is used to traverse all the nodes map<int,int> linemap; queue<pair<Node*,int>> q; q.push({root,0}); linemap[0]=root->data; while(!q.empty()){ auto it= q.front(); q.pop(); int line= it.second; Node * n= it.first; if(linemap.find(line)==linemap.end()){ linemap[line]= n->data; } // now traverse the left and right nodes if(n->left){ q.push({n->left, line-1}); } if(n->right){ q.push({n->right, line+1}); } } for(auto i:linemap){ res.push_back(i.second); } return res; }
0
rohanmeher1641 week ago
//Java solution
class Solution{ static ArrayList<Integer> topView(Node root) { ArrayList<Integer> list=new ArrayList<Integer>(); if(root==null) return list; Queue<Pair> q=new LinkedList<Pair>(); Map<Integer,Integer> m= new TreeMap<Integer,Integer>(); q.add(new Pair(0,root)); m.put(0,root.data); while(!q.isEmpty()) { Pair c=q.poll(); if(!m.containsKey(c.hd)) m.put(c.hd,c.node.data); if(c.node.left!=null) { q.add(new Pair(c.hd-1,c.node.left)); } if(c.node.right!=null) { q.add(new Pair(c.hd+1,c.node.right)); } } for(Map.Entry<Integer,Integer> e:m.entrySet()) list.add(e.getValue()); return list; } } class Pair { int hd; Node node; public Pair(int h,Node n) { hd=h; node=n; } }
+1
devangrao251 week ago
C++ || Easy || O(n)
vector<int> topView(Node *root) {
//vertical order traversal code with modification unordered_map<int, int> mp; queue<pair<Node*, int>> q; q.push({root, 0}); int mn = 0, mx = 0; while(!q.empty()) //simple level order traversal { pair<Node*, int> p = q.front(); q.pop(); int hd = p.second; Node* t = p.first;
//we store only first node of each Horizontal dist if(mp.count(hd) == 0) mp[hd] = (t->data); if(t->left) //for left child=> hd is hd(root) - 1; q.push({t->left, hd - 1}); if(t->right) q.push({t->right, hd + 1}); mn = min(mn, hd); mx = max(mx, hd); } vector<int> ans; for(int i = mn; i <= mx; i++) //for hd to be in order { ans.push_back(mp[i]); //directly print as we stored only first node of each hd } return ans; }
0
tirtha19025681 week ago
class Solution
{
static ArrayList<Integer> topView(Node root)
{
if(root == null) return null;
ArrayList<Integer>ans = new ArrayList<>();
topView(root,ans);
return ans;
}
static class pair{
int dist;
Node node;
pair(int dist,Node node){
this.node = node;
this.dist = dist;
}
}
static void topView(Node root,ArrayList<Integer>ans) {
if(root == null) return;
Map<Integer,Integer>map = new TreeMap<>();
Queue<pair>q = new LinkedList<>();
q.add(new pair(0,root));
while(!q.isEmpty()) {
pair curr = q.poll();
map.putIfAbsent(curr.dist, curr.node.data);
if(curr.node.left != null) {
q.add(new pair(curr.dist-1,curr.node.left));
}
if(curr.node.right != null) {
q.add(new pair(curr.dist+1,curr.node.right));
}
}
for(Map.Entry<Integer, Integer>m:map.entrySet()) {
ans.add(m.getValue());
}
}
}
+2
badgujarsachin832 weeks ago
vector<int> topView(Node *root)
{
vector<int> v;
if(root==NULL){
return v;
}
queue<pair<Node*,int>> q;
int dis=0;
q.push({root,0});
map<int,int> mp;
while(!q.empty()){
int size=q.size();
for(int i=0;i<size;i++){
Node* temp=q.front().first;
int dis=q.front().second;
q.pop();
if(mp.find(dis)==mp.end()){
mp[dis]=temp->data;
}
if(temp->left){
q.push({temp->left,dis-1});
}
if(temp->right){
q.push({temp->right,dis+1});
}
}
}
for(auto it:mp){
v.push_back(it.second);
}
return v;
}
+1
kumkumjain6162 weeks ago
class Pair{
Node node;
int hd;
public Pair(Node node, int hd){
this.node = node;
this.hd = hd;
}
}
class Solution
{
static ArrayList<Integer> topView(Node root)
{
ArrayList<Integer> ans = new ArrayList<>();
TreeMap<Integer,Integer> map = new TreeMap<>();
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(root, 0));
while(! q.isEmpty()){
Pair pair = q.poll();
Node node = pair.node;
int hd = pair.hd;
if(map.get(hd) == null){
map.put(hd, node.data);
}
if(node.left != null)
q.offer(new Pair(node.left, hd-1));
if(node.right != null){
q.offer(new Pair(node.right, hd+1));
}
}
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
ans.add(entry.getValue());
}
return ans;
}
}
0
amit092 weeks ago
class Solution
{
map<int,pair<int,int>> myMap; //Map<width,pair<level,data>>
public:
//Function to return a list of nodes visible from the top view
//from left to right in Binary Tree.
void topView(Node* root, int width, int level)
{
if(!root) return;
auto iter = myMap.find(width) ;
if(iter == myMap.end() ){
myMap[width] = {level,root->data};
//cout<<width<< " "<<root->data<<endl;
} else {
if(iter->second.first > level){
myMap[width] = {level,root->data};
}
}
topView(root->left, width-1, level+1);
topView(root->right, width+1, level+1);
}
vector<int> topView(Node *root)
{
vector<int> retVec;
topView(root, 0, 1);
for(auto it : myMap){
retVec.push_back(it.second.second);
}
return retVec;
}
};
0
shilsoumyadip2 weeks ago
vector<int> topView(Node *root) { //Your code vector <int> bottomView(Node *root) { // Your Code Here map<int ,int>m; queue<pair <Node*, int>>q; vector<int>ans; if(!root) return ans; q.push({root,0}); while(!q.empty()) { Node* t = q.front().first; int h = q.front().second; q.pop(); if(!m[h]) m[h] = t-> data; if(t->left) q.push({t->left ,h-1}); if(t-> right) q.push({ t-> right , h+1}); } for(auto x:m) ans.push_back(x.second); return ans; }
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": 435,
"s": 238,
"text": "Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree"
},
{
"code": null,
"e": 499,
"s": 435,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n4 5 6 7"
},
{
"code": null,
"e": 584,
"s": 499,
"text": "Top view will be: 4 2 1 3 7\nNote: Return nodes from leftmost node to rightmost node."
},
{
"code": null,
"e": 595,
"s": 584,
"text": "Example 1:"
},
{
"code": null,
"e": 646,
"s": 595,
"text": "Input:\n 1\n / \\\n 2 3\nOutput: 2 1 3\n"
},
{
"code": null,
"e": 657,
"s": 646,
"text": "Example 2:"
},
{
"code": null,
"e": 763,
"s": 657,
"text": "Input:\n 10\n / \\\n 20 30\n / \\ / \\\n40 60 90 100\nOutput: 40 20 10 30 100\n"
},
{
"code": null,
"e": 983,
"s": 763,
"text": "Your Task:\nSince this is a function problem. You don't have to take input. Just complete the function topView() that takes root node as parameter and returns a list of nodes visible from the top view from left to right."
},
{
"code": null,
"e": 1046,
"s": 983,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1093,
"s": 1046,
"text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ Node Data ≤ 105\n "
},
{
"code": null,
"e": 1402,
"s": 1093,
"text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1404,
"s": 1402,
"text": "0"
},
{
"code": null,
"e": 1422,
"s": 1404,
"text": "rmn51243 days ago"
},
{
"code": null,
"e": 2134,
"s": 1422,
"text": "vector<int> topView(Node *root)\n {\n queue<pair<Node*,int>>q; //node,level\n map<int,int>m; //level,verticle\n q.push({root,0});\n while(!q.empty()){\n auto f=q.front();\n q.pop();\n auto node=f.first;\n int x=f.second;\n \n if(m.find(x)==m.end())\n m[x]=node->data; // only insert if its first vertical i.e only diff from bottom view\n \n if(node->left) q.push({node->left,x-1});\n if(node->right)\n q.push({node->right,x+1});\n }\n vector<int>v;\n for(auto i:m){\n v.push_back(i.second); // insert value\n }\n return v;\n }\n"
},
{
"code": null,
"e": 2137,
"s": 2134,
"text": "+1"
},
{
"code": null,
"e": 2163,
"s": 2137,
"text": "jeffprivate03136 days ago"
},
{
"code": null,
"e": 2194,
"s": 2163,
"text": "Runs in 0.05, simple solution."
},
{
"code": null,
"e": 2227,
"s": 2194,
"text": "global: vector<pair<int,int>> a;"
},
{
"code": null,
"e": 3276,
"s": 2227,
"text": " void tr(Node * n, int level,int pos) { if(n==NULL){ return; } if(a[pos].first==0){//initialize a[pos]=make_pair(n->data, level);//switch }else if(a[pos].first!=0){ if(level<a[pos].second){//higher, will cover the old node a[pos]=make_pair(n->data,level); } } tr(n->left, level+1, pos-1);//go to left node, level+1,position-1 tr(n->right, level+1, pos+1);//same } vector<int> topView(Node *root) { a.clear();//clear since global vector for(int g=0;g<20002;g++){ a.push_back({0,20000});//value and level, we initialize since we note all data are 1≤data≤10000. } tr(root,0,10000);//traverse with position 10000 since we don't want to die from negative numbers vector<int>final={};//just solution vector for(int i=0;i<20002;i++){//look from left to right if(a[i].first!=0){//if initialized final.push_back(a[i].first);//include } } return final; }"
},
{
"code": null,
"e": 3280,
"s": 3278,
"text": "0"
},
{
"code": null,
"e": 3304,
"s": 3280,
"text": "jainmuskan5651 week ago"
},
{
"code": null,
"e": 4321,
"s": 3304,
"text": "vector<int> topView(Node *root) { // we are going to use queue and map // line traversal where root is zero, left is -1 and right is +1 // base case vector<int> res; if(root==NULL){ return res; } // first element of each line level is appended in map // queue is used to traverse all the nodes map<int,int> linemap; queue<pair<Node*,int>> q; q.push({root,0}); linemap[0]=root->data; while(!q.empty()){ auto it= q.front(); q.pop(); int line= it.second; Node * n= it.first; if(linemap.find(line)==linemap.end()){ linemap[line]= n->data; } // now traverse the left and right nodes if(n->left){ q.push({n->left, line-1}); } if(n->right){ q.push({n->right, line+1}); } } for(auto i:linemap){ res.push_back(i.second); } return res; }"
},
{
"code": null,
"e": 4323,
"s": 4321,
"text": "0"
},
{
"code": null,
"e": 4347,
"s": 4323,
"text": "rohanmeher1641 week ago"
},
{
"code": null,
"e": 4363,
"s": 4347,
"text": "//Java solution"
},
{
"code": null,
"e": 5393,
"s": 4367,
"text": "class Solution{ static ArrayList<Integer> topView(Node root) { ArrayList<Integer> list=new ArrayList<Integer>(); if(root==null) return list; Queue<Pair> q=new LinkedList<Pair>(); Map<Integer,Integer> m= new TreeMap<Integer,Integer>(); q.add(new Pair(0,root)); m.put(0,root.data); while(!q.isEmpty()) { Pair c=q.poll(); if(!m.containsKey(c.hd)) m.put(c.hd,c.node.data); if(c.node.left!=null) { q.add(new Pair(c.hd-1,c.node.left)); } if(c.node.right!=null) { q.add(new Pair(c.hd+1,c.node.right)); } } for(Map.Entry<Integer,Integer> e:m.entrySet()) list.add(e.getValue()); return list; } } class Pair { int hd; Node node; public Pair(int h,Node n) { hd=h; node=n; } } "
},
{
"code": null,
"e": 5396,
"s": 5393,
"text": "+1"
},
{
"code": null,
"e": 5418,
"s": 5396,
"text": "devangrao251 week ago"
},
{
"code": null,
"e": 5439,
"s": 5418,
"text": "C++ || Easy || O(n) "
},
{
"code": null,
"e": 5477,
"s": 5441,
"text": "vector<int> topView(Node *root) {"
},
{
"code": null,
"e": 5864,
"s": 5477,
"text": " //vertical order traversal code with modification unordered_map<int, int> mp; queue<pair<Node*, int>> q; q.push({root, 0}); int mn = 0, mx = 0; while(!q.empty()) //simple level order traversal { pair<Node*, int> p = q.front(); q.pop(); int hd = p.second; Node* t = p.first; "
},
{
"code": null,
"e": 6491,
"s": 5864,
"text": " //we store only first node of each Horizontal dist if(mp.count(hd) == 0) mp[hd] = (t->data); if(t->left) //for left child=> hd is hd(root) - 1; q.push({t->left, hd - 1}); if(t->right) q.push({t->right, hd + 1}); mn = min(mn, hd); mx = max(mx, hd); } vector<int> ans; for(int i = mn; i <= mx; i++) //for hd to be in order { ans.push_back(mp[i]); //directly print as we stored only first node of each hd } return ans; }"
},
{
"code": null,
"e": 6493,
"s": 6491,
"text": "0"
},
{
"code": null,
"e": 6517,
"s": 6493,
"text": "tirtha19025681 week ago"
},
{
"code": null,
"e": 7383,
"s": 6517,
"text": "\nclass Solution\n{\n static ArrayList<Integer> topView(Node root)\n {\n if(root == null) return null;\n ArrayList<Integer>ans = new ArrayList<>();\n topView(root,ans);\n return ans;\n \n }\n \nstatic class pair{\n int dist;\n Node node;\n pair(int dist,Node node){\n this.node = node;\n this.dist = dist;\n }\n}\n\nstatic void topView(Node root,ArrayList<Integer>ans) {\n if(root == null) return;\nMap<Integer,Integer>map = new TreeMap<>();\nQueue<pair>q = new LinkedList<>();\nq.add(new pair(0,root));\n\nwhile(!q.isEmpty()) {\n pair curr = q.poll();\n map.putIfAbsent(curr.dist, curr.node.data);\n if(curr.node.left != null) {\n q.add(new pair(curr.dist-1,curr.node.left));\n }\n if(curr.node.right != null) {\n q.add(new pair(curr.dist+1,curr.node.right));\n }\n}\n\nfor(Map.Entry<Integer, Integer>m:map.entrySet()) {\n ans.add(m.getValue());\n}\n \n}\n\n \n}"
},
{
"code": null,
"e": 7386,
"s": 7383,
"text": "+2"
},
{
"code": null,
"e": 7414,
"s": 7386,
"text": "badgujarsachin832 weeks ago"
},
{
"code": null,
"e": 8233,
"s": 7414,
"text": "vector<int> topView(Node *root)\n {\n vector<int> v;\n if(root==NULL){\n return v;\n }\n queue<pair<Node*,int>> q;\n int dis=0;\n q.push({root,0});\n map<int,int> mp;\n while(!q.empty()){\n int size=q.size();\n for(int i=0;i<size;i++){\n Node* temp=q.front().first;\n int dis=q.front().second;\n q.pop();\n\n if(mp.find(dis)==mp.end()){\n mp[dis]=temp->data;\n }\n if(temp->left){\n q.push({temp->left,dis-1});\n }\n if(temp->right){\n q.push({temp->right,dis+1});\n }\n }\n }\n for(auto it:mp){\n v.push_back(it.second);\n }\n return v;\n }\n"
},
{
"code": null,
"e": 8236,
"s": 8233,
"text": "+1"
},
{
"code": null,
"e": 8261,
"s": 8236,
"text": "kumkumjain6162 weeks ago"
},
{
"code": null,
"e": 9264,
"s": 8261,
"text": "class Pair{\n Node node;\n int hd;\n \n public Pair(Node node, int hd){\n this.node = node;\n this.hd = hd;\n }\n}\nclass Solution\n{\n static ArrayList<Integer> topView(Node root)\n {\n ArrayList<Integer> ans = new ArrayList<>();\n TreeMap<Integer,Integer> map = new TreeMap<>();\n \n Queue<Pair> q = new LinkedList<>();\n \n q.add(new Pair(root, 0));\n \n while(! q.isEmpty()){\n Pair pair = q.poll();\n \n Node node = pair.node;\n int hd = pair.hd;\n \n if(map.get(hd) == null){\n map.put(hd, node.data);\n }\n \n if(node.left != null)\n q.offer(new Pair(node.left, hd-1));\n \n if(node.right != null){\n q.offer(new Pair(node.right, hd+1));\n }\n }\n \n for(Map.Entry<Integer, Integer> entry : map.entrySet()){\n ans.add(entry.getValue());\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 9266,
"s": 9264,
"text": "0"
},
{
"code": null,
"e": 9284,
"s": 9266,
"text": "amit092 weeks ago"
},
{
"code": null,
"e": 10227,
"s": 9284,
"text": "class Solution\n{\n map<int,pair<int,int>> myMap; //Map<width,pair<level,data>>\n public:\n //Function to return a list of nodes visible from the top view \n //from left to right in Binary Tree.\n void topView(Node* root, int width, int level)\n {\n if(!root) return;\n auto iter = myMap.find(width) ;\n if(iter == myMap.end() ){\n myMap[width] = {level,root->data};\n //cout<<width<< \" \"<<root->data<<endl;\n } else {\n if(iter->second.first > level){\n myMap[width] = {level,root->data};\n }\n }\n \n topView(root->left, width-1, level+1);\n topView(root->right, width+1, level+1);\n }\n vector<int> topView(Node *root)\n {\n vector<int> retVec;\n topView(root, 0, 1);\n \n for(auto it : myMap){\n retVec.push_back(it.second.second);\n }\n \n return retVec;\n }\n\n};\n"
},
{
"code": null,
"e": 10229,
"s": 10227,
"text": "0"
},
{
"code": null,
"e": 10254,
"s": 10229,
"text": "shilsoumyadip2 weeks ago"
},
{
"code": null,
"e": 10870,
"s": 10254,
"text": "vector<int> topView(Node *root) { //Your code vector <int> bottomView(Node *root) { // Your Code Here map<int ,int>m; queue<pair <Node*, int>>q; vector<int>ans; if(!root) return ans; q.push({root,0}); while(!q.empty()) { Node* t = q.front().first; int h = q.front().second; q.pop(); if(!m[h]) m[h] = t-> data; if(t->left) q.push({t->left ,h-1}); if(t-> right) q.push({ t-> right , h+1}); } for(auto x:m) ans.push_back(x.second); return ans; }"
},
{
"code": null,
"e": 11016,
"s": 10870,
"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": 11052,
"s": 11016,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11062,
"s": 11052,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11072,
"s": 11062,
"text": "\nContest\n"
},
{
"code": null,
"e": 11135,
"s": 11072,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11283,
"s": 11135,
"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": 11491,
"s": 11283,
"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": 11597,
"s": 11491,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Controlling the Visibility of Class and Interface in Java - GeeksforGeeks
|
22 Feb, 2021
Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component’s visibility low is more maintainable than one that exposes its component more. You’re not going to know it upfront, but when redesigning the application, you’re going to miss it terribly.
You end up patching and repeating the same errors, as maintaining backward compatibility is a must-have requirement for many applications. You will not do much because the class and interfaces are tightly integrated with a lot of other applications. Java has always prioritized encapsulation, providing access modifiers of support from the very beginning. By making them public, package-private or private provides ways to monitor the visibility of some type, such as class or interface.
Below are some rules to control the visibility:
A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change.
A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.
A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.
The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.
Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.
If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change.
How to control Visibility of Class or Interface in Java?
In addition to decreasing class or interface visibility using the access modifier, based on your runtime environment, there are many other ways to do so. At the component level, such as Websphere, Weblogic, or JBoss in Application Server, an interface class may be proxied or wrapped to reduce external visibility.
No matter what you do, there will still be certain types that need to be exposed to the outside world, but you can always handle them with proxy or wrapper. Although client programs will load proxied implementation classes, an immutable proxy or wrapper would often be obtained.
For example, the Java Servlet API (javax.servlet) getServletContext() returns an implementation of javax.servlet.ServletContext, which is typically an immutable proxy to satisfy the ServletContext framework promises. It is most possible that a separate version of the javax.servlet.ServletContext specification operates on the application server.
It is possible to use a similar pattern in the implementation of other externally accessible interfaces, e.g. Javax.ejb.EJBContext, Javax.ejb.TimerService, ServletRequest, ServletResponse, etc. To support these global interfaces, various application servers can use various applications.
JDK Example of Controlling Visibility of Java Class
EnumSet class is another fascinating example of managing visibility. In order to prevent instantiation, the Java designer made the abstract class and provided factory methods as the only way to create an instance of that class, e.g. Methods from EnumSet.of() or EnumSet.noneOf().
Internally, in the form of RegularEnumSet and JumboEnumSet, they have two separate implementations, which are automatically selected based on the size of the main universe by static factory methods.
For instance, if the number of values in Enum is less than 64, then RegularEnumSet is used, otherwise, the JumboEnumSet instance is returned. The beauty of this design is that package-private means that consumers have no idea about any of these implementations.
Private Access Modifier
Java
// Java program for showcasing the behaviour// of Private Access Modifier class Data { // private variable private String name;}public class Main { public static void main(String[] main){ // create an object of Data Data d = new Data(); // access private variable and field from another class d.name = "Kapil"; }}
Output:
Main.java:18: error: name has private access in Data
d.name = "Programiz";
^
In the above example, we have declared a private variable named name and a private method named display(). When we run the program, we will get the above error:
Protected Access Modifier
Java
// Java program for showcasing the behaviour// of Protected Access Modifier class Animal { // protected method protected void display() { System.out.println("I am an animal"); }} class Dog extends Animal { public static void main(String[] args) { // create an object of Dog class Dog dog = new Dog(); // access protected method dog.display(); }}
I am an animal
Public Access Modifier:
Java
// Java program for showcasing the behaviour// of Public Access Modifier // Animal.java file// public class class Animal { // public variable public int legCount; // public method public void display() { System.out.println("I am an animal."); System.out.println("I have " + legCount + " legs."); }} // Main.javapublic class Main { public static void main( String[] args ) { // accessing the public class Animal animal = new Animal(); // accessing the public variable animal.legCount = 4; // accessing the public method animal.display(); }}
I am an animal.
I have 4 legs.
Java-Classes
java-interfaces
Java-Modifier
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 23883,
"s": 23557,
"text": "Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component’s visibility low is more maintainable than one that exposes its component more. You’re not going to know it upfront, but when redesigning the application, you’re going to miss it terribly."
},
{
"code": null,
"e": 24371,
"s": 23883,
"text": "You end up patching and repeating the same errors, as maintaining backward compatibility is a must-have requirement for many applications. You will not do much because the class and interfaces are tightly integrated with a lot of other applications. Java has always prioritized encapsulation, providing access modifiers of support from the very beginning. By making them public, package-private or private provides ways to monitor the visibility of some type, such as class or interface."
},
{
"code": null,
"e": 24419,
"s": 24371,
"text": "Below are some rules to control the visibility:"
},
{
"code": null,
"e": 25573,
"s": 24419,
"text": "A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change."
},
{
"code": null,
"e": 25837,
"s": 25573,
"text": "A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class."
},
{
"code": null,
"e": 26014,
"s": 25837,
"text": "A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature."
},
{
"code": null,
"e": 26270,
"s": 26014,
"text": "The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible."
},
{
"code": null,
"e": 26526,
"s": 26270,
"text": "Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package."
},
{
"code": null,
"e": 26731,
"s": 26526,
"text": "If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change."
},
{
"code": null,
"e": 26788,
"s": 26731,
"text": "How to control Visibility of Class or Interface in Java?"
},
{
"code": null,
"e": 27103,
"s": 26788,
"text": "In addition to decreasing class or interface visibility using the access modifier, based on your runtime environment, there are many other ways to do so. At the component level, such as Websphere, Weblogic, or JBoss in Application Server, an interface class may be proxied or wrapped to reduce external visibility."
},
{
"code": null,
"e": 27382,
"s": 27103,
"text": "No matter what you do, there will still be certain types that need to be exposed to the outside world, but you can always handle them with proxy or wrapper. Although client programs will load proxied implementation classes, an immutable proxy or wrapper would often be obtained."
},
{
"code": null,
"e": 27729,
"s": 27382,
"text": "For example, the Java Servlet API (javax.servlet) getServletContext() returns an implementation of javax.servlet.ServletContext, which is typically an immutable proxy to satisfy the ServletContext framework promises. It is most possible that a separate version of the javax.servlet.ServletContext specification operates on the application server."
},
{
"code": null,
"e": 28017,
"s": 27729,
"text": "It is possible to use a similar pattern in the implementation of other externally accessible interfaces, e.g. Javax.ejb.EJBContext, Javax.ejb.TimerService, ServletRequest, ServletResponse, etc. To support these global interfaces, various application servers can use various applications."
},
{
"code": null,
"e": 28069,
"s": 28017,
"text": "JDK Example of Controlling Visibility of Java Class"
},
{
"code": null,
"e": 28349,
"s": 28069,
"text": "EnumSet class is another fascinating example of managing visibility. In order to prevent instantiation, the Java designer made the abstract class and provided factory methods as the only way to create an instance of that class, e.g. Methods from EnumSet.of() or EnumSet.noneOf()."
},
{
"code": null,
"e": 28548,
"s": 28349,
"text": "Internally, in the form of RegularEnumSet and JumboEnumSet, they have two separate implementations, which are automatically selected based on the size of the main universe by static factory methods."
},
{
"code": null,
"e": 28810,
"s": 28548,
"text": "For instance, if the number of values in Enum is less than 64, then RegularEnumSet is used, otherwise, the JumboEnumSet instance is returned. The beauty of this design is that package-private means that consumers have no idea about any of these implementations."
},
{
"code": null,
"e": 28834,
"s": 28810,
"text": "Private Access Modifier"
},
{
"code": null,
"e": 28839,
"s": 28834,
"text": "Java"
},
{
"code": "// Java program for showcasing the behaviour// of Private Access Modifier class Data { // private variable private String name;}public class Main { public static void main(String[] main){ // create an object of Data Data d = new Data(); // access private variable and field from another class d.name = \"Kapil\"; }}",
"e": 29204,
"s": 28839,
"text": null
},
{
"code": null,
"e": 29212,
"s": 29204,
"text": "Output:"
},
{
"code": null,
"e": 29300,
"s": 29212,
"text": "Main.java:18: error: name has private access in Data\n d.name = \"Programiz\";\n ^"
},
{
"code": null,
"e": 29461,
"s": 29300,
"text": "In the above example, we have declared a private variable named name and a private method named display(). When we run the program, we will get the above error:"
},
{
"code": null,
"e": 29487,
"s": 29461,
"text": "Protected Access Modifier"
},
{
"code": null,
"e": 29492,
"s": 29487,
"text": "Java"
},
{
"code": "// Java program for showcasing the behaviour// of Protected Access Modifier class Animal { // protected method protected void display() { System.out.println(\"I am an animal\"); }} class Dog extends Animal { public static void main(String[] args) { // create an object of Dog class Dog dog = new Dog(); // access protected method dog.display(); }}",
"e": 29908,
"s": 29492,
"text": null
},
{
"code": null,
"e": 29923,
"s": 29908,
"text": "I am an animal"
},
{
"code": null,
"e": 29947,
"s": 29923,
"text": "Public Access Modifier:"
},
{
"code": null,
"e": 29952,
"s": 29947,
"text": "Java"
},
{
"code": "// Java program for showcasing the behaviour// of Public Access Modifier // Animal.java file// public class class Animal { // public variable public int legCount; // public method public void display() { System.out.println(\"I am an animal.\"); System.out.println(\"I have \" + legCount + \" legs.\"); }} // Main.javapublic class Main { public static void main( String[] args ) { // accessing the public class Animal animal = new Animal(); // accessing the public variable animal.legCount = 4; // accessing the public method animal.display(); }}",
"e": 30580,
"s": 29952,
"text": null
},
{
"code": null,
"e": 30611,
"s": 30580,
"text": "I am an animal.\nI have 4 legs."
},
{
"code": null,
"e": 30624,
"s": 30611,
"text": "Java-Classes"
},
{
"code": null,
"e": 30640,
"s": 30624,
"text": "java-interfaces"
},
{
"code": null,
"e": 30654,
"s": 30640,
"text": "Java-Modifier"
},
{
"code": null,
"e": 30661,
"s": 30654,
"text": "Picked"
},
{
"code": null,
"e": 30666,
"s": 30661,
"text": "Java"
},
{
"code": null,
"e": 30671,
"s": 30666,
"text": "Java"
},
{
"code": null,
"e": 30769,
"s": 30671,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30778,
"s": 30769,
"text": "Comments"
},
{
"code": null,
"e": 30791,
"s": 30778,
"text": "Old Comments"
},
{
"code": null,
"e": 30821,
"s": 30791,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30836,
"s": 30821,
"text": "Stream In Java"
},
{
"code": null,
"e": 30857,
"s": 30836,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30903,
"s": 30857,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30922,
"s": 30903,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30939,
"s": 30922,
"text": "Generics in Java"
},
{
"code": null,
"e": 30982,
"s": 30939,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30998,
"s": 30982,
"text": "Strings in Java"
},
{
"code": null,
"e": 31047,
"s": 30998,
"text": "How to remove an element from ArrayList in Java?"
}
] |
How to Install PowerShell in Linux? - GeeksforGeeks
|
06 Oct, 2021
PowerShell is well-known among Windows administrators. It is a.NET-based task-based command-line shell and scripting language. You can quickly automate tasks for operating system maintenance and much more with PowerShell. PowerShell was once only available for Microsoft Windows. This admin tool, on the other hand, can now be installed and used on Linux.
1. The least complex approach to install PowerShell using snap is as per the following :
sudo snap install powershell --classic
Installing PowerShell using snap
2. Now you can simply launch PowerShell by using a simple command :
pwsh
Opening PowerShell
Installing PowerShell from a package repository is the preferred approach in Linux.
1. First update list of system packages using below command :
sudo apt-get update
Update system source
2. Install pre-requisite packages using the below command :
sudo apt-get install -y wget apt-transport-https software-properties-common
Installing pre-requisite packages
3. Now download the Microsoft repository GPG keys :
wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb
Downloading Microsoft GPG key
4. Then register the Microsoft repository GPG keys :
sudo dpkg -i packages-microsoft-prod.deb
Registering GPG key
5. Then update the system source :
sudo apt-get update
Updating system source
6. Enabling the universe repositories :
sudo add-apt-repository universe
Enable universe repositories
7. Now we can finally install PowerShell using the below command :
sudo apt-get install -y powershell
Installing PowerShell
8. Now we can start PowerShell by simply typing the below command :
$ pwsh
Starting PowerShell
how-to-install
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 24633,
"s": 24602,
"text": " \n06 Oct, 2021\n"
},
{
"code": null,
"e": 24989,
"s": 24633,
"text": "PowerShell is well-known among Windows administrators. It is a.NET-based task-based command-line shell and scripting language. You can quickly automate tasks for operating system maintenance and much more with PowerShell. PowerShell was once only available for Microsoft Windows. This admin tool, on the other hand, can now be installed and used on Linux."
},
{
"code": null,
"e": 25078,
"s": 24989,
"text": "1. The least complex approach to install PowerShell using snap is as per the following :"
},
{
"code": null,
"e": 25117,
"s": 25078,
"text": "sudo snap install powershell --classic"
},
{
"code": null,
"e": 25150,
"s": 25117,
"text": "Installing PowerShell using snap"
},
{
"code": null,
"e": 25218,
"s": 25150,
"text": "2. Now you can simply launch PowerShell by using a simple command :"
},
{
"code": null,
"e": 25223,
"s": 25218,
"text": "pwsh"
},
{
"code": null,
"e": 25242,
"s": 25223,
"text": "Opening PowerShell"
},
{
"code": null,
"e": 25326,
"s": 25242,
"text": "Installing PowerShell from a package repository is the preferred approach in Linux."
},
{
"code": null,
"e": 25388,
"s": 25326,
"text": "1. First update list of system packages using below command :"
},
{
"code": null,
"e": 25408,
"s": 25388,
"text": "sudo apt-get update"
},
{
"code": null,
"e": 25429,
"s": 25408,
"text": "Update system source"
},
{
"code": null,
"e": 25489,
"s": 25429,
"text": "2. Install pre-requisite packages using the below command :"
},
{
"code": null,
"e": 25565,
"s": 25489,
"text": "sudo apt-get install -y wget apt-transport-https software-properties-common"
},
{
"code": null,
"e": 25599,
"s": 25565,
"text": "Installing pre-requisite packages"
},
{
"code": null,
"e": 25651,
"s": 25599,
"text": "3. Now download the Microsoft repository GPG keys :"
},
{
"code": null,
"e": 25738,
"s": 25651,
"text": "wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb"
},
{
"code": null,
"e": 25768,
"s": 25738,
"text": "Downloading Microsoft GPG key"
},
{
"code": null,
"e": 25821,
"s": 25768,
"text": "4. Then register the Microsoft repository GPG keys :"
},
{
"code": null,
"e": 25862,
"s": 25821,
"text": "sudo dpkg -i packages-microsoft-prod.deb"
},
{
"code": null,
"e": 25882,
"s": 25862,
"text": "Registering GPG key"
},
{
"code": null,
"e": 25917,
"s": 25882,
"text": "5. Then update the system source :"
},
{
"code": null,
"e": 25937,
"s": 25917,
"text": "sudo apt-get update"
},
{
"code": null,
"e": 25960,
"s": 25937,
"text": "Updating system source"
},
{
"code": null,
"e": 26000,
"s": 25960,
"text": "6. Enabling the universe repositories :"
},
{
"code": null,
"e": 26033,
"s": 26000,
"text": "sudo add-apt-repository universe"
},
{
"code": null,
"e": 26062,
"s": 26033,
"text": "Enable universe repositories"
},
{
"code": null,
"e": 26129,
"s": 26062,
"text": "7. Now we can finally install PowerShell using the below command :"
},
{
"code": null,
"e": 26164,
"s": 26129,
"text": "sudo apt-get install -y powershell"
},
{
"code": null,
"e": 26186,
"s": 26164,
"text": "Installing PowerShell"
},
{
"code": null,
"e": 26254,
"s": 26186,
"text": "8. Now we can start PowerShell by simply typing the below command :"
},
{
"code": null,
"e": 26261,
"s": 26254,
"text": "$ pwsh"
},
{
"code": null,
"e": 26281,
"s": 26261,
"text": "Starting PowerShell"
},
{
"code": null,
"e": 26298,
"s": 26281,
"text": "\nhow-to-install\n"
},
{
"code": null,
"e": 26307,
"s": 26298,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26316,
"s": 26307,
"text": "\nHow To\n"
},
{
"code": null,
"e": 26337,
"s": 26316,
"text": "\nInstallation Guide\n"
},
{
"code": null,
"e": 26350,
"s": 26337,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 26555,
"s": 26350,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26589,
"s": 26555,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26638,
"s": 26589,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 26696,
"s": 26638,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 26738,
"s": 26696,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 26798,
"s": 26738,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 26831,
"s": 26798,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26865,
"s": 26831,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 26900,
"s": 26865,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 26958,
"s": 26900,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Dice throw | Practice | GeeksforGeeks
|
Given N dice each with M faces, numbered from 1 to M, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown.
Example 1:
Input:
M = 6, N = 3, X = 12
Output:
25
Explanation:
There are 25 total ways to get
the Sum 12 using 3 dices with
faces from 1 to 6.
Example 2:
Input:
M = 2, N = 3, X = 6
Output:
1
Explanation:
There is only 1 way to get
the Sum 6 using 3 dices with
faces from 1 to 2. All the
dices will have to land on 2.
Your Task:
You don't need to read input or print anything. Your task is to complete the function noOfWays() which takes 3 Integers M,N and X as input and returns the answer.
Expected Time Complexity: O(M*N*X)
Expected Auxiliary Space: O(N*X)
Constraints:
1 <= M,N,X <= 50
0
hamidnourashraf1 month ago
recursive, too slow
class Solution:
def throw_dice(self, M, N, X):
if N == 0 and X == 0:
return 1
if N == 0 and X > 0:
return 0
cnt = 0
for i in range(1, M+1):
if X >= i:
cnt += self.throw_dice(M, N-1, X-i)
return cnt
def noOfWays(self, M, N, X):
return self.throw_dice(M, N, X)
recursive with memorization: Time: 0.1/1.3
class Solution:
def throw_dice(self, M, N, X, mem):
if N == 0 and X == 0:
mem[N][X] = 1
return mem[N][X]
if N == 0 and X > 0:
mem[N][X] = 0
return mem[N][X]
if mem[N][X] != -1:
return mem[N][X]
cnt = 0
for i in range(1, M+1):
if X >= i:
cnt += self.throw_dice(M, N-1, X-i, mem)
mem[N][X] = cnt
return mem[N][X]
def noOfWays(self, M, N, X):
mem = [[-1]*(X+1) for i in range(N+1)]
return self.throw_dice(M, N, X, mem)
+1
ruchitchudasama1232 months ago
public:
long long go(int m,int n,int target,vector<vector<long long>> &dp){
if(n==0){
return target==0?1:0;
}
if(dp[n][target]!=-1)
return dp[n][target];
long long count=0;
for(int i=1 ; i<=m && target>=i ; i++){
count+=go(m,n-1,target-i,dp);
}
return dp[n][target]=count;
}
long long noOfWays(int M , int N , int X) {
vector<vector<long long>> dp(N+1,vector<long long>(X+1,-1));
return go(M,N,X,dp);
}
0
kiranrkuyate20212 months ago
long long noOfWays(int M , int N , int X) {
// code here
vector<vector<long long int>>dp(N+1,vector<long long int>(X+1,-1));
return go(M,N,X,dp);
}
long long int go(int m,int n,int x,vector<vector<long long int>>&dp){
if(n==0){
return x==0?1:0;
}
if(dp[n][x]!=-1){
return dp[n][x];
}
long long int ways=0;
for(int dice=1;dice<=m&&x>=dice;dice++){
ways+=go(m,n-1,x-dice,dp)*1ll;
}
return dp[n][x]=ways;
}
0
harshanenwani1212 months ago
long long noOfWays(int M , int N , int X) {
//Create a dp table of dimension N+1 and X+1 and fill up the value -1. (Number of dice is directly used as row index and sum is directly used as column index).
vector<vector<long long int>> dp(N+1,vector<long long int>(X+1,-1));
return go(M,N,X,dp);
}
long long int go(int m,int n,int x,vector<vector<long long int>>& dp){
// when there are no dice and the sum to be made is 0
if(n==0){
return x==0?1ll:0ll;
}
if(dp[n][x]!=-1){
return dp[n][x];
}
long long int ways=0;
// Here ,dice should be less than equal to x i.e( x>=dice),to have it as positive value
for(int dice=1;dice<=m && x>=dice;dice++)
{
// Say the first dice is taken from n dices so the ways to achieve the other dices will be n-1 and the sum(x) substracting to the dice that comes i.e(x-dice).
ways=ways+0ll+go(m,n-1,x-dice,dp);
}
return dp[n][x]=ways;
}
0
harshanenwani121
This comment was deleted.
+1
bhargabnath6912 months ago
BACKTRACK SOLUTION USING MAP:-
Time Taken: 0.1 / 3.4
class Solution {
public:
unordered_map<string, long long> dp;
long long noOfWays(int M , int N , int X) {
// code here
if(X<N or X>N*M) return 0;
if(N==1) return X<=M;
string temp = to_string(M) + to_string(N) + to_string(X);
if(dp.find(temp) == dp.end()){
long long sum = 0;
for(int i=1; i<=M; i++) sum += noOfWays(M, N-1, X-i);
dp[temp] = sum;
}
return dp[temp];
}
};
+1
utkarshrdce2 months ago
// C++ O(N*X) use prefix sum to calculate the dp values
class Solution {
public:
#define ll long long
ll dp[52][52];
long long noOfWays(int M , int N , int X) {
memset(dp, 0 , sizeof(dp));
dp[0][0] = 1;
for(int i = 0; i <= N; i++) {
for(int j = 1; j <= X; j++) {
if(i == 0) {
dp[i][j] += dp[i][j-1];
} else {
int start = max(0, j - M);
dp[i][j] = dp[i - 1][j - 1] - (start > 0 ? dp[i - 1][start - 1] : 0);
if(i == N && j == X) return dp[i][j];
dp[i][j]+=dp[i][j - 1];
}
}
}
return dp[N][X];
}
};
0
himanshukug19cs3 months ago
java solution
if(X>M*N) return 0; long[][] dp = new long[N+1][M*N+1]; for(int i=0;i<=M*N;i++){ dp[0][i]=0; } for(int i=0;i<=M*N;i++){ if(i>=1&&i<=M) dp[1][i]=1; else dp[1][i]=0; } for(int i=2;i<=N;i++){ for(int j=0;j<=N*M;j++){ dp[i][j]=0; int k=1; while(k<=M&&j-k>=0){ dp[i][j]+=dp[i-1][j-k]; k++; } } } return dp[N][X];
+2
ankitpodder4 months ago
Total Time Taken:
0.0/3.4
class Solution {
long long recFunc(int m , int n , int x){
if(n == 0 && x == 0) return 1;
else if(n == 0 || x<=0) return 0;
long long ans = 0;
for(int i = 1 ; i <= min(x , m) ; i++){
ans += recFunc(m , n-1 , x-i);
}
return ans;
}
public:
long long noOfWays(int m , int n , int x) {
// code here
// return recFunc(M , N , X);
vector<vector<long long>> dp(n+1 , vector<long long>(x+1 , 0));
dp[0][0] = 1;
for(int i = 1 ; i < n+1 ; i++){
for(int j = 1 ; j < x+1 ; j++){
for(int k = 1 ; k <= min(m , j) ; k++){
dp[i][j] += dp[i-1][j-k];
}
}
}
return dp[n][x];
}
};
0
anant dahiya6 months ago
long long noOfWays(int m , int n , int x) { /* * Creare a dp vector to store number a ways to get * all numbers using all numbers of dice * */ vector<vector<long long>> dp(n, vector<long long>(x+1, 0)); //Iterate through row (No. of Dice) for(int i=0;i<n;i++){ // Iterate through sum to be achieved for(int j=1;j<x+1;j++){ // Iterate through numbers which can come on the dice for(int k=1;k<=m;k++){ // For initializing the first line of the dp array if(k<=j && i==0){ if(j == k){ dp[i][j] = 1; } }else if(k<=j && i!=0){ // For other cases except the first row dp[i][j] = dp[i][j]+dp[i-1][j-k]; } } } } // return right bottom number return dp[n-1][x]; }
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": 402,
"s": 238,
"text": "Given N dice each with M faces, numbered from 1 to M, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown."
},
{
"code": null,
"e": 415,
"s": 404,
"text": "Example 1:"
},
{
"code": null,
"e": 547,
"s": 415,
"text": "Input:\nM = 6, N = 3, X = 12\nOutput:\n25\nExplanation:\nThere are 25 total ways to get\nthe Sum 12 using 3 dices with\nfaces from 1 to 6."
},
{
"code": null,
"e": 558,
"s": 547,
"text": "Example 2:"
},
{
"code": null,
"e": 721,
"s": 558,
"text": "Input:\nM = 2, N = 3, X = 6\nOutput:\n1\nExplanation:\nThere is only 1 way to get\nthe Sum 6 using 3 dices with\nfaces from 1 to 2. All the\ndices will have to land on 2."
},
{
"code": null,
"e": 897,
"s": 723,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function noOfWays() which takes 3 Integers M,N and X as input and returns the answer."
},
{
"code": null,
"e": 967,
"s": 899,
"text": "Expected Time Complexity: O(M*N*X)\nExpected Auxiliary Space: O(N*X)"
},
{
"code": null,
"e": 999,
"s": 969,
"text": "Constraints:\n1 <= M,N,X <= 50"
},
{
"code": null,
"e": 1001,
"s": 999,
"text": "0"
},
{
"code": null,
"e": 1028,
"s": 1001,
"text": "hamidnourashraf1 month ago"
},
{
"code": null,
"e": 2062,
"s": 1028,
"text": "recursive, too slow\n\nclass Solution:\n def throw_dice(self, M, N, X):\n if N == 0 and X == 0:\n return 1\n if N == 0 and X > 0:\n return 0\n cnt = 0\n for i in range(1, M+1):\n if X >= i:\n cnt += self.throw_dice(M, N-1, X-i)\n return cnt\n \n def noOfWays(self, M, N, X):\n return self.throw_dice(M, N, X)\n\n\nrecursive with memorization: Time: 0.1/1.3\n\nclass Solution:\n def throw_dice(self, M, N, X, mem):\n if N == 0 and X == 0:\n mem[N][X] = 1\n return mem[N][X]\n if N == 0 and X > 0:\n mem[N][X] = 0\n return mem[N][X]\n if mem[N][X] != -1:\n return mem[N][X]\n cnt = 0\n for i in range(1, M+1):\n if X >= i:\n cnt += self.throw_dice(M, N-1, X-i, mem)\n mem[N][X] = cnt\n return mem[N][X]\n \n def noOfWays(self, M, N, X):\n mem = [[-1]*(X+1) for i in range(N+1)]\n return self.throw_dice(M, N, X, mem)"
},
{
"code": null,
"e": 2065,
"s": 2062,
"text": "+1"
},
{
"code": null,
"e": 2096,
"s": 2065,
"text": "ruchitchudasama1232 months ago"
},
{
"code": null,
"e": 2645,
"s": 2096,
"text": " public:\n \n long long go(int m,int n,int target,vector<vector<long long>> &dp){\n if(n==0){\n return target==0?1:0;\n }\n \n if(dp[n][target]!=-1)\n return dp[n][target];\n \n long long count=0;\n for(int i=1 ; i<=m && target>=i ; i++){\n count+=go(m,n-1,target-i,dp);\n }\n return dp[n][target]=count;\n }\n long long noOfWays(int M , int N , int X) {\n vector<vector<long long>> dp(N+1,vector<long long>(X+1,-1));\n return go(M,N,X,dp);\n }"
},
{
"code": null,
"e": 2647,
"s": 2645,
"text": "0"
},
{
"code": null,
"e": 2676,
"s": 2647,
"text": "kiranrkuyate20212 months ago"
},
{
"code": null,
"e": 3222,
"s": 2676,
"text": "long long noOfWays(int M , int N , int X) {\n // code here\n vector<vector<long long int>>dp(N+1,vector<long long int>(X+1,-1));\n return go(M,N,X,dp);\n }\n \n long long int go(int m,int n,int x,vector<vector<long long int>>&dp){\n if(n==0){\n return x==0?1:0;\n }\n if(dp[n][x]!=-1){\n return dp[n][x];\n }\n long long int ways=0;\n for(int dice=1;dice<=m&&x>=dice;dice++){\n ways+=go(m,n-1,x-dice,dp)*1ll;\n }\n return dp[n][x]=ways;\n }\n"
},
{
"code": null,
"e": 3224,
"s": 3222,
"text": "0"
},
{
"code": null,
"e": 3253,
"s": 3224,
"text": "harshanenwani1212 months ago"
},
{
"code": null,
"e": 4303,
"s": 3253,
"text": "long long noOfWays(int M , int N , int X) {\n //Create a dp table of dimension N+1 and X+1 and fill up the value -1. (Number of dice is directly used as row index and sum is directly used as column index).\n \n vector<vector<long long int>> dp(N+1,vector<long long int>(X+1,-1));\n return go(M,N,X,dp);\n }\n \n long long int go(int m,int n,int x,vector<vector<long long int>>& dp){\n // when there are no dice and the sum to be made is 0\n \n if(n==0){\n return x==0?1ll:0ll;\n }\n \n if(dp[n][x]!=-1){\n return dp[n][x];\n }\n long long int ways=0;\n \n // Here ,dice should be less than equal to x i.e( x>=dice),to have it as positive value \n for(int dice=1;dice<=m && x>=dice;dice++)\n { \n // Say the first dice is taken from n dices so the ways to achieve the other dices will be n-1 and the sum(x) substracting to the dice that comes i.e(x-dice).\n \n ways=ways+0ll+go(m,n-1,x-dice,dp);\n }\n return dp[n][x]=ways;\n }"
},
{
"code": null,
"e": 4305,
"s": 4303,
"text": "0"
},
{
"code": null,
"e": 4322,
"s": 4305,
"text": "harshanenwani121"
},
{
"code": null,
"e": 4348,
"s": 4322,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4351,
"s": 4348,
"text": "+1"
},
{
"code": null,
"e": 4378,
"s": 4351,
"text": "bhargabnath6912 months ago"
},
{
"code": null,
"e": 4409,
"s": 4378,
"text": "BACKTRACK SOLUTION USING MAP:-"
},
{
"code": null,
"e": 4431,
"s": 4409,
"text": "Time Taken: 0.1 / 3.4"
},
{
"code": null,
"e": 4907,
"s": 4431,
"text": "class Solution {\n public:\n unordered_map<string, long long> dp;\n long long noOfWays(int M , int N , int X) {\n // code here\n if(X<N or X>N*M) return 0;\n if(N==1) return X<=M;\n string temp = to_string(M) + to_string(N) + to_string(X);\n if(dp.find(temp) == dp.end()){\n long long sum = 0;\n for(int i=1; i<=M; i++) sum += noOfWays(M, N-1, X-i);\n dp[temp] = sum;\n }\n return dp[temp];\n }\n};"
},
{
"code": null,
"e": 4910,
"s": 4907,
"text": "+1"
},
{
"code": null,
"e": 4934,
"s": 4910,
"text": "utkarshrdce2 months ago"
},
{
"code": null,
"e": 5720,
"s": 4934,
"text": "// C++ O(N*X) use prefix sum to calculate the dp values\nclass Solution {\n public:\n #define ll long long\n ll dp[52][52];\n \n long long noOfWays(int M , int N , int X) {\n \n \n memset(dp, 0 , sizeof(dp));\n dp[0][0] = 1;\n \n for(int i = 0; i <= N; i++) {\n for(int j = 1; j <= X; j++) {\n if(i == 0) {\n dp[i][j] += dp[i][j-1];\n } else {\n int start = max(0, j - M);\n dp[i][j] = dp[i - 1][j - 1] - (start > 0 ? dp[i - 1][start - 1] : 0);\n if(i == N && j == X) return dp[i][j];\n dp[i][j]+=dp[i][j - 1];\n }\n }\n }\n \n return dp[N][X];\n \n \n }\n};"
},
{
"code": null,
"e": 5722,
"s": 5720,
"text": "0"
},
{
"code": null,
"e": 5750,
"s": 5722,
"text": "himanshukug19cs3 months ago"
},
{
"code": null,
"e": 5764,
"s": 5750,
"text": "java solution"
},
{
"code": null,
"e": 6296,
"s": 5766,
"text": " if(X>M*N) return 0; long[][] dp = new long[N+1][M*N+1]; for(int i=0;i<=M*N;i++){ dp[0][i]=0; } for(int i=0;i<=M*N;i++){ if(i>=1&&i<=M) dp[1][i]=1; else dp[1][i]=0; } for(int i=2;i<=N;i++){ for(int j=0;j<=N*M;j++){ dp[i][j]=0; int k=1; while(k<=M&&j-k>=0){ dp[i][j]+=dp[i-1][j-k]; k++; } } } return dp[N][X];"
},
{
"code": null,
"e": 6301,
"s": 6298,
"text": "+2"
},
{
"code": null,
"e": 6325,
"s": 6301,
"text": "ankitpodder4 months ago"
},
{
"code": null,
"e": 6343,
"s": 6325,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 6351,
"s": 6343,
"text": "0.0/3.4"
},
{
"code": null,
"e": 7131,
"s": 6351,
"text": "class Solution {\n long long recFunc(int m , int n , int x){\n if(n == 0 && x == 0) return 1;\n else if(n == 0 || x<=0) return 0;\n long long ans = 0;\n for(int i = 1 ; i <= min(x , m) ; i++){\n ans += recFunc(m , n-1 , x-i);\n }\n return ans;\n }\n public:\n long long noOfWays(int m , int n , int x) {\n // code here\n // return recFunc(M , N , X);\n vector<vector<long long>> dp(n+1 , vector<long long>(x+1 , 0));\n dp[0][0] = 1;\n for(int i = 1 ; i < n+1 ; i++){\n for(int j = 1 ; j < x+1 ; j++){\n for(int k = 1 ; k <= min(m , j) ; k++){\n dp[i][j] += dp[i-1][j-k];\n }\n }\n }\n \n return dp[n][x];\n }\n};"
},
{
"code": null,
"e": 7133,
"s": 7131,
"text": "0"
},
{
"code": null,
"e": 7158,
"s": 7133,
"text": "anant dahiya6 months ago"
},
{
"code": null,
"e": 8152,
"s": 7158,
"text": " long long noOfWays(int m , int n , int x) { /* * Creare a dp vector to store number a ways to get * all numbers using all numbers of dice * */ vector<vector<long long>> dp(n, vector<long long>(x+1, 0)); //Iterate through row (No. of Dice) for(int i=0;i<n;i++){ // Iterate through sum to be achieved for(int j=1;j<x+1;j++){ // Iterate through numbers which can come on the dice for(int k=1;k<=m;k++){ // For initializing the first line of the dp array if(k<=j && i==0){ if(j == k){ dp[i][j] = 1; } }else if(k<=j && i!=0){ // For other cases except the first row dp[i][j] = dp[i][j]+dp[i-1][j-k]; } } } } // return right bottom number return dp[n-1][x]; }"
},
{
"code": null,
"e": 8298,
"s": 8152,
"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": 8334,
"s": 8298,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8344,
"s": 8334,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8354,
"s": 8344,
"text": "\nContest\n"
},
{
"code": null,
"e": 8417,
"s": 8354,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8565,
"s": 8417,
"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": 8773,
"s": 8565,
"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": 8879,
"s": 8773,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Difference between process.nextTick() and setImmediate() Methods - GeeksforGeeks
|
11 Apr, 2022
To understand the difference between process.nextTick() and setImmediate() methods, we first need to understand the working of Node.js Event Loop.
What is Node.js Event Loop?Due to the fact that JavaScript is single-threaded i.e. it performs only a single process at a time, so it is the Event Loop that allows Node.js to perform non-blocking I/O operations.
Working of Event Loop?At the start of a JavaScript program, an event loop is initialized. There are several operations that execute in an event loop. Below is the sequence in which different they are executed in a single iteration of the event loop. These operations are processed in a queue.
timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks
Understanding process.nextTick() method: Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.
Syntax:
process.nextTick(callback);
Understanding setImmdeiate() method: Whenever we call setImmediate() method, it’s callback function is placed in the check phase of the next event queue. There is slight detail to be noted here that setImmediate() method is called in the poll phase and it’s callback functions are invoked in the check phase.
Syntax:
setImmediate(callback);
Example:
setImmediate(function A() { console.log("1st immediate");}); setImmediate(function B() { console.log("2nd immediate");}); process.nextTick(function C() { console.log("1st process");}); process.nextTick(function D() { console.log("2nd process");}); // First event queue ends hereconsole.log("program started");
For the above program, event queues are initialized in the following manner:
In the first event queue only ‘program started is printed’.Then second event queue is started and function C i.e. callback of process.nextTick() method is placed at the start of the event queue. C is executed and the queue ends.Then previous event queue ends and third event queue is initialized with callback D. Then callback function A of setImmdeiate() method is placed in the followed by B.Now, the third event queue looks like this,D A BNow functions D, A, B are executed in the order they are present in the queue.Output:
In the first event queue only ‘program started is printed’.
Then second event queue is started and function C i.e. callback of process.nextTick() method is placed at the start of the event queue. C is executed and the queue ends.
Then previous event queue ends and third event queue is initialized with callback D. Then callback function A of setImmdeiate() method is placed in the followed by B.Now, the third event queue looks like this,D A BNow functions D, A, B are executed in the order they are present in the queue.Output:
D A B
Now functions D, A, B are executed in the order they are present in the queue.
Output:
Let us see the differences in a tabular form -:
Its syntax is -:
process.nextTick(callback);
Its syntax is -:
setImmediate(callback);
mayank007rawa
Node.js-Methods
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 24024,
"s": 23877,
"text": "To understand the difference between process.nextTick() and setImmediate() methods, we first need to understand the working of Node.js Event Loop."
},
{
"code": null,
"e": 24236,
"s": 24024,
"text": "What is Node.js Event Loop?Due to the fact that JavaScript is single-threaded i.e. it performs only a single process at a time, so it is the Event Loop that allows Node.js to perform non-blocking I/O operations."
},
{
"code": null,
"e": 24529,
"s": 24236,
"text": "Working of Event Loop?At the start of a JavaScript program, an event loop is initialized. There are several operations that execute in an event loop. Below is the sequence in which different they are executed in a single iteration of the event loop. These operations are processed in a queue."
},
{
"code": null,
"e": 24621,
"s": 24529,
"text": "timers–>pending callbacks–>idle,prepare–>connections(poll,data,etc)–>check–>close callbacks"
},
{
"code": null,
"e": 24984,
"s": 24621,
"text": "Understanding process.nextTick() method: Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed."
},
{
"code": null,
"e": 24992,
"s": 24984,
"text": "Syntax:"
},
{
"code": null,
"e": 25020,
"s": 24992,
"text": "process.nextTick(callback);"
},
{
"code": null,
"e": 25329,
"s": 25020,
"text": "Understanding setImmdeiate() method: Whenever we call setImmediate() method, it’s callback function is placed in the check phase of the next event queue. There is slight detail to be noted here that setImmediate() method is called in the poll phase and it’s callback functions are invoked in the check phase."
},
{
"code": null,
"e": 25337,
"s": 25329,
"text": "Syntax:"
},
{
"code": null,
"e": 25361,
"s": 25337,
"text": "setImmediate(callback);"
},
{
"code": null,
"e": 25370,
"s": 25361,
"text": "Example:"
},
{
"code": "setImmediate(function A() { console.log(\"1st immediate\");}); setImmediate(function B() { console.log(\"2nd immediate\");}); process.nextTick(function C() { console.log(\"1st process\");}); process.nextTick(function D() { console.log(\"2nd process\");}); // First event queue ends hereconsole.log(\"program started\");",
"e": 25696,
"s": 25370,
"text": null
},
{
"code": null,
"e": 25773,
"s": 25696,
"text": "For the above program, event queues are initialized in the following manner:"
},
{
"code": null,
"e": 26301,
"s": 25773,
"text": "In the first event queue only ‘program started is printed’.Then second event queue is started and function C i.e. callback of process.nextTick() method is placed at the start of the event queue. C is executed and the queue ends.Then previous event queue ends and third event queue is initialized with callback D. Then callback function A of setImmdeiate() method is placed in the followed by B.Now, the third event queue looks like this,D A BNow functions D, A, B are executed in the order they are present in the queue.Output:"
},
{
"code": null,
"e": 26361,
"s": 26301,
"text": "In the first event queue only ‘program started is printed’."
},
{
"code": null,
"e": 26531,
"s": 26361,
"text": "Then second event queue is started and function C i.e. callback of process.nextTick() method is placed at the start of the event queue. C is executed and the queue ends."
},
{
"code": null,
"e": 26831,
"s": 26531,
"text": "Then previous event queue ends and third event queue is initialized with callback D. Then callback function A of setImmdeiate() method is placed in the followed by B.Now, the third event queue looks like this,D A BNow functions D, A, B are executed in the order they are present in the queue.Output:"
},
{
"code": null,
"e": 26837,
"s": 26831,
"text": "D A B"
},
{
"code": null,
"e": 26916,
"s": 26837,
"text": "Now functions D, A, B are executed in the order they are present in the queue."
},
{
"code": null,
"e": 26924,
"s": 26916,
"text": "Output:"
},
{
"code": null,
"e": 26972,
"s": 26924,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 26989,
"s": 26972,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 27017,
"s": 26989,
"text": "process.nextTick(callback);"
},
{
"code": null,
"e": 27034,
"s": 27017,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 27058,
"s": 27034,
"text": "setImmediate(callback);"
},
{
"code": null,
"e": 27072,
"s": 27058,
"text": "mayank007rawa"
},
{
"code": null,
"e": 27088,
"s": 27072,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 27095,
"s": 27088,
"text": "Picked"
},
{
"code": null,
"e": 27103,
"s": 27095,
"text": "Node.js"
},
{
"code": null,
"e": 27120,
"s": 27103,
"text": "Web Technologies"
},
{
"code": null,
"e": 27218,
"s": 27120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27227,
"s": 27218,
"text": "Comments"
},
{
"code": null,
"e": 27240,
"s": 27227,
"text": "Old Comments"
},
{
"code": null,
"e": 27269,
"s": 27240,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 27299,
"s": 27269,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 27356,
"s": 27299,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 27410,
"s": 27356,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 27447,
"s": 27410,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 27503,
"s": 27447,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27565,
"s": 27503,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27608,
"s": 27565,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27658,
"s": 27608,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Partition Equal Subset Sum | Practice | GeeksforGeeks
|
Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.
Example 1:
Input: N = 4
arr = {1, 5, 11, 5}
Output: YES
Explaination:
The two parts are {1, 5, 5} and {11}.
Example 2:
Input: N = 3
arr = {1, 3, 5}
Output: NO
Explaination: This array can never be
partitioned into two such parts.
Your Task:
You do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0.
Expected Time Complexity: O(N*sum of elements)
Expected Auxiliary Space: O(N*sum of elements)
Constraints:
1 ≤ N ≤ 100
1 ≤ arr[i] ≤ 1000
0
adarshgupta4014 days ago
Easy Java DP knapSack technique-
class Solution{
static int equalPartition(int n, int nums[])
{
int sum = 0;
for(int a : nums) sum += a;
if(sum % 2 != 0) return 0; // return false if odd sum
return subsetSum( nums,n, sum/2);
}
private static int subsetSum(int[] nums, int n, int sum){
int dp[][] = new int[n+1][sum+1];
for(int i =0 ; i< sum+1 ; ++i) dp[0][i] = 0;
for(int i = 0; i< n+1 ; ++i) dp[i][0] = 1;
for(int i = 1; i< n+1 ; i++){
for( int j = 1; j < sum+1 ; j++){
if(nums[i-1] <= j)
dp[i][j] = Math.max( dp[i-1][j-nums[i-1]], dp[i-1][j] );
else dp[i][j] = dp[i-1][j];
}
}
return dp[n][sum];
}
}
0
milindprajapatmst196 days ago
const int N = 1e2, M = 1e5;
bool dp[N][M + 1];
class Solution {
public:
int equalPartition(int n, int arr[]) {
int _sum = 0;
for (int i = 0; i < n; i++)
_sum += arr[i];
if (_sum & 1) return false;
memset(dp, false, sizeof(dp));
dp[0][0] = dp[0][arr[0]] = true;
for (int i = 1; i < n; i++) {
dp[i][0] = true;
for (int j = 0; j <= _sum; j++) {
dp[i][j] |= dp[i - 1][j];
dp[i][j + arr[i]] |= dp[i - 1][j];
}
}
return dp[n - 1][_sum >> 1];
}
};
+1
shishir17pandey1 week ago
int sum=0; int n=N; for(int i=0;i<n;i++){ sum=sum+arr[i]; } int a=0; if(sum%2!=0){return false; } else{ a=sum/2; } bool dp[n+1][a+1]; dp[0][0]=true; for(int i=1;i<=n;i++){ for(int j=0;j<=a;j++){ if(j>=arr[i-1]){ dp[i][j]= dp[i-1][j] || dp[i-1][j-arr[i-1]]; } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][a]; }
0
deepakkumarshaw662 weeks ago
int helperDP(int n, int *arr, int sum) { int **dp = new int*[n + 1]; for(int i = 0; i <= n; i++) dp[i] = new int[sum + 1]; //INITIALIZING FIRST ROW for(int i = 0; i <= sum; i++) dp[0][i] = 0; //INITIALISING FIRST COLUMN for(int i = 0; i <= n; i++) dp[i][0] = 1; //FILLING REAINING ROWS AND COLUMNS for(int i = 1; i <= n; i++) { for(int j = 1; j <= sum; j++) { if(arr[i - 1] <= j) dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i - 1][j]; else dp[i][j] = dp[i - 1][j]; } } return dp[n][sum]; } int equalPartition(int N, int arr[]) { long sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; //IF SUM IS ODD if(sum % 2 != 0) return 0; return helperDP(N, arr, sum/2); }
+1
aniketsaraswat1122 weeks ago
int equalPartition(int n, int arr[]){
int sum = 0;
for(int i = 0; i<n; i++) sum += arr[i];
if(sum&1) return 0;
sum /= 2;
int dp[n+1][sum+1] = {};
for(int i = 0; i<n+1; i++) dp[i][0] = 1;
for(int i = 1; i<n+1; i++){
for(int j = 1; j<= sum; j++)
if(dp[i-1][j] || (arr[i-1] <= j && dp[i-1][j-arr[i-1]]))
dp[i][j] = 1;
}
return dp[n][sum];
}
0
uratabhi3 weeks ago
class Solution{public: int dp[102][1002]; Solution(){ memset(dp, -1, sizeof(dp)); } bool ispossible(int arr[], int N, int sum){ if(dp[N][sum]!=-1){ return dp[N][sum]; } if(sum==0) return 1; if(N<=0 || sum<0) return 0; if(arr[N-1]>sum){ dp[N][sum] = ispossible(arr, N-1, sum); } else{ dp[N][sum] = ispossible(arr, N-1, sum-arr[N-1]) || ispossible(arr, N-1, sum); } return dp[N][sum]; } int equalPartition(int N, int arr[]) { int sum =0; for(int i=0; i<N; i++) sum+=arr[i]; if(sum%2==1){ return 0; } int k = ispossible(arr, N, sum/2); return k; }};
0
pravin_swv3 weeks ago
// { Driver Code Starts// Initial Template for C++
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends// User function Template for C++
class Solution{public:
// bool rec(int ind,int arr[],int sum,vector<vector<int>>dp) // { // //base case // if(sum==0) return true; // if(ind==0) // { // if(arr[0]==sum ) return true; // } // if(ind==0 && sum!=0) return false; // if(dp[ind][sum]!=-1) return dp[ind][sum]; // bool not_pick=rec(ind-1,arr,sum,dp); // bool pick=false; // if(arr[ind]<=sum) pick=rec(ind-1,arr,sum-arr[ind],dp); // return dp[ind][sum]=not_pick || pick; // } //Tabulation code int equalPartition(int N, int arr[]) { // code here int tot_sum=0; for(int i=0;i<N;i++) { tot_sum+=arr[i]; } if(tot_sum%2==1) return 0; int k=tot_sum/2; vector<vector<int>> dp( N , vector<int> (k+1, 0)); for(int i=0;i<N;i++) { dp[i][0]=1; } if(arr[0]<=k) dp[0][arr[0]]=1; for(int ind=1;ind<N;ind++){ for(int tar=1;tar<=k;tar++) { bool not_pick=dp[ind-1][tar]; bool pick=0; if(arr[ind]<=tar) pick=dp[ind-1][tar-arr[ind]]; dp[ind][tar]=not_pick || pick; } } return dp[N-1][k]; }};
// { Driver Code Starts.
int main(){ int t; cin>>t; while(t--){ int N; cin>>N; int arr[N]; for(int i = 0;i < N;i++) cin>>arr[i]; Solution ob; if(ob.equalPartition(N, arr)) cout<<"YES\n"; else cout<<"NO\n"; } return 0;} // } Driver Code Ends
0
rounakdiptaghosh19993 weeks ago
bool solve(int arr[],int n ,int sum) { int dp[n+1][sum+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=sum;j++){ if(i==0) dp[i][j]=false; if(j==0) dp[i][j]=true; } } for(int i=1;i<n+1;i++){ for(int j=1;j<sum+1;j++){ if(arr[i-1]<=j) dp[i][j]=dp[i-1][j-arr[i-1]]||dp[i-1][j]; else dp[i][j]=dp[i-1][j]; } } return dp[n][sum]; }
int equalPartition(int n, int arr[]) { // code here int sum=0; for(int i=0;i<n;i++) sum+=arr[i]; if(sum%2!=0) return false; else if(sum%2==0) return solve(arr,n,sum/2); }
0
rockskhare2613 weeks ago
#DP_LOGIC
class Solution: def equalPartition(self, N, arr): def subs(arr,sum_,n): dp=[[False]*(sum_+1) for i in range(n+1)] for i in range(n+1): dp[i][0]=True for i in range(n+1): for j in range(sum_+1): if arr[i-1]>j: dp[i][j]=dp[i-1][j] else: dp[i][j] = dp[i - 1][j] or dp[i - 1][j-arr[i-1]] return dp[n][sum_] sum_=sum(arr) if sum_%2!=0: return False else: return subs(arr,sum_//2,len(arr))
0
jainmuskan5653 weeks ago
int equalPartition(int N, int arr[]) { //knapsack algo will be used int sum=0; for(int i=0;i<N;i++){ sum+= arr[i]; } if(sum%2 !=0){ return 0; } else{ int k=sum/2; bool dp[N+1][k+1]; for(int i=0;i<=N;i++){ for(int j=0;j<=k;j++){ if(i==0){ dp[i][j]=false; } if(j==0){ dp[i][j]= true; } } } //dp[0][0]=false; for(int i=1;i<=N;i++){ for(int j=1;j<=k;j++){ if(arr[i-1]<=j){ dp[i][j]= dp[i-1][j] || dp[i-1][j-arr[i-1]]; } else{ dp[i][j]= dp[i-1][j]; } } } if(dp[N][k]==true){ return 1; } return 0; } }
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": 373,
"s": 238,
"text": "Given an array arr[] of size N, check if it can be partitioned into two parts such that the sum of elements in both parts is the same."
},
{
"code": null,
"e": 384,
"s": 373,
"text": "Example 1:"
},
{
"code": null,
"e": 483,
"s": 384,
"text": "Input: N = 4\narr = {1, 5, 11, 5}\nOutput: YES\nExplaination: \nThe two parts are {1, 5, 5} and {11}.\n"
},
{
"code": null,
"e": 494,
"s": 483,
"text": "Example 2:"
},
{
"code": null,
"e": 606,
"s": 494,
"text": "Input: N = 3\narr = {1, 3, 5}\nOutput: NO\nExplaination: This array can never be \npartitioned into two such parts."
},
{
"code": null,
"e": 846,
"s": 606,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function equalPartition() which takes the value N and the array as input parameters and returns 1 if the partition is possible. Otherwise, returns 0."
},
{
"code": null,
"e": 941,
"s": 846,
"text": "\nExpected Time Complexity: O(N*sum of elements)\nExpected Auxiliary Space: O(N*sum of elements)"
},
{
"code": null,
"e": 985,
"s": 941,
"text": "\nConstraints:\n1 ≤ N ≤ 100\n1 ≤ arr[i] ≤ 1000"
},
{
"code": null,
"e": 987,
"s": 985,
"text": "0"
},
{
"code": null,
"e": 1012,
"s": 987,
"text": "adarshgupta4014 days ago"
},
{
"code": null,
"e": 1045,
"s": 1012,
"text": "Easy Java DP knapSack technique-"
},
{
"code": null,
"e": 1840,
"s": 1045,
"text": "class Solution{\n static int equalPartition(int n, int nums[])\n {\n int sum = 0;\n for(int a : nums) sum += a;\n \n if(sum % 2 != 0) return 0; // return false if odd sum\n \n return subsetSum( nums,n, sum/2);\n }\n private static int subsetSum(int[] nums, int n, int sum){\n int dp[][] = new int[n+1][sum+1];\n \n for(int i =0 ; i< sum+1 ; ++i) dp[0][i] = 0;\n for(int i = 0; i< n+1 ; ++i) dp[i][0] = 1;\n \n for(int i = 1; i< n+1 ; i++){\n for( int j = 1; j < sum+1 ; j++){\n if(nums[i-1] <= j)\n dp[i][j] = Math.max( dp[i-1][j-nums[i-1]], dp[i-1][j] );\n else dp[i][j] = dp[i-1][j];\n }\n }\n return dp[n][sum];\n }\n}"
},
{
"code": null,
"e": 1842,
"s": 1840,
"text": "0"
},
{
"code": null,
"e": 1872,
"s": 1842,
"text": "milindprajapatmst196 days ago"
},
{
"code": null,
"e": 2475,
"s": 1872,
"text": "const int N = 1e2, M = 1e5;\nbool dp[N][M + 1];\n\nclass Solution {\npublic:\n int equalPartition(int n, int arr[]) {\n int _sum = 0;\n for (int i = 0; i < n; i++)\n _sum += arr[i];\n if (_sum & 1) return false;\n \n memset(dp, false, sizeof(dp));\n dp[0][0] = dp[0][arr[0]] = true;\n for (int i = 1; i < n; i++) {\n dp[i][0] = true;\n for (int j = 0; j <= _sum; j++) {\n dp[i][j] |= dp[i - 1][j];\n dp[i][j + arr[i]] |= dp[i - 1][j];\n }\n }\n return dp[n - 1][_sum >> 1];\n }\n};"
},
{
"code": null,
"e": 2478,
"s": 2475,
"text": "+1"
},
{
"code": null,
"e": 2504,
"s": 2478,
"text": "shishir17pandey1 week ago"
},
{
"code": null,
"e": 3038,
"s": 2504,
"text": " int sum=0; int n=N; for(int i=0;i<n;i++){ sum=sum+arr[i]; } int a=0; if(sum%2!=0){return false; } else{ a=sum/2; } bool dp[n+1][a+1]; dp[0][0]=true; for(int i=1;i<=n;i++){ for(int j=0;j<=a;j++){ if(j>=arr[i-1]){ dp[i][j]= dp[i-1][j] || dp[i-1][j-arr[i-1]]; } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][a]; }"
},
{
"code": null,
"e": 3040,
"s": 3038,
"text": "0"
},
{
"code": null,
"e": 3069,
"s": 3040,
"text": "deepakkumarshaw662 weeks ago"
},
{
"code": null,
"e": 4012,
"s": 3069,
"text": "int helperDP(int n, int *arr, int sum) { int **dp = new int*[n + 1]; for(int i = 0; i <= n; i++) dp[i] = new int[sum + 1]; //INITIALIZING FIRST ROW for(int i = 0; i <= sum; i++) dp[0][i] = 0; //INITIALISING FIRST COLUMN for(int i = 0; i <= n; i++) dp[i][0] = 1; //FILLING REAINING ROWS AND COLUMNS for(int i = 1; i <= n; i++) { for(int j = 1; j <= sum; j++) { if(arr[i - 1] <= j) dp[i][j] = dp[i - 1][j - arr[i - 1]] || dp[i - 1][j]; else dp[i][j] = dp[i - 1][j]; } } return dp[n][sum]; } int equalPartition(int N, int arr[]) { long sum = 0; for(int i = 0; i < N; i++) sum += arr[i]; //IF SUM IS ODD if(sum % 2 != 0) return 0; return helperDP(N, arr, sum/2); }"
},
{
"code": null,
"e": 4015,
"s": 4012,
"text": "+1"
},
{
"code": null,
"e": 4044,
"s": 4015,
"text": "aniketsaraswat1122 weeks ago"
},
{
"code": null,
"e": 4508,
"s": 4044,
"text": "int equalPartition(int n, int arr[]){\n int sum = 0; \n for(int i = 0; i<n; i++) sum += arr[i];\n if(sum&1) return 0;\n sum /= 2;\n int dp[n+1][sum+1] = {};\n for(int i = 0; i<n+1; i++) dp[i][0] = 1;\n for(int i = 1; i<n+1; i++){\n for(int j = 1; j<= sum; j++)\n if(dp[i-1][j] || (arr[i-1] <= j && dp[i-1][j-arr[i-1]])) \n dp[i][j] = 1;\n }\n return dp[n][sum];\n }"
},
{
"code": null,
"e": 4510,
"s": 4508,
"text": "0"
},
{
"code": null,
"e": 4530,
"s": 4510,
"text": "uratabhi3 weeks ago"
},
{
"code": null,
"e": 5296,
"s": 4530,
"text": "class Solution{public: int dp[102][1002]; Solution(){ memset(dp, -1, sizeof(dp)); } bool ispossible(int arr[], int N, int sum){ if(dp[N][sum]!=-1){ return dp[N][sum]; } if(sum==0) return 1; if(N<=0 || sum<0) return 0; if(arr[N-1]>sum){ dp[N][sum] = ispossible(arr, N-1, sum); } else{ dp[N][sum] = ispossible(arr, N-1, sum-arr[N-1]) || ispossible(arr, N-1, sum); } return dp[N][sum]; } int equalPartition(int N, int arr[]) { int sum =0; for(int i=0; i<N; i++) sum+=arr[i]; if(sum%2==1){ return 0; } int k = ispossible(arr, N, sum/2); return k; }};"
},
{
"code": null,
"e": 5298,
"s": 5296,
"text": "0"
},
{
"code": null,
"e": 5320,
"s": 5298,
"text": "pravin_swv3 weeks ago"
},
{
"code": null,
"e": 5371,
"s": 5320,
"text": "// { Driver Code Starts// Initial Template for C++"
},
{
"code": null,
"e": 5416,
"s": 5371,
"text": "#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 5471,
"s": 5416,
"text": "// } Driver Code Ends// User function Template for C++"
},
{
"code": null,
"e": 5494,
"s": 5471,
"text": "class Solution{public:"
},
{
"code": null,
"e": 6740,
"s": 5494,
"text": " // bool rec(int ind,int arr[],int sum,vector<vector<int>>dp) // { // //base case // if(sum==0) return true; // if(ind==0) // { // if(arr[0]==sum ) return true; // } // if(ind==0 && sum!=0) return false; // if(dp[ind][sum]!=-1) return dp[ind][sum]; // bool not_pick=rec(ind-1,arr,sum,dp); // bool pick=false; // if(arr[ind]<=sum) pick=rec(ind-1,arr,sum-arr[ind],dp); // return dp[ind][sum]=not_pick || pick; // } //Tabulation code int equalPartition(int N, int arr[]) { // code here int tot_sum=0; for(int i=0;i<N;i++) { tot_sum+=arr[i]; } if(tot_sum%2==1) return 0; int k=tot_sum/2; vector<vector<int>> dp( N , vector<int> (k+1, 0)); for(int i=0;i<N;i++) { dp[i][0]=1; } if(arr[0]<=k) dp[0][arr[0]]=1; for(int ind=1;ind<N;ind++){ for(int tar=1;tar<=k;tar++) { bool not_pick=dp[ind-1][tar]; bool pick=0; if(arr[ind]<=tar) pick=dp[ind-1][tar-arr[ind]]; dp[ind][tar]=not_pick || pick; } } return dp[N-1][k]; }};"
},
{
"code": null,
"e": 6765,
"s": 6740,
"text": "// { Driver Code Starts."
},
{
"code": null,
"e": 7071,
"s": 6765,
"text": "int main(){ int t; cin>>t; while(t--){ int N; cin>>N; int arr[N]; for(int i = 0;i < N;i++) cin>>arr[i]; Solution ob; if(ob.equalPartition(N, arr)) cout<<\"YES\\n\"; else cout<<\"NO\\n\"; } return 0;} // } Driver Code Ends"
},
{
"code": null,
"e": 7073,
"s": 7071,
"text": "0"
},
{
"code": null,
"e": 7105,
"s": 7073,
"text": "rounakdiptaghosh19993 weeks ago"
},
{
"code": null,
"e": 7578,
"s": 7105,
"text": "bool solve(int arr[],int n ,int sum) { int dp[n+1][sum+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=sum;j++){ if(i==0) dp[i][j]=false; if(j==0) dp[i][j]=true; } } for(int i=1;i<n+1;i++){ for(int j=1;j<sum+1;j++){ if(arr[i-1]<=j) dp[i][j]=dp[i-1][j-arr[i-1]]||dp[i-1][j]; else dp[i][j]=dp[i-1][j]; } } return dp[n][sum]; }"
},
{
"code": null,
"e": 7784,
"s": 7578,
"text": " int equalPartition(int n, int arr[]) { // code here int sum=0; for(int i=0;i<n;i++) sum+=arr[i]; if(sum%2!=0) return false; else if(sum%2==0) return solve(arr,n,sum/2); }"
},
{
"code": null,
"e": 7786,
"s": 7784,
"text": "0"
},
{
"code": null,
"e": 7811,
"s": 7786,
"text": "rockskhare2613 weeks ago"
},
{
"code": null,
"e": 7821,
"s": 7811,
"text": "#DP_LOGIC"
},
{
"code": null,
"e": 8406,
"s": 7821,
"text": "class Solution: def equalPartition(self, N, arr): def subs(arr,sum_,n): dp=[[False]*(sum_+1) for i in range(n+1)] for i in range(n+1): dp[i][0]=True for i in range(n+1): for j in range(sum_+1): if arr[i-1]>j: dp[i][j]=dp[i-1][j] else: dp[i][j] = dp[i - 1][j] or dp[i - 1][j-arr[i-1]] return dp[n][sum_] sum_=sum(arr) if sum_%2!=0: return False else: return subs(arr,sum_//2,len(arr)) "
},
{
"code": null,
"e": 8408,
"s": 8406,
"text": "0"
},
{
"code": null,
"e": 8433,
"s": 8408,
"text": "jainmuskan5653 weeks ago"
},
{
"code": null,
"e": 9403,
"s": 8433,
"text": "int equalPartition(int N, int arr[]) { //knapsack algo will be used int sum=0; for(int i=0;i<N;i++){ sum+= arr[i]; } if(sum%2 !=0){ return 0; } else{ int k=sum/2; bool dp[N+1][k+1]; for(int i=0;i<=N;i++){ for(int j=0;j<=k;j++){ if(i==0){ dp[i][j]=false; } if(j==0){ dp[i][j]= true; } } } //dp[0][0]=false; for(int i=1;i<=N;i++){ for(int j=1;j<=k;j++){ if(arr[i-1]<=j){ dp[i][j]= dp[i-1][j] || dp[i-1][j-arr[i-1]]; } else{ dp[i][j]= dp[i-1][j]; } } } if(dp[N][k]==true){ return 1; } return 0; } }"
},
{
"code": null,
"e": 9549,
"s": 9403,
"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": 9585,
"s": 9549,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9595,
"s": 9585,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9605,
"s": 9595,
"text": "\nContest\n"
},
{
"code": null,
"e": 9668,
"s": 9605,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9816,
"s": 9668,
"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": 10024,
"s": 9816,
"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": 10130,
"s": 10024,
"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 insert data in MySQL database from an HTML form using Django
|
Theory of Computation
In this article, you will learn how to insert a contact form data to a MySQL database using Django. Django is a free, open-source Python based framework. It enables fast development of any type of web applications. Like other programming languages, it can easily connect with a database. Django opens a connection to the database when it first makes a database query. It keeps this connection open and reuses it in subsequent requests. Here, we have explained the insertion process in detail. For this, we have created an HTML template file that contains a 'Contact' form.
For creating a new Django project, open your terminal window and activate the virtual environment. If you want to know more about how to install and activate the virtual environment, you can look at this article Install Virtual Environment. The following command creates a new Django project 'contactform' and an application 'contact'.
(env) c:\python37\Scripts\projects>django-admin startproject contactform
(env) c:\python37\Scripts\projects>cd contactform
(env) c:\python37\Scripts\projects\contactform>django-admin startapp contact
You can see a folder on your current project containing the django files named 'contactform'.
Suppose we have a MySQL database name 'employee'. For connecting to MySQL with Django, we will have to do database configuration changes in 'settings.py'. Make sure to replace 'NAME', 'USER', 'PASSWORD' and 'HOST' with your database configurations.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'employee',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
The Model helps to map the fields to the database. It represents a database table. To do this, look for the file 'models.py' in your app folder and place the following code. It has five fields - cid, fullname, email, contact, message.
from django.db import models
class ContactForm(models.Model):
fullname= models.CharField(max_length=100)
email= models.EmailField()
contact= models.CharField(max_length=50)
message= models.CharField(max_length=200)
The ModelForm is required to collect the form data. So, we have created a ModelForm 'forms.py' in the app directory, whose fields are taken from the database table.
from django import forms
from .models import ContactForm
class FormContactForm(forms.ModelForm):
class Meta:
model= ContactForm
fields= ["fullname", "email", "contact", "message"]
We have placed the following code in 'views.py'. It takes the data that the user has entered into the contect form fields and insert the data into a database. The 'form.save()' method is responsible for saving the form data to the database.
from django.shortcuts import render
from .forms import FormContactForm
def showform(request):
form= FormContactForm(request.POST or None)
if form.is_valid():
form.save()
context= {'form': form }
return render(request, 'contactform.html', context)
Next, we should have a user interface where user can submit a form. So, we have created an HTML template file 'contactform.html'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Contact Form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form method="POST" class="post-form" action="#">
{% csrf_token %}
<div class="container">
<div class="form-group">
<label for="fullname" class="control-label col-sm-2">Full Name</label>
<div class="col-sm-10">
<input type="text" name="fullname" value=""/>
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-sm-2">Email</label>
<div class="col-sm-10">
<input type="text" name="email" value=""/>
</div>
</div>
<div class="form-group">
<label for="contact" class="control-label col-sm-2">Contact</label>
<div class="col-sm-10">
<input type="text" name="contact" value=""/>
</div>
</div>
<div class="form-group">
<label for="message" class="control-label col-sm-2">Message</label>
<div class="col-sm-10">
<input type="text" name="message" value=""/>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>
At last, we have added a path to the route page to the particular link.
from django.contrib import admin
from django.urls import path
from contact import views
urlpatterns = [
path('admin/', admin.site.urls),
path('showform', views.showform),
]
Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...
In this article, we have mentioned the analyzed results of the best programming language for 2021...
Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...
Python has a set of useful Libraries and Packages that minimize the use of code...
July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 685,
"s": 112,
"text": "In this article, you will learn how to insert a contact form data to a MySQL database using Django. Django is a free, open-source Python based framework. It enables fast development of any type of web applications. Like other programming languages, it can easily connect with a database. Django opens a connection to the database when it first makes a database query. It keeps this connection open and reuses it in subsequent requests. Here, we have explained the insertion process in detail. For this, we have created an HTML template file that contains a 'Contact' form."
},
{
"code": null,
"e": 1021,
"s": 685,
"text": "For creating a new Django project, open your terminal window and activate the virtual environment. If you want to know more about how to install and activate the virtual environment, you can look at this article Install Virtual Environment. The following command creates a new Django project 'contactform' and an application 'contact'."
},
{
"code": null,
"e": 1223,
"s": 1021,
"text": "(env) c:\\python37\\Scripts\\projects>django-admin startproject contactform\n\n(env) c:\\python37\\Scripts\\projects>cd contactform\n\n(env) c:\\python37\\Scripts\\projects\\contactform>django-admin startapp contact"
},
{
"code": null,
"e": 1317,
"s": 1223,
"text": "You can see a folder on your current project containing the django files named 'contactform'."
},
{
"code": null,
"e": 1566,
"s": 1317,
"text": "Suppose we have a MySQL database name 'employee'. For connecting to MySQL with Django, we will have to do database configuration changes in 'settings.py'. Make sure to replace 'NAME', 'USER', 'PASSWORD' and 'HOST' with your database configurations."
},
{
"code": null,
"e": 1880,
"s": 1566,
"text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'employee',\n 'USER': 'root',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '3306',\n 'OPTIONS': {\n 'init_command': \"SET sql_mode='STRICT_TRANS_TABLES'\"\n } \n }\n}"
},
{
"code": null,
"e": 2115,
"s": 1880,
"text": "The Model helps to map the fields to the database. It represents a database table. To do this, look for the file 'models.py' in your app folder and place the following code. It has five fields - cid, fullname, email, contact, message."
},
{
"code": null,
"e": 2348,
"s": 2115,
"text": "from django.db import models\n\nclass ContactForm(models.Model):\n fullname= models.CharField(max_length=100)\n email= models.EmailField()\n contact= models.CharField(max_length=50)\n message= models.CharField(max_length=200)\n"
},
{
"code": null,
"e": 2513,
"s": 2348,
"text": "The ModelForm is required to collect the form data. So, we have created a ModelForm 'forms.py' in the app directory, whose fields are taken from the database table."
},
{
"code": null,
"e": 2715,
"s": 2513,
"text": "from django import forms\nfrom .models import ContactForm\n\nclass FormContactForm(forms.ModelForm):\n class Meta:\n model= ContactForm\n fields= [\"fullname\", \"email\", \"contact\", \"message\"]\n"
},
{
"code": null,
"e": 2956,
"s": 2715,
"text": "We have placed the following code in 'views.py'. It takes the data that the user has entered into the contect form fields and insert the data into a database. The 'form.save()' method is responsible for saving the form data to the database."
},
{
"code": null,
"e": 3241,
"s": 2956,
"text": "from django.shortcuts import render\nfrom .forms import FormContactForm\n\ndef showform(request):\n form= FormContactForm(request.POST or None)\n if form.is_valid():\n form.save()\n \n context= {'form': form }\n \n return render(request, 'contactform.html', context)\n"
},
{
"code": null,
"e": 3371,
"s": 3241,
"text": "Next, we should have a user interface where user can submit a form. So, we have created an HTML template file 'contactform.html'."
},
{
"code": null,
"e": 4734,
"s": 3371,
"text": "<!DOCTYPE html> \n<html lang=\"en\"> \n<head> \n<meta charset=\"UTF-8\"> \n<title>Django Contact Form</title> \n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> \n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script> \n<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"></script> \n</head> \n<body> \n<form method=\"POST\" class=\"post-form\" action=\"#\"> \n{% csrf_token %} \n<div class=\"container\"> \n<div class=\"form-group\">\n\t<label for=\"fullname\" class=\"control-label col-sm-2\">Full Name</label>\n\t<div class=\"col-sm-10\">\n\t<input type=\"text\" name=\"fullname\" value=\"\"/>\n\t</div>\n</div> \n<div class=\"form-group\">\n\t<label for=\"email\" class=\"control-label col-sm-2\">Email</label>\n\t<div class=\"col-sm-10\">\n\t<input type=\"text\" name=\"email\" value=\"\"/>\n\t</div>\n</div> \n<div class=\"form-group\">\n\t<label for=\"contact\" class=\"control-label col-sm-2\">Contact</label>\n\t<div class=\"col-sm-10\">\n\t<input type=\"text\" name=\"contact\" value=\"\"/>\n\t</div>\n</div> \n<div class=\"form-group\">\n\t<label for=\"message\" class=\"control-label col-sm-2\">Message</label>\n\t<div class=\"col-sm-10\">\n\t<input type=\"text\" name=\"message\" value=\"\"/>\n\t</div>\n</div> \n<div class=\"form-group\">\n<button type=\"submit\" class=\"btn btn-default\">Submit</button> \n</div>\n</div> \n</form> \n</body> \n</html> "
},
{
"code": null,
"e": 4806,
"s": 4734,
"text": "At last, we have added a path to the route page to the particular link."
},
{
"code": null,
"e": 4988,
"s": 4806,
"text": "from django.contrib import admin\nfrom django.urls import path\nfrom contact import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('showform', views.showform),\n]"
},
{
"code": null,
"e": 5134,
"s": 4988,
"text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n"
},
{
"code": null,
"e": 5250,
"s": 5134,
"text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..."
},
{
"code": null,
"e": 5403,
"s": 5250,
"text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n"
},
{
"code": null,
"e": 5504,
"s": 5403,
"text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..."
},
{
"code": null,
"e": 5643,
"s": 5504,
"text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n"
},
{
"code": null,
"e": 5726,
"s": 5643,
"text": "Python has a set of useful Libraries and Packages that minimize the use of code..."
},
{
"code": null,
"e": 5892,
"s": 5726,
"text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n"
},
{
"code": null,
"e": 6026,
"s": 5892,
"text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..."
},
{
"code": null,
"e": 6193,
"s": 6026,
"text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n"
},
{
"code": null,
"e": 6314,
"s": 6193,
"text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..."
}
] |
PostgreSQL - Array Function
|
PostgreSQL ARRAY_AGG function is used to concatenate the input values including null into an array.
To understand the ARRAY_AGG function, consider the table COMPANY having records as follows −
testdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Now, based on the above table, suppose you want to use the ARRAY_AGG, you can do so by using the following command −
testdb=# SELECT ARRAY_AGG(SALARY) FROM COMPANY;
The above given PostgreSQL statement will produce the following result −
array_agg
---------------------------------------------
{20000,15000,20000,65000,85000,45000,10000}
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2925,
"s": 2825,
"text": "PostgreSQL ARRAY_AGG function is used to concatenate the input values including null into an array."
},
{
"code": null,
"e": 3018,
"s": 2925,
"text": "To understand the ARRAY_AGG function, consider the table COMPANY having records as follows −"
},
{
"code": null,
"e": 3410,
"s": 3018,
"text": "testdb# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 3527,
"s": 3410,
"text": "Now, based on the above table, suppose you want to use the ARRAY_AGG, you can do so by using the following command −"
},
{
"code": null,
"e": 3575,
"s": 3527,
"text": "testdb=# SELECT ARRAY_AGG(SALARY) FROM COMPANY;"
},
{
"code": null,
"e": 3648,
"s": 3575,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 3768,
"s": 3648,
"text": " array_agg\n---------------------------------------------\n {20000,15000,20000,65000,85000,45000,10000}\n"
},
{
"code": null,
"e": 3803,
"s": 3768,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3815,
"s": 3803,
"text": " John Elder"
},
{
"code": null,
"e": 3850,
"s": 3815,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3866,
"s": 3850,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 3903,
"s": 3866,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3925,
"s": 3903,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3958,
"s": 3925,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3972,
"s": 3958,
"text": " Karthikeya T"
},
{
"code": null,
"e": 4003,
"s": 3972,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4016,
"s": 4003,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4047,
"s": 4016,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 4060,
"s": 4047,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4067,
"s": 4060,
"text": " Print"
},
{
"code": null,
"e": 4078,
"s": 4067,
"text": " Add Notes"
}
] |
Defining the Moving Average Model for Time Series Forecasting in Python | by Marco Peixeiro | Towards Data Science
|
One of the foundational models for time series forecasting is the moving average model, denoted as MA(q). This is one of the basic statistical models that is a building block of more complex models such as the ARMA, ARIMA, SARIMA and SARIMAX models. A deep understanding of the MA(q) is thus a key step prior to using more complex models to forecast intricate time series.
In this article, we first define the moving average process and explore its inner workings. We then use a dataset to apply our knowledge and use the ACF plot to determine the order of an MA(q) model.
This article is an excerpt of my upcoming book Time Series Forecasting in Python. If you are interested in learning more about time series forecasting, using both statistical and deep learning models with applied scenarios, you can learn more here.
You can grab the dataset here. Note that the data is synthetic, as we rarely observe real-life time series that can be modeled with a pure moving average process. This dataset is thus for learning purposes.
The full source code is available here.
A moving average process, or the moving average model, states that the current value is linearly dependent on the current and past error terms. Again, the error terms are assumed to be mutually independent and normally distributed, just like white noise.
A moving average model is denoted as MA(q) where q is the order. The model expresses the present value as a linear combination of the mean of the series (mu), the present error term (epsilon), and past error terms (epsilon). The magnitude of the impact of past errors on the present value is quantified using a coefficient denoted with theta. Mathematically, we express a general moving average process as follows:
The order q of the moving average model determines the number of past error terms that affect the present value. For example, if it is of order one, meaning that we have a MA(1) process, then the model is expressed as follows:
If we have a moving average process of order two, or MA(2), then we express the equation like this:
Hence, we can see how the order q of the MA(q) process affects the number of past error terms that must be included in the model. The larger q is, the more past error terms affect the present value. Therefore, it is important to determine the order of the moving average process in order to fit the appropriate model, meaning that if we have a second-order moving average process, then a second-order moving average model will be used for forecasting.
To identify the order of a moving average process, we follow the steps outlined below:
As usual, the first step is to gather the data. Then, we test for stationarity. In the event where our series is not stationary, we apply transformations, such as differencing, until the series is stationary. Then, we plot the ACF and look for significant autocorrelation coefficients. In the case of a random walk, we will not see significant coefficients after lag 0. On the other hand, if we see significant coefficients, then we must check if they become abruptly non-significant after some lag q. If that is the case, then we know that we have a moving average process of order q. Otherwise, we must follow a different set of steps to discover the underlying process of our time series.
Let’s put this in action using our data for the volume of sales of widgets for the XYZ Widget Company. The dataset contains 500 days of sales volume data starting on January 1, 2019. We will follow the set of steps outlined in figure 4.3 and determine the order of the underlying moving average process.
The first step is to gather the data. While this step was already done for you, this is a great time to load the data into a DataFrame using pandas and display the first five rows of data:
import pandas as pdf = pd.read_csv('data/widget_sales.csv')df.head()
You see that our volume of sales is in the column widget_sales. Note that the volume of sales is in units of thousands of US dollars.
We can then plot the data using the following piece of code:
import matplotlib.pyplot as pltfig, ax = plt.subplots()ax.plot(df.widget_sales) ax.set_xlabel('Time') ax.set_ylabel('Widget sales (k$)') plt.xticks([0, 30, 57, 87, 116, 145, 175, 204, 234, 264, 293, 323, 352, 382, 409, 439, 468, 498],['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '2020', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) #Dfig.autofmt_xdate()plt.tight_layout()
The next step is to test for stationarity. We intuitively know that the series is not stationary since there is an observable trend as see in the figure above. Still, we will use the ADF test to make sure. Again, we use the adfuller function from the statsmodels library and extract the ADF statistic and p-value. If the ADF statistic is a large negative number and the p-value is smaller than 0.05, then our series is stationary. Otherwise, we must apply transformations.
from statsmodels.tsa.stattools import adfullerADF_result = adfuller(df.widget_sales) print(f'ADF Statistic: {ADF_result[0]}') print(f'p-value: {ADF_result[1]}')
This results in an ADF statistic of -1.51 and a p-value of 0.53. Here, the ADF statistic is not a large negative number and the p-value is greater than 0.05. Therefore, our time series is not stationary and we must apply transformations to make it stationary.
In order to make our series stationary, we will try to stabilize the trend by applying a first-order differencing. We can do so by using the diff method from the numpy library. Remember that this method takes in a parameter n that specifies the order of differencing. In this case, because it is a first-order differencing, n will be equal to 1.
import numpy as npwidget_sales_diff = np.diff(df.widget_sales, n=1)
With a transformation applied to our series, we can test for stationarity again using the ADF test. This time, make sure to run the test on the differenced data stored in the widget_sales_diff variable.
ADF_result = adfuller(widget_sales_diff)print(f'ADF Statistic: {ADF_result[0]}')print(f'p-value: {ADF_result[1]}')
This gives an ADF statistic of -10.6 and a p-value of virtually 0. Therefore, with a large negative ADF statistic and a p-value much smaller than 0.05, we can say that our series is stationary.
Our next step is to plot the autocorrelation function. The statsmodels library conveniently includes the plot_acf function for us. We simply pass in our differenced series and specify the number of lags in the lags parameter. Remember that the number of lags determines the range of values on the x-axis.
from statsmodels.graphics.tsaplots import plot_acfplot_acf(widget_sales_diff, lags=30);plt.tight_layout()
The resulting ACF plot is shown below. We notice that there are significant coefficients after lag 0. In fact, they are significant up until lag 2. Then, they abruptly become non-significant as they remain in the shaded area of the plot. We can see some significance around lag 20, but this is likely due to chance, as the following coefficients are not significant.
Since we have significant autocorrelation coefficients up until lag 2, this means that we have a stationary moving average process of order 2. Therefore, we can use a second-order moving average model, or MA(2) model, to forecast our stationary time series.
Thus, we can see how the ACF plot helps us determine the order of a moving average process. The ACF plot will show significant autocorrelation coefficients up until lag q, after which all coefficients will be non-significant. We can then conclude that we have a moving average process of order q or MA(q) process. In our case, working with the volume of widget sales, we discovered that the stationary process is a second-order moving average process since the ACF plot showed significant coefficients up until lag 2.
In this article, we defined the moving average process and experienced how the ACF plot can be used to find the right order of the MA(q) model. This model can be used to forecast the time series.
I hope you enjoyed the read!
Cheers 🍺!
Source: Time Series Forecasting in Python
|
[
{
"code": null,
"e": 544,
"s": 171,
"text": "One of the foundational models for time series forecasting is the moving average model, denoted as MA(q). This is one of the basic statistical models that is a building block of more complex models such as the ARMA, ARIMA, SARIMA and SARIMAX models. A deep understanding of the MA(q) is thus a key step prior to using more complex models to forecast intricate time series."
},
{
"code": null,
"e": 744,
"s": 544,
"text": "In this article, we first define the moving average process and explore its inner workings. We then use a dataset to apply our knowledge and use the ACF plot to determine the order of an MA(q) model."
},
{
"code": null,
"e": 993,
"s": 744,
"text": "This article is an excerpt of my upcoming book Time Series Forecasting in Python. If you are interested in learning more about time series forecasting, using both statistical and deep learning models with applied scenarios, you can learn more here."
},
{
"code": null,
"e": 1200,
"s": 993,
"text": "You can grab the dataset here. Note that the data is synthetic, as we rarely observe real-life time series that can be modeled with a pure moving average process. This dataset is thus for learning purposes."
},
{
"code": null,
"e": 1240,
"s": 1200,
"text": "The full source code is available here."
},
{
"code": null,
"e": 1495,
"s": 1240,
"text": "A moving average process, or the moving average model, states that the current value is linearly dependent on the current and past error terms. Again, the error terms are assumed to be mutually independent and normally distributed, just like white noise."
},
{
"code": null,
"e": 1910,
"s": 1495,
"text": "A moving average model is denoted as MA(q) where q is the order. The model expresses the present value as a linear combination of the mean of the series (mu), the present error term (epsilon), and past error terms (epsilon). The magnitude of the impact of past errors on the present value is quantified using a coefficient denoted with theta. Mathematically, we express a general moving average process as follows:"
},
{
"code": null,
"e": 2137,
"s": 1910,
"text": "The order q of the moving average model determines the number of past error terms that affect the present value. For example, if it is of order one, meaning that we have a MA(1) process, then the model is expressed as follows:"
},
{
"code": null,
"e": 2237,
"s": 2137,
"text": "If we have a moving average process of order two, or MA(2), then we express the equation like this:"
},
{
"code": null,
"e": 2689,
"s": 2237,
"text": "Hence, we can see how the order q of the MA(q) process affects the number of past error terms that must be included in the model. The larger q is, the more past error terms affect the present value. Therefore, it is important to determine the order of the moving average process in order to fit the appropriate model, meaning that if we have a second-order moving average process, then a second-order moving average model will be used for forecasting."
},
{
"code": null,
"e": 2776,
"s": 2689,
"text": "To identify the order of a moving average process, we follow the steps outlined below:"
},
{
"code": null,
"e": 3468,
"s": 2776,
"text": "As usual, the first step is to gather the data. Then, we test for stationarity. In the event where our series is not stationary, we apply transformations, such as differencing, until the series is stationary. Then, we plot the ACF and look for significant autocorrelation coefficients. In the case of a random walk, we will not see significant coefficients after lag 0. On the other hand, if we see significant coefficients, then we must check if they become abruptly non-significant after some lag q. If that is the case, then we know that we have a moving average process of order q. Otherwise, we must follow a different set of steps to discover the underlying process of our time series."
},
{
"code": null,
"e": 3772,
"s": 3468,
"text": "Let’s put this in action using our data for the volume of sales of widgets for the XYZ Widget Company. The dataset contains 500 days of sales volume data starting on January 1, 2019. We will follow the set of steps outlined in figure 4.3 and determine the order of the underlying moving average process."
},
{
"code": null,
"e": 3961,
"s": 3772,
"text": "The first step is to gather the data. While this step was already done for you, this is a great time to load the data into a DataFrame using pandas and display the first five rows of data:"
},
{
"code": null,
"e": 4031,
"s": 3961,
"text": "import pandas as pdf = pd.read_csv('data/widget_sales.csv')df.head() "
},
{
"code": null,
"e": 4165,
"s": 4031,
"text": "You see that our volume of sales is in the column widget_sales. Note that the volume of sales is in units of thousands of US dollars."
},
{
"code": null,
"e": 4226,
"s": 4165,
"text": "We can then plot the data using the following piece of code:"
},
{
"code": null,
"e": 4642,
"s": 4226,
"text": "import matplotlib.pyplot as pltfig, ax = plt.subplots()ax.plot(df.widget_sales) ax.set_xlabel('Time') ax.set_ylabel('Widget sales (k$)') plt.xticks([0, 30, 57, 87, 116, 145, 175, 204, 234, 264, 293, 323, 352, 382, 409, 439, 468, 498],['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '2020', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) #Dfig.autofmt_xdate()plt.tight_layout() "
},
{
"code": null,
"e": 5115,
"s": 4642,
"text": "The next step is to test for stationarity. We intuitively know that the series is not stationary since there is an observable trend as see in the figure above. Still, we will use the ADF test to make sure. Again, we use the adfuller function from the statsmodels library and extract the ADF statistic and p-value. If the ADF statistic is a large negative number and the p-value is smaller than 0.05, then our series is stationary. Otherwise, we must apply transformations."
},
{
"code": null,
"e": 5278,
"s": 5115,
"text": "from statsmodels.tsa.stattools import adfullerADF_result = adfuller(df.widget_sales) print(f'ADF Statistic: {ADF_result[0]}') print(f'p-value: {ADF_result[1]}')"
},
{
"code": null,
"e": 5538,
"s": 5278,
"text": "This results in an ADF statistic of -1.51 and a p-value of 0.53. Here, the ADF statistic is not a large negative number and the p-value is greater than 0.05. Therefore, our time series is not stationary and we must apply transformations to make it stationary."
},
{
"code": null,
"e": 5884,
"s": 5538,
"text": "In order to make our series stationary, we will try to stabilize the trend by applying a first-order differencing. We can do so by using the diff method from the numpy library. Remember that this method takes in a parameter n that specifies the order of differencing. In this case, because it is a first-order differencing, n will be equal to 1."
},
{
"code": null,
"e": 5952,
"s": 5884,
"text": "import numpy as npwidget_sales_diff = np.diff(df.widget_sales, n=1)"
},
{
"code": null,
"e": 6155,
"s": 5952,
"text": "With a transformation applied to our series, we can test for stationarity again using the ADF test. This time, make sure to run the test on the differenced data stored in the widget_sales_diff variable."
},
{
"code": null,
"e": 6270,
"s": 6155,
"text": "ADF_result = adfuller(widget_sales_diff)print(f'ADF Statistic: {ADF_result[0]}')print(f'p-value: {ADF_result[1]}')"
},
{
"code": null,
"e": 6464,
"s": 6270,
"text": "This gives an ADF statistic of -10.6 and a p-value of virtually 0. Therefore, with a large negative ADF statistic and a p-value much smaller than 0.05, we can say that our series is stationary."
},
{
"code": null,
"e": 6769,
"s": 6464,
"text": "Our next step is to plot the autocorrelation function. The statsmodels library conveniently includes the plot_acf function for us. We simply pass in our differenced series and specify the number of lags in the lags parameter. Remember that the number of lags determines the range of values on the x-axis."
},
{
"code": null,
"e": 6875,
"s": 6769,
"text": "from statsmodels.graphics.tsaplots import plot_acfplot_acf(widget_sales_diff, lags=30);plt.tight_layout()"
},
{
"code": null,
"e": 7242,
"s": 6875,
"text": "The resulting ACF plot is shown below. We notice that there are significant coefficients after lag 0. In fact, they are significant up until lag 2. Then, they abruptly become non-significant as they remain in the shaded area of the plot. We can see some significance around lag 20, but this is likely due to chance, as the following coefficients are not significant."
},
{
"code": null,
"e": 7500,
"s": 7242,
"text": "Since we have significant autocorrelation coefficients up until lag 2, this means that we have a stationary moving average process of order 2. Therefore, we can use a second-order moving average model, or MA(2) model, to forecast our stationary time series."
},
{
"code": null,
"e": 8018,
"s": 7500,
"text": "Thus, we can see how the ACF plot helps us determine the order of a moving average process. The ACF plot will show significant autocorrelation coefficients up until lag q, after which all coefficients will be non-significant. We can then conclude that we have a moving average process of order q or MA(q) process. In our case, working with the volume of widget sales, we discovered that the stationary process is a second-order moving average process since the ACF plot showed significant coefficients up until lag 2."
},
{
"code": null,
"e": 8214,
"s": 8018,
"text": "In this article, we defined the moving average process and experienced how the ACF plot can be used to find the right order of the MA(q) model. This model can be used to forecast the time series."
},
{
"code": null,
"e": 8243,
"s": 8214,
"text": "I hope you enjoyed the read!"
},
{
"code": null,
"e": 8253,
"s": 8243,
"text": "Cheers 🍺!"
}
] |
Automate Your Python Script with Process Manager 2 (PM2) | by Joe T. Santhanavanich | Towards Data Science
|
In Data Science, you may have to run or process your Python script periodically especially the data collection to make your workflow up-to-date as it directly related to your result accuracy. You may have a Python script to run every 1,2,..., xx minutes/hours or at 6 am, 9 pm, yy am/pm every day. And doing it yourself every time is tiresome and boring.
When you google about it online, there might have already been several articles talking about it. If you are using Windows, you may consider using a Windows Task Scheduler which you can schedule your windows system to run any execute (.exe) or batch (.bat) file. Although it has a good-looking user interface, some people still don’t like it so much. (Source here)
Or if you are using macOS or Linux, you might consider using a Crontab. But you may find it difficult to manage when you have too many scripts or jobs to manage/logging.
So, let’s check this alternative solution >>>
PM2 is the Process Manager which is built for Node.js application.
As my experience in web development using Node.js. I had to schedule and manage several Node.js applications with CRON which give me a very hard time until I knew PM2!! My life is much better since then. The PM2 keeps my apps running forever and automatically reloads when I updated something to the app. Also, I can manually schedule the reload time with CRON or the restart delay on any application and it can run perfectly on all operation systems!!
NO! It is true that PM2 is intended to serve Node.js application but it is not limited to the Node.js runtime. After I used PM2 for some time, I realized that it can be used to manage any programming script/runtime! From that moment, I tried it with Python and it works just fine!
In this article, I will show an example of how you can schedule and automate your Python script using PM2!!
Installing can be also done in one line which you can either use npm or yarn .
$ npm install pm2@latest -g# OR $ yarn global add pm2# Done!# Check if program runs.$ pm2 -vvx.x.x
If you install PM2 on your Windows 10, the first time you run it you may face an error due to the current user having an undefined ExecutionPolicy. You can fix it by the following code:
$ Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
After installation is done, you can start any python script through the PM2 by using $ pm2 start <script name> command.
If you have multiple jobs to run, I also recommend naming each job meaningfully so that you won’t get confused later. You can name each job with --name <name>. By default, PM2 will run your script with Python when you start any .py file. However, if you have several versions of Python installed in your machine, you may select a specific Python version with--interpreter <interpreter name: node, python, python3, python3.x, ...>.
Overall, the command to start a python script would look like this:
$ pm2 start job1.py --name job1 --interpreter python3
By PM2 default setting, it will try to make your app run forever which means your script will be automatically restarted immediately after it finishes.
Well, that may be too much for a machine! So, there are 2 ways to set your Python script to run periodically with PM2: 1. using restart-delay 2. using cron
You can set your Python script to run periodically with--restart-delay <xxxx ms> option. This way, after your Python script finishes its job, it will wait(sleep) for xxxx ms until the next restart.
For example, if you want your script to restart every 10 seconds after each job, you may normally use while & time.sleep as follows in your Python:
while True:... time.sleep(10)
With the PM2, you don’t need the while loop anymore, you can keep your code clean and left the restart job to PM2. The command to run your script with 10-second sleep after each job would look like this:
$ pm2 start job1.py --name job1-10s-delay --interpreter python3 --restart-delay 10000
You can also use cron option to schedule your Python script with--cron <'cron pattern'> . It is also important for you to deactivate the PM2 auto-restart option with --no-autorestart so it won't automatically restart itself after complete a job and will only follow the cron expression.
For example, the command to restart your script every 1 hour (at minute 0) would look like this:
$ pm2 start .\testPm2.py --cron '0 * * * *' --no-autorestart
A tip about cron: if you are new to cron. It is a time-based job scheduler in a Unix os. The cron schedule expression allows you to let your program restart periodically at a specific time. The format of cron is'<minutes 0:60> <hour 0:24> <day of month 1:31> <month 1:12> <day of week 0:6>'. I recommend that you may try to create your own cron expression through this website: here.
Let’s end this boring part and let’s go through a real-world example together!
Scraping Global COVID-19 Data
Assume, you want to monitor and store the data of COVID-19 cases from Worldometer every 5 minutes. You can do it easily using Beautifulsoap4. For example, my Python script (getCovid19Data.py) will allow you to get the COVID-19 case data from Worldometer and store data to the CSV file (world_corona_case.csv).
Instead of using while loop and time.sleep()inside the script or using regular cron to restart the script every 5 minutes.
You can do it using PM2 with restart-delay (5 min=300000 msec):
$ pm2 start getCovid19Data.py --name covid19-5minInt restart-delay 300000
Or, you can do it using PM2 with cron (5min = ‘*/5 * * * *’)
$ pm2 start getCovid19Data.py --name covid19-5minInt --cron '*/5 * * * *' --no-autorestart
That’s it! Now, the Python script gonna run every 5 minutes. Now you can check your logs with this command
$ pm2 l
The list table will show up. You can see here all the jobs that had been run with PM2 which will contain all your Node.js app or Python script running in the background.
You can use a commandpm2 log <id or name> to see the log of a specific job. In this example, you can use the following command:
$ pm2 log 0
From the log status, you can see that the Python script stores COVID-19 data every 5 minutes and the residual of [~1.6 to 2.5 seconds] is the time that Python script used to request data and save add updated data to CSV file each time. Now, let’s check the result in the result CSV file below. The PM2 works well!
When you have several processes running with PM2. You may want to manipulate each project differently. Here is a list of some useful commands I used most.
$ pm2 stop <name or id> #stop specific process$ pm2 restart <name or id> #restart specific process$ pm2 flush <name or id> #Clear logs of specific process$ pm2 save #save list of all application$ pm2 resurrect #brings back previously saved processes$ pm2 startup #Command for running PM2 on startup
I hope you enjoy this article and it helps you schedule your Python script easier and apply it to your Python workflow. Feel free to share with me if you have some questions, comments, or suggestions.
About me & Check out all my blog contents: Link
Be Safe and Healthy!Thank you for Reading. 👋😄
|
[
{
"code": null,
"e": 527,
"s": 172,
"text": "In Data Science, you may have to run or process your Python script periodically especially the data collection to make your workflow up-to-date as it directly related to your result accuracy. You may have a Python script to run every 1,2,..., xx minutes/hours or at 6 am, 9 pm, yy am/pm every day. And doing it yourself every time is tiresome and boring."
},
{
"code": null,
"e": 892,
"s": 527,
"text": "When you google about it online, there might have already been several articles talking about it. If you are using Windows, you may consider using a Windows Task Scheduler which you can schedule your windows system to run any execute (.exe) or batch (.bat) file. Although it has a good-looking user interface, some people still don’t like it so much. (Source here)"
},
{
"code": null,
"e": 1062,
"s": 892,
"text": "Or if you are using macOS or Linux, you might consider using a Crontab. But you may find it difficult to manage when you have too many scripts or jobs to manage/logging."
},
{
"code": null,
"e": 1108,
"s": 1062,
"text": "So, let’s check this alternative solution >>>"
},
{
"code": null,
"e": 1175,
"s": 1108,
"text": "PM2 is the Process Manager which is built for Node.js application."
},
{
"code": null,
"e": 1628,
"s": 1175,
"text": "As my experience in web development using Node.js. I had to schedule and manage several Node.js applications with CRON which give me a very hard time until I knew PM2!! My life is much better since then. The PM2 keeps my apps running forever and automatically reloads when I updated something to the app. Also, I can manually schedule the reload time with CRON or the restart delay on any application and it can run perfectly on all operation systems!!"
},
{
"code": null,
"e": 1909,
"s": 1628,
"text": "NO! It is true that PM2 is intended to serve Node.js application but it is not limited to the Node.js runtime. After I used PM2 for some time, I realized that it can be used to manage any programming script/runtime! From that moment, I tried it with Python and it works just fine!"
},
{
"code": null,
"e": 2017,
"s": 1909,
"text": "In this article, I will show an example of how you can schedule and automate your Python script using PM2!!"
},
{
"code": null,
"e": 2096,
"s": 2017,
"text": "Installing can be also done in one line which you can either use npm or yarn ."
},
{
"code": null,
"e": 2195,
"s": 2096,
"text": "$ npm install pm2@latest -g# OR $ yarn global add pm2# Done!# Check if program runs.$ pm2 -vvx.x.x"
},
{
"code": null,
"e": 2381,
"s": 2195,
"text": "If you install PM2 on your Windows 10, the first time you run it you may face an error due to the current user having an undefined ExecutionPolicy. You can fix it by the following code:"
},
{
"code": null,
"e": 2452,
"s": 2381,
"text": "$ Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted"
},
{
"code": null,
"e": 2572,
"s": 2452,
"text": "After installation is done, you can start any python script through the PM2 by using $ pm2 start <script name> command."
},
{
"code": null,
"e": 3003,
"s": 2572,
"text": "If you have multiple jobs to run, I also recommend naming each job meaningfully so that you won’t get confused later. You can name each job with --name <name>. By default, PM2 will run your script with Python when you start any .py file. However, if you have several versions of Python installed in your machine, you may select a specific Python version with--interpreter <interpreter name: node, python, python3, python3.x, ...>."
},
{
"code": null,
"e": 3071,
"s": 3003,
"text": "Overall, the command to start a python script would look like this:"
},
{
"code": null,
"e": 3125,
"s": 3071,
"text": "$ pm2 start job1.py --name job1 --interpreter python3"
},
{
"code": null,
"e": 3277,
"s": 3125,
"text": "By PM2 default setting, it will try to make your app run forever which means your script will be automatically restarted immediately after it finishes."
},
{
"code": null,
"e": 3433,
"s": 3277,
"text": "Well, that may be too much for a machine! So, there are 2 ways to set your Python script to run periodically with PM2: 1. using restart-delay 2. using cron"
},
{
"code": null,
"e": 3631,
"s": 3433,
"text": "You can set your Python script to run periodically with--restart-delay <xxxx ms> option. This way, after your Python script finishes its job, it will wait(sleep) for xxxx ms until the next restart."
},
{
"code": null,
"e": 3779,
"s": 3631,
"text": "For example, if you want your script to restart every 10 seconds after each job, you may normally use while & time.sleep as follows in your Python:"
},
{
"code": null,
"e": 3811,
"s": 3779,
"text": "while True:... time.sleep(10)"
},
{
"code": null,
"e": 4015,
"s": 3811,
"text": "With the PM2, you don’t need the while loop anymore, you can keep your code clean and left the restart job to PM2. The command to run your script with 10-second sleep after each job would look like this:"
},
{
"code": null,
"e": 4101,
"s": 4015,
"text": "$ pm2 start job1.py --name job1-10s-delay --interpreter python3 --restart-delay 10000"
},
{
"code": null,
"e": 4388,
"s": 4101,
"text": "You can also use cron option to schedule your Python script with--cron <'cron pattern'> . It is also important for you to deactivate the PM2 auto-restart option with --no-autorestart so it won't automatically restart itself after complete a job and will only follow the cron expression."
},
{
"code": null,
"e": 4485,
"s": 4388,
"text": "For example, the command to restart your script every 1 hour (at minute 0) would look like this:"
},
{
"code": null,
"e": 4546,
"s": 4485,
"text": "$ pm2 start .\\testPm2.py --cron '0 * * * *' --no-autorestart"
},
{
"code": null,
"e": 4930,
"s": 4546,
"text": "A tip about cron: if you are new to cron. It is a time-based job scheduler in a Unix os. The cron schedule expression allows you to let your program restart periodically at a specific time. The format of cron is'<minutes 0:60> <hour 0:24> <day of month 1:31> <month 1:12> <day of week 0:6>'. I recommend that you may try to create your own cron expression through this website: here."
},
{
"code": null,
"e": 5009,
"s": 4930,
"text": "Let’s end this boring part and let’s go through a real-world example together!"
},
{
"code": null,
"e": 5039,
"s": 5009,
"text": "Scraping Global COVID-19 Data"
},
{
"code": null,
"e": 5349,
"s": 5039,
"text": "Assume, you want to monitor and store the data of COVID-19 cases from Worldometer every 5 minutes. You can do it easily using Beautifulsoap4. For example, my Python script (getCovid19Data.py) will allow you to get the COVID-19 case data from Worldometer and store data to the CSV file (world_corona_case.csv)."
},
{
"code": null,
"e": 5472,
"s": 5349,
"text": "Instead of using while loop and time.sleep()inside the script or using regular cron to restart the script every 5 minutes."
},
{
"code": null,
"e": 5536,
"s": 5472,
"text": "You can do it using PM2 with restart-delay (5 min=300000 msec):"
},
{
"code": null,
"e": 5610,
"s": 5536,
"text": "$ pm2 start getCovid19Data.py --name covid19-5minInt restart-delay 300000"
},
{
"code": null,
"e": 5671,
"s": 5610,
"text": "Or, you can do it using PM2 with cron (5min = ‘*/5 * * * *’)"
},
{
"code": null,
"e": 5762,
"s": 5671,
"text": "$ pm2 start getCovid19Data.py --name covid19-5minInt --cron '*/5 * * * *' --no-autorestart"
},
{
"code": null,
"e": 5869,
"s": 5762,
"text": "That’s it! Now, the Python script gonna run every 5 minutes. Now you can check your logs with this command"
},
{
"code": null,
"e": 5877,
"s": 5869,
"text": "$ pm2 l"
},
{
"code": null,
"e": 6047,
"s": 5877,
"text": "The list table will show up. You can see here all the jobs that had been run with PM2 which will contain all your Node.js app or Python script running in the background."
},
{
"code": null,
"e": 6175,
"s": 6047,
"text": "You can use a commandpm2 log <id or name> to see the log of a specific job. In this example, you can use the following command:"
},
{
"code": null,
"e": 6187,
"s": 6175,
"text": "$ pm2 log 0"
},
{
"code": null,
"e": 6501,
"s": 6187,
"text": "From the log status, you can see that the Python script stores COVID-19 data every 5 minutes and the residual of [~1.6 to 2.5 seconds] is the time that Python script used to request data and save add updated data to CSV file each time. Now, let’s check the result in the result CSV file below. The PM2 works well!"
},
{
"code": null,
"e": 6656,
"s": 6501,
"text": "When you have several processes running with PM2. You may want to manipulate each project differently. Here is a list of some useful commands I used most."
},
{
"code": null,
"e": 6955,
"s": 6656,
"text": "$ pm2 stop <name or id> #stop specific process$ pm2 restart <name or id> #restart specific process$ pm2 flush <name or id> #Clear logs of specific process$ pm2 save #save list of all application$ pm2 resurrect #brings back previously saved processes$ pm2 startup #Command for running PM2 on startup"
},
{
"code": null,
"e": 7156,
"s": 6955,
"text": "I hope you enjoy this article and it helps you schedule your Python script easier and apply it to your Python workflow. Feel free to share with me if you have some questions, comments, or suggestions."
},
{
"code": null,
"e": 7204,
"s": 7156,
"text": "About me & Check out all my blog contents: Link"
}
] |
Characteristics of a Clean Code - GeeksforGeeks
|
17 Apr, 2020
Programmers or developers usually write codes for their project or for some companies. Or some start writing code as a beginner in the programming world. In all these scenarios a nostalgic moment comes when you revisit your code after a long time. You find your own code so difficult to understand. Here are a few good practices or the characteristics of a clean code that you should follow:
1. Naming Conventions: This is a very basic practice to be followed. Correct naming the variables and functions are very much important. Suppose someone is going to check your code then he/she should be able to understand the code at a glance.
One should name the variables according to the project domain.
One should use ‘is’ as a prefix to Boolean variables.
Example: Suppose you are creating a banking app or something that has to do with payment.
double totalBalance; // Represents the user account balance
double amountToDebit; // Represents the amount to charge the user
double amountToCredit; // Represents the amount to give to the user
boolean isUserActive;
One Must Follow:
Camel Case for variables and data structures.Example:String merchantName = "John Perry";
int integerArray[] = new int[10];
Example:
String merchantName = "John Perry";
int integerArray[] = new int[10];
Screaming Snake Case for Constants.Example:final long ACCOUNT_NUMBER = 123456;
Example:
final long ACCOUNT_NUMBER = 123456;
2. Its all about methods/functions
“The more useful methods you write the better coder you are”– Mitch Tabian, CodingWithMitch
Use Camel Case for naming functions.
Name the functions on the verb-noun sounds.
Opening bracket of the method must be on the same line as the method name.
Function should only accept 1 or 2 arguments not more than that.
Example:
double getUserBalance(long int accountNumber) {
// Method Defination
}
3. File Structure: It’s very much important to maintain the structure of the project. This makes it very clean and more understandable. The structure differs from web development to mobile development but the idea remains the same.
Example:
4. Indentation: Sometimes you write some code and that code is composed inside another or you can say the nested code. This composition is very tricky to sort and to differentiate is not easy. So it is better to use indentation. It means to put the brackets in the right place.
5. Logging: When it comes to writing code it doesn’t mean that you just write code and boom compiled successfully. It is far from the truth that someday or many times you will have to debug. Writing log statements helps you in those dreadful moments. Writing log statements in functions is a great choice. Most processing is done through function so having a log statement there means we can get an indication of success and failure.
6. Avoiding self-explanatory comments: We all like to add the comment around the code. On an important note, we should avoid comments that are self-explanatory as its time consuming and useless. One should write code that explains itself.
Example:
final double PI = 3.14; // This is pi value //
The above statement’s comment isn’t necessary. So avoid this practice.
gupta_shrinath
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Add External JAR File to an IntelliJ IDEA Project?
How to Delete Temporary Files in Windows 10?
How to Convert Kotlin Code to Java Code in Android Studio?
Difference between RUN vs CMD vs ENTRYPOINT Docker Commands
How to Install Flutter on Windows?
How to Install Z Shell(zsh) on Linux?
How to Clone Android Project from GitHub in Android Studio?
How to Access Localhost on Mobile Browsers?
How to setup OpenGL with Visual Studio 2019 on Windows 10?
Autorun a Python script on windows startup
|
[
{
"code": null,
"e": 24908,
"s": 24880,
"text": "\n17 Apr, 2020"
},
{
"code": null,
"e": 25300,
"s": 24908,
"text": "Programmers or developers usually write codes for their project or for some companies. Or some start writing code as a beginner in the programming world. In all these scenarios a nostalgic moment comes when you revisit your code after a long time. You find your own code so difficult to understand. Here are a few good practices or the characteristics of a clean code that you should follow:"
},
{
"code": null,
"e": 25544,
"s": 25300,
"text": "1. Naming Conventions: This is a very basic practice to be followed. Correct naming the variables and functions are very much important. Suppose someone is going to check your code then he/she should be able to understand the code at a glance."
},
{
"code": null,
"e": 25607,
"s": 25544,
"text": "One should name the variables according to the project domain."
},
{
"code": null,
"e": 25661,
"s": 25607,
"text": "One should use ‘is’ as a prefix to Boolean variables."
},
{
"code": null,
"e": 25751,
"s": 25661,
"text": "Example: Suppose you are creating a banking app or something that has to do with payment."
},
{
"code": null,
"e": 25986,
"s": 25751,
"text": "double totalBalance; // Represents the user account balance\n\ndouble amountToDebit; // Represents the amount to charge the user\n\ndouble amountToCredit; // Represents the amount to give to the user\n\nboolean isUserActive;\n"
},
{
"code": null,
"e": 26003,
"s": 25986,
"text": "One Must Follow:"
},
{
"code": null,
"e": 26130,
"s": 26003,
"text": "Camel Case for variables and data structures.Example:String merchantName = \"John Perry\";\n\nint integerArray[] = new int[10];\n"
},
{
"code": null,
"e": 26139,
"s": 26130,
"text": "Example:"
},
{
"code": null,
"e": 26213,
"s": 26139,
"text": "String merchantName = \"John Perry\";\n\nint integerArray[] = new int[10];\n"
},
{
"code": null,
"e": 26292,
"s": 26213,
"text": "Screaming Snake Case for Constants.Example:final long ACCOUNT_NUMBER = 123456;"
},
{
"code": null,
"e": 26301,
"s": 26292,
"text": "Example:"
},
{
"code": null,
"e": 26337,
"s": 26301,
"text": "final long ACCOUNT_NUMBER = 123456;"
},
{
"code": null,
"e": 26372,
"s": 26337,
"text": "2. Its all about methods/functions"
},
{
"code": null,
"e": 26464,
"s": 26372,
"text": "“The more useful methods you write the better coder you are”– Mitch Tabian, CodingWithMitch"
},
{
"code": null,
"e": 26501,
"s": 26464,
"text": "Use Camel Case for naming functions."
},
{
"code": null,
"e": 26545,
"s": 26501,
"text": "Name the functions on the verb-noun sounds."
},
{
"code": null,
"e": 26620,
"s": 26545,
"text": "Opening bracket of the method must be on the same line as the method name."
},
{
"code": null,
"e": 26685,
"s": 26620,
"text": "Function should only accept 1 or 2 arguments not more than that."
},
{
"code": null,
"e": 26694,
"s": 26685,
"text": "Example:"
},
{
"code": null,
"e": 26768,
"s": 26694,
"text": "double getUserBalance(long int accountNumber) {\n\n// Method Defination\n\n}\n"
},
{
"code": null,
"e": 27000,
"s": 26768,
"text": "3. File Structure: It’s very much important to maintain the structure of the project. This makes it very clean and more understandable. The structure differs from web development to mobile development but the idea remains the same."
},
{
"code": null,
"e": 27009,
"s": 27000,
"text": "Example:"
},
{
"code": null,
"e": 27287,
"s": 27009,
"text": "4. Indentation: Sometimes you write some code and that code is composed inside another or you can say the nested code. This composition is very tricky to sort and to differentiate is not easy. So it is better to use indentation. It means to put the brackets in the right place."
},
{
"code": null,
"e": 27721,
"s": 27287,
"text": "5. Logging: When it comes to writing code it doesn’t mean that you just write code and boom compiled successfully. It is far from the truth that someday or many times you will have to debug. Writing log statements helps you in those dreadful moments. Writing log statements in functions is a great choice. Most processing is done through function so having a log statement there means we can get an indication of success and failure."
},
{
"code": null,
"e": 27960,
"s": 27721,
"text": "6. Avoiding self-explanatory comments: We all like to add the comment around the code. On an important note, we should avoid comments that are self-explanatory as its time consuming and useless. One should write code that explains itself."
},
{
"code": null,
"e": 27969,
"s": 27960,
"text": "Example:"
},
{
"code": null,
"e": 28016,
"s": 27969,
"text": "final double PI = 3.14; // This is pi value //"
},
{
"code": null,
"e": 28087,
"s": 28016,
"text": "The above statement’s comment isn’t necessary. So avoid this practice."
},
{
"code": null,
"e": 28102,
"s": 28087,
"text": "gupta_shrinath"
},
{
"code": null,
"e": 28111,
"s": 28102,
"text": "TechTips"
},
{
"code": null,
"e": 28209,
"s": 28111,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28218,
"s": 28209,
"text": "Comments"
},
{
"code": null,
"e": 28231,
"s": 28218,
"text": "Old Comments"
},
{
"code": null,
"e": 28289,
"s": 28231,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28334,
"s": 28289,
"text": "How to Delete Temporary Files in Windows 10?"
},
{
"code": null,
"e": 28393,
"s": 28334,
"text": "How to Convert Kotlin Code to Java Code in Android Studio?"
},
{
"code": null,
"e": 28453,
"s": 28393,
"text": "Difference between RUN vs CMD vs ENTRYPOINT Docker Commands"
},
{
"code": null,
"e": 28488,
"s": 28453,
"text": "How to Install Flutter on Windows?"
},
{
"code": null,
"e": 28526,
"s": 28488,
"text": "How to Install Z Shell(zsh) on Linux?"
},
{
"code": null,
"e": 28586,
"s": 28526,
"text": "How to Clone Android Project from GitHub in Android Studio?"
},
{
"code": null,
"e": 28630,
"s": 28586,
"text": "How to Access Localhost on Mobile Browsers?"
},
{
"code": null,
"e": 28689,
"s": 28630,
"text": "How to setup OpenGL with Visual Studio 2019 on Windows 10?"
}
] |
Check if an array is sorted and rotated in Python
|
Suppose we have an array of n unique values. We have to check whether this array is sorted and rotated anti-clockwise. Here at least one rotation is required so a fully sorted array is not considered as sorted and rotated.
So, if the input is like nums = [4,5,6,8,1,3], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8].
To solve this, we will follow these steps −
min_element := minimum of nums
min_index := index of min_element in nums
before_sorted := True
for i in range 1 to min_index - 1, doif nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop
if nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop
before_sorted := False
come out from loop
after_sorted := True
for i in range min_index + 1 to size of nums - 1, doif nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop
if nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop
after_sorted := False
come out from loop
if before_sorted and after_sorted are true and last element of nums < nums[0], thenreturn True
return True
otherwise,return False
return False
Let us see the following implementation to get better understanding −
Live Demo
def solve(nums):
min_element = 999999
min_index = -1
min_element = min(nums)
min_index = nums.index(min_element) before_sorted = True
for i in range(1, min_index):
if nums[i] < nums[i - 1]:
before_sorted = False
break
after_sorted = True
for i in range(min_index + 1, len(nums)):
if nums[i] < nums[i - 1]:
after_sorted = False
break
if before_sorted and after_sorted and nums[-1] < nums[0]:
return True
else:
return False
nums = [4,5,6,8,1,3]
print(solve(nums))
[4,5,6,8,1,3]
True
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "Suppose we have an array of n unique values. We have to check whether this array is sorted and rotated anti-clockwise. Here at least one rotation is required so a fully sorted array is not considered as sorted and rotated."
},
{
"code": null,
"e": 1463,
"s": 1285,
"text": "So, if the input is like nums = [4,5,6,8,1,3], then the output will be True as we can rotate two times to the clockwise direction then it will be sorted like [1, 3, 4, 5, 6, 8]."
},
{
"code": null,
"e": 1507,
"s": 1463,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1538,
"s": 1507,
"text": "min_element := minimum of nums"
},
{
"code": null,
"e": 1580,
"s": 1538,
"text": "min_index := index of min_element in nums"
},
{
"code": null,
"e": 1602,
"s": 1580,
"text": "before_sorted := True"
},
{
"code": null,
"e": 1710,
"s": 1602,
"text": "for i in range 1 to min_index - 1, doif nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop"
},
{
"code": null,
"e": 1781,
"s": 1710,
"text": "if nums[i] < nums[i - 1], thenbefore_sorted := Falsecome out from loop"
},
{
"code": null,
"e": 1804,
"s": 1781,
"text": "before_sorted := False"
},
{
"code": null,
"e": 1823,
"s": 1804,
"text": "come out from loop"
},
{
"code": null,
"e": 1844,
"s": 1823,
"text": "after_sorted := True"
},
{
"code": null,
"e": 1966,
"s": 1844,
"text": "for i in range min_index + 1 to size of nums - 1, doif nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop"
},
{
"code": null,
"e": 2036,
"s": 1966,
"text": "if nums[i] < nums[i - 1], thenafter_sorted := Falsecome out from loop"
},
{
"code": null,
"e": 2058,
"s": 2036,
"text": "after_sorted := False"
},
{
"code": null,
"e": 2077,
"s": 2058,
"text": "come out from loop"
},
{
"code": null,
"e": 2172,
"s": 2077,
"text": "if before_sorted and after_sorted are true and last element of nums < nums[0], thenreturn True"
},
{
"code": null,
"e": 2184,
"s": 2172,
"text": "return True"
},
{
"code": null,
"e": 2207,
"s": 2184,
"text": "otherwise,return False"
},
{
"code": null,
"e": 2220,
"s": 2207,
"text": "return False"
},
{
"code": null,
"e": 2290,
"s": 2220,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2301,
"s": 2290,
"text": " Live Demo"
},
{
"code": null,
"e": 2850,
"s": 2301,
"text": "def solve(nums):\n min_element = 999999\n min_index = -1\n min_element = min(nums)\n min_index = nums.index(min_element) before_sorted = True\n for i in range(1, min_index):\n if nums[i] < nums[i - 1]:\n before_sorted = False\n break\n after_sorted = True\n for i in range(min_index + 1, len(nums)):\n if nums[i] < nums[i - 1]:\n after_sorted = False\n break\n if before_sorted and after_sorted and nums[-1] < nums[0]:\n return True\n else:\n return False\nnums = [4,5,6,8,1,3]\nprint(solve(nums))"
},
{
"code": null,
"e": 2864,
"s": 2850,
"text": "[4,5,6,8,1,3]"
},
{
"code": null,
"e": 2869,
"s": 2864,
"text": "True"
}
] |
K-Means Clustering Tutorial for Data Scientists | Towards Data Science
|
IntroductionTutorialSummaryReferences
Introduction
Tutorial
Summary
References
Customer segmentation is widely used by both Data Scientists and Machine Learning Engineers to detect data that is the most similar to one another. These are groups that are closely related to that same group, but different enough to be a new group when compared to another group. These segments can be used to identify customer groups that can be targeted for a marketing campaign through an email perhaps, for example. The ultimate goal is to identify groups of people that are in large numbers that you would have not noticed yourself, manually. This Machine Learning algorithm makes it much easier for you to group customers or something similar by features. Those features can be easily targeted as well for a business. For example, people who get coffee at 8 am at a store, might be more likely to get coffee again at that same store at 3 pm — because they already had one so early. Those people are more likely to get two coffees over someone who would get their first coffee at 1 pm. This information can be highly beneficial and tunable for a campaign in a company.
Below, I will give a Python tutorial on using unsupervised learning by means of clustering automatically. You can apply this code and concepts it to your dataset as well to follow along. Variables that will be different for you include your data of course, k itself, and the specific features you are targeting.
This tutorial will include importing some important libraries, preprocessing your data, transforming it, creating a clustering model, utilizing principal component analysis (PCA) and elbow plots, as well as ultimately grouping data together for customer segmentation. Unsupervised clustering is a facet of Machine Learning algorithms that do not have labels already, like a 0 or 1, or red-blue-green, and however, are data points that share similar attributes that could be classified as the same or similar thing. The clusters are ultimately up to you to decide on — naming wise.
The following code includes reading in your data, scaling it, and transforming it as a preprocessing step for the eventual model. There are several key libraries to import, and some that you have already most likely used like pandas and matplotlib. Here is part one of this article tutorial:
# import librariesfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom matplotlib import pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn import preprocessingimport pandas as pdimport numpy as np# read in your datadata = pd.read_csv(‘your_file_path.csv’)# scale datascaler = preprocessing.StandardScaler()scaled_df = scaler.fit_transform(data)data = pd.DataFrame(scaled_df)pca = PCA(n_components=2)# transform datadata = pca.fit_transform(data)scaled = scaler.fit_transform(data)data = pd.DataFrame(scaled)
This next part of the tutorial is determining the best amount of k for the k-means Machine Learning algorithm, which is determined by the elbow plot method. You will essentially want to look at where the graphed line breaks significantly — or where it looks like the elbow, and plot it. You will also assign that best k amount to the k-means algorithm parameter. In this case, we see that 3 is the best amount of k for our data determined by the elbow plot method. Sometimes this is less clear and you can use the silhouette coefficient method instead to find the peak point which, for that plot, would be the k value.
# create an elbow plot to determine k (where the elbow occurs/line bends)n_cluster = range(1, 7) kmeans = [KMeans(n_clusters=i).fit(data) for i in n_cluster] scores = [kmeans[i].score(data) for i in range(len(kmeans))] fig, ax = plt.subplots() ax.plot(n_cluster, scores) plt.show()
The next part of the tutorial is to use the k-means clustering algorithm for the clusters for the new data. You will also see the value counts of the respective clusters. I’m using 4 instead for this graph to show what 4 would look like. You can use 3 or whatever your specific data shows you in your elbow plot — or you can plot any amount of clusters if that’s what a business stakeholder is requesting. You can gain a sense of your general groupings. Finally, you will plot the clusters after colorizing them.
# predict clusters with your k# k = however many clusters you determined from your elbow plot or silhouette methoddata['cluster'] = kmeans[k].predict(data)data['principal_feature1'] = data[0]data['principal_feature2'] = data[1]# plot the clusters and their respective amounts of datadata['cluster'].value_counts()# plot the different clusters with the 2 main PCA features fig, ax = plt.subplots() colors = {0:'red', 1:'blue', 2:'green', 3:'pink'} ax.scatter(data['principal_feature1'], data['principal_feature2'], c=data["cluster"].apply(lambda x: colors[x]))plt.show()
As an example, the pink group would be people who have high feature 1, but low feature 2, while the green cluster would be people who have high feature 2, and medium level feature 1. Features could be something to describe a group of people like age or orders per customer, for example. Therefore, the pink group would be people who are older and order less frequently — meaning you would create a marketing campaign for older ages to encourage them to order more since they are the group that has the most opportunity to order more. In this case, you would save money from spending less on ads for younger people, and optimize to spend the extra money on older ages. You can apply this concept to pretty much any features that you are working with in your data, and of course, make sure it makes sense to use those features in your business use case (meaningful features that you can promote, increase, or decrease, for example).
As you can see, with the use of Machine Learning algorithms, you can create a Data Science model that can be saved and used to group data for customer segmentation. Product enhancements can be optimized from different features, for example, and you can target those specific groups in a way that makes sense for the data and business. There are several use cases for using customer segmentation. Data Science only makes it easier to segment, and these use cases can benefit from an algorithmic way of detecting similar groups:
customer segmentationgrouping for ad campaignscustomer behavior
I hope you found my article both interesting and useful. Feel free to comment down below on how you use customer segmentation, and what steps you take to perform it as a Data Scientist or Machine Learning Engineer. Thank you for reading!
~ Changed original article from anomaly detection to customer segmentation to highlight clustering better. ~
[1] Photo by Will Myers on Unsplash, (2018)
[2] Photo by Markus Winkler on Unsplash, (2020)
[3] M.Przybyla, elbow plot screenshot, (2020)
[4] M.Przybyla, clustering screenshot, (2020)
|
[
{
"code": null,
"e": 210,
"s": 172,
"text": "IntroductionTutorialSummaryReferences"
},
{
"code": null,
"e": 223,
"s": 210,
"text": "Introduction"
},
{
"code": null,
"e": 232,
"s": 223,
"text": "Tutorial"
},
{
"code": null,
"e": 240,
"s": 232,
"text": "Summary"
},
{
"code": null,
"e": 251,
"s": 240,
"text": "References"
},
{
"code": null,
"e": 1326,
"s": 251,
"text": "Customer segmentation is widely used by both Data Scientists and Machine Learning Engineers to detect data that is the most similar to one another. These are groups that are closely related to that same group, but different enough to be a new group when compared to another group. These segments can be used to identify customer groups that can be targeted for a marketing campaign through an email perhaps, for example. The ultimate goal is to identify groups of people that are in large numbers that you would have not noticed yourself, manually. This Machine Learning algorithm makes it much easier for you to group customers or something similar by features. Those features can be easily targeted as well for a business. For example, people who get coffee at 8 am at a store, might be more likely to get coffee again at that same store at 3 pm — because they already had one so early. Those people are more likely to get two coffees over someone who would get their first coffee at 1 pm. This information can be highly beneficial and tunable for a campaign in a company."
},
{
"code": null,
"e": 1638,
"s": 1326,
"text": "Below, I will give a Python tutorial on using unsupervised learning by means of clustering automatically. You can apply this code and concepts it to your dataset as well to follow along. Variables that will be different for you include your data of course, k itself, and the specific features you are targeting."
},
{
"code": null,
"e": 2219,
"s": 1638,
"text": "This tutorial will include importing some important libraries, preprocessing your data, transforming it, creating a clustering model, utilizing principal component analysis (PCA) and elbow plots, as well as ultimately grouping data together for customer segmentation. Unsupervised clustering is a facet of Machine Learning algorithms that do not have labels already, like a 0 or 1, or red-blue-green, and however, are data points that share similar attributes that could be classified as the same or similar thing. The clusters are ultimately up to you to decide on — naming wise."
},
{
"code": null,
"e": 2511,
"s": 2219,
"text": "The following code includes reading in your data, scaling it, and transforming it as a preprocessing step for the eventual model. There are several key libraries to import, and some that you have already most likely used like pandas and matplotlib. Here is part one of this article tutorial:"
},
{
"code": null,
"e": 3066,
"s": 2511,
"text": "# import librariesfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom matplotlib import pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn import preprocessingimport pandas as pdimport numpy as np# read in your datadata = pd.read_csv(‘your_file_path.csv’)# scale datascaler = preprocessing.StandardScaler()scaled_df = scaler.fit_transform(data)data = pd.DataFrame(scaled_df)pca = PCA(n_components=2)# transform datadata = pca.fit_transform(data)scaled = scaler.fit_transform(data)data = pd.DataFrame(scaled)"
},
{
"code": null,
"e": 3685,
"s": 3066,
"text": "This next part of the tutorial is determining the best amount of k for the k-means Machine Learning algorithm, which is determined by the elbow plot method. You will essentially want to look at where the graphed line breaks significantly — or where it looks like the elbow, and plot it. You will also assign that best k amount to the k-means algorithm parameter. In this case, we see that 3 is the best amount of k for our data determined by the elbow plot method. Sometimes this is less clear and you can use the silhouette coefficient method instead to find the peak point which, for that plot, would be the k value."
},
{
"code": null,
"e": 3967,
"s": 3685,
"text": "# create an elbow plot to determine k (where the elbow occurs/line bends)n_cluster = range(1, 7) kmeans = [KMeans(n_clusters=i).fit(data) for i in n_cluster] scores = [kmeans[i].score(data) for i in range(len(kmeans))] fig, ax = plt.subplots() ax.plot(n_cluster, scores) plt.show()"
},
{
"code": null,
"e": 4480,
"s": 3967,
"text": "The next part of the tutorial is to use the k-means clustering algorithm for the clusters for the new data. You will also see the value counts of the respective clusters. I’m using 4 instead for this graph to show what 4 would look like. You can use 3 or whatever your specific data shows you in your elbow plot — or you can plot any amount of clusters if that’s what a business stakeholder is requesting. You can gain a sense of your general groupings. Finally, you will plot the clusters after colorizing them."
},
{
"code": null,
"e": 5050,
"s": 4480,
"text": "# predict clusters with your k# k = however many clusters you determined from your elbow plot or silhouette methoddata['cluster'] = kmeans[k].predict(data)data['principal_feature1'] = data[0]data['principal_feature2'] = data[1]# plot the clusters and their respective amounts of datadata['cluster'].value_counts()# plot the different clusters with the 2 main PCA features fig, ax = plt.subplots() colors = {0:'red', 1:'blue', 2:'green', 3:'pink'} ax.scatter(data['principal_feature1'], data['principal_feature2'], c=data[\"cluster\"].apply(lambda x: colors[x]))plt.show()"
},
{
"code": null,
"e": 5981,
"s": 5050,
"text": "As an example, the pink group would be people who have high feature 1, but low feature 2, while the green cluster would be people who have high feature 2, and medium level feature 1. Features could be something to describe a group of people like age or orders per customer, for example. Therefore, the pink group would be people who are older and order less frequently — meaning you would create a marketing campaign for older ages to encourage them to order more since they are the group that has the most opportunity to order more. In this case, you would save money from spending less on ads for younger people, and optimize to spend the extra money on older ages. You can apply this concept to pretty much any features that you are working with in your data, and of course, make sure it makes sense to use those features in your business use case (meaningful features that you can promote, increase, or decrease, for example)."
},
{
"code": null,
"e": 6508,
"s": 5981,
"text": "As you can see, with the use of Machine Learning algorithms, you can create a Data Science model that can be saved and used to group data for customer segmentation. Product enhancements can be optimized from different features, for example, and you can target those specific groups in a way that makes sense for the data and business. There are several use cases for using customer segmentation. Data Science only makes it easier to segment, and these use cases can benefit from an algorithmic way of detecting similar groups:"
},
{
"code": null,
"e": 6572,
"s": 6508,
"text": "customer segmentationgrouping for ad campaignscustomer behavior"
},
{
"code": null,
"e": 6810,
"s": 6572,
"text": "I hope you found my article both interesting and useful. Feel free to comment down below on how you use customer segmentation, and what steps you take to perform it as a Data Scientist or Machine Learning Engineer. Thank you for reading!"
},
{
"code": null,
"e": 6919,
"s": 6810,
"text": "~ Changed original article from anomaly detection to customer segmentation to highlight clustering better. ~"
},
{
"code": null,
"e": 6963,
"s": 6919,
"text": "[1] Photo by Will Myers on Unsplash, (2018)"
},
{
"code": null,
"e": 7011,
"s": 6963,
"text": "[2] Photo by Markus Winkler on Unsplash, (2020)"
},
{
"code": null,
"e": 7057,
"s": 7011,
"text": "[3] M.Przybyla, elbow plot screenshot, (2020)"
}
] |
Python os.remove() Method
|
Python method remove() removes the file path. If the path is a directory, OSError is raised.
Following is the syntax for remove() method −
os.remove(path)
path − This is the path, which is to be removed.
path − This is the path, which is to be removed.
This method does not return any value.
The following example shows the usage of remove() method.
# !/usr/bin/python
import os, sys
# listing directories
print "The dir is: %s" %os.listdir(os.getcwd())
# removing
os.remove("aa.txt")
# listing directories after removing path
print "The dir after removal of path : %s" %os.listdir(os.getcwd())
When we run above program, it produces following result −
The dir is:
[ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal of path :
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2337,
"s": 2244,
"text": "Python method remove() removes the file path. If the path is a directory, OSError is raised."
},
{
"code": null,
"e": 2383,
"s": 2337,
"text": "Following is the syntax for remove() method −"
},
{
"code": null,
"e": 2400,
"s": 2383,
"text": "os.remove(path)\n"
},
{
"code": null,
"e": 2449,
"s": 2400,
"text": "path − This is the path, which is to be removed."
},
{
"code": null,
"e": 2498,
"s": 2449,
"text": "path − This is the path, which is to be removed."
},
{
"code": null,
"e": 2537,
"s": 2498,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2595,
"s": 2537,
"text": "The following example shows the usage of remove() method."
},
{
"code": null,
"e": 2844,
"s": 2595,
"text": "# !/usr/bin/python\n\nimport os, sys\n\n# listing directories\nprint \"The dir is: %s\" %os.listdir(os.getcwd())\n\n# removing\nos.remove(\"aa.txt\")\n\n# listing directories after removing path\nprint \"The dir after removal of path : %s\" %os.listdir(os.getcwd())"
},
{
"code": null,
"e": 2902,
"s": 2844,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3085,
"s": 2902,
"text": "The dir is:\n[ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]\nThe dir after removal of path : \n[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]\n"
},
{
"code": null,
"e": 3122,
"s": 3085,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3138,
"s": 3122,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3171,
"s": 3138,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3190,
"s": 3171,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3225,
"s": 3190,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3247,
"s": 3225,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3281,
"s": 3247,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3309,
"s": 3281,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3344,
"s": 3309,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3358,
"s": 3344,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3391,
"s": 3358,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3408,
"s": 3391,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3415,
"s": 3408,
"text": " Print"
},
{
"code": null,
"e": 3426,
"s": 3415,
"text": " Add Notes"
}
] |
Equilibrium index of an array | Practice | GeeksforGeeks
|
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.
Given an array, your task is to find the index of first Equilibrium point in the array.
Input Format:
The first line of input takes an integer T denoting the no of test cases, then T test cases follow. The first line of each test case is an integer N denoting The size of the array. Then in the next line are N space-separated values of the array.
Output Format:
For each test case, the output will be the equilibrium index of the array. If no such index exists output will be -1.
User Task :
Your task is to complete the function (findEquilibrium) below which returns the index of the first Equilibrium point in the array. The function takes two arguments. The first argument is the array A[ ] and the second argument is the size of the array A.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<=T<=100
1<=N<=105
-1000<=A[]<=1000
Example(To be used only for expected output):
Input
2
4
1 2 0 3
4
1 1 1 1
Output
2
-1
Note: The Input/Output format and Examples given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
swapniltayal4221 month ago
def findEquilibrium(a,n): # Code here rsum = sum(arr) lsum = 0 for i in range(n-1, -1, -1): rsum -= a[i] if rsum == lsum: return i lsum += a[i] return -1
0
lakshaychauhan1 month ago
C++ | PREFIX SUM METHOD | EASY | T.C - O(N)
int sum = 0; for (int i = 0; i < n; i++) sum += A[i]; int lsum = 0, rsum = sum; for (int i = 0; i < n; i++) { rsum -= A[i]; if (lsum == rsum) return i; lsum += A[i]; } return -1;
0
ramdurgasais2 months ago
In Python
def findEquilibrium(a,n):
left_sum, right_sum = 0, sum(a)
for i in range(n):
right_sum -= a[i]
if left_sum == right_sum : return i
left_sum += a[i]
return -1
0
kartikeyashokgautam2 months ago
int total = 0, sum = 0; for (int num : arr) total += num; for (int i = 0; i < n;i++)
{ sum += arr[i]; if (sum * 2 == total - arr[i]) return i;
} return -1;
+1
kartikeyashokgautam
This comment was deleted.
+1
singhalsarthak7773 months ago
EASY CPP SOLUTION
int rightsum=0,leftsum=0;for(int i=0;i<n;i++){ rightsum+=a[i];} for(int i=0;i<n;i++){ rightsum=rightsum-a[i]; if(rightsum==leftsum) return i; leftsum=leftsum+a[i];}return -1;
0
mauryasangeeta33213 months ago
int findEquilibrium(int A[], int n){ //Your code here int sum1=0,sum2=0; for(int i=0;i<n;i++) sum1+=A[i]; for(int i=0;i<n;i++) { if(sum1-A[i]==2*sum2) return i; sum2+=A[i]; } return -1;}
0
mauryasangeeta3321
This comment was deleted.
0
ekkafranco3 months ago
int findEquilibrium(int A[], int n){ if (n==1) return 0; if (n==2) return -1; int mid = n/2; int res1=0; int res2=0; for(int i=0;i<mid;i++) res1+=A[i]; for(int j=mid+1;j<n;j++) res2+=A[j];
while(mid>0){ if(res1==res2) return mid; res1= res1-A[mid-1]; res2=res2+A[mid]; mid--; } while(mid<n){ if(res1==res2) return mid; res1= res1+A[mid]; res2=res2-A[mid+1]; mid++; } return -1;}
+1
ekkafranco
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": 862,
"s": 238,
"text": "Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.\nGiven an array, your task is to find the index of first Equilibrium point in the array.\n\nInput Format:\nThe first line of input takes an integer T denoting the no of test cases, then T test cases follow. The first line of each test case is an integer N denoting The size of the array. Then in the next line are N space-separated values of the array. \n\nOutput Format:\nFor each test case, the output will be the equilibrium index of the array. If no such index exists output will be -1."
},
{
"code": null,
"e": 1128,
"s": 862,
"text": "User Task :\nYour task is to complete the function (findEquilibrium) below which returns the index of the first Equilibrium point in the array. The function takes two arguments. The first argument is the array A[ ] and the second argument is the size of the array A."
},
{
"code": null,
"e": 1646,
"s": 1128,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<=T<=100\n1<=N<=105\n-1000<=A[]<=1000\n\nExample(To be used only for expected output):\nInput\n2\n4\n1 2 0 3\n4\n1 1 1 1\n\nOutput\n2\n-1\n\nNote: The Input/Output format and Examples given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1648,
"s": 1646,
"text": "0"
},
{
"code": null,
"e": 1675,
"s": 1648,
"text": "swapniltayal4221 month ago"
},
{
"code": null,
"e": 1891,
"s": 1675,
"text": "def findEquilibrium(a,n): # Code here rsum = sum(arr) lsum = 0 for i in range(n-1, -1, -1): rsum -= a[i] if rsum == lsum: return i lsum += a[i] return -1"
},
{
"code": null,
"e": 1893,
"s": 1891,
"text": "0"
},
{
"code": null,
"e": 1919,
"s": 1893,
"text": "lakshaychauhan1 month ago"
},
{
"code": null,
"e": 1963,
"s": 1919,
"text": "C++ | PREFIX SUM METHOD | EASY | T.C - O(N)"
},
{
"code": null,
"e": 2192,
"s": 1963,
"text": " int sum = 0; for (int i = 0; i < n; i++) sum += A[i]; int lsum = 0, rsum = sum; for (int i = 0; i < n; i++) { rsum -= A[i]; if (lsum == rsum) return i; lsum += A[i]; } return -1;"
},
{
"code": null,
"e": 2194,
"s": 2192,
"text": "0"
},
{
"code": null,
"e": 2219,
"s": 2194,
"text": "ramdurgasais2 months ago"
},
{
"code": null,
"e": 2229,
"s": 2219,
"text": "In Python"
},
{
"code": null,
"e": 2423,
"s": 2229,
"text": "def findEquilibrium(a,n):\n left_sum, right_sum = 0, sum(a)\n for i in range(n):\n right_sum -= a[i]\n if left_sum == right_sum : return i\n left_sum += a[i]\n return -1"
},
{
"code": null,
"e": 2425,
"s": 2423,
"text": "0"
},
{
"code": null,
"e": 2457,
"s": 2425,
"text": "kartikeyashokgautam2 months ago"
},
{
"code": null,
"e": 2566,
"s": 2457,
"text": " int total = 0, sum = 0; for (int num : arr) total += num; for (int i = 0; i < n;i++)"
},
{
"code": null,
"e": 2644,
"s": 2566,
"text": " { sum += arr[i]; if (sum * 2 == total - arr[i]) return i;"
},
{
"code": null,
"e": 2684,
"s": 2650,
"text": " } return -1; "
},
{
"code": null,
"e": 2687,
"s": 2684,
"text": "+1"
},
{
"code": null,
"e": 2707,
"s": 2687,
"text": "kartikeyashokgautam"
},
{
"code": null,
"e": 2733,
"s": 2707,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2736,
"s": 2733,
"text": "+1"
},
{
"code": null,
"e": 2766,
"s": 2736,
"text": "singhalsarthak7773 months ago"
},
{
"code": null,
"e": 2784,
"s": 2766,
"text": "EASY CPP SOLUTION"
},
{
"code": null,
"e": 2977,
"s": 2784,
"text": "int rightsum=0,leftsum=0;for(int i=0;i<n;i++){ rightsum+=a[i];} for(int i=0;i<n;i++){ rightsum=rightsum-a[i]; if(rightsum==leftsum) return i; leftsum=leftsum+a[i];}return -1;"
},
{
"code": null,
"e": 2979,
"s": 2977,
"text": "0"
},
{
"code": null,
"e": 3010,
"s": 2979,
"text": "mauryasangeeta33213 months ago"
},
{
"code": null,
"e": 3218,
"s": 3010,
"text": "int findEquilibrium(int A[], int n){ //Your code here int sum1=0,sum2=0; for(int i=0;i<n;i++) sum1+=A[i]; for(int i=0;i<n;i++) { if(sum1-A[i]==2*sum2) return i; sum2+=A[i]; } return -1;}"
},
{
"code": null,
"e": 3220,
"s": 3218,
"text": "0"
},
{
"code": null,
"e": 3239,
"s": 3220,
"text": "mauryasangeeta3321"
},
{
"code": null,
"e": 3265,
"s": 3239,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3267,
"s": 3265,
"text": "0"
},
{
"code": null,
"e": 3290,
"s": 3267,
"text": "ekkafranco3 months ago"
},
{
"code": null,
"e": 3535,
"s": 3290,
"text": "int findEquilibrium(int A[], int n){ if (n==1) return 0; if (n==2) return -1; int mid = n/2; int res1=0; int res2=0; for(int i=0;i<mid;i++) res1+=A[i]; for(int j=mid+1;j<n;j++) res2+=A[j];"
},
{
"code": null,
"e": 3860,
"s": 3535,
"text": " while(mid>0){ if(res1==res2) return mid; res1= res1-A[mid-1]; res2=res2+A[mid]; mid--; } while(mid<n){ if(res1==res2) return mid; res1= res1+A[mid]; res2=res2-A[mid+1]; mid++; } return -1;}"
},
{
"code": null,
"e": 3863,
"s": 3860,
"text": "+1"
},
{
"code": null,
"e": 3874,
"s": 3863,
"text": "ekkafranco"
},
{
"code": null,
"e": 3900,
"s": 3874,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4046,
"s": 3900,
"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": 4082,
"s": 4046,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4092,
"s": 4082,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4102,
"s": 4092,
"text": "\nContest\n"
},
{
"code": null,
"e": 4165,
"s": 4102,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4313,
"s": 4165,
"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": 4521,
"s": 4313,
"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": 4627,
"s": 4521,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Protected vs Private Access Modifiers in Java - GeeksforGeeks
|
28 Apr, 2021
Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers.
Access Modifier 1: Protected
The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected.
Syntax:
protected void method_name(){
......code goes here..........
}
Example:
Java
// Java Program to illustrate Protected Access Modifier
// Importing input output classes
import java.io.*;
// Main class
public class Main {
// Input custom string
protected String name = "Geeks for Geeks";
// Main driver method
public static void main(String[] args) {
// Creating an object of Main class
Main obj1 = new Main();
// Displaying the object content as created
// above of Main class itself
System.out.println( obj1.name );
}
}
Geeks for Geeks
Access Modifier 2: Private
The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private.
Syntax:
private void method_name(){
......code goes here..........
}
Example:
Java
// Java Program to illustrate Private Access Modifier
// Importing input output classes
import java.io.*;
// Main class
public class Main {
// Input custom string
private String name = "Geeks for Geeks";
// Main driver method
public static void main(String[] args)
{
// Creating an object of Main class
Main obj1 = new Main();
// Displaying the object content as created
// above of Main class itself
System.out.println(obj1.name);
}
}
Geeks for Geeks
Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers.
Java-Modifier
Picked
Difference Between
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 24932,
"s": 24901,
"text": " \n28 Apr, 2021\n"
},
{
"code": null,
"e": 25189,
"s": 24932,
"text": "Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. "
},
{
"code": null,
"e": 25218,
"s": 25189,
"text": "Access Modifier 1: Protected"
},
{
"code": null,
"e": 25404,
"s": 25218,
"text": "The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected."
},
{
"code": null,
"e": 25412,
"s": 25404,
"text": "Syntax:"
},
{
"code": null,
"e": 25477,
"s": 25412,
"text": "protected void method_name(){\n\n......code goes here..........\n\n}"
},
{
"code": null,
"e": 25486,
"s": 25477,
"text": "Example:"
},
{
"code": null,
"e": 25491,
"s": 25486,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to illustrate Protected Access Modifier \n \n// Importing input output classes \nimport java.io.*; \n \n// Main class \npublic class Main { \n \n // Input custom string \n protected String name = \"Geeks for Geeks\"; \n \n // Main driver method \n public static void main(String[] args) { \n \n // Creating an object of Main class \n Main obj1 = new Main(); \n \n // Displaying the object content as created \n // above of Main class itself \n System.out.println( obj1.name ); \n \n} \n} \n\n\n\n\n\n",
"e": 26041,
"s": 25501,
"text": null
},
{
"code": null,
"e": 26057,
"s": 26041,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 26085,
"s": 26057,
"text": "Access Modifier 2: Private "
},
{
"code": null,
"e": 26267,
"s": 26085,
"text": "The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private."
},
{
"code": null,
"e": 26276,
"s": 26267,
"text": "Syntax: "
},
{
"code": null,
"e": 26339,
"s": 26276,
"text": "private void method_name(){\n\n......code goes here..........\n\n}"
},
{
"code": null,
"e": 26348,
"s": 26339,
"text": "Example:"
},
{
"code": null,
"e": 26353,
"s": 26348,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java Program to illustrate Private Access Modifier \n \n// Importing input output classes \nimport java.io.*; \n \n// Main class \npublic class Main { \n \n // Input custom string \n private String name = \"Geeks for Geeks\"; \n \n // Main driver method \n public static void main(String[] args) \n { \n \n // Creating an object of Main class \n Main obj1 = new Main(); \n \n // Displaying the object content as created \n // above of Main class itself \n System.out.println(obj1.name); \n } \n}\n\n\n\n\n\n",
"e": 26910,
"s": 26363,
"text": null
},
{
"code": null,
"e": 26926,
"s": 26910,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 27084,
"s": 26926,
"text": "Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers. "
},
{
"code": null,
"e": 27100,
"s": 27084,
"text": "\nJava-Modifier\n"
},
{
"code": null,
"e": 27109,
"s": 27100,
"text": "\nPicked\n"
},
{
"code": null,
"e": 27130,
"s": 27109,
"text": "\nDifference Between\n"
},
{
"code": null,
"e": 27137,
"s": 27130,
"text": "\nJava\n"
},
{
"code": null,
"e": 27342,
"s": 27137,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27403,
"s": 27342,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27471,
"s": 27403,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27529,
"s": 27471,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27584,
"s": 27529,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27658,
"s": 27584,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 27673,
"s": 27658,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27717,
"s": 27673,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27739,
"s": 27717,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 27775,
"s": 27739,
"text": "Arrays.sort() in Java with examples"
}
] |
Python Pillow - Creating a Watermark
|
You have noticed that, some of the online photos are watermarked. Watermark is definitely one of the better ways to protect your images from misuse. Also, it is recommended to add watermark to your creative photos, before sharing them on social media to prevent it from being misused.
Watermark is generally some text or logo overlaid on the photo that identifies who took the photo or who owns the rights to the photo.
Pillow package allows us to add watermarks to your images. For adding watermark to our image, we need “Image”, “ImageDraw” and “ImageFont” modules from pillow package.
The ‘ImageDraw’ module adds functionality to draw 2D graphics onto new or existing images. The ‘ImageFont’ module is employed for loading bitmap, TrueType and OpenType font files.
Following python program demonstrates how to add watermark to an image using python pillow −
#Import required Image library
from PIL import Image, ImageDraw, ImageFont
#Create an Image Object from an Image
im = Image.open('images/boy.jpg')
width, height = im.size
draw = ImageDraw.Draw(im)
text = "sample watermark"
font = ImageFont.truetype('arial.ttf', 36)
textwidth, textheight = draw.textsize(text, font)
# calculate the x,y coordinates of the text
margin = 10
x = width - textwidth - margin
y = height - textheight - margin
# draw watermark in the bottom right corner
draw.text((x, y), text, font=font)
im.show()
#Save watermarked image
im.save('images/watermark.jpg')
Suppose, following is the input image boy.jpg located in the folder image.
After executing the above program, if you observe the output folder you can see the resultant watermark.jpg file with watermark on it as shown below −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2485,
"s": 2200,
"text": "You have noticed that, some of the online photos are watermarked. Watermark is definitely one of the better ways to protect your images from misuse. Also, it is recommended to add watermark to your creative photos, before sharing them on social media to prevent it from being misused."
},
{
"code": null,
"e": 2620,
"s": 2485,
"text": "Watermark is generally some text or logo overlaid on the photo that identifies who took the photo or who owns the rights to the photo."
},
{
"code": null,
"e": 2788,
"s": 2620,
"text": "Pillow package allows us to add watermarks to your images. For adding watermark to our image, we need “Image”, “ImageDraw” and “ImageFont” modules from pillow package."
},
{
"code": null,
"e": 2968,
"s": 2788,
"text": "The ‘ImageDraw’ module adds functionality to draw 2D graphics onto new or existing images. The ‘ImageFont’ module is employed for loading bitmap, TrueType and OpenType font files."
},
{
"code": null,
"e": 3061,
"s": 2968,
"text": "Following python program demonstrates how to add watermark to an image using python pillow −"
},
{
"code": null,
"e": 3648,
"s": 3061,
"text": "#Import required Image library\nfrom PIL import Image, ImageDraw, ImageFont\n\n#Create an Image Object from an Image\nim = Image.open('images/boy.jpg')\nwidth, height = im.size\n\ndraw = ImageDraw.Draw(im)\ntext = \"sample watermark\"\n\nfont = ImageFont.truetype('arial.ttf', 36)\ntextwidth, textheight = draw.textsize(text, font)\n\n# calculate the x,y coordinates of the text\nmargin = 10\nx = width - textwidth - margin\ny = height - textheight - margin\n\n# draw watermark in the bottom right corner\ndraw.text((x, y), text, font=font)\nim.show()\n\n#Save watermarked image\nim.save('images/watermark.jpg')"
},
{
"code": null,
"e": 3723,
"s": 3648,
"text": "Suppose, following is the input image boy.jpg located in the folder image."
},
{
"code": null,
"e": 3874,
"s": 3723,
"text": "After executing the above program, if you observe the output folder you can see the resultant watermark.jpg file with watermark on it as shown below −"
},
{
"code": null,
"e": 3911,
"s": 3874,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3927,
"s": 3911,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3960,
"s": 3927,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3979,
"s": 3960,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4014,
"s": 3979,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4036,
"s": 4014,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4070,
"s": 4036,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4098,
"s": 4070,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4133,
"s": 4098,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4147,
"s": 4133,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4180,
"s": 4147,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4197,
"s": 4180,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4204,
"s": 4197,
"text": " Print"
},
{
"code": null,
"e": 4215,
"s": 4204,
"text": " Add Notes"
}
] |
Getting Minimum and Maximum Value in MySQL
|
We need to use the MAX(columnName) to find the Maximum value in a column, whereas use the MIN(columnName) to find the Maximum value in a column.
Let’s say following is the syntax to find the highest and lowest value in a specific column −
mysql> SELECT @min_val:=MIN(columnName),@max_val:=MAX(columnName) FROM tableName;
mysql> SELECT * FROM tableName WHERE columnName=@min_val OR columnName=@max_val;
Note: Let’s say we have a database named ‘StudentsRecords’ and a table named ‘STUDENT.
Following is our table <STUDENT> −
We will now write the query −
mysql> SELECT @min_val:=MIN(StudentMarks),@max_val:=MAX(StudentMarks) FROM STUDENT;
mysql> SELECT * FROM STUDENT WHERE StudentMarks =@min_val OR StudentMarks =@max_val;
+---------------------+
| StudentMarks |
+---------------------+
| 97 |
+---------------------+
In the above query, ‘StudentMarks’refers to the name of the column. The ‘STUDENT’ refers to the name of the table from which the minimum and maximum value is being queried.
|
[
{
"code": null,
"e": 1207,
"s": 1062,
"text": "We need to use the MAX(columnName) to find the Maximum value in a column, whereas use the MIN(columnName) to find the Maximum value in a column."
},
{
"code": null,
"e": 1301,
"s": 1207,
"text": "Let’s say following is the syntax to find the highest and lowest value in a specific column −"
},
{
"code": null,
"e": 1464,
"s": 1301,
"text": "mysql> SELECT @min_val:=MIN(columnName),@max_val:=MAX(columnName) FROM tableName;\nmysql> SELECT * FROM tableName WHERE columnName=@min_val OR columnName=@max_val;"
},
{
"code": null,
"e": 1551,
"s": 1464,
"text": "Note: Let’s say we have a database named ‘StudentsRecords’ and a table named ‘STUDENT."
},
{
"code": null,
"e": 1586,
"s": 1551,
"text": "Following is our table <STUDENT> −"
},
{
"code": null,
"e": 1616,
"s": 1586,
"text": "We will now write the query −"
},
{
"code": null,
"e": 1785,
"s": 1616,
"text": "mysql> SELECT @min_val:=MIN(StudentMarks),@max_val:=MAX(StudentMarks) FROM STUDENT;\nmysql> SELECT * FROM STUDENT WHERE StudentMarks =@min_val OR StudentMarks =@max_val;"
},
{
"code": null,
"e": 1905,
"s": 1785,
"text": "+---------------------+\n| StudentMarks |\n+---------------------+\n| 97 |\n+---------------------+"
},
{
"code": null,
"e": 2078,
"s": 1905,
"text": "In the above query, ‘StudentMarks’refers to the name of the column. The ‘STUDENT’ refers to the name of the table from which the minimum and maximum value is being queried."
}
] |
Unit Testing for Data Scientists. Using Pytest to improve the stability... | by Maarten Grootendorst | Towards Data Science
|
As Data Science becomes more of a staple in large organizations, the need for proper testing of code slowly becomes more integrated into the skillset of a Data Scientist.
Imagine you have been creating a pipeline for predicting customer churn in your organization. A few months after deploying your solution, there are new variables that might improve its performance.
Unfortunately, after adding those variables, the code suddenly stops working! You are not familiar with the error message and you are having trouble finding your mistake.
This is where testing, and specifically unit testing, comes in!
Writing tests for specific modules improves the stability of your code and makes mistakes easier to spot. Especially when working on large projects, having proper tests is essentially a basic need.
No data solution is complete without some form of testing
This article will focus on a small, but very important and arguably the foundation of testing, namely unit tests. Below, I will discuss in detail why testing is necessary, what unit tests are, and how to integrate them into your Data Science projects.
Although this seems like a no-brainer, there are actually many reasons for testing your code:
Prevent unexpected output
Simplifies updating code
Increases overall efficiency of developing code
Helps to detect edge cases
And most importantly prevents you from pushing any broken code into production!
And that was only from the top of my head!
Even for those who do write production code, I would advise them to write tests for at least the most important modules of their code.
What if you run a deep learning pipeline and fails after 3 hours on something you could have easily tested?
NOTE: I can definitely imagine not wanting to write dedicated tests for one-off analyses that only took you 2 days to write. That is okay! It is up to you to decide when tests seem helpful. The most important thing to realize is that they can save you a lot of work.
Unit testing is a method of software testing that checks which specific individual units of code are fit to be used. For example, if you would want to test the sum function in python, you could write the following test:
assert sum([1, 2, 3]) == 6
We know that 1+2+3=6, so it should pass without any problems.
We can extend this example by creating a custom sum function and testing it for tuples and lists:
The output will be an assertion error for test_new_sum_tuple as -1+2+3 does not equal 6.
Unit testing helps you test pieces of code under many different circumstances. However, there is one important thing to remember:
Unit tests are not perfect and it is near impossible to achieve 100% code coverage
Unit tests are great for catching bugs, but will not capture everything as tests are prone to the same logical errors as the code you are trying to test for.
Ideally, you would want to include integration tests, code reviews, formal verification, etc. but that is beyond the scope of this article.
The issue with the example above is that it will stop running the first time it faces an AssertionError. Ideally, we want to see an overview of all tests that pass or fail.
This is where test runners, such as Pytest, come in. Pytest is a great tool for creating extensive diagnoses based on the tests that you have defined.
We start by installing Pytest:
pip install pytest
After doing so, create a test_new_sum.py file and fill it with the following code:
Finally, cd into the folder where test_new_sum.py is stored and simply run pytest -v. The result should look something like this:
What you can see in the image above is that it shows which tests passed and which failed.
The amazing thing is that Pytest shows you what values were expected and where it had failed. This allows you to quickly see what is going wrong!
To understand how we could use Pytest for Data Science solutions, I will go through several examples. The following data is used for the examples:
In this data, we have a target class and several features that could be used as predictors.
Let us start with a few simple preprocessing functions. We want to know the average value of each feature per class. To do that, we created the following basic function, aggregate_mean:
Great! We throw in a data frame and column, and it should spit out a dictionary with the average per class.
To test this, we write the following test_aggregate_mean.py file:
When we run pytest -v it should give no errors!
Run multiple test cases with Parametrize
If we want to test for many different scenarios it would cumbersome to create many duplicates of a test. To prevent that, we can use Pytest’s parametrize function.
Parameterize extends a test function by allowing us to test for multiple scenarios. We simply add the parametrize decorator and state the different scenarios.
For example, if we want to test the aggregate_mean function for features 1 and 3, we adopt the code as follows:
After running pytest -v it seems that the result for feature 3 was not what we expected. As it turns out, the None value that we saw before is actually a string!
We might not have found this bug ourselves if we had not tested for it.
Prevent repeating code in your unit tests with Fixtures
When creating these test cases we often want to run some code before every test case. Instead of repeating the same code in every test, we create fixtures that establish a baseline code for our tests.
They are often used to initialize database connections, load data, or instantiate classes.
Using the previous example, we would like to turn load_data() into a fixture. We change its name to data() in order to better represent the fixture. Then, @pytest.fixture(scope='module') is added to the function as a decorator. Finally, we add the fixture as a parameter to the unit test:
As you can see, there is no need to set data() to a variable since it is automatically evoked and stored in the input parameter.
Fixtures are a great way to increase readability and reduce the chance of any errors in the test functions.
Imitate code in your pipeline to speed up testing with Mocking
In many data-driven solutions, you will have large files to work with which can slow down your pipeline tremendously. Creating tests for these pieces of code is difficult as fast tests are preferred.
Imagine you load in a 2GB csv file with pd.read_csv and you would like to test if the output of a pipeline is correct. With unittest.mock.patch, we can replace the output ofpd.read_csv with our own to test the pipeline with smaller data.
Let’s say you have created the following codebase for your pipeline:
Now, to test whether this pipeline works as intended, we want to use a smaller dataset so we can more accurately test cases. To do so, we patch the pd.read_csv with the smaller dataset that we have been using thus far:
When we run pytest -v, the large .csv will not be loaded and instead replaced with our small dataset. The test runs quickly and we can easily test new cases!
Have you covered most of your code with unit tests?
Unit testing is not a perfect method by any means, but knowing how much of your code you are testing is extremely helpful. Especially when you have complicated pipelines, it would be nice to know if your tests cover most of your code.
In order to check for that, I would advise you to install Pytest-cov, which is an extension to Pytest, and shows you how much of your code is covered by tests.
Simply install Pytest-cov as follows:
pip install pytest-cov
After doing so, run the following test:
pytest --cov=codebase
This means that we are running Pytest and check how much of the tests cover codebase.py. The result is the following output:
Fortunately, our test covers all code in codebase.py!
If there were any lines that we note covered, then that value would be shown under Miss.
If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter.
All examples and code in this article can be found here:
|
[
{
"code": null,
"e": 343,
"s": 172,
"text": "As Data Science becomes more of a staple in large organizations, the need for proper testing of code slowly becomes more integrated into the skillset of a Data Scientist."
},
{
"code": null,
"e": 541,
"s": 343,
"text": "Imagine you have been creating a pipeline for predicting customer churn in your organization. A few months after deploying your solution, there are new variables that might improve its performance."
},
{
"code": null,
"e": 712,
"s": 541,
"text": "Unfortunately, after adding those variables, the code suddenly stops working! You are not familiar with the error message and you are having trouble finding your mistake."
},
{
"code": null,
"e": 776,
"s": 712,
"text": "This is where testing, and specifically unit testing, comes in!"
},
{
"code": null,
"e": 974,
"s": 776,
"text": "Writing tests for specific modules improves the stability of your code and makes mistakes easier to spot. Especially when working on large projects, having proper tests is essentially a basic need."
},
{
"code": null,
"e": 1032,
"s": 974,
"text": "No data solution is complete without some form of testing"
},
{
"code": null,
"e": 1284,
"s": 1032,
"text": "This article will focus on a small, but very important and arguably the foundation of testing, namely unit tests. Below, I will discuss in detail why testing is necessary, what unit tests are, and how to integrate them into your Data Science projects."
},
{
"code": null,
"e": 1378,
"s": 1284,
"text": "Although this seems like a no-brainer, there are actually many reasons for testing your code:"
},
{
"code": null,
"e": 1404,
"s": 1378,
"text": "Prevent unexpected output"
},
{
"code": null,
"e": 1429,
"s": 1404,
"text": "Simplifies updating code"
},
{
"code": null,
"e": 1477,
"s": 1429,
"text": "Increases overall efficiency of developing code"
},
{
"code": null,
"e": 1504,
"s": 1477,
"text": "Helps to detect edge cases"
},
{
"code": null,
"e": 1584,
"s": 1504,
"text": "And most importantly prevents you from pushing any broken code into production!"
},
{
"code": null,
"e": 1627,
"s": 1584,
"text": "And that was only from the top of my head!"
},
{
"code": null,
"e": 1762,
"s": 1627,
"text": "Even for those who do write production code, I would advise them to write tests for at least the most important modules of their code."
},
{
"code": null,
"e": 1870,
"s": 1762,
"text": "What if you run a deep learning pipeline and fails after 3 hours on something you could have easily tested?"
},
{
"code": null,
"e": 2137,
"s": 1870,
"text": "NOTE: I can definitely imagine not wanting to write dedicated tests for one-off analyses that only took you 2 days to write. That is okay! It is up to you to decide when tests seem helpful. The most important thing to realize is that they can save you a lot of work."
},
{
"code": null,
"e": 2357,
"s": 2137,
"text": "Unit testing is a method of software testing that checks which specific individual units of code are fit to be used. For example, if you would want to test the sum function in python, you could write the following test:"
},
{
"code": null,
"e": 2384,
"s": 2357,
"text": "assert sum([1, 2, 3]) == 6"
},
{
"code": null,
"e": 2446,
"s": 2384,
"text": "We know that 1+2+3=6, so it should pass without any problems."
},
{
"code": null,
"e": 2544,
"s": 2446,
"text": "We can extend this example by creating a custom sum function and testing it for tuples and lists:"
},
{
"code": null,
"e": 2633,
"s": 2544,
"text": "The output will be an assertion error for test_new_sum_tuple as -1+2+3 does not equal 6."
},
{
"code": null,
"e": 2763,
"s": 2633,
"text": "Unit testing helps you test pieces of code under many different circumstances. However, there is one important thing to remember:"
},
{
"code": null,
"e": 2846,
"s": 2763,
"text": "Unit tests are not perfect and it is near impossible to achieve 100% code coverage"
},
{
"code": null,
"e": 3004,
"s": 2846,
"text": "Unit tests are great for catching bugs, but will not capture everything as tests are prone to the same logical errors as the code you are trying to test for."
},
{
"code": null,
"e": 3144,
"s": 3004,
"text": "Ideally, you would want to include integration tests, code reviews, formal verification, etc. but that is beyond the scope of this article."
},
{
"code": null,
"e": 3317,
"s": 3144,
"text": "The issue with the example above is that it will stop running the first time it faces an AssertionError. Ideally, we want to see an overview of all tests that pass or fail."
},
{
"code": null,
"e": 3468,
"s": 3317,
"text": "This is where test runners, such as Pytest, come in. Pytest is a great tool for creating extensive diagnoses based on the tests that you have defined."
},
{
"code": null,
"e": 3499,
"s": 3468,
"text": "We start by installing Pytest:"
},
{
"code": null,
"e": 3518,
"s": 3499,
"text": "pip install pytest"
},
{
"code": null,
"e": 3601,
"s": 3518,
"text": "After doing so, create a test_new_sum.py file and fill it with the following code:"
},
{
"code": null,
"e": 3731,
"s": 3601,
"text": "Finally, cd into the folder where test_new_sum.py is stored and simply run pytest -v. The result should look something like this:"
},
{
"code": null,
"e": 3821,
"s": 3731,
"text": "What you can see in the image above is that it shows which tests passed and which failed."
},
{
"code": null,
"e": 3967,
"s": 3821,
"text": "The amazing thing is that Pytest shows you what values were expected and where it had failed. This allows you to quickly see what is going wrong!"
},
{
"code": null,
"e": 4114,
"s": 3967,
"text": "To understand how we could use Pytest for Data Science solutions, I will go through several examples. The following data is used for the examples:"
},
{
"code": null,
"e": 4206,
"s": 4114,
"text": "In this data, we have a target class and several features that could be used as predictors."
},
{
"code": null,
"e": 4392,
"s": 4206,
"text": "Let us start with a few simple preprocessing functions. We want to know the average value of each feature per class. To do that, we created the following basic function, aggregate_mean:"
},
{
"code": null,
"e": 4500,
"s": 4392,
"text": "Great! We throw in a data frame and column, and it should spit out a dictionary with the average per class."
},
{
"code": null,
"e": 4566,
"s": 4500,
"text": "To test this, we write the following test_aggregate_mean.py file:"
},
{
"code": null,
"e": 4614,
"s": 4566,
"text": "When we run pytest -v it should give no errors!"
},
{
"code": null,
"e": 4655,
"s": 4614,
"text": "Run multiple test cases with Parametrize"
},
{
"code": null,
"e": 4819,
"s": 4655,
"text": "If we want to test for many different scenarios it would cumbersome to create many duplicates of a test. To prevent that, we can use Pytest’s parametrize function."
},
{
"code": null,
"e": 4978,
"s": 4819,
"text": "Parameterize extends a test function by allowing us to test for multiple scenarios. We simply add the parametrize decorator and state the different scenarios."
},
{
"code": null,
"e": 5090,
"s": 4978,
"text": "For example, if we want to test the aggregate_mean function for features 1 and 3, we adopt the code as follows:"
},
{
"code": null,
"e": 5252,
"s": 5090,
"text": "After running pytest -v it seems that the result for feature 3 was not what we expected. As it turns out, the None value that we saw before is actually a string!"
},
{
"code": null,
"e": 5324,
"s": 5252,
"text": "We might not have found this bug ourselves if we had not tested for it."
},
{
"code": null,
"e": 5380,
"s": 5324,
"text": "Prevent repeating code in your unit tests with Fixtures"
},
{
"code": null,
"e": 5581,
"s": 5380,
"text": "When creating these test cases we often want to run some code before every test case. Instead of repeating the same code in every test, we create fixtures that establish a baseline code for our tests."
},
{
"code": null,
"e": 5672,
"s": 5581,
"text": "They are often used to initialize database connections, load data, or instantiate classes."
},
{
"code": null,
"e": 5961,
"s": 5672,
"text": "Using the previous example, we would like to turn load_data() into a fixture. We change its name to data() in order to better represent the fixture. Then, @pytest.fixture(scope='module') is added to the function as a decorator. Finally, we add the fixture as a parameter to the unit test:"
},
{
"code": null,
"e": 6090,
"s": 5961,
"text": "As you can see, there is no need to set data() to a variable since it is automatically evoked and stored in the input parameter."
},
{
"code": null,
"e": 6198,
"s": 6090,
"text": "Fixtures are a great way to increase readability and reduce the chance of any errors in the test functions."
},
{
"code": null,
"e": 6261,
"s": 6198,
"text": "Imitate code in your pipeline to speed up testing with Mocking"
},
{
"code": null,
"e": 6461,
"s": 6261,
"text": "In many data-driven solutions, you will have large files to work with which can slow down your pipeline tremendously. Creating tests for these pieces of code is difficult as fast tests are preferred."
},
{
"code": null,
"e": 6699,
"s": 6461,
"text": "Imagine you load in a 2GB csv file with pd.read_csv and you would like to test if the output of a pipeline is correct. With unittest.mock.patch, we can replace the output ofpd.read_csv with our own to test the pipeline with smaller data."
},
{
"code": null,
"e": 6768,
"s": 6699,
"text": "Let’s say you have created the following codebase for your pipeline:"
},
{
"code": null,
"e": 6987,
"s": 6768,
"text": "Now, to test whether this pipeline works as intended, we want to use a smaller dataset so we can more accurately test cases. To do so, we patch the pd.read_csv with the smaller dataset that we have been using thus far:"
},
{
"code": null,
"e": 7145,
"s": 6987,
"text": "When we run pytest -v, the large .csv will not be loaded and instead replaced with our small dataset. The test runs quickly and we can easily test new cases!"
},
{
"code": null,
"e": 7197,
"s": 7145,
"text": "Have you covered most of your code with unit tests?"
},
{
"code": null,
"e": 7432,
"s": 7197,
"text": "Unit testing is not a perfect method by any means, but knowing how much of your code you are testing is extremely helpful. Especially when you have complicated pipelines, it would be nice to know if your tests cover most of your code."
},
{
"code": null,
"e": 7592,
"s": 7432,
"text": "In order to check for that, I would advise you to install Pytest-cov, which is an extension to Pytest, and shows you how much of your code is covered by tests."
},
{
"code": null,
"e": 7630,
"s": 7592,
"text": "Simply install Pytest-cov as follows:"
},
{
"code": null,
"e": 7653,
"s": 7630,
"text": "pip install pytest-cov"
},
{
"code": null,
"e": 7693,
"s": 7653,
"text": "After doing so, run the following test:"
},
{
"code": null,
"e": 7715,
"s": 7693,
"text": "pytest --cov=codebase"
},
{
"code": null,
"e": 7840,
"s": 7715,
"text": "This means that we are running Pytest and check how much of the tests cover codebase.py. The result is the following output:"
},
{
"code": null,
"e": 7894,
"s": 7840,
"text": "Fortunately, our test covers all code in codebase.py!"
},
{
"code": null,
"e": 7983,
"s": 7894,
"text": "If there were any lines that we note covered, then that value would be shown under Miss."
},
{
"code": null,
"e": 8118,
"s": 7983,
"text": "If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter."
}
] |
boost::split in C++ library - GeeksforGeeks
|
14 Dec, 2021
This function is similar to strtok in C. Input sequence is split into tokens, separated by separators. Separators are given by means of the predicate.Syntax:
Template:
split(Result, Input, Predicate Pred);
Parameters:
Input: A container which will be searched.
Pred: A predicate to identify separators.
This predicate is supposed to return true
if a given element is a separator.
Result: A container that can hold copies of
references to the substrings.
Returns: A reference the result
Application : It is used to split a string into substrings which are separated by separators. Example:
Input : boost::split(result, input, boost::is_any_of("\t"))
input = "geeks\tfor\tgeeks"
Output : geeks
for
geeks
Explanation: Here in input string we have "geeks\tfor\tgeeks"
and result is a container in which we want to store our result
here separator is "\t".
CPP
// C++ program to split// string into substrings// which are separated by// separator using boost::split // this header file contains boost::split function#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; int main(){ string input("geeks\tfor\tgeeks"); vector<string> result; boost::split(result, input, boost::is_any_of("\t")); for (int i = 0; i < result.size(); i++) cout << result[i] << endl; return 0;}
Output:
geeks
for
geeks
sweetyty
avtarkumar719
cpp-boost
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
vector erase() and clear() in C++
Virtual Function in C++
Templates in C++ with Examples
unordered_map in C++ STL
C++ Data Types
|
[
{
"code": null,
"e": 24334,
"s": 24306,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 24493,
"s": 24334,
"text": "This function is similar to strtok in C. Input sequence is split into tokens, separated by separators. Separators are given by means of the predicate.Syntax: "
},
{
"code": null,
"e": 24826,
"s": 24493,
"text": "Template:\nsplit(Result, Input, Predicate Pred);\n\nParameters:\nInput: A container which will be searched.\nPred: A predicate to identify separators. \nThis predicate is supposed to return true \nif a given element is a separator.\nResult: A container that can hold copies of \nreferences to the substrings.\n\nReturns: A reference the result"
},
{
"code": null,
"e": 24930,
"s": 24826,
"text": "Application : It is used to split a string into substrings which are separated by separators. Example: "
},
{
"code": null,
"e": 25217,
"s": 24930,
"text": "Input : boost::split(result, input, boost::is_any_of(\"\\t\"))\n input = \"geeks\\tfor\\tgeeks\"\nOutput : geeks\n for\n geeks\nExplanation: Here in input string we have \"geeks\\tfor\\tgeeks\"\nand result is a container in which we want to store our result\nhere separator is \"\\t\".\n "
},
{
"code": null,
"e": 25221,
"s": 25217,
"text": "CPP"
},
{
"code": "// C++ program to split// string into substrings// which are separated by// separator using boost::split // this header file contains boost::split function#include <bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; int main(){ string input(\"geeks\\tfor\\tgeeks\"); vector<string> result; boost::split(result, input, boost::is_any_of(\"\\t\")); for (int i = 0; i < result.size(); i++) cout << result[i] << endl; return 0;}",
"e": 25682,
"s": 25221,
"text": null
},
{
"code": null,
"e": 25691,
"s": 25682,
"text": "Output: "
},
{
"code": null,
"e": 25715,
"s": 25691,
"text": "geeks\nfor\ngeeks "
},
{
"code": null,
"e": 25726,
"s": 25717,
"text": "sweetyty"
},
{
"code": null,
"e": 25740,
"s": 25726,
"text": "avtarkumar719"
},
{
"code": null,
"e": 25750,
"s": 25740,
"text": "cpp-boost"
},
{
"code": null,
"e": 25762,
"s": 25750,
"text": "CPP-Library"
},
{
"code": null,
"e": 25766,
"s": 25762,
"text": "C++"
},
{
"code": null,
"e": 25770,
"s": 25766,
"text": "CPP"
},
{
"code": null,
"e": 25868,
"s": 25770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25877,
"s": 25868,
"text": "Comments"
},
{
"code": null,
"e": 25890,
"s": 25877,
"text": "Old Comments"
},
{
"code": null,
"e": 25910,
"s": 25890,
"text": "Constructors in C++"
},
{
"code": null,
"e": 25938,
"s": 25910,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 25966,
"s": 25938,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26001,
"s": 25966,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26025,
"s": 26001,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 26059,
"s": 26025,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 26083,
"s": 26059,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26114,
"s": 26083,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 26139,
"s": 26114,
"text": "unordered_map in C++ STL"
}
] |
Queries for elements greater than K in the given index range using Segment Tree - GeeksforGeeks
|
30 Nov, 2021
Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K.
Examples:
Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}} Output: 3 2 Query 1: Only 7, 9 and 13 are greater than 6 in the subarray {7, 3, 9, 13}. Query 2: Only 9 and 13 are greater than 8 in the subarray {3, 9, 13, 5, 4}.
Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}, q[] = {{0, 7, 3}, {4, 6, 10}} Output: 4 0
Prerequisite: Segment tree
Naive approach: Find the answer for each query by simply traversing the array from index l till r and keep adding 1 to the count whenever the array element is greater than k. The Time Complexity of this approach will be O(n * q).
Efficient approach: Build a Segment Tree with a vector at each node containing all the elements of the sub-range in sorted order. Answer each query using the segment tree where Binary Search can be used to calculate how many numbers are present in each node whose sub-range lies within the query range which is greater than K. Time complexity of this approach will be O(q * log(n) * log(n))
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; // Merge procedure to merge two// vectors into a single vectorvector<int> merge(vector<int>& v1, vector<int>& v2){ int i = 0, j = 0; // Final vector to return // after merging vector<int> v; // Loop continues until it reaches // the end of one of the vectors while (i < v1.size() && j < v2.size()) { if (v1[i] <= v2[j]) { v.push_back(v1[i]); i++; } else { v.push_back(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.size(); k++) v.push_back(v1[k]); for (int k = j; k < v2.size(); k++) v.push_back(v2[k]); return v;} // Procedure to build the segment treevoid buildTree(vector<int>* tree, int* arr, int index, int s, int e){ // Reached the leaf node // of the segment tree if (s == e) { tree[index].push_back(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} // Query procedure to get the answer// for each query l and r are query rangeint query(vector<int>* tree, int index, int s, int e, int l, int r, int k){ // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].size() - (lower_bound(tree[index].begin(), tree[index].end(), k) - tree[index].begin())); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k));} // Function to perform the queriesvoid performQueries(int L[], int R[], int K[], int n, int q, vector<int> tree[]){ for (int i = 0; i < q; i++) { cout << query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i]) << endl; }} // Driver codeint main(){ int arr[] = { 7, 3, 9, 13, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); vector<int> tree[4 * n + 1]; buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int L[] = { 1, 2 }; int R[] = { 4, 6 }; int K[] = { 6, 8 }; // Number of queries int q = sizeof(L) / sizeof(L[0]); performQueries(L, R, K, n, q, tree); return 0;}
// Java implementation of the approachimport java.util.*; class GFG { // Merge procedure to merge two // vectors into a single vector static Vector<Integer> merge(Vector<Integer> v1, Vector<Integer> v2) { int i = 0, j = 0; // Final vector to return // after merging Vector<Integer> v = new Vector<>(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.size() && j < v2.size()) { if (v1.elementAt(i) <= v2.elementAt(j)) { v.add(v1.elementAt(i)); i++; } else { v.add(v2.elementAt(j)); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.size(); k++) v.add(v1.elementAt(k)); for (int k = j; k < v2.size(); k++) v.add(v2.elementAt(k)); return v; } // Procedure to build the segment tree static void buildTree(Vector<Integer>[] tree, int[] arr, int index, int s, int e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].add(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } // Query procedure to get the answer // for each query l and r are query range static int query(Vector<Integer>[] tree, int index, int s, int e, int l, int r, int k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].size() - lowerBound(tree[index], tree[index].size(), k)); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k)); } // Function to perform the queries static void performQueries(int L[], int R[], int K[], int n, int q, Vector<Integer> tree[]) { for (int i = 0; i < q; i++) { System.out.println(query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i])); } } static int lowerBound(Vector<Integer> array, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value <= array.elementAt(mid)) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void main(String[] args) { int arr[] = { 7, 3, 9, 13, 5, 4 }; int n = arr.length; @SuppressWarnings("unchecked") Vector<Integer>[] tree = new Vector[4 * n + 1]; for (int i = 0; i < (4 * n + 1); i++) { tree[i] = new Vector<>(); } buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int L[] = { 1, 2 }; int R[] = { 4, 6 }; int K[] = { 6, 8 }; // Number of queries int q = L.length; performQueries(L, R, K, n, q, tree); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approachfrom bisect import bisect_left as lower_bound # Merge procedure to merge two# vectors into a single vectordef merge(v1, v2): i = 0 j = 0 # Final vector to return # after merging v = [] # Loop continues until it reaches # the end of one of the vectors while (i < len(v1) and j < len(v2)): if (v1[i] <= v2[j]): v.append(v1[i]) i += 1 else: v.append(v2[j]) j += 1 # Here, simply add the remaining # elements to the vector v for k in range(i, len(v1)): v.append(v1[k]) for k in range(j, len(v2)): v.append(v2[k]) return v # Procedure to build the segment treedef buildTree(tree,arr,index, s, e): # Reached the leaf node # of the segment tree if (s == e): tree[index].append(arr[s]) return # Recursively call the buildTree # on both the nodes of the tree mid = (s + e) // 2 buildTree(tree, arr, 2 * index, s, mid) buildTree(tree, arr, 2 * index + 1, mid + 1, e) # Storing the final vector after merging # the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]) # Query procedure to get the answer# for each query l and r are query rangedef query(tree, index, s, e, l, r, k): # out of bound or no overlap if (r < s or l > e): return 0 # Complete overlap # Query range completely lies in # the segment tree node range if (s >= l and e <= r): # binary search to find index of k return len(tree[index]) - (lower_bound(tree[index], k)) # Partially overlap # Query range partially lies in # the segment tree node range mid = (s + e) // 2 return (query(tree, 2 * index, s,mid, l, r, k) + query(tree, 2 * index + 1, mid + 1,e, l, r, k)) # Function to perform the queriesdef performQueries(L, R, K,n, q,tree): for i in range(q): print(query(tree, 1, 0, n - 1,L[i] - 1, R[i] - 1, K[i])) # Driver codeif __name__ == '__main__': arr = [7, 3, 9, 13, 5, 4] n = len(arr) tree = [[] for i in range(4 * n + 1)] buildTree(tree, arr, 1, 0, n - 1) # 1-based indexing L = [1, 2] R = [4, 6] K = [6, 8] # Number of queries q = len(L) performQueries(L, R, K, n, q, tree) # This code is contributed by mohit kumar 29
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Merge procedure to merge two // vectors into a single vector static List<int> merge(List<int> v1, List<int> v2) { int i = 0, j = 0; // Final vector to return // after merging List<int> v = new List<int>(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.Count && j < v2.Count) { if (v1[i] <= v2[j]) { v.Add(v1[i]); i++; } else { v.Add(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.Count; k++) v.Add(v1[k]); for (int k = j; k < v2.Count; k++) v.Add(v2[k]); return v; } // Procedure to build the segment tree static void buildTree(List<int>[] tree, int[] arr, int index, int s, int e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].Add(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the readonly vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } // Query procedure to get the answer // for each query l and r are query range static int query(List<int>[] tree, int index, int s, int e, int l, int r, int k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].Count - lowerBound(tree[index], tree[index].Count, k)); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k)); } // Function to perform the queries static void performQueries(int []L, int []R, int []K, int n, int q, List<int> []tree) { for (int i = 0; i < q; i++) { Console.WriteLine(query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i])); } } static int lowerBound(List<int> array, int length, int value) { int low = 0; int high = length; while (low < high) { int mid = (low + high) / 2; if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void Main(String[] args) { int []arr = { 7, 3, 9, 13, 5, 4 }; int n = arr.Length; List<int>[] tree = new List<int>[4 * n + 1]; for (int i = 0; i < (4 * n + 1); i++) { tree[i] = new List<int>(); } buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int []L = { 1, 2 }; int []R = { 4, 6 }; int []K = { 6, 8 }; // Number of queries int q = L.Length; performQueries(L, R, K, n, q, tree); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the approach // Merge procedure to merge two// vectors into a single vectorfunction merge(v1, v2) { let i = 0, j = 0; // Final vector to return // after merging let v = new Array(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.length && j < v2.length) { if (v1[i] <= v2[j]) { v.push(v1[i]); i++; } else { v.push(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (let k = i; k < v1.length; k++) v.push(v1[k]); for (let k = j; k < v2.length; k++) v.push(v2[k]); return v;} // Procedure to build the segment treefunction buildTree(tree, arr, index, s, e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].push(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree let mid = Math.floor((s + e) / 2); buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} // Query procedure to get the answer// for each query l and r are query rangefunction query(tree, index, s, e, l, r, k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].length - (lowerBound(tree[index], tree[index].length, k))); } // Partially overlap // Query range partially lies in // the segment tree node range let mid = Math.floor((s + e) / 2); return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k));} function lowerBound(array, length, value) { let low = 0; let high = length; while (low < high) { let mid = Math.floor((low + high) / 2); if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low;} // Function to perform the queriesfunction performQueries(L, R, K, n, q, tree) { for (let i = 0; i < q; i++) { document.write( query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i]) + "<br>" ); }} // Driver code let arr = [7, 3, 9, 13, 5, 4];let n = arr.length;let tree = new Array(); for (let i = 0; i < 4 * n + 1; i++) { tree.push([])}buildTree(tree, arr, 1, 0, n - 1); // 1-based indexinglet L = [1, 2];let R = [4, 6];let K = [6, 8]; // Number of querieslet q = L.length; performQueries(L, R, K, n, q, tree); </script>
3
2
Another Approach:
Another way of doing it using segment trees is by storing the first element greater than K in each node (if present) in that range, otherwise storing 0.
Here, we need to consider 3 cases for building the tree.
If both left and right children contain a number other than 0, the answer is always the left child. (we need to consider the very first occurrence of the number greater than K.)If any one of the left or right child contains 0, the answer is always a number other than 0.If both left and right children contain 0, the answer is always 0 (indicating that no number greater than K is present in that range).
If both left and right children contain a number other than 0, the answer is always the left child. (we need to consider the very first occurrence of the number greater than K.)
If any one of the left or right child contains 0, the answer is always a number other than 0.
If both left and right children contain 0, the answer is always 0 (indicating that no number greater than K is present in that range).
The query function remains the same as always.
Consider the following example: arr[] = {7, 3, 9, 13, 5, 4} , K = 6
The tree in this case will look like this:
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; vector<int> arr(1000000), tree(4 * arr.size()); // combine function to make parent nodeint combine(int a, int b){ if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b;} // building the treevoid buildTree(int ind, int low, int high, int x){ // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (low + high) / 2; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking. tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]);}// performing queryint query(int ind, int low, int high, int l, int r){ int mid = (low + high) / 2; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine(query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r));} // Driver Codeint main(){ arr = { 7, 3, 9, 13, 5, 4 }; int n = 6; int k = 6; // 1-based indexing int l = 1, r = 4; buildTree(0, 0, n - 1, k); cout << query(0, 0, n - 1, l - 1, r - 1); return 0;}// This code is contributed by yashbeersingh42
// Java implementation of the approachpublic class GFG { int[] arr, tree; // combine function to make parent node int combine(int a, int b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree void buildTree(int ind, int low, int high, int x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (high - low) / 2 + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query int query(int ind, int low, int high, int l, int r) { int mid = (high - low) / 2 + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } // Driver Code public static void main(String args[]) { GFG ob = new GFG(); ob.arr = new int[] { 7, 3, 9, 13, 5, 4 }; int n = ob.arr.length; int k = 6; ob.tree = new int[4 * n]; // 1-based indexing int l = 1, r = 4; ob.buildTree(0, 0, n - 1, k); System.out.println( ob.query(0, 0, n - 1, l - 1, r - 1)); }} // This code is contributed by sarvjot.
# Python implementation of the approachimport math # combine function to make parent nodedef combine(a, b): if a != 0 and b != 0: return a if a >= b: return a return b # building the treedef build_tree(arr, tree, ind, low, high, x): # leaf node if low == high: if arr[low] > x: tree[ind] = arr[low] else: tree[ind] = 0 return mid = (high - low) / 2 + low mid = math.floor(mid) mid = int(mid) build_tree(arr, tree, 2 * ind + 1, low, mid, x) build_tree(arr, tree, 2 * ind + 2, mid + 1, high, x) # merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]) # performing querydef query(tree, ind, low, high, l, r): mid = (high - low) / 2 + low mid = math.floor(mid) mid = int(mid) # out of bounds if low > r or high < l: return 0 # complete overlaps if l <= low and r >= high: return tree[ind] # partial overlaps q1 = query(tree, 2 * ind + 1, low, mid, l, r) q2 = query(tree, 2 * ind + 2, mid + 1, high, l, r) return combine(q1, q2) # Driver Codeif __name__ == '__main__': arr = [7, 3, 9, 13, 5, 4] n = len(arr) k = 6 tree = [[] for i in range(4 * n)] # 1-based indexing l = 1 r = 4 build_tree(arr, tree, 0, 0, n - 1, k) print(query(tree, 0, 0, n - 1, l - 1, r - 1)) # This code is contributed by sarvjot.
// C# implementation of the approachusing System;class GFG { static int[] arr, tree; // combine function to make parent node static int combine(int a, int b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree static void buildTree(int ind, int low, int high, int x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (high - low) / 2 + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query static int query(int ind, int low, int high, int l, int r) { int mid = (high - low) / 2 + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } static void Main() { arr = new int[] { 7, 3, 9, 13, 5, 4 }; int n = arr.Length; int k = 6; tree = new int[4 * n]; // 1-based indexing int l = 1, r = 4; buildTree(0, 0, n - 1, k); Console.Write(query(0, 0, n - 1, l - 1, r - 1)); }} // This code is contributed by suresh07.
<script> // Javascript implementation of the approach let arr, tree; // combine function to make parent node function combine(a, b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree function buildTree(ind, low, high, x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } let mid = parseInt((high - low) / 2, 10) + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query function query(ind, low, high, l, r) { let mid = parseInt((high - low) / 2, 10) + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } arr = [ 7, 3, 9, 13, 5, 4 ]; let n = arr.length; let k = 6; tree = new Array(4 * n); tree.fill(0); // 1-based indexing let l = 1, r = 4; buildTree(0, 0, n - 1, k); document.write(query(0, 0, n - 1, l - 1, r - 1)); // This code is contributed by divyesh072019.</script>
Output:
7
Time Complexity: O(N * log N) to build the tree and O(log N) for each query.
Space Complexity: O(N)
sanjeev2552
princiraj1992
mohit kumar 29
yashbeersingh42
_saurabh_jaiswal
khushboogoyal499
sarvjot
suresh07
divyesh072019
array-range-queries
Segment-Tree
Advanced Data Structure
Arrays
Recursion
Searching
Arrays
Searching
Recursion
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 24403,
"s": 24375,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24632,
"s": 24403,
"text": "Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K."
},
{
"code": null,
"e": 24643,
"s": 24632,
"text": "Examples: "
},
{
"code": null,
"e": 24872,
"s": 24643,
"text": "Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}} Output: 3 2 Query 1: Only 7, 9 and 13 are greater than 6 in the subarray {7, 3, 9, 13}. Query 2: Only 9 and 13 are greater than 8 in the subarray {3, 9, 13, 5, 4}."
},
{
"code": null,
"e": 24956,
"s": 24872,
"text": "Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}, q[] = {{0, 7, 3}, {4, 6, 10}} Output: 4 0 "
},
{
"code": null,
"e": 24983,
"s": 24956,
"text": "Prerequisite: Segment tree"
},
{
"code": null,
"e": 25213,
"s": 24983,
"text": "Naive approach: Find the answer for each query by simply traversing the array from index l till r and keep adding 1 to the count whenever the array element is greater than k. The Time Complexity of this approach will be O(n * q)."
},
{
"code": null,
"e": 25604,
"s": 25213,
"text": "Efficient approach: Build a Segment Tree with a vector at each node containing all the elements of the sub-range in sorted order. Answer each query using the segment tree where Binary Search can be used to calculate how many numbers are present in each node whose sub-range lies within the query range which is greater than K. Time complexity of this approach will be O(q * log(n) * log(n))"
},
{
"code": null,
"e": 25656,
"s": 25604,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25660,
"s": 25656,
"text": "C++"
},
{
"code": null,
"e": 25665,
"s": 25660,
"text": "Java"
},
{
"code": null,
"e": 25673,
"s": 25665,
"text": "Python3"
},
{
"code": null,
"e": 25676,
"s": 25673,
"text": "C#"
},
{
"code": null,
"e": 25687,
"s": 25676,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Merge procedure to merge two// vectors into a single vectorvector<int> merge(vector<int>& v1, vector<int>& v2){ int i = 0, j = 0; // Final vector to return // after merging vector<int> v; // Loop continues until it reaches // the end of one of the vectors while (i < v1.size() && j < v2.size()) { if (v1[i] <= v2[j]) { v.push_back(v1[i]); i++; } else { v.push_back(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.size(); k++) v.push_back(v1[k]); for (int k = j; k < v2.size(); k++) v.push_back(v2[k]); return v;} // Procedure to build the segment treevoid buildTree(vector<int>* tree, int* arr, int index, int s, int e){ // Reached the leaf node // of the segment tree if (s == e) { tree[index].push_back(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} // Query procedure to get the answer// for each query l and r are query rangeint query(vector<int>* tree, int index, int s, int e, int l, int r, int k){ // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].size() - (lower_bound(tree[index].begin(), tree[index].end(), k) - tree[index].begin())); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k));} // Function to perform the queriesvoid performQueries(int L[], int R[], int K[], int n, int q, vector<int> tree[]){ for (int i = 0; i < q; i++) { cout << query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i]) << endl; }} // Driver codeint main(){ int arr[] = { 7, 3, 9, 13, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); vector<int> tree[4 * n + 1]; buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int L[] = { 1, 2 }; int R[] = { 4, 6 }; int K[] = { 6, 8 }; // Number of queries int q = sizeof(L) / sizeof(L[0]); performQueries(L, R, K, n, q, tree); return 0;}",
"e": 28591,
"s": 25687,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG { // Merge procedure to merge two // vectors into a single vector static Vector<Integer> merge(Vector<Integer> v1, Vector<Integer> v2) { int i = 0, j = 0; // Final vector to return // after merging Vector<Integer> v = new Vector<>(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.size() && j < v2.size()) { if (v1.elementAt(i) <= v2.elementAt(j)) { v.add(v1.elementAt(i)); i++; } else { v.add(v2.elementAt(j)); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.size(); k++) v.add(v1.elementAt(k)); for (int k = j; k < v2.size(); k++) v.add(v2.elementAt(k)); return v; } // Procedure to build the segment tree static void buildTree(Vector<Integer>[] tree, int[] arr, int index, int s, int e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].add(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } // Query procedure to get the answer // for each query l and r are query range static int query(Vector<Integer>[] tree, int index, int s, int e, int l, int r, int k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].size() - lowerBound(tree[index], tree[index].size(), k)); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k)); } // Function to perform the queries static void performQueries(int L[], int R[], int K[], int n, int q, Vector<Integer> tree[]) { for (int i = 0; i < q; i++) { System.out.println(query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i])); } } static int lowerBound(Vector<Integer> array, int length, int value) { int low = 0; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value <= array.elementAt(mid)) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void main(String[] args) { int arr[] = { 7, 3, 9, 13, 5, 4 }; int n = arr.length; @SuppressWarnings(\"unchecked\") Vector<Integer>[] tree = new Vector[4 * n + 1]; for (int i = 0; i < (4 * n + 1); i++) { tree[i] = new Vector<>(); } buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int L[] = { 1, 2 }; int R[] = { 4, 6 }; int K[] = { 6, 8 }; // Number of queries int q = L.length; performQueries(L, R, K, n, q, tree); }} // This code is contributed by// sanjeev2552",
"e": 32567,
"s": 28591,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom bisect import bisect_left as lower_bound # Merge procedure to merge two# vectors into a single vectordef merge(v1, v2): i = 0 j = 0 # Final vector to return # after merging v = [] # Loop continues until it reaches # the end of one of the vectors while (i < len(v1) and j < len(v2)): if (v1[i] <= v2[j]): v.append(v1[i]) i += 1 else: v.append(v2[j]) j += 1 # Here, simply add the remaining # elements to the vector v for k in range(i, len(v1)): v.append(v1[k]) for k in range(j, len(v2)): v.append(v2[k]) return v # Procedure to build the segment treedef buildTree(tree,arr,index, s, e): # Reached the leaf node # of the segment tree if (s == e): tree[index].append(arr[s]) return # Recursively call the buildTree # on both the nodes of the tree mid = (s + e) // 2 buildTree(tree, arr, 2 * index, s, mid) buildTree(tree, arr, 2 * index + 1, mid + 1, e) # Storing the final vector after merging # the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]) # Query procedure to get the answer# for each query l and r are query rangedef query(tree, index, s, e, l, r, k): # out of bound or no overlap if (r < s or l > e): return 0 # Complete overlap # Query range completely lies in # the segment tree node range if (s >= l and e <= r): # binary search to find index of k return len(tree[index]) - (lower_bound(tree[index], k)) # Partially overlap # Query range partially lies in # the segment tree node range mid = (s + e) // 2 return (query(tree, 2 * index, s,mid, l, r, k) + query(tree, 2 * index + 1, mid + 1,e, l, r, k)) # Function to perform the queriesdef performQueries(L, R, K,n, q,tree): for i in range(q): print(query(tree, 1, 0, n - 1,L[i] - 1, R[i] - 1, K[i])) # Driver codeif __name__ == '__main__': arr = [7, 3, 9, 13, 5, 4] n = len(arr) tree = [[] for i in range(4 * n + 1)] buildTree(tree, arr, 1, 0, n - 1) # 1-based indexing L = [1, 2] R = [4, 6] K = [6, 8] # Number of queries q = len(L) performQueries(L, R, K, n, q, tree) # This code is contributed by mohit kumar 29 ",
"e": 34932,
"s": 32567,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Merge procedure to merge two // vectors into a single vector static List<int> merge(List<int> v1, List<int> v2) { int i = 0, j = 0; // Final vector to return // after merging List<int> v = new List<int>(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.Count && j < v2.Count) { if (v1[i] <= v2[j]) { v.Add(v1[i]); i++; } else { v.Add(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (int k = i; k < v1.Count; k++) v.Add(v1[k]); for (int k = j; k < v2.Count; k++) v.Add(v2[k]); return v; } // Procedure to build the segment tree static void buildTree(List<int>[] tree, int[] arr, int index, int s, int e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].Add(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree int mid = (s + e) / 2; buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the readonly vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]); } // Query procedure to get the answer // for each query l and r are query range static int query(List<int>[] tree, int index, int s, int e, int l, int r, int k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].Count - lowerBound(tree[index], tree[index].Count, k)); } // Partially overlap // Query range partially lies in // the segment tree node range int mid = (s + e) / 2; return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k)); } // Function to perform the queries static void performQueries(int []L, int []R, int []K, int n, int q, List<int> []tree) { for (int i = 0; i < q; i++) { Console.WriteLine(query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i])); } } static int lowerBound(List<int> array, int length, int value) { int low = 0; int high = length; while (low < high) { int mid = (low + high) / 2; if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void Main(String[] args) { int []arr = { 7, 3, 9, 13, 5, 4 }; int n = arr.Length; List<int>[] tree = new List<int>[4 * n + 1]; for (int i = 0; i < (4 * n + 1); i++) { tree[i] = new List<int>(); } buildTree(tree, arr, 1, 0, n - 1); // 1-based indexing int []L = { 1, 2 }; int []R = { 4, 6 }; int []K = { 6, 8 }; // Number of queries int q = L.Length; performQueries(L, R, K, n, q, tree); }} // This code is contributed by PrinciRaj1992",
"e": 38786,
"s": 34932,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Merge procedure to merge two// vectors into a single vectorfunction merge(v1, v2) { let i = 0, j = 0; // Final vector to return // after merging let v = new Array(); // Loop continues until it reaches // the end of one of the vectors while (i < v1.length && j < v2.length) { if (v1[i] <= v2[j]) { v.push(v1[i]); i++; } else { v.push(v2[j]); j++; } } // Here, simply add the remaining // elements to the vector v for (let k = i; k < v1.length; k++) v.push(v1[k]); for (let k = j; k < v2.length; k++) v.push(v2[k]); return v;} // Procedure to build the segment treefunction buildTree(tree, arr, index, s, e) { // Reached the leaf node // of the segment tree if (s == e) { tree[index].push(arr[s]); return; } // Recursively call the buildTree // on both the nodes of the tree let mid = Math.floor((s + e) / 2); buildTree(tree, arr, 2 * index, s, mid); buildTree(tree, arr, 2 * index + 1, mid + 1, e); // Storing the final vector after merging // the two of its sorted child vector tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} // Query procedure to get the answer// for each query l and r are query rangefunction query(tree, index, s, e, l, r, k) { // out of bound or no overlap if (r < s || l > e) return 0; // Complete overlap // Query range completely lies in // the segment tree node range if (s >= l && e <= r) { // binary search to find index of k return (tree[index].length - (lowerBound(tree[index], tree[index].length, k))); } // Partially overlap // Query range partially lies in // the segment tree node range let mid = Math.floor((s + e) / 2); return (query(tree, 2 * index, s, mid, l, r, k) + query(tree, 2 * index + 1, mid + 1, e, l, r, k));} function lowerBound(array, length, value) { let low = 0; let high = length; while (low < high) { let mid = Math.floor((low + high) / 2); if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low;} // Function to perform the queriesfunction performQueries(L, R, K, n, q, tree) { for (let i = 0; i < q; i++) { document.write( query(tree, 1, 0, n - 1, L[i] - 1, R[i] - 1, K[i]) + \"<br>\" ); }} // Driver code let arr = [7, 3, 9, 13, 5, 4];let n = arr.length;let tree = new Array(); for (let i = 0; i < 4 * n + 1; i++) { tree.push([])}buildTree(tree, arr, 1, 0, n - 1); // 1-based indexinglet L = [1, 2];let R = [4, 6];let K = [6, 8]; // Number of querieslet q = L.length; performQueries(L, R, K, n, q, tree); </script>",
"e": 41633,
"s": 38786,
"text": null
},
{
"code": null,
"e": 41637,
"s": 41633,
"text": "3\n2"
},
{
"code": null,
"e": 41657,
"s": 41639,
"text": "Another Approach:"
},
{
"code": null,
"e": 41811,
"s": 41657,
"text": "Another way of doing it using segment trees is by storing the first element greater than K in each node (if present) in that range, otherwise storing 0."
},
{
"code": null,
"e": 41868,
"s": 41811,
"text": "Here, we need to consider 3 cases for building the tree."
},
{
"code": null,
"e": 42273,
"s": 41868,
"text": "If both left and right children contain a number other than 0, the answer is always the left child. (we need to consider the very first occurrence of the number greater than K.)If any one of the left or right child contains 0, the answer is always a number other than 0.If both left and right children contain 0, the answer is always 0 (indicating that no number greater than K is present in that range)."
},
{
"code": null,
"e": 42451,
"s": 42273,
"text": "If both left and right children contain a number other than 0, the answer is always the left child. (we need to consider the very first occurrence of the number greater than K.)"
},
{
"code": null,
"e": 42545,
"s": 42451,
"text": "If any one of the left or right child contains 0, the answer is always a number other than 0."
},
{
"code": null,
"e": 42680,
"s": 42545,
"text": "If both left and right children contain 0, the answer is always 0 (indicating that no number greater than K is present in that range)."
},
{
"code": null,
"e": 42727,
"s": 42680,
"text": "The query function remains the same as always."
},
{
"code": null,
"e": 42796,
"s": 42727,
"text": "Consider the following example: arr[] = {7, 3, 9, 13, 5, 4} , K = 6"
},
{
"code": null,
"e": 42839,
"s": 42796,
"text": "The tree in this case will look like this:"
},
{
"code": null,
"e": 42892,
"s": 42839,
"text": " Below is the implementation of the above approach:"
},
{
"code": null,
"e": 42896,
"s": 42892,
"text": "C++"
},
{
"code": null,
"e": 42901,
"s": 42896,
"text": "Java"
},
{
"code": null,
"e": 42909,
"s": 42901,
"text": "Python3"
},
{
"code": null,
"e": 42912,
"s": 42909,
"text": "C#"
},
{
"code": null,
"e": 42923,
"s": 42912,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; vector<int> arr(1000000), tree(4 * arr.size()); // combine function to make parent nodeint combine(int a, int b){ if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b;} // building the treevoid buildTree(int ind, int low, int high, int x){ // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (low + high) / 2; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking. tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]);}// performing queryint query(int ind, int low, int high, int l, int r){ int mid = (low + high) / 2; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine(query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r));} // Driver Codeint main(){ arr = { 7, 3, 9, 13, 5, 4 }; int n = 6; int k = 6; // 1-based indexing int l = 1, r = 4; buildTree(0, 0, n - 1, k); cout << query(0, 0, n - 1, l - 1, r - 1); return 0;}// This code is contributed by yashbeersingh42",
"e": 44367,
"s": 42923,
"text": null
},
{
"code": "// Java implementation of the approachpublic class GFG { int[] arr, tree; // combine function to make parent node int combine(int a, int b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree void buildTree(int ind, int low, int high, int x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (high - low) / 2 + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query int query(int ind, int low, int high, int l, int r) { int mid = (high - low) / 2 + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } // Driver Code public static void main(String args[]) { GFG ob = new GFG(); ob.arr = new int[] { 7, 3, 9, 13, 5, 4 }; int n = ob.arr.length; int k = 6; ob.tree = new int[4 * n]; // 1-based indexing int l = 1, r = 4; ob.buildTree(0, 0, n - 1, k); System.out.println( ob.query(0, 0, n - 1, l - 1, r - 1)); }} // This code is contributed by sarvjot.",
"e": 46151,
"s": 44367,
"text": null
},
{
"code": "# Python implementation of the approachimport math # combine function to make parent nodedef combine(a, b): if a != 0 and b != 0: return a if a >= b: return a return b # building the treedef build_tree(arr, tree, ind, low, high, x): # leaf node if low == high: if arr[low] > x: tree[ind] = arr[low] else: tree[ind] = 0 return mid = (high - low) / 2 + low mid = math.floor(mid) mid = int(mid) build_tree(arr, tree, 2 * ind + 1, low, mid, x) build_tree(arr, tree, 2 * ind + 2, mid + 1, high, x) # merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]) # performing querydef query(tree, ind, low, high, l, r): mid = (high - low) / 2 + low mid = math.floor(mid) mid = int(mid) # out of bounds if low > r or high < l: return 0 # complete overlaps if l <= low and r >= high: return tree[ind] # partial overlaps q1 = query(tree, 2 * ind + 1, low, mid, l, r) q2 = query(tree, 2 * ind + 2, mid + 1, high, l, r) return combine(q1, q2) # Driver Codeif __name__ == '__main__': arr = [7, 3, 9, 13, 5, 4] n = len(arr) k = 6 tree = [[] for i in range(4 * n)] # 1-based indexing l = 1 r = 4 build_tree(arr, tree, 0, 0, n - 1, k) print(query(tree, 0, 0, n - 1, l - 1, r - 1)) # This code is contributed by sarvjot.",
"e": 47571,
"s": 46151,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG { static int[] arr, tree; // combine function to make parent node static int combine(int a, int b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree static void buildTree(int ind, int low, int high, int x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } int mid = (high - low) / 2 + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query static int query(int ind, int low, int high, int l, int r) { int mid = (high - low) / 2 + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } static void Main() { arr = new int[] { 7, 3, 9, 13, 5, 4 }; int n = arr.Length; int k = 6; tree = new int[4 * n]; // 1-based indexing int l = 1, r = 4; buildTree(0, 0, n - 1, k); Console.Write(query(0, 0, n - 1, l - 1, r - 1)); }} // This code is contributed by suresh07.",
"e": 49268,
"s": 47571,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let arr, tree; // combine function to make parent node function combine(a, b) { if (a != 0 && b != 0) { return a; } if (a >= b) { return a; } return b; } // building the tree function buildTree(ind, low, high, x) { // leaf node if (low == high) { if (arr[low] > x) { tree[ind] = arr[low]; } else { tree[ind] = 0; } return; } let mid = parseInt((high - low) / 2, 10) + low; buildTree(2 * ind + 1, low, mid, x); buildTree(2 * ind + 2, mid + 1, high, x); // merging the nodes while backtracking tree[ind] = combine(tree[2 * ind + 1], tree[2 * ind + 2]); } // performing query function query(ind, low, high, l, r) { let mid = parseInt((high - low) / 2, 10) + low; // Out of Bounds if (low > r || high < l) { return 0; } // completely overlaps if (l <= low && r >= high) { return tree[ind]; } // partially overlaps return combine( query(2 * ind + 1, low, mid, l, r), query(2 * ind + 2, mid + 1, high, l, r)); } arr = [ 7, 3, 9, 13, 5, 4 ]; let n = arr.length; let k = 6; tree = new Array(4 * n); tree.fill(0); // 1-based indexing let l = 1, r = 4; buildTree(0, 0, n - 1, k); document.write(query(0, 0, n - 1, l - 1, r - 1)); // This code is contributed by divyesh072019.</script>",
"e": 50944,
"s": 49268,
"text": null
},
{
"code": null,
"e": 50952,
"s": 50944,
"text": "Output:"
},
{
"code": null,
"e": 50954,
"s": 50952,
"text": "7"
},
{
"code": null,
"e": 51031,
"s": 50954,
"text": "Time Complexity: O(N * log N) to build the tree and O(log N) for each query."
},
{
"code": null,
"e": 51054,
"s": 51031,
"text": "Space Complexity: O(N)"
},
{
"code": null,
"e": 51066,
"s": 51054,
"text": "sanjeev2552"
},
{
"code": null,
"e": 51080,
"s": 51066,
"text": "princiraj1992"
},
{
"code": null,
"e": 51095,
"s": 51080,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 51111,
"s": 51095,
"text": "yashbeersingh42"
},
{
"code": null,
"e": 51128,
"s": 51111,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 51145,
"s": 51128,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 51153,
"s": 51145,
"text": "sarvjot"
},
{
"code": null,
"e": 51162,
"s": 51153,
"text": "suresh07"
},
{
"code": null,
"e": 51176,
"s": 51162,
"text": "divyesh072019"
},
{
"code": null,
"e": 51196,
"s": 51176,
"text": "array-range-queries"
},
{
"code": null,
"e": 51209,
"s": 51196,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51233,
"s": 51209,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 51240,
"s": 51233,
"text": "Arrays"
},
{
"code": null,
"e": 51250,
"s": 51240,
"text": "Recursion"
},
{
"code": null,
"e": 51260,
"s": 51250,
"text": "Searching"
},
{
"code": null,
"e": 51267,
"s": 51260,
"text": "Arrays"
},
{
"code": null,
"e": 51277,
"s": 51267,
"text": "Searching"
},
{
"code": null,
"e": 51287,
"s": 51277,
"text": "Recursion"
},
{
"code": null,
"e": 51300,
"s": 51287,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51398,
"s": 51300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51407,
"s": 51398,
"text": "Comments"
},
{
"code": null,
"e": 51420,
"s": 51407,
"text": "Old Comments"
},
{
"code": null,
"e": 51454,
"s": 51420,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 51494,
"s": 51454,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 51522,
"s": 51494,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 51554,
"s": 51522,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 51583,
"s": 51554,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 51598,
"s": 51583,
"text": "Arrays in Java"
},
{
"code": null,
"e": 51614,
"s": 51598,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 51641,
"s": 51614,
"text": "Program for array rotation"
},
{
"code": null,
"e": 51689,
"s": 51641,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Check whether an array can be made strictly increasing by incrementing and decrementing adjacent pairs - GeeksforGeeks
|
16 Dec, 2021
Given an array arr[] of size N consisting of non-negative integers. In one move ith index element of the array is decreased by 1 and (i+1)th index is increased by 1. The task is to check if there is any possibility to make the given array strictly increasing (containing non-negative integers only) by making any number of moves.
Examples:
Input: arr[3] = [1, 2, 3]Output: YesExplanation: The array is already sorted in strictly increasing order.
Input: arr[2] = [2, 0]Output: YesExplanation: Consider i = 0 for the 1st move arr[0] = 2-1 = 1, arr[1] = 0 + 1 = 1. Now the array becomes, [1, 1].In 2nd move consider i = 0. So now arr[0] = 1 – 1 = 0, arr[1] = 1 + 1 = 2. The final array becomes, arr[2] = [0, 2] which is strictly increasing.
Input: arr[3] = [0, 1, 0]Output: NoExplanation: This array cannot be made strictly increasing containing only non negative integers by performing any number of moves.
Approach: The problem can be solved using the following mathematical observation.
Since all the array elements are non-negative, so minimum strictly increasing order of an array of size N can be: 0, 1, 2, 3 . . . (N-1).
So the minimum sum(min_sum) of first i elements (till (i-t)th index) of any such array is min_sum = (i*(i-1))/2.
Therefore, the sum of first i elements of given array(cur_sum) must satisfy the condition cur_sum ≥ min_sum .
If the condition is not satisfied, then it is not possible to make the given array strictly increasing. Consider the following example
Illustration 1:
arr[] = 4 5 1 2 3min_sum = 0 1 3 6 10sum(arr) = 4 9 10 12 15
As this array satisfies the condition for every i, it is possible to convert this array to strictly increasing array
Illustration 2:
arr[] = 2 3 1 0 2min_sum = 0 1 3 6 10sum(arr) = 2 5 6 6 8
Here at index 4 the sum of array does not satisfy the condition of having minimum sum 10. So it is not possible to change the array into a strictly increasing one.
Follow the steps mentioned below to implement the concept:
Traverse from index = 0 to index = N – 1, and for each i check if sum till that is greater than or equal to (i*(i+1))/2.
If the condition is satisfied then the array can be made strictly increasing. Otherwise, it cannot be made strictly increasing.
Follow the below implementation for the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to check if the given array// can be made strictly increasing#include <bits/stdc++.h>using namespace std; // Function to check if// the array can be made strictly increasingvoid CheckStrictlyIncreasing(int arr[], int N){ // variable to store sum till current // index element int cur_sum = 0; bool possible = true; for (int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) cout << "Yes"; else cout << "No";} // Driver codeint main(){ int arr[3] = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N); return 0;}
// Java code to check if the given array// can be made strictly increasingimport java.util.*; class GFG{ // Function to check if// the array can be made strictly increasingstatic void CheckStrictlyIncreasing(int arr[], int N){ // variable to store sum till current // index element int cur_sum = 0; boolean possible = true; for (int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) System.out.print("Yes"); else System.out.print("No");} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N);}} // This code is contributed by shikhasingrajput
# Python 3 code to check if the given array# can be made strictly increasing # Function to check if# the array can be made strictly increasingdef CheckStrictlyIncreasing(arr, N): # variable to store sum till current # index element cur_sum = 0 possible = True for index in range(N): cur_sum += arr[index] # Sum of 0, 1, ...(i)th element req_sum = (index * (index + 1)) // 2 # Check if valid or not if (req_sum > cur_sum): possible = False break # If can be made strictly increasing if (possible): print("Yes") else: print("No") # Driver codeif __name__ == "__main__": arr = [1, 2, 3] N = 3 CheckStrictlyIncreasing(arr, N) # This code is contributed by ukasp.
// C# code to check if the given array// can be made strictly increasingusing System; class GFG{ // Function to check if the array can// be made strictly increasingstatic void CheckStrictlyIncreasing(int []arr, int N){ // Variable to store sum till current // index element int cur_sum = 0; bool possible = true; for(int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) Console.Write("Yes"); else Console.Write("No");} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N);}} // This code is contributed by shikhasingrajput
<script> // JavaScript code for the above approach // Function to check if // the array can be made strictly increasing function CheckStrictlyIncreasing(arr, N) { // variable to store sum till current // index element let cur_sum = 0; let possible = true; for (let index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element let req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) document.write("Yes"); else document.write("No"); } // Driver code let arr = [1, 2, 3]; let N = 3; CheckStrictlyIncreasing(arr, N); // This code is contributed by Potta Lokesh </script>
Yes
Time Complexity: O(N)Space Complexity: O(1)
lokeshpotta20
shikhasingrajput
ukasp
sagartomar9927
Sequence and Series
Arrays
Mathematical
Pattern Searching
Arrays
Mathematical
Pattern Searching
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
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 24735,
"s": 24405,
"text": "Given an array arr[] of size N consisting of non-negative integers. In one move ith index element of the array is decreased by 1 and (i+1)th index is increased by 1. The task is to check if there is any possibility to make the given array strictly increasing (containing non-negative integers only) by making any number of moves."
},
{
"code": null,
"e": 24746,
"s": 24735,
"text": "Examples: "
},
{
"code": null,
"e": 24853,
"s": 24746,
"text": "Input: arr[3] = [1, 2, 3]Output: YesExplanation: The array is already sorted in strictly increasing order."
},
{
"code": null,
"e": 25145,
"s": 24853,
"text": "Input: arr[2] = [2, 0]Output: YesExplanation: Consider i = 0 for the 1st move arr[0] = 2-1 = 1, arr[1] = 0 + 1 = 1. Now the array becomes, [1, 1].In 2nd move consider i = 0. So now arr[0] = 1 – 1 = 0, arr[1] = 1 + 1 = 2. The final array becomes, arr[2] = [0, 2] which is strictly increasing."
},
{
"code": null,
"e": 25312,
"s": 25145,
"text": "Input: arr[3] = [0, 1, 0]Output: NoExplanation: This array cannot be made strictly increasing containing only non negative integers by performing any number of moves."
},
{
"code": null,
"e": 25395,
"s": 25312,
"text": "Approach: The problem can be solved using the following mathematical observation. "
},
{
"code": null,
"e": 25533,
"s": 25395,
"text": "Since all the array elements are non-negative, so minimum strictly increasing order of an array of size N can be: 0, 1, 2, 3 . . . (N-1)."
},
{
"code": null,
"e": 25646,
"s": 25533,
"text": "So the minimum sum(min_sum) of first i elements (till (i-t)th index) of any such array is min_sum = (i*(i-1))/2."
},
{
"code": null,
"e": 25756,
"s": 25646,
"text": "Therefore, the sum of first i elements of given array(cur_sum) must satisfy the condition cur_sum ≥ min_sum ."
},
{
"code": null,
"e": 25891,
"s": 25756,
"text": "If the condition is not satisfied, then it is not possible to make the given array strictly increasing. Consider the following example"
},
{
"code": null,
"e": 25907,
"s": 25891,
"text": "Illustration 1:"
},
{
"code": null,
"e": 25991,
"s": 25907,
"text": "arr[] = 4 5 1 2 3min_sum = 0 1 3 6 10sum(arr) = 4 9 10 12 15"
},
{
"code": null,
"e": 26108,
"s": 25991,
"text": "As this array satisfies the condition for every i, it is possible to convert this array to strictly increasing array"
},
{
"code": null,
"e": 26124,
"s": 26108,
"text": "Illustration 2:"
},
{
"code": null,
"e": 26196,
"s": 26124,
"text": "arr[] = 2 3 1 0 2min_sum = 0 1 3 6 10sum(arr) = 2 5 6 6 8"
},
{
"code": null,
"e": 26360,
"s": 26196,
"text": "Here at index 4 the sum of array does not satisfy the condition of having minimum sum 10. So it is not possible to change the array into a strictly increasing one."
},
{
"code": null,
"e": 26419,
"s": 26360,
"text": "Follow the steps mentioned below to implement the concept:"
},
{
"code": null,
"e": 26540,
"s": 26419,
"text": "Traverse from index = 0 to index = N – 1, and for each i check if sum till that is greater than or equal to (i*(i+1))/2."
},
{
"code": null,
"e": 26668,
"s": 26540,
"text": "If the condition is satisfied then the array can be made strictly increasing. Otherwise, it cannot be made strictly increasing."
},
{
"code": null,
"e": 26724,
"s": 26668,
"text": "Follow the below implementation for the above approach:"
},
{
"code": null,
"e": 26728,
"s": 26724,
"text": "C++"
},
{
"code": null,
"e": 26733,
"s": 26728,
"text": "Java"
},
{
"code": null,
"e": 26741,
"s": 26733,
"text": "Python3"
},
{
"code": null,
"e": 26744,
"s": 26741,
"text": "C#"
},
{
"code": null,
"e": 26755,
"s": 26744,
"text": "Javascript"
},
{
"code": "// C++ code to check if the given array// can be made strictly increasing#include <bits/stdc++.h>using namespace std; // Function to check if// the array can be made strictly increasingvoid CheckStrictlyIncreasing(int arr[], int N){ // variable to store sum till current // index element int cur_sum = 0; bool possible = true; for (int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) cout << \"Yes\"; else cout << \"No\";} // Driver codeint main(){ int arr[3] = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N); return 0;}",
"e": 27651,
"s": 26755,
"text": null
},
{
"code": "// Java code to check if the given array// can be made strictly increasingimport java.util.*; class GFG{ // Function to check if// the array can be made strictly increasingstatic void CheckStrictlyIncreasing(int arr[], int N){ // variable to store sum till current // index element int cur_sum = 0; boolean possible = true; for (int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) System.out.print(\"Yes\"); else System.out.print(\"No\");} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N);}} // This code is contributed by shikhasingrajput",
"e": 28627,
"s": 27651,
"text": null
},
{
"code": "# Python 3 code to check if the given array# can be made strictly increasing # Function to check if# the array can be made strictly increasingdef CheckStrictlyIncreasing(arr, N): # variable to store sum till current # index element cur_sum = 0 possible = True for index in range(N): cur_sum += arr[index] # Sum of 0, 1, ...(i)th element req_sum = (index * (index + 1)) // 2 # Check if valid or not if (req_sum > cur_sum): possible = False break # If can be made strictly increasing if (possible): print(\"Yes\") else: print(\"No\") # Driver codeif __name__ == \"__main__\": arr = [1, 2, 3] N = 3 CheckStrictlyIncreasing(arr, N) # This code is contributed by ukasp.",
"e": 29428,
"s": 28627,
"text": null
},
{
"code": "// C# code to check if the given array// can be made strictly increasingusing System; class GFG{ // Function to check if the array can// be made strictly increasingstatic void CheckStrictlyIncreasing(int []arr, int N){ // Variable to store sum till current // index element int cur_sum = 0; bool possible = true; for(int index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element int req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 2, 3 }; int N = 3; CheckStrictlyIncreasing(arr, N);}} // This code is contributed by shikhasingrajput",
"e": 30411,
"s": 29428,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to check if // the array can be made strictly increasing function CheckStrictlyIncreasing(arr, N) { // variable to store sum till current // index element let cur_sum = 0; let possible = true; for (let index = 0; index < N; index++) { cur_sum += arr[index]; // Sum of 0, 1, ...(i)th element let req_sum = (index * (index + 1)) / 2; // Check if valid or not if (req_sum > cur_sum) { possible = false; break; } } // If can be made strictly increasing if (possible) document.write(\"Yes\"); else document.write(\"No\"); } // Driver code let arr = [1, 2, 3]; let N = 3; CheckStrictlyIncreasing(arr, N); // This code is contributed by Potta Lokesh </script>",
"e": 31456,
"s": 30411,
"text": null
},
{
"code": null,
"e": 31460,
"s": 31456,
"text": "Yes"
},
{
"code": null,
"e": 31504,
"s": 31460,
"text": "Time Complexity: O(N)Space Complexity: O(1)"
},
{
"code": null,
"e": 31518,
"s": 31504,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31535,
"s": 31518,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 31541,
"s": 31535,
"text": "ukasp"
},
{
"code": null,
"e": 31556,
"s": 31541,
"text": "sagartomar9927"
},
{
"code": null,
"e": 31576,
"s": 31556,
"text": "Sequence and Series"
},
{
"code": null,
"e": 31583,
"s": 31576,
"text": "Arrays"
},
{
"code": null,
"e": 31596,
"s": 31583,
"text": "Mathematical"
},
{
"code": null,
"e": 31614,
"s": 31596,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31621,
"s": 31614,
"text": "Arrays"
},
{
"code": null,
"e": 31634,
"s": 31621,
"text": "Mathematical"
},
{
"code": null,
"e": 31652,
"s": 31634,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31750,
"s": 31652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31759,
"s": 31750,
"text": "Comments"
},
{
"code": null,
"e": 31772,
"s": 31759,
"text": "Old Comments"
},
{
"code": null,
"e": 31793,
"s": 31772,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31818,
"s": 31793,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31845,
"s": 31818,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31894,
"s": 31845,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31932,
"s": 31894,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31962,
"s": 31932,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32022,
"s": 31962,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32037,
"s": 32022,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32080,
"s": 32037,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Daily life Linux Commands - GeeksforGeeks
|
06 Aug, 2020
Clear the Terminal : In our daily life, we use to work on Terminal if we are using LINUX. Continuous working on terminal makes the terminal screen full of commands and for removing them and making our screen totally free of character, we often use clear command. Key combination ‘Ctrl+l‘ has the same effect as ‘clear‘ command. So from next time use ctrl+l to clear your Linux Command Line Interface.Note: Since ctrl+l is a key combination, so we can not use it inside a script. If we need to clear screen inside a shell script, we just have to call command ‘clear’.Run command and get back to the directory, together: This is also an amazing hack not known to many people. We may run command no matter what it is and then return back to the current directory. For this, all we need to do is to run the command in parentheses i.e., in between ( and ).For Example :Input :cd /home/shivam/Downloads/ && ls -lOutput :-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt
Explanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory.Shortcut to Directories: You can create a shortcut to frequently accessed directories by adding them to the CDPATH environment variable. So, say If you frequently access “/var/www/html/”.Instead of typing “cd /var/www/html”, you can add /var/www/ to CDPATH and then you have to type “cd html” only.shivam:~> export CDPATH=$CDPATH:/var/www/
shivam:~> cd html
shivam:~:html>
Replacing words or characters:If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt
Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt
Here are some useful shortcuts which you may use while working on terminal:Cursor Movement Control:Ctrl-a: Move cursor to the start of a lineCtrl-e: Move cursor to the end of a lineCtrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:Ctrl-w: Delete the whole word to the left of the cursorCtrl-k: Erase to end of lineCtrl-u: Erase to beginning of lineRun top in batch mode: ‘top’ is a handy utility for monitoring the utilization of your system. It is invoked from the command line and it works by displaying lots of useful information, including CPU and memory usage, the number of running processes, load, the top resource hitters, and other useful bits. By default, top refreshes its report every 3 seconds.Mostly we run ‘top’ inside the terminal, look on the statistics for a few seconds and then graciously quit and continue our work.Better yet, if we wants to run such a utility only for a given period of time, without any user interaction:There are many possible answers:You could schedule a job via cron.You could run a shell script that runs ps every X secondsInstead of going wild about trying to patch a script, there’s a much, much simpler solution:top -b -d 10 -n 3 >> top-file
We have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:Duplicate pipe content: ‘tee’ is a very useful utility that duplicates pipe content. Now, what makes tee really useful is that it can append data to existing files, making it ideal for writing periodic log information to multiple files at once.ps | tee file1 file2 file3
We’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data.export: The ‘export’ command is one of the bash shell BUILTINS commands.It has three available command options. In general, it marks an environment variable to be exported with any newly forked child processes and thus it allows a child process to inherit all marked variables.Frequently Used Options with ‘export’-p : List of all names that are exported in the current shell-n: Remove names from export list-f : Names are exported as functionsExample :command without ‘export’:$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ bash
$ echo $a
From the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ export a
$ bash
$ echo $a
geeksforgeeks.org
$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created.basename – Strips directory and suffix from filenames. basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX. For example: To get the name of the file present in test folder$ basename test/gfg.txt
gfg.txtgrep: grep searches files for a given character string or pattern and can replace the string with another. This is one method of searching for files within Linux.grep [option(s)] pattern [file(s)]Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *There are lot of more options which can be tried using grep command.
Clear the Terminal : In our daily life, we use to work on Terminal if we are using LINUX. Continuous working on terminal makes the terminal screen full of commands and for removing them and making our screen totally free of character, we often use clear command. Key combination ‘Ctrl+l‘ has the same effect as ‘clear‘ command. So from next time use ctrl+l to clear your Linux Command Line Interface.Note: Since ctrl+l is a key combination, so we can not use it inside a script. If we need to clear screen inside a shell script, we just have to call command ‘clear’.
Run command and get back to the directory, together: This is also an amazing hack not known to many people. We may run command no matter what it is and then return back to the current directory. For this, all we need to do is to run the command in parentheses i.e., in between ( and ).For Example :Input :cd /home/shivam/Downloads/ && ls -lOutput :-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt
Explanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory.
cd /home/shivam/Downloads/ && ls -l
Output :
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt
-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt
Explanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory.
Shortcut to Directories: You can create a shortcut to frequently accessed directories by adding them to the CDPATH environment variable. So, say If you frequently access “/var/www/html/”.Instead of typing “cd /var/www/html”, you can add /var/www/ to CDPATH and then you have to type “cd html” only.shivam:~> export CDPATH=$CDPATH:/var/www/
shivam:~> cd html
shivam:~:html>
shivam:~> export CDPATH=$CDPATH:/var/www/
shivam:~> cd html
shivam:~:html>
Replacing words or characters:If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt
Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt
If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt
# sed 's/version/story/g' myfile.txt
Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt
# sed 's/version/story/gi' myfile.txt
Here are some useful shortcuts which you may use while working on terminal:Cursor Movement Control:Ctrl-a: Move cursor to the start of a lineCtrl-e: Move cursor to the end of a lineCtrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:Ctrl-w: Delete the whole word to the left of the cursorCtrl-k: Erase to end of lineCtrl-u: Erase to beginning of line
Ctrl-a: Move cursor to the start of a line
Ctrl-e: Move cursor to the end of a line
Ctrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:
Ctrl-w: Delete the whole word to the left of the cursor
Ctrl-k: Erase to end of line
Ctrl-u: Erase to beginning of line
Run top in batch mode: ‘top’ is a handy utility for monitoring the utilization of your system. It is invoked from the command line and it works by displaying lots of useful information, including CPU and memory usage, the number of running processes, load, the top resource hitters, and other useful bits. By default, top refreshes its report every 3 seconds.Mostly we run ‘top’ inside the terminal, look on the statistics for a few seconds and then graciously quit and continue our work.Better yet, if we wants to run such a utility only for a given period of time, without any user interaction:There are many possible answers:You could schedule a job via cron.You could run a shell script that runs ps every X secondsInstead of going wild about trying to patch a script, there’s a much, much simpler solution:top -b -d 10 -n 3 >> top-file
We have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:
You could schedule a job via cron.
You could run a shell script that runs ps every X seconds
Instead of going wild about trying to patch a script, there’s a much, much simpler solution:
top -b -d 10 -n 3 >> top-file
We have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:
Duplicate pipe content: ‘tee’ is a very useful utility that duplicates pipe content. Now, what makes tee really useful is that it can append data to existing files, making it ideal for writing periodic log information to multiple files at once.ps | tee file1 file2 file3
We’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data.
ps | tee file1 file2 file3
We’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data.
export: The ‘export’ command is one of the bash shell BUILTINS commands.It has three available command options. In general, it marks an environment variable to be exported with any newly forked child processes and thus it allows a child process to inherit all marked variables.Frequently Used Options with ‘export’-p : List of all names that are exported in the current shell-n: Remove names from export list-f : Names are exported as functionsExample :command without ‘export’:$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ bash
$ echo $a
From the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ export a
$ bash
$ echo $a
geeksforgeeks.org
$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created.
-p : List of all names that are exported in the current shell
-n: Remove names from export list
-f : Names are exported as functions
Example :
command without ‘export’:$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ bash
$ echo $a
From the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ export a
$ bash
$ echo $a
geeksforgeeks.org
$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created.
$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ bash
$ echo $a
From the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.
$ a = geeksforgeeks.org
$ echo $a
geeksforgeeks.org
$ export a
$ bash
$ echo $a
geeksforgeeks.org
$
On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created.
basename – Strips directory and suffix from filenames. basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX. For example: To get the name of the file present in test folder$ basename test/gfg.txt
gfg.txt
$ basename test/gfg.txt
gfg.txt
grep: grep searches files for a given character string or pattern and can replace the string with another. This is one method of searching for files within Linux.grep [option(s)] pattern [file(s)]Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *There are lot of more options which can be tried using grep command.
grep [option(s)] pattern [file(s)]
Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3
grep GfG file1 file2 file3
Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *
grep 'Linux is' *
There are lot of more options which can be tried using grep command.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
manav014
linux-command
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
'crontab' in Linux with Examples
How to Find the Wi-Fi Password Using CMD in Windows?
How to Run a Python Script using Docker?
Docker - COPY Instruction
Running Python script on GPU.
Setting up the environment in Java
|
[
{
"code": null,
"e": 24654,
"s": 24626,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 30585,
"s": 24654,
"text": "Clear the Terminal : In our daily life, we use to work on Terminal if we are using LINUX. Continuous working on terminal makes the terminal screen full of commands and for removing them and making our screen totally free of character, we often use clear command. Key combination ‘Ctrl+l‘ has the same effect as ‘clear‘ command. So from next time use ctrl+l to clear your Linux Command Line Interface.Note: Since ctrl+l is a key combination, so we can not use it inside a script. If we need to clear screen inside a shell script, we just have to call command ‘clear’.Run command and get back to the directory, together: This is also an amazing hack not known to many people. We may run command no matter what it is and then return back to the current directory. For this, all we need to do is to run the command in parentheses i.e., in between ( and ).For Example :Input :cd /home/shivam/Downloads/ && ls -lOutput :-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt\nExplanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory.Shortcut to Directories: You can create a shortcut to frequently accessed directories by adding them to the CDPATH environment variable. So, say If you frequently access “/var/www/html/”.Instead of typing “cd /var/www/html”, you can add /var/www/ to CDPATH and then you have to type “cd html” only.shivam:~> export CDPATH=$CDPATH:/var/www/\nshivam:~> cd html\nshivam:~:html>\nReplacing words or characters:If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt\n Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt\nHere are some useful shortcuts which you may use while working on terminal:Cursor Movement Control:Ctrl-a: Move cursor to the start of a lineCtrl-e: Move cursor to the end of a lineCtrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:Ctrl-w: Delete the whole word to the left of the cursorCtrl-k: Erase to end of lineCtrl-u: Erase to beginning of lineRun top in batch mode: ‘top’ is a handy utility for monitoring the utilization of your system. It is invoked from the command line and it works by displaying lots of useful information, including CPU and memory usage, the number of running processes, load, the top resource hitters, and other useful bits. By default, top refreshes its report every 3 seconds.Mostly we run ‘top’ inside the terminal, look on the statistics for a few seconds and then graciously quit and continue our work.Better yet, if we wants to run such a utility only for a given period of time, without any user interaction:There are many possible answers:You could schedule a job via cron.You could run a shell script that runs ps every X secondsInstead of going wild about trying to patch a script, there’s a much, much simpler solution:top -b -d 10 -n 3 >> top-file\nWe have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:Duplicate pipe content: ‘tee’ is a very useful utility that duplicates pipe content. Now, what makes tee really useful is that it can append data to existing files, making it ideal for writing periodic log information to multiple files at once.ps | tee file1 file2 file3\nWe’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data.export: The ‘export’ command is one of the bash shell BUILTINS commands.It has three available command options. In general, it marks an environment variable to be exported with any newly forked child processes and thus it allows a child process to inherit all marked variables.Frequently Used Options with ‘export’-p : List of all names that are exported in the current shell-n: Remove names from export list-f : Names are exported as functionsExample :command without ‘export’:$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ bash\n$ echo $a\nFrom the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ export a\n$ bash\n$ echo $a\ngeeksforgeeks.org\n$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created.basename – Strips directory and suffix from filenames. basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX. For example: To get the name of the file present in test folder$ basename test/gfg.txt\ngfg.txtgrep: grep searches files for a given character string or pattern and can replace the string with another. This is one method of searching for files within Linux.grep [option(s)] pattern [file(s)]Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *There are lot of more options which can be tried using grep command."
},
{
"code": null,
"e": 31152,
"s": 30585,
"text": "Clear the Terminal : In our daily life, we use to work on Terminal if we are using LINUX. Continuous working on terminal makes the terminal screen full of commands and for removing them and making our screen totally free of character, we often use clear command. Key combination ‘Ctrl+l‘ has the same effect as ‘clear‘ command. So from next time use ctrl+l to clear your Linux Command Line Interface.Note: Since ctrl+l is a key combination, so we can not use it inside a script. If we need to clear screen inside a shell script, we just have to call command ‘clear’."
},
{
"code": null,
"e": 31854,
"s": 31152,
"text": "Run command and get back to the directory, together: This is also an amazing hack not known to many people. We may run command no matter what it is and then return back to the current directory. For this, all we need to do is to run the command in parentheses i.e., in between ( and ).For Example :Input :cd /home/shivam/Downloads/ && ls -lOutput :-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt\nExplanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory."
},
{
"code": null,
"e": 31890,
"s": 31854,
"text": "cd /home/shivam/Downloads/ && ls -l"
},
{
"code": null,
"e": 31899,
"s": 31890,
"text": "Output :"
},
{
"code": null,
"e": 32074,
"s": 31899,
"text": "-rw-r----- 1 shivam shivam 54272 May 3 18:37 text1.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text2.txt\n-rw-r----- 1 shivam shivam 54272 May 3 18:37 text3.txt\n"
},
{
"code": null,
"e": 32253,
"s": 32074,
"text": "Explanation : In the above command it first changed the current directory to Downloads and then list the content of that directory before returning back to the current directory."
},
{
"code": null,
"e": 32627,
"s": 32253,
"text": "Shortcut to Directories: You can create a shortcut to frequently accessed directories by adding them to the CDPATH environment variable. So, say If you frequently access “/var/www/html/”.Instead of typing “cd /var/www/html”, you can add /var/www/ to CDPATH and then you have to type “cd html” only.shivam:~> export CDPATH=$CDPATH:/var/www/\nshivam:~> cd html\nshivam:~:html>\n"
},
{
"code": null,
"e": 32703,
"s": 32627,
"text": "shivam:~> export CDPATH=$CDPATH:/var/www/\nshivam:~> cd html\nshivam:~:html>\n"
},
{
"code": null,
"e": 33047,
"s": 32703,
"text": "Replacing words or characters:If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt\n Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt\n"
},
{
"code": null,
"e": 33235,
"s": 33047,
"text": "If you are working with any text file then to replace every instance of any word say “version” with “story” in myfile.txt, you can use sed command as:# sed 's/version/story/g' myfile.txt\n"
},
{
"code": null,
"e": 33273,
"s": 33235,
"text": "# sed 's/version/story/g' myfile.txt\n"
},
{
"code": null,
"e": 33400,
"s": 33273,
"text": " Additionally, if you want to ignore character case then you may use gi instead of g as:# sed 's/version/story/gi' myfile.txt\n"
},
{
"code": null,
"e": 33439,
"s": 33400,
"text": "# sed 's/version/story/gi' myfile.txt\n"
},
{
"code": null,
"e": 33820,
"s": 33439,
"text": "Here are some useful shortcuts which you may use while working on terminal:Cursor Movement Control:Ctrl-a: Move cursor to the start of a lineCtrl-e: Move cursor to the end of a lineCtrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:Ctrl-w: Delete the whole word to the left of the cursorCtrl-k: Erase to end of lineCtrl-u: Erase to beginning of line"
},
{
"code": null,
"e": 33863,
"s": 33820,
"text": "Ctrl-a: Move cursor to the start of a line"
},
{
"code": null,
"e": 33904,
"s": 33863,
"text": "Ctrl-e: Move cursor to the end of a line"
},
{
"code": null,
"e": 33987,
"s": 33904,
"text": "Ctrl-Left/Right: Navigate word by word (may not work in all terminals)Modify Text:"
},
{
"code": null,
"e": 34043,
"s": 33987,
"text": "Ctrl-w: Delete the whole word to the left of the cursor"
},
{
"code": null,
"e": 34072,
"s": 34043,
"text": "Ctrl-k: Erase to end of line"
},
{
"code": null,
"e": 34107,
"s": 34072,
"text": "Ctrl-u: Erase to beginning of line"
},
{
"code": null,
"e": 35171,
"s": 34107,
"text": "Run top in batch mode: ‘top’ is a handy utility for monitoring the utilization of your system. It is invoked from the command line and it works by displaying lots of useful information, including CPU and memory usage, the number of running processes, load, the top resource hitters, and other useful bits. By default, top refreshes its report every 3 seconds.Mostly we run ‘top’ inside the terminal, look on the statistics for a few seconds and then graciously quit and continue our work.Better yet, if we wants to run such a utility only for a given period of time, without any user interaction:There are many possible answers:You could schedule a job via cron.You could run a shell script that runs ps every X secondsInstead of going wild about trying to patch a script, there’s a much, much simpler solution:top -b -d 10 -n 3 >> top-file\nWe have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:"
},
{
"code": null,
"e": 35206,
"s": 35171,
"text": "You could schedule a job via cron."
},
{
"code": null,
"e": 35264,
"s": 35206,
"text": "You could run a shell script that runs ps every X seconds"
},
{
"code": null,
"e": 35357,
"s": 35264,
"text": "Instead of going wild about trying to patch a script, there’s a much, much simpler solution:"
},
{
"code": null,
"e": 35388,
"s": 35357,
"text": "top -b -d 10 -n 3 >> top-file\n"
},
{
"code": null,
"e": 35611,
"s": 35388,
"text": "We have top running in batch mode (-b). It’s going to refresh every 10 seconds, as specified by the delay (-d) flag, for a total count of 3 iterations (-n). The output will be sent to a file.Here is a screenshots of outut:"
},
{
"code": null,
"e": 36097,
"s": 35611,
"text": "Duplicate pipe content: ‘tee’ is a very useful utility that duplicates pipe content. Now, what makes tee really useful is that it can append data to existing files, making it ideal for writing periodic log information to multiple files at once.ps | tee file1 file2 file3\nWe’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data."
},
{
"code": null,
"e": 36125,
"s": 36097,
"text": "ps | tee file1 file2 file3\n"
},
{
"code": null,
"e": 36340,
"s": 36125,
"text": "We’re sending the output of the ps command to three different files! Or as many as we want. As you can see in the screenshots below, all three files were created at the same time and they all contain the same data."
},
{
"code": null,
"e": 37401,
"s": 36340,
"text": "export: The ‘export’ command is one of the bash shell BUILTINS commands.It has three available command options. In general, it marks an environment variable to be exported with any newly forked child processes and thus it allows a child process to inherit all marked variables.Frequently Used Options with ‘export’-p : List of all names that are exported in the current shell-n: Remove names from export list-f : Names are exported as functionsExample :command without ‘export’:$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ bash\n$ echo $a\nFrom the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ export a\n$ bash\n$ echo $a\ngeeksforgeeks.org\n$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created."
},
{
"code": null,
"e": 37463,
"s": 37401,
"text": "-p : List of all names that are exported in the current shell"
},
{
"code": null,
"e": 37497,
"s": 37463,
"text": "-n: Remove names from export list"
},
{
"code": null,
"e": 37534,
"s": 37497,
"text": "-f : Names are exported as functions"
},
{
"code": null,
"e": 37544,
"s": 37534,
"text": "Example :"
},
{
"code": null,
"e": 38152,
"s": 37544,
"text": "command without ‘export’:$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ bash\n$ echo $a\nFrom the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy.$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ export a\n$ bash\n$ echo $a\ngeeksforgeeks.org\n$On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created."
},
{
"code": null,
"e": 38222,
"s": 38152,
"text": "$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ bash\n$ echo $a\n"
},
{
"code": null,
"e": 38398,
"s": 38222,
"text": "From the above we can see that any new child process forked from a parent process by default does not inherit parent’s variables. This is where the export command comes handy."
},
{
"code": null,
"e": 38498,
"s": 38398,
"text": "$ a = geeksforgeeks.org\n$ echo $a\ngeeksforgeeks.org\n$ export a\n$ bash\n$ echo $a\ngeeksforgeeks.org\n$"
},
{
"code": null,
"e": 38738,
"s": 38498,
"text": "On line 3, we now have used the export command to make the variable “a” to be exported when a new child process is created. As a result the variable “a” still contains the string “geeksforgeeks.org” even after a new bash shell was created."
},
{
"code": null,
"e": 39019,
"s": 38738,
"text": "basename – Strips directory and suffix from filenames. basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX. For example: To get the name of the file present in test folder$ basename test/gfg.txt\ngfg.txt"
},
{
"code": null,
"e": 39051,
"s": 39019,
"text": "$ basename test/gfg.txt\ngfg.txt"
},
{
"code": null,
"e": 39731,
"s": 39051,
"text": "grep: grep searches files for a given character string or pattern and can replace the string with another. This is one method of searching for files within Linux.grep [option(s)] pattern [file(s)]Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *There are lot of more options which can be tried using grep command."
},
{
"code": null,
"e": 39766,
"s": 39731,
"text": "grep [option(s)] pattern [file(s)]"
},
{
"code": null,
"e": 39995,
"s": 39766,
"text": "Search number of files: grep can search any number of files simultaneously. Thus, for example, the following would search the three files file1, file2 and file3 for any line that contains the string GfGgrep GfG file1 file2 file3"
},
{
"code": null,
"e": 40022,
"s": 39995,
"text": "grep GfG file1 file2 file3"
},
{
"code": null,
"e": 40210,
"s": 40022,
"text": "Search text in all files: To search all text files in the current directory (i.e., the directory in which the user is currently working), if there is a phrase “Linux is” grep 'Linux is' *"
},
{
"code": null,
"e": 40229,
"s": 40210,
"text": " grep 'Linux is' *"
},
{
"code": null,
"e": 40298,
"s": 40229,
"text": "There are lot of more options which can be tried using grep command."
},
{
"code": null,
"e": 40613,
"s": 40298,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 40738,
"s": 40613,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 40747,
"s": 40738,
"text": "manav014"
},
{
"code": null,
"e": 40761,
"s": 40747,
"text": "linux-command"
},
{
"code": null,
"e": 40772,
"s": 40761,
"text": "Linux-Unix"
},
{
"code": null,
"e": 40781,
"s": 40772,
"text": "TechTips"
},
{
"code": null,
"e": 40879,
"s": 40781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40917,
"s": 40879,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 40952,
"s": 40917,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 40988,
"s": 40952,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 41026,
"s": 40988,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 41059,
"s": 41026,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 41112,
"s": 41059,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 41153,
"s": 41112,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 41179,
"s": 41153,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 41209,
"s": 41179,
"text": "Running Python script on GPU."
}
] |
Mockito - Resetting Mock
|
Mockito provides the capability to a reset a mock so that it can be reused later. Take a look at the following code snippet.
//reset mock
reset(calcService);
Here we've reset mock object. MathApplication makes use of calcService and after reset the mock, using mocked method will fail the test.
Step 1 − Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2 − Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
return calcService.add(input1, input2);
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3 − Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito.
File: MathApplicationTester.java
package com.tutorialspoint.mock;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.reset;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
private MathApplication mathApplication;
private CalculatorService calcService;
@Before
public void setUp(){
mathApplication = new MathApplication();
calcService = mock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAddAndSubtract(){
//add the behavior to add numbers
when(calcService.add(20.0,10.0)).thenReturn(30.0);
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
//reset the mock
reset(calcService);
//test the add functionality after resetting the mock
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
}
}
Step 4 − Execute test cases
Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5 − Verify the Result
Compile the classes using javac compiler as follows −
C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.
java MathApplicationTester.java TestRunner.java
Now run the Test Runner to see the result −
C:\Mockito_WORKSPACE>java TestRunner
Verify the output.
testAddAndSubtract(MathApplicationTester): expected:<0.0> but was:<30.0>
false
31 Lectures
43 mins
Abhinav Manchanda
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2105,
"s": 1980,
"text": "Mockito provides the capability to a reset a mock so that it can be reused later. Take a look at the following code snippet."
},
{
"code": null,
"e": 2139,
"s": 2105,
"text": "//reset mock\nreset(calcService);\n"
},
{
"code": null,
"e": 2276,
"s": 2139,
"text": "Here we've reset mock object. MathApplication makes use of calcService and after reset the mock, using mocked method will fail the test."
},
{
"code": null,
"e": 2364,
"s": 2276,
"text": "Step 1 − Create an interface called CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2393,
"s": 2364,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2653,
"s": 2393,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2711,
"s": 2653,
"text": "Step 2 − Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2738,
"s": 2711,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3381,
"s": 2738,
"text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3421,
"s": 3381,
"text": "Step 3 − Test the MathApplication class"
},
{
"code": null,
"e": 3540,
"s": 3421,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito."
},
{
"code": null,
"e": 3573,
"s": 3540,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 4758,
"s": 3573,
"text": "package com.tutorialspoint.mock;\n\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\nimport static org.mockito.Mockito.reset;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n private MathApplication mathApplication;\n private CalculatorService calcService;\n\n @Before\n public void setUp(){\n mathApplication = new MathApplication();\n calcService = mock(CalculatorService.class);\n mathApplication.setCalculatorService(calcService);\n }\n\n @Test\n public void testAddAndSubtract(){\n\n //add the behavior to add numbers\n when(calcService.add(20.0,10.0)).thenReturn(30.0);\n \n //test the add functionality\n Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);\n\n //reset the mock\t \n reset(calcService);\n\n //test the add functionality after resetting the mock\n Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); \n }\n}"
},
{
"code": null,
"e": 4786,
"s": 4758,
"text": "Step 4 − Execute test cases"
},
{
"code": null,
"e": 4879,
"s": 4786,
"text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 4901,
"s": 4879,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 5342,
"s": 4901,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 5369,
"s": 5342,
"text": "Step 5 − Verify the Result"
},
{
"code": null,
"e": 5423,
"s": 5369,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 5542,
"s": 5423,
"text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n"
},
{
"code": null,
"e": 5586,
"s": 5542,
"text": "Now run the Test Runner to see the result −"
},
{
"code": null,
"e": 5624,
"s": 5586,
"text": "C:\\Mockito_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 5643,
"s": 5624,
"text": "Verify the output."
},
{
"code": null,
"e": 5723,
"s": 5643,
"text": "testAddAndSubtract(MathApplicationTester): expected:<0.0> but was:<30.0>\nfalse\n"
},
{
"code": null,
"e": 5755,
"s": 5723,
"text": "\n 31 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 5774,
"s": 5755,
"text": " Abhinav Manchanda"
},
{
"code": null,
"e": 5781,
"s": 5774,
"text": " Print"
},
{
"code": null,
"e": 5792,
"s": 5781,
"text": " Add Notes"
}
] |
An Implementation of DBSCAN on PySpark | by Salil Jain | Towards Data Science
|
DBSCAN is a well-known clustering algorithm that has stood the test of time. Though the algorithm is not included in Spark MLLib. There are a few implementations (1, 2, 3) though they are in scala. Implementation in PySpark uses the cartesian product of rdd to itself which results in O(n2) complexity and possibly O(n2) memory before the filter.
ptsFullNeighborRDD=rdd.cartesian(rdd) .filter(lambda (pt1,pt2): dist(pt1,pt2)<eps) .map(lambda (pt1,pt2):(pt1,[pt2])) .reduceByKey(lambda pts1,pts2: pts1+pts2) .filter(lambda (pt, pts): len(pts)>=minPts)source: https://github.com/htleeab/DBSCAN-pyspark/blob/master/DBSCAN.py
For a quick primer on the complexity of the DBSCAN algorithm:
https://en.wikipedia.org/wiki/DBSCAN#Complexity
DBSCAN visits each point of the database, possibly multiple times (e.g., as candidates to different clusters). For practical considerations, however, the time complexity is mostly governed by the number of regionQuery invocations. DBSCAN executes exactly one such query for each point, and if an indexing structure is used that executes a neighborhood query in O(log n), an overall average runtime complexity of O(n log n) is obtained (if parameter ε is chosen in a meaningful way, i.e. such that on average only O(log n) points are returned). Without the use of an accelerating index structure, or on degenerated data (e.g. all points within a distance less than ε), the worst case run time complexity remains O(n2). The distance matrix of size (n2-n)/2 can be materialized to avoid distance recomputations, but this needs O(n2) memory, whereas a non-matrix based implementation of DBSCAN only needs O(n) memory.
In this post, we will explore how we can implement DBSCAN in PySpark efficiently without using O(n2) operations by reducing the number of distance calculations. We would implement an indexing/partitioning structure based on Triangle Inequality to achieve this.
Let’s refresh triangle inequality. If there are three vertices of the triangle a, b and c, and given distance metric d. Then
d(a, b) ≤ d(a, c) + d(c, b)
d(a, c) ≤ d(a, b) + d(b, c)
d(b, c) ≤ d(b, a) + d(a, c)
In DBSCAN there is a parameter ε, which is used to find the linkage between points. Now, let us use this parameter to see if we can use triangle inequality to reduce the number of operations.
Let’s say there are four points x, y, z, and c.
Lemma 1: If d(x, c) ≥ (k+1)ε and d(y, c) < kε then d(x, y) > ε
As per triangle inequality,
d(x, c) ≤ d(x, y) + d(y, c)
d(x, c)-d(y, c)≤ d(x, y)
d(x, c)-d(y, c) > (k+1)ε -kε > ε
so d(x, y) > ε
Lemma 2: If d(x, c) ≤ lε and d(z, c) > (l+1)ε then d(x, z) > ε
As per triangle inequality,
d(z, c) ≤ d(x, z) + d(x, c)
d(z, c)-d(x, c)≤ d(x, z)
d(z, c)-d(x, c) > (l+1)ε -lε
d(z, c)-d(x, c) > ε
so d(x, z) > ε
What we can deduce from above is that if we compute distances of all points from c then we can filter points y and z using above criteria. We can compute distances from c and partition points in concentric rings (center being c).
From the above lemmas, we can see that if
(m+1)ε ≥ d(x, c) ≥ mε then we can filter out points y and z if d(y, c) < (m-1)ε and d(z, c) > (m+2)ε
From this, we can deduce that for any point for which (m+1)ε ≥ d(x, c) ≥ mε is true we can have a partition of (m+3)ε width starting at (m-1)ε and ending at (m+2)ε.
Here is a depiction how it would look like. Two-dimensional space is divided into quantiles of ε euclidean distance. Green rings show the partition. x1 is at the (m+1/2)ε distance from c (center of (m-1)ε — (m+2)ε partition). x2 and x3 are at mε and (m+1)ε distance from c. It is clear that for x1, x2, and x3 all points of relevance (within the circle of radius ε) are within the partition.
If we create mutually exclusive partitions and compute distances among points within that partition, it would be incomplete. For example, x4 and x5’s range circle will overlap two partitions. Hence the need for overlapping partition. One strategy could be to move the partition by ε. Though in that case if partition width is 3ε, then one point may occur in three different partitions. Instead, partitions are created of 2ε width and move them by ε. In this case, one point may occur only in two partitions.
The above two images show how this partition scheme works. Two partitions in combination allow a range query of ε radius for all the points from mε to (m+1)ε. The first partition covers all the points from mε to (m+1/2)ε (x2 covered but x3 not) and the second covers (m+1/2)ε to (m+1)ε (x3 covered but x2 not).
Let us see how these partitions look like on some generated data.
The above data and image are generated by the following code:
The above partitions from data are generated by the following code:
partition_index identifies each partition. Each data point is put into two partitions as discussed before based on the distance from c (pivot) and ε. distance method handles one point at a time. In PySpark flatMap method is used to map every point into an array of tuples (out).
All data points within a partition are merged before generating the visualization. They also need to be merged for further processing DBSCAN on PySpark.
reduceByKey method is used to merge partition data in one. The use of word partition may confuse with PySpark partitions but those are two separate things. Though partitionBy method could be used to reconcile that as well.
After reduceByKey, we will get each row of the rdd as a ring depicted in figure 4. As you can see there is an overlap so points would be in two rows of rdd and that is intentional.
The above code computes distance within each partition. The output of the method is a list of tuples. Each tuple has the id of point and set of its neighbors within ε distance. As we know that point would occur in two partitions so we need to combine the sets for a given point so we get all of its neighbors within ε distance in whole data. reduceByKey is used to combine the sets by doing union operation on them.
reduceByKey(lambda x, y: x.union(y))
Combined code till now looks as follows:
Once we have neighbors within ε distance for a point we can identify if it is a core or border point.
Core Point: There are at least min_pts within ε distance
Border Point: There are less than min_pts within ε distance but one of them is the core point.
To identify core and border points, first, we assign them to a cluster. For each point which is a core point, we create a cluster label the same to its id (assuming the ids are unique). We create a tuple for each core point and its neighbors of the form (id, [(cluster_label, is_core_point)]). All the neighbors in this scenario would be labeled as a base point. Let's take an example
min_pts = 3Input: (3, set(4,6,2))Output: [(3, [(3, True)]), (4, [(3, False)]), (6, [(3, False)]), (2, [(3, False)])]
Input is a tuple where 3 is the id of point and (4, 6, 2) are its neighbors within ε distance.
As one can see all points are assigned cluster label 3. While 3 is assigned True for is_core_point as a core point and all other points are considered base points and assigned False for is_core_point.
We may have similar input tuples for 4, 6, and 2 where they may or may not be assigned as core points. The idea is to eventually combine all cluster labels for a point and if at least one of the assignment for is_core_point is True then its a core point otherwise its a border point.
We combine all (cluster_label, is_core_point) tuples for a point using reduceByKey method and then investigate if its a core point or not while combining all clusters labels for that point. If its a border point then we would only leave one cluster label for it.
The above method is used to combine all cluster label for a point. Again if it is a border point then we return only 1st cluster label.
Code in PySpark till now looks like the following:
Now for each point, we have cluster labels. If a point has more than one cluster label then it means those clusters are connected. Those connected clusters are the final clusters we need to solve DBSCAN. We solve this by creating a graph with vertices as cluster labels and edges between cluster labels if they are assigned to the same point.
In the above code, combine_cluster_rdd is a collection of rows where each row is a tuple (point, cluster_labels). Each cluster label is vertices and combinations of cluster labels for a point are the edges. Connected components of this graph give a mapping between each cluster label and a connected cluster. which we can apply to points to get final clusters.
Above is how the final method looks like which returns a Spark Dataframe with point id, cluster component label, and a boolean indicator if its a core point.
Now I compare the results in terms of accuracy with sklearn implementation of DBSCAN.
The make_blobs method creates blobs around three input centers. Running DBSCAN using sklearn and my implementation with ε=0.3 and min_pts=10 gives the following results.
Core points are bigger circles while border points are smaller ones. Noise points are colored black which is the same in both implementations. One thing that jumps out is the border points are assigned different clusters that speak to the non-deterministic nature of DBSCAN. My other post also talks about it.
medium.com
For ε=0.2 we get the border points assigned to the same clusters. Following is some code and results on data in rings.
For n=750, the number of distance operations required by a simple implementation of DBSCAN would be n(n-1)/2 which is 280875. As we create the partition based on ε, the smaller the ε less the number of distance operations would be needed. In this case, there were a total of 149716(ε=.2) and 217624(ε=0.3) operations needed.
A pyspark implementation which would be efficient based on the value of ε with the following steps:
Partitioning Data: Partition with overlapping rings of 2ε width moved by ε.Merging Partition Data: So we get all partition data in a single record.Distance Calculations: Calculate distance within the same partitionPoint Labeling: Based on the number of neighbors, label core, and border points.Connected Clusters: Use Graphframe to connect clusters labels to evaluate final DBSCAN labels.
Partitioning Data: Partition with overlapping rings of 2ε width moved by ε.
Merging Partition Data: So we get all partition data in a single record.
Distance Calculations: Calculate distance within the same partition
Point Labeling: Based on the number of neighbors, label core, and border points.
Connected Clusters: Use Graphframe to connect clusters labels to evaluate final DBSCAN labels.
A comparison with the existing implementation shows the accuracy of the algorithm and the implementation of this post.
On the local machine with both driver and worker nodes, implementation is slower than sklearn. There could be a couple of reasons which need to be investigated:
For a small amount of data, sklearn may be much faster but is it the case for big-data?Graphframe takes quite some time to execute and wondering if connected components analysis can be performed on the driver with some other graph library?
For a small amount of data, sklearn may be much faster but is it the case for big-data?
Graphframe takes quite some time to execute and wondering if connected components analysis can be performed on the driver with some other graph library?
Complete PySpark Implementation can be fount at:
|
[
{
"code": null,
"e": 519,
"s": 172,
"text": "DBSCAN is a well-known clustering algorithm that has stood the test of time. Though the algorithm is not included in Spark MLLib. There are a few implementations (1, 2, 3) though they are in scala. Implementation in PySpark uses the cartesian product of rdd to itself which results in O(n2) complexity and possibly O(n2) memory before the filter."
},
{
"code": null,
"e": 902,
"s": 519,
"text": "ptsFullNeighborRDD=rdd.cartesian(rdd) .filter(lambda (pt1,pt2): dist(pt1,pt2)<eps) .map(lambda (pt1,pt2):(pt1,[pt2])) .reduceByKey(lambda pts1,pts2: pts1+pts2) .filter(lambda (pt, pts): len(pts)>=minPts)source: https://github.com/htleeab/DBSCAN-pyspark/blob/master/DBSCAN.py"
},
{
"code": null,
"e": 964,
"s": 902,
"text": "For a quick primer on the complexity of the DBSCAN algorithm:"
},
{
"code": null,
"e": 1012,
"s": 964,
"text": "https://en.wikipedia.org/wiki/DBSCAN#Complexity"
},
{
"code": null,
"e": 1926,
"s": 1012,
"text": "DBSCAN visits each point of the database, possibly multiple times (e.g., as candidates to different clusters). For practical considerations, however, the time complexity is mostly governed by the number of regionQuery invocations. DBSCAN executes exactly one such query for each point, and if an indexing structure is used that executes a neighborhood query in O(log n), an overall average runtime complexity of O(n log n) is obtained (if parameter ε is chosen in a meaningful way, i.e. such that on average only O(log n) points are returned). Without the use of an accelerating index structure, or on degenerated data (e.g. all points within a distance less than ε), the worst case run time complexity remains O(n2). The distance matrix of size (n2-n)/2 can be materialized to avoid distance recomputations, but this needs O(n2) memory, whereas a non-matrix based implementation of DBSCAN only needs O(n) memory."
},
{
"code": null,
"e": 2187,
"s": 1926,
"text": "In this post, we will explore how we can implement DBSCAN in PySpark efficiently without using O(n2) operations by reducing the number of distance calculations. We would implement an indexing/partitioning structure based on Triangle Inequality to achieve this."
},
{
"code": null,
"e": 2312,
"s": 2187,
"text": "Let’s refresh triangle inequality. If there are three vertices of the triangle a, b and c, and given distance metric d. Then"
},
{
"code": null,
"e": 2340,
"s": 2312,
"text": "d(a, b) ≤ d(a, c) + d(c, b)"
},
{
"code": null,
"e": 2368,
"s": 2340,
"text": "d(a, c) ≤ d(a, b) + d(b, c)"
},
{
"code": null,
"e": 2396,
"s": 2368,
"text": "d(b, c) ≤ d(b, a) + d(a, c)"
},
{
"code": null,
"e": 2588,
"s": 2396,
"text": "In DBSCAN there is a parameter ε, which is used to find the linkage between points. Now, let us use this parameter to see if we can use triangle inequality to reduce the number of operations."
},
{
"code": null,
"e": 2636,
"s": 2588,
"text": "Let’s say there are four points x, y, z, and c."
},
{
"code": null,
"e": 2699,
"s": 2636,
"text": "Lemma 1: If d(x, c) ≥ (k+1)ε and d(y, c) < kε then d(x, y) > ε"
},
{
"code": null,
"e": 2727,
"s": 2699,
"text": "As per triangle inequality,"
},
{
"code": null,
"e": 2755,
"s": 2727,
"text": "d(x, c) ≤ d(x, y) + d(y, c)"
},
{
"code": null,
"e": 2780,
"s": 2755,
"text": "d(x, c)-d(y, c)≤ d(x, y)"
},
{
"code": null,
"e": 2813,
"s": 2780,
"text": "d(x, c)-d(y, c) > (k+1)ε -kε > ε"
},
{
"code": null,
"e": 2828,
"s": 2813,
"text": "so d(x, y) > ε"
},
{
"code": null,
"e": 2891,
"s": 2828,
"text": "Lemma 2: If d(x, c) ≤ lε and d(z, c) > (l+1)ε then d(x, z) > ε"
},
{
"code": null,
"e": 2919,
"s": 2891,
"text": "As per triangle inequality,"
},
{
"code": null,
"e": 2947,
"s": 2919,
"text": "d(z, c) ≤ d(x, z) + d(x, c)"
},
{
"code": null,
"e": 2972,
"s": 2947,
"text": "d(z, c)-d(x, c)≤ d(x, z)"
},
{
"code": null,
"e": 3001,
"s": 2972,
"text": "d(z, c)-d(x, c) > (l+1)ε -lε"
},
{
"code": null,
"e": 3021,
"s": 3001,
"text": "d(z, c)-d(x, c) > ε"
},
{
"code": null,
"e": 3036,
"s": 3021,
"text": "so d(x, z) > ε"
},
{
"code": null,
"e": 3266,
"s": 3036,
"text": "What we can deduce from above is that if we compute distances of all points from c then we can filter points y and z using above criteria. We can compute distances from c and partition points in concentric rings (center being c)."
},
{
"code": null,
"e": 3308,
"s": 3266,
"text": "From the above lemmas, we can see that if"
},
{
"code": null,
"e": 3409,
"s": 3308,
"text": "(m+1)ε ≥ d(x, c) ≥ mε then we can filter out points y and z if d(y, c) < (m-1)ε and d(z, c) > (m+2)ε"
},
{
"code": null,
"e": 3574,
"s": 3409,
"text": "From this, we can deduce that for any point for which (m+1)ε ≥ d(x, c) ≥ mε is true we can have a partition of (m+3)ε width starting at (m-1)ε and ending at (m+2)ε."
},
{
"code": null,
"e": 3966,
"s": 3574,
"text": "Here is a depiction how it would look like. Two-dimensional space is divided into quantiles of ε euclidean distance. Green rings show the partition. x1 is at the (m+1/2)ε distance from c (center of (m-1)ε — (m+2)ε partition). x2 and x3 are at mε and (m+1)ε distance from c. It is clear that for x1, x2, and x3 all points of relevance (within the circle of radius ε) are within the partition."
},
{
"code": null,
"e": 4474,
"s": 3966,
"text": "If we create mutually exclusive partitions and compute distances among points within that partition, it would be incomplete. For example, x4 and x5’s range circle will overlap two partitions. Hence the need for overlapping partition. One strategy could be to move the partition by ε. Though in that case if partition width is 3ε, then one point may occur in three different partitions. Instead, partitions are created of 2ε width and move them by ε. In this case, one point may occur only in two partitions."
},
{
"code": null,
"e": 4785,
"s": 4474,
"text": "The above two images show how this partition scheme works. Two partitions in combination allow a range query of ε radius for all the points from mε to (m+1)ε. The first partition covers all the points from mε to (m+1/2)ε (x2 covered but x3 not) and the second covers (m+1/2)ε to (m+1)ε (x3 covered but x2 not)."
},
{
"code": null,
"e": 4851,
"s": 4785,
"text": "Let us see how these partitions look like on some generated data."
},
{
"code": null,
"e": 4913,
"s": 4851,
"text": "The above data and image are generated by the following code:"
},
{
"code": null,
"e": 4981,
"s": 4913,
"text": "The above partitions from data are generated by the following code:"
},
{
"code": null,
"e": 5260,
"s": 4981,
"text": "partition_index identifies each partition. Each data point is put into two partitions as discussed before based on the distance from c (pivot) and ε. distance method handles one point at a time. In PySpark flatMap method is used to map every point into an array of tuples (out)."
},
{
"code": null,
"e": 5413,
"s": 5260,
"text": "All data points within a partition are merged before generating the visualization. They also need to be merged for further processing DBSCAN on PySpark."
},
{
"code": null,
"e": 5636,
"s": 5413,
"text": "reduceByKey method is used to merge partition data in one. The use of word partition may confuse with PySpark partitions but those are two separate things. Though partitionBy method could be used to reconcile that as well."
},
{
"code": null,
"e": 5817,
"s": 5636,
"text": "After reduceByKey, we will get each row of the rdd as a ring depicted in figure 4. As you can see there is an overlap so points would be in two rows of rdd and that is intentional."
},
{
"code": null,
"e": 6233,
"s": 5817,
"text": "The above code computes distance within each partition. The output of the method is a list of tuples. Each tuple has the id of point and set of its neighbors within ε distance. As we know that point would occur in two partitions so we need to combine the sets for a given point so we get all of its neighbors within ε distance in whole data. reduceByKey is used to combine the sets by doing union operation on them."
},
{
"code": null,
"e": 6270,
"s": 6233,
"text": "reduceByKey(lambda x, y: x.union(y))"
},
{
"code": null,
"e": 6311,
"s": 6270,
"text": "Combined code till now looks as follows:"
},
{
"code": null,
"e": 6413,
"s": 6311,
"text": "Once we have neighbors within ε distance for a point we can identify if it is a core or border point."
},
{
"code": null,
"e": 6470,
"s": 6413,
"text": "Core Point: There are at least min_pts within ε distance"
},
{
"code": null,
"e": 6565,
"s": 6470,
"text": "Border Point: There are less than min_pts within ε distance but one of them is the core point."
},
{
"code": null,
"e": 6950,
"s": 6565,
"text": "To identify core and border points, first, we assign them to a cluster. For each point which is a core point, we create a cluster label the same to its id (assuming the ids are unique). We create a tuple for each core point and its neighbors of the form (id, [(cluster_label, is_core_point)]). All the neighbors in this scenario would be labeled as a base point. Let's take an example"
},
{
"code": null,
"e": 7067,
"s": 6950,
"text": "min_pts = 3Input: (3, set(4,6,2))Output: [(3, [(3, True)]), (4, [(3, False)]), (6, [(3, False)]), (2, [(3, False)])]"
},
{
"code": null,
"e": 7162,
"s": 7067,
"text": "Input is a tuple where 3 is the id of point and (4, 6, 2) are its neighbors within ε distance."
},
{
"code": null,
"e": 7363,
"s": 7162,
"text": "As one can see all points are assigned cluster label 3. While 3 is assigned True for is_core_point as a core point and all other points are considered base points and assigned False for is_core_point."
},
{
"code": null,
"e": 7647,
"s": 7363,
"text": "We may have similar input tuples for 4, 6, and 2 where they may or may not be assigned as core points. The idea is to eventually combine all cluster labels for a point and if at least one of the assignment for is_core_point is True then its a core point otherwise its a border point."
},
{
"code": null,
"e": 7910,
"s": 7647,
"text": "We combine all (cluster_label, is_core_point) tuples for a point using reduceByKey method and then investigate if its a core point or not while combining all clusters labels for that point. If its a border point then we would only leave one cluster label for it."
},
{
"code": null,
"e": 8046,
"s": 7910,
"text": "The above method is used to combine all cluster label for a point. Again if it is a border point then we return only 1st cluster label."
},
{
"code": null,
"e": 8097,
"s": 8046,
"text": "Code in PySpark till now looks like the following:"
},
{
"code": null,
"e": 8440,
"s": 8097,
"text": "Now for each point, we have cluster labels. If a point has more than one cluster label then it means those clusters are connected. Those connected clusters are the final clusters we need to solve DBSCAN. We solve this by creating a graph with vertices as cluster labels and edges between cluster labels if they are assigned to the same point."
},
{
"code": null,
"e": 8801,
"s": 8440,
"text": "In the above code, combine_cluster_rdd is a collection of rows where each row is a tuple (point, cluster_labels). Each cluster label is vertices and combinations of cluster labels for a point are the edges. Connected components of this graph give a mapping between each cluster label and a connected cluster. which we can apply to points to get final clusters."
},
{
"code": null,
"e": 8959,
"s": 8801,
"text": "Above is how the final method looks like which returns a Spark Dataframe with point id, cluster component label, and a boolean indicator if its a core point."
},
{
"code": null,
"e": 9045,
"s": 8959,
"text": "Now I compare the results in terms of accuracy with sklearn implementation of DBSCAN."
},
{
"code": null,
"e": 9215,
"s": 9045,
"text": "The make_blobs method creates blobs around three input centers. Running DBSCAN using sklearn and my implementation with ε=0.3 and min_pts=10 gives the following results."
},
{
"code": null,
"e": 9525,
"s": 9215,
"text": "Core points are bigger circles while border points are smaller ones. Noise points are colored black which is the same in both implementations. One thing that jumps out is the border points are assigned different clusters that speak to the non-deterministic nature of DBSCAN. My other post also talks about it."
},
{
"code": null,
"e": 9536,
"s": 9525,
"text": "medium.com"
},
{
"code": null,
"e": 9655,
"s": 9536,
"text": "For ε=0.2 we get the border points assigned to the same clusters. Following is some code and results on data in rings."
},
{
"code": null,
"e": 9980,
"s": 9655,
"text": "For n=750, the number of distance operations required by a simple implementation of DBSCAN would be n(n-1)/2 which is 280875. As we create the partition based on ε, the smaller the ε less the number of distance operations would be needed. In this case, there were a total of 149716(ε=.2) and 217624(ε=0.3) operations needed."
},
{
"code": null,
"e": 10080,
"s": 9980,
"text": "A pyspark implementation which would be efficient based on the value of ε with the following steps:"
},
{
"code": null,
"e": 10469,
"s": 10080,
"text": "Partitioning Data: Partition with overlapping rings of 2ε width moved by ε.Merging Partition Data: So we get all partition data in a single record.Distance Calculations: Calculate distance within the same partitionPoint Labeling: Based on the number of neighbors, label core, and border points.Connected Clusters: Use Graphframe to connect clusters labels to evaluate final DBSCAN labels."
},
{
"code": null,
"e": 10545,
"s": 10469,
"text": "Partitioning Data: Partition with overlapping rings of 2ε width moved by ε."
},
{
"code": null,
"e": 10618,
"s": 10545,
"text": "Merging Partition Data: So we get all partition data in a single record."
},
{
"code": null,
"e": 10686,
"s": 10618,
"text": "Distance Calculations: Calculate distance within the same partition"
},
{
"code": null,
"e": 10767,
"s": 10686,
"text": "Point Labeling: Based on the number of neighbors, label core, and border points."
},
{
"code": null,
"e": 10862,
"s": 10767,
"text": "Connected Clusters: Use Graphframe to connect clusters labels to evaluate final DBSCAN labels."
},
{
"code": null,
"e": 10981,
"s": 10862,
"text": "A comparison with the existing implementation shows the accuracy of the algorithm and the implementation of this post."
},
{
"code": null,
"e": 11142,
"s": 10981,
"text": "On the local machine with both driver and worker nodes, implementation is slower than sklearn. There could be a couple of reasons which need to be investigated:"
},
{
"code": null,
"e": 11382,
"s": 11142,
"text": "For a small amount of data, sklearn may be much faster but is it the case for big-data?Graphframe takes quite some time to execute and wondering if connected components analysis can be performed on the driver with some other graph library?"
},
{
"code": null,
"e": 11470,
"s": 11382,
"text": "For a small amount of data, sklearn may be much faster but is it the case for big-data?"
},
{
"code": null,
"e": 11623,
"s": 11470,
"text": "Graphframe takes quite some time to execute and wondering if connected components analysis can be performed on the driver with some other graph library?"
}
] |
Getting started with Apache Cassandra and Python | by Adnan Siddiqi | Towards Data Science
|
In this post, I am going to talk about Apache Cassandra, its purpose, usage, configuration, and setting up a cluster and in the end, how can you access it in your Python applications. At the end of this post, you should have a basic understanding of Cassandra and how you can use in your Python apps.
According to Wikipedia:
Apache Cassandra is a free and open-source, distributed, wide column store, NoSQL database management system designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. Cassandra offers robust support for clusters spanning multiple datacenters,[1] with asynchronous masterless replication allowing low latency operations for all clients.
Cassandra developed by two Facebook engineers to deal with search mechanism of Inbox. Later Facebook released it as an opensource project on Google code and after a while, it was handed over to Apache foundation. Cassandra is being used by many big names like Netflix, Apple, Weather channel, eBay and many more. It’s decentralized nature( a Masterless system), fault tolerance, scalability, and durability makes it superior to its competitors. Let’s discuss a bit of its architecture, if you want, you may skip to the installation and setup part. I’d suggest you skim thru the architecture section as it will give you an idea about why you would want to use it.
Cassandra Architecture consists of the following components:
It is the basic component of the data, a machine where the data is stored
A collection of related nodes. It can be a physical datacenter or virtual
A cluster contains one or more datacenters, it could span across locations.
Every write operation is first stored in the commit log. It is used for crash recovery.
After data is written to the commit log it then is stored in Mem-Table(Memory Table) which remains there till it reaches to the threshold.
Sorted-String Table or SSTable is a disk file which stores data from MemTable once it reaches to the threshold. SSTables are stored on disk sequentially and maintained for each database table.
As soon as the write request is received, it is first dumped into commit log to make sure that data is saved.
Data is also written in MemTable, an in-memory system that holds the data till it’s get fulled.
Once MemTable reaches its threshold, its data is then flushed to SS Table.
The node that accepts the write requests called coordinator for that particular operation. It acts as a proxy between the client that sent the request and other nodes. The coordinator then determines which node should be sent this data in a ring based on the cluster configuration.
Consistency level determines how many nodes will respond back with the success acknowledgment.
There are three types of read requests that a coordinator can send to a replica:
Direct Request:- The coordinator node sends the read request to one of the replicas. After that send a digest request to the other replicas to make sure whether the returned data is an updated data.Digest Request: The coordinator contacts the replicas specified by the consistency level. The contacted nodes respond with a digest request of the required data. The rows from each replica are compared in memory for consistency. If they are not consistent, the replica having the most recent data (timestamp) is used by the coordinator to forward the result back to the client.Read Repair Request: In case of data is not consistent across the node, a background read repair request is initiated that makes sure that the most recent data is available across the nodes.
Direct Request:- The coordinator node sends the read request to one of the replicas. After that send a digest request to the other replicas to make sure whether the returned data is an updated data.
Digest Request: The coordinator contacts the replicas specified by the consistency level. The contacted nodes respond with a digest request of the required data. The rows from each replica are compared in memory for consistency. If they are not consistent, the replica having the most recent data (timestamp) is used by the coordinator to forward the result back to the client.
Read Repair Request: In case of data is not consistent across the node, a background read repair request is initiated that makes sure that the most recent data is available across the nodes.
Data replication is a must feature to make sure that no data is lost due to hardware or network failure. A replication strategy determines which nodes to place replicas on. Cassandra provides two different replication strategies.
Simple Strategy
SimpleStrategy is used when you have only one data center. It places the first replica on the node selected by the partitioner. A partitioner determines how data is distributed across the nodes in the cluster (including replicas). After that, remaining replicas are placed in a clockwise direction in the Node ring.
Network Topology Strategy
It is used when you have deployments across multiple data centers. This strategy places replicas in the same datacenter by traversing the ring clockwise until reaching the first node in another rack. This is due to the reason that sometimes failure or problem can occur in the rack. Then replicas on other nodes can provide data. This strategy is highly recommended for scalability purpose and future expansion.
Okay, enough theory is discussed, let’s do something practical.
You can download the package from Official website and run in single mode for the development purpose but it will not help you to know the true strength of Cassandra as it’d be behaving like any other database. Therefore, I am going with the docker version of it where I will set up a cluster of two nodes.
Note: Before you even start, make sure you set up the Docker Memory to at least 4GB otherwise the container can exit with the error code 137. It took me an hour to figure it out as this error due to low memory resources.
Create a folder on your machine, like I created as /Development/PetProjects/CassandraTut/data. Inside that folder, I created two sub-folders for storing data of both nodes. Once done, it will look like below:
➜ data tree -a.├── node1└── node22 directories, 1 file
Stay in the same folder and run the command docker pull cassandra to download the official image. If you are new to docker then you should check my posts in the Docker Series. Once downloaded, docker images the command will show it on your terminal. Make sure that docker is installed and running. Also, you have to give writing permissions to the folder where the data will be stored by Cassandra.
We will set up two nodes: Node1 as the main node and the Node2 as a seed node. Seeds are used during startup to discover the cluster. Let’s run the first node.
docker run --name cas1 -p 9042:9042 -v /Development/PetProjects/CassandraTut/data/node1:/var/lib/cassandra/data -e CASSANDRA_CLUSTER_NAME=MyCluster -e CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch -e CASSANDRA_DC=datacenter1 -d cassandra
Many environment variables were self-explanatory, I will discuss CASSANDRA_ENDPOINT_SNITCH
Snitches determine how Cassandra distribute replicas. This snitch is recommended for production. GossipingPropertyFileSnitch automatically updates all nodes using gossip protocol when adding new nodes and is recommended for production. Run the following command to learn about the status of the node.
➜ data docker exec -it cas1 nodetool statusDatacenter: datacenter1=======================Status=Up/Down|/ State=Normal/Leaving/Joining/Moving-- Address Load Tokens Owns (effective) Host ID RackUN 172.17.0.2 103.67 KiB 256 100.0% bcb57440-7303-4849-9afc-af0237587870 rack1
UN tells the status that it is Up and Normal. When other nodes join, you may see the status UJ which means Up and Joining. I am using -d switch of docker run to run it in the background. Also, notice the content of the node1 folder. It creates the default system databases, something akin to MySQL.
➜ node1 lssystem system_auth system_distributed system_schema system_traces➜ node1
Now let’s run the 2nd node:
docker run --name cas2 -v /Development/PetProjects/CassandraTut/data/node2:/var/lib/cassandra/data -e CASSANDRA_SEEDS="$(docker inspect --format='{{ .NetworkSettings.IPAddress }}' cas1)" -e CASSANDRA_CLUSTER_NAME=MyCluster -e CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch -e CASSANDRA_DC=datacenter1 -d cassandra:latest
After setting the relevant container name and data center, you will also set CASSANDRA_SEEDS here to the IP address of the node cas1 which can fetch by using the docker inspect command. After a while when you run the nodetool status command in cas1 you should see something like below:
As you can see, our second node is joining the cluster and we learned it from the status UJ.
If you look go the mounted volume, node2 folder you will see the system folders there as well.
Running commands from the terminal is irritating therefore I created a docker-compose.yaml file to run the cluster without any hassle.
In order to make sure that cas1 is up and running, I am making cas2 dependant of cas1 and also put a sleep of 60 seconds.
I was getting RPC error INFO [main] 2019-05-14 01:51:07,336 CassandraDaemon.java:556 - Not starting RPC server as requested. Use JMX (StorageService->startRPCServer()) or nodetool (enablethrift) to start it so I am calling CASSANDRA_START_RPC environment parameter too and set it to True.
Let’s run the docker-compose up -d to run in detached mode.
As you can see that the first node is not up, the second node initiation process has not started either.
After a while, both nodes are up with their unique IPs.
All Cassandra config files reside in /etc/cassandra/ folder inside containers.
Let’s run the CQL shell.
➜ CassandraTut docker exec -it cas2 cqlsh Connected to MyCluster at 127.0.0.1:9042.[cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]Use HELP for help.cqlsh>
it is similar to MySQL shell. CQL, Cassandra Query Language is similar to SQL in syntax but its usage is not as similar to RDBMS systems. We will look further on it soon. Hang on!
If you notice I had exposed the default Cassandra port that is 9042 in both docker run and docker composecommand. Using terminal like is not fascinating, how about using a GUI client? I am using TablePlus, a SQL/NoSQL client.
Once connected, you will see default system databases.
Let’s create a test KEYSPACE, the Cassandra version of Database, and a Table on node cas1. Do not worry, I will discuss it in details later. Right now the purpose is to tell you how data is replicated.
Setting Replication factor to 2, which means there will be 2 copies of data, one on each node.
Let’s connect to the second node.
Notice the port 9043. The 9042 was already assigned to cas1.
Lo and Behold! MyKeySpace exists here as well, it was well replicated from Cas1 to Cas2
Either you make changes on Cas1 or Cas2, it will eventually be propagated. This is not similar to a typical Master/Slave concept, it is rather called Masterless as the entire system is decentralized and P2P connection is established in the ring(Does it reminds you Blockchain?)
Next up is Data Modeling concepts and creating entities in CQL.
Cassandra is a beast and it is not possible to cover every aspect of data modeling here. Therefore I will be covering the basics to give you a little bit idea that how is it different than a typical relational database system. Despite CQL looks very much similar to SQL or MySQL based SQL, it is not SQL at all. Prepare yourself to be ready to unlearn RDBMS things.
Below is a little comparison between Cassandra and RDBMS world.
Keyspace:- It is the container collection of column families. You can think of it as a Database in the RDBMS world.
Column Family:- A column family is a container for an ordered collection of rows. Each row, in turn, is an ordered collection of columns. Think of it as a Table in the RDBMS world.
Row:- A row is the collection of columns ordered columns.
Column:- A column is the collection of key/value pairs.
RowKey:- A primary key is called a row key.
Compound Primary Key:- A primary key consist of multiple columns. One part of that key then called Partition Key and rest a Cluster Key.
Partition Key:- Data in Cassandra is spread across the nodes. The purpose of the partition key is to identify the node that has stored that particular row which is being asked for. A function, called partition, is used to compute the hash value of the partition key at the time of row is being written. For instance, node 1 has key values range from 1–10, node 2 contains 11–20 and node 3 consists of range 21–30. When a SELECT command with WHERE clause is executed, the hash value of partition key is used to find the required node, once the node is found, it then fetches the data and returns to the client. For instance, the query is SELECT * FROM users where id = 5, and suppose the hash value of partition key(which is 5 in this case) is 15, it’d be the node 2which will have that row available. Below is the pictorial representation of it.
Let’s come up with an example. You are working on a system that keeps information about the site users and their cities. We will create a Keyspace, called, CityInfo. You may use CQLSH or TablePlus GUI, up to you.
create keyspace CityInfo with replication = {'class' : 'SimpleStrategy', 'replication_factor':2}
Since I have 2 nodes so I set the replication_factor to 2.
In RDBMS we have a facility like JOINs and writing is not cheap hence we avoid duplicates by using foreign keys in relevant tables. This is not the case in Cassandra. Cassandra is a distributed system, writing is cheap hence you are most welcome to de-normalize data where needed. This helps to retrieve data which you usually fetch via JOINs. On the other hand, data reads could be expensive because data is spanned across nodes and retrieve via partition keys. While designing models you should have the following goals in mind:
Evenly spread of data in a cluster:- The primary key is the partition key if it is consist of a single column and a partition key and cluster key in case of a composite primary key. To spread data evenly you must select a column for PK which has uniqueness thus could be spread across nodes. Things like ID, Username, and email have uniqueness and will fully utilize the cluster of nodes. But if you use keys like first/last name, gender, etc then there will be very fewer choices of partition keys and despite having 100s of nodes only a few will always be used thus making a partition fat and less performant.Minimize the number of Reads:- As I mentioned, reads are expensive. If you model in a way that a single query is fetching from multiple partitions it will make the system slow.
Evenly spread of data in a cluster:- The primary key is the partition key if it is consist of a single column and a partition key and cluster key in case of a composite primary key. To spread data evenly you must select a column for PK which has uniqueness thus could be spread across nodes. Things like ID, Username, and email have uniqueness and will fully utilize the cluster of nodes. But if you use keys like first/last name, gender, etc then there will be very fewer choices of partition keys and despite having 100s of nodes only a few will always be used thus making a partition fat and less performant.
Minimize the number of Reads:- As I mentioned, reads are expensive. If you model in a way that a single query is fetching from multiple partitions it will make the system slow.
Therefore, unlike RDBMS where you design schema first and get the liberty of creating queries based on your requirements, this is not the case for Cassandra. You must know the queries in advance which are required in the system and then design model accordingly.
We have a system where users of different cities visit a website. The management has asked to come up with the following information:
List of all usersList of all cities.List of users by cities
List of all users
List of all cities.
List of users by cities
Let’s create the cities table first.
CREATE TABLE cities ( id int, name text, country text, PRIMARY KEY(id));
then users
CREATE TABLE users ( username text, name text, age int, PRIMARY KEY(username));
Inserting a few cities.
INSERT INTO cities(id,name,country) VALUES (1,'Karachi','Pakistan');INSERT INTO cities(id,name,country) VALUES (2,'Lahore','Pakistan');INSERT INTO cities(id,name,country) VALUES (3,'Dubai','UAE');INSERT INTO cities(id,name,country) VALUES (4,'Berlin','Germany');
And inserting a few users
INSERT INTO users(username,name,age) VALUES ('aali24','Ali Amin',34);INSERT INTO users(username,name,age) VALUES ('jack01','Jack David',23);INSERT INTO users(username,name,age) VALUES ('ninopk','Nina Rehman',34);
These insertions fulfill our first two requirements but what about the 3rd one? In RDBMS world we would have used city_id as an FK in users table and a JOIN would easily return the data but this is Cassandra, we can’t do this, what is left for us create another table that would satisfy our needs.
CREATE TABLE users_by_cities ( username text, name text, city text, age int, PRIMARY KEY(city,age));
This primary key has two components: First becomes partition key and the second becomes cluster key. It will look up w.r.t city and all the records are clustered/grouped by age.
Insert a few records now:
INSERT INTO users_by_cities(username,name,city,age) VALUES ('aali24','Ali Amin','Karachi',34);INSERT INTO users_by_cities(username,name,city, age) VALUES ('jack01','Jack David','Berlin',23);INSERT INTO users_by_cities(username,name,city, age) VALUES ('ninopk','Nina Rehman','Lahore',34);
Normally these insertions in two tables will be done in a go from an “Add User” interface, from CQL side you can do something like this to add a user’s information.
BEGIN BATCHINSERT into users(username,name,age) VALUES('raziz12','Rashid Aziz',34);INSERT INTO users_by_cities(username,name,city, age) VALUES ('raziz12','Rashid Aziz','Karachi',30);APPLY BATCH;
Before I move further, I would like to remind you about the hashed token I discussed earlier. First, run the EXPAND ON command on CQL shell. Once you do that you see the results like below:
Looks good, No? OK, now we are going to see the token value of our primary key. It returns the below result:
cqlsh:cityinfo> select token(username) from users;@ Row 1------------------------+---------------------- system.token(username) | -7905752472182359000@ Row 2------------------------+---------------------- system.token(username) | 2621513098312339776@ Row 3------------------------+---------------------- system.token(username) | 6013687671608201304
Make sense, tokens are unique because the usernames are unique. These tokens will spread across nodes. When the user runs the command SELECT * FROM users where username = 'raziz12', it will pick the node based on this token value. I already showed this in pictorial form a few lines above.
The query below shows the token values from users_by_cities table.
cqlsh:cityinfo> select token(username),username,city from users_by_cities;@ Row 1------------------------+---------------------- system.token(username) | 2621513098312339776 username | jack01 city | Berlin@ Row 2------------------------+---------------------- system.token(username) | 6013687671608201304 username | ninopk city | Lahore@ Row 3------------------------+---------------------- system.token(username) | -882788003101376442 username | raziz12 city | Karachi@ Row 4------------------------+---------------------- system.token(username) | -7905752472182359000 username | aali24 city | Karachi
Select * from users_by_cities where city = 'Karachi'; returns the following:
cqlsh:cityinfo> select * from users_by_cities where city = 'Karachi';@ Row 1----------+------------- city | Karachi username | aali24 name | Ali Amin@ Row 2----------+------------- city | Karachi username | raziz12 name | Rashid Aziz
The model also serves the query select * from users_by_cities where city = 'Karachi' and age = 34
But what if you want to pick a record based on name the field?
SELECT * from users_by_cities where name = 'Ali Amin';
You’d get the following error.
Error from server: code=2200 [Invalid query] message="Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability
It is because no partition key was mentioned, Cassandra is asking to hunt the required name in ALL nodes, yes ALL nodes and imagine if nodes are 10 or 100, it’d take time to return the data. Hence it is not suggested. If you want to find something w.r.t field, either create another table(highly recommended) or create a secondary index(not recommended)
The data is partitioned by city, on lookup, one node responds with the token of the city, once the node is discovered, it fetches all the record in that partition for the users belong to the city of Karachi. Something similar could be visualized about the clustering of data related to Karachi. The data is clustered against agecolumn.
So for a partition holding records of all Karachiites, you will be seeing clusters of records w.r.t age.
Your head must be spinning and would be missing your beloved MySQL but I am telling you that this is something worth learning, I am learning too and I just scratched the surface of this beast.
You’d be wondering that title of the post mentions Python but so far no Python code written at all, I hear you. It was necessary to prepare a ground because you will just be executing queries in your Python app. The main work is somewhere else, right above.
OK before I move to development, I discussed that Cassandra initially wrote data in Commitlog.
The path of Cassandra CommitLog can be obtained from /etc/cassandra/cassandra.yaml which is /var/lib/cassandra/commitlog here it creates log file w.r.t timestamp. It is not as readable but when I searched a few inserted record then found a few traces. Check the screen below:
You can find traces of jack01, aali, and ninopk here. You also find text related to repairing mechanism.
SSTables are found in /var/lib/cassandra/data/<keyspacename> .In my case it is cityinfo
For every table/Column Family it generates manifest.json files, a few *.db and a few other types of file, below are the files of the table users_by_cities table.
./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/manifest.json./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-CompressionInfo.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Data.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Digest.crc32./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Filter.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Index.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Statistics.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Summary.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-TOC.txt./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/schema.cql
You can learn more about it here.
Alright, so, first of all, we’d need to install the driver. I am out the docker shell as I’d be accessing it from my host machine. Run the command pip install cassandra-driver
It takes a while during building the driver:
Requirement already satisfied: six>=1.9 in /anaconda3/anaconda/lib/python3.6/site-packages (from cassandra-driver) (1.11.0)Building wheels for collected packages: cassandra-driver Building wheel for cassandra-driver (setup.py) ... done Stored in directory: /Users/AdnanAhmad/Library/Caches/pip/wheels/df/f4/40/941c98128d60f08d2f628b04a7a1b10006655aac3803e0e227Successfully built cassandra-driverInstalling collected packages: cassandra-driverSuccessfully installed cassandra-driver-3.17.1
Below is the code connecting to the Cassandra Cluster within Docker from the Python script running out of the Docker.
from cassandra.cluster import Clusterif __name__ == "__main__": cluster = Cluster(['0.0.0.0'],port=9042) session = cluster.connect('cityinfo',wait_for_all_pools=True) session.execute('USE cityinfo') rows = session.execute('SELECT * FROM users') for row in rows: print(row.age,row.name,row.username)
The following output returned:
➜ CassandraTut python cassandra_connect.py34 Ali Amin aali2434 Rashid Aziz raziz1223 Jack David jack0134 Nina Rehman ninopk➜ CassandraTut
You can learn more about it here
So in this post, you learned a bit about Cassandra and how to use CQL and connecting it in your Python scripts. Leave your comment below for comments, correction or feedback. As always, the code is on Github.
This post was originally published here.
|
[
{
"code": null,
"e": 473,
"s": 172,
"text": "In this post, I am going to talk about Apache Cassandra, its purpose, usage, configuration, and setting up a cluster and in the end, how can you access it in your Python applications. At the end of this post, you should have a basic understanding of Cassandra and how you can use in your Python apps."
},
{
"code": null,
"e": 497,
"s": 473,
"text": "According to Wikipedia:"
},
{
"code": null,
"e": 908,
"s": 497,
"text": "Apache Cassandra is a free and open-source, distributed, wide column store, NoSQL database management system designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure. Cassandra offers robust support for clusters spanning multiple datacenters,[1] with asynchronous masterless replication allowing low latency operations for all clients."
},
{
"code": null,
"e": 1571,
"s": 908,
"text": "Cassandra developed by two Facebook engineers to deal with search mechanism of Inbox. Later Facebook released it as an opensource project on Google code and after a while, it was handed over to Apache foundation. Cassandra is being used by many big names like Netflix, Apple, Weather channel, eBay and many more. It’s decentralized nature( a Masterless system), fault tolerance, scalability, and durability makes it superior to its competitors. Let’s discuss a bit of its architecture, if you want, you may skip to the installation and setup part. I’d suggest you skim thru the architecture section as it will give you an idea about why you would want to use it."
},
{
"code": null,
"e": 1632,
"s": 1571,
"text": "Cassandra Architecture consists of the following components:"
},
{
"code": null,
"e": 1706,
"s": 1632,
"text": "It is the basic component of the data, a machine where the data is stored"
},
{
"code": null,
"e": 1780,
"s": 1706,
"text": "A collection of related nodes. It can be a physical datacenter or virtual"
},
{
"code": null,
"e": 1856,
"s": 1780,
"text": "A cluster contains one or more datacenters, it could span across locations."
},
{
"code": null,
"e": 1944,
"s": 1856,
"text": "Every write operation is first stored in the commit log. It is used for crash recovery."
},
{
"code": null,
"e": 2083,
"s": 1944,
"text": "After data is written to the commit log it then is stored in Mem-Table(Memory Table) which remains there till it reaches to the threshold."
},
{
"code": null,
"e": 2276,
"s": 2083,
"text": "Sorted-String Table or SSTable is a disk file which stores data from MemTable once it reaches to the threshold. SSTables are stored on disk sequentially and maintained for each database table."
},
{
"code": null,
"e": 2386,
"s": 2276,
"text": "As soon as the write request is received, it is first dumped into commit log to make sure that data is saved."
},
{
"code": null,
"e": 2482,
"s": 2386,
"text": "Data is also written in MemTable, an in-memory system that holds the data till it’s get fulled."
},
{
"code": null,
"e": 2557,
"s": 2482,
"text": "Once MemTable reaches its threshold, its data is then flushed to SS Table."
},
{
"code": null,
"e": 2839,
"s": 2557,
"text": "The node that accepts the write requests called coordinator for that particular operation. It acts as a proxy between the client that sent the request and other nodes. The coordinator then determines which node should be sent this data in a ring based on the cluster configuration."
},
{
"code": null,
"e": 2934,
"s": 2839,
"text": "Consistency level determines how many nodes will respond back with the success acknowledgment."
},
{
"code": null,
"e": 3015,
"s": 2934,
"text": "There are three types of read requests that a coordinator can send to a replica:"
},
{
"code": null,
"e": 3781,
"s": 3015,
"text": "Direct Request:- The coordinator node sends the read request to one of the replicas. After that send a digest request to the other replicas to make sure whether the returned data is an updated data.Digest Request: The coordinator contacts the replicas specified by the consistency level. The contacted nodes respond with a digest request of the required data. The rows from each replica are compared in memory for consistency. If they are not consistent, the replica having the most recent data (timestamp) is used by the coordinator to forward the result back to the client.Read Repair Request: In case of data is not consistent across the node, a background read repair request is initiated that makes sure that the most recent data is available across the nodes."
},
{
"code": null,
"e": 3980,
"s": 3781,
"text": "Direct Request:- The coordinator node sends the read request to one of the replicas. After that send a digest request to the other replicas to make sure whether the returned data is an updated data."
},
{
"code": null,
"e": 4358,
"s": 3980,
"text": "Digest Request: The coordinator contacts the replicas specified by the consistency level. The contacted nodes respond with a digest request of the required data. The rows from each replica are compared in memory for consistency. If they are not consistent, the replica having the most recent data (timestamp) is used by the coordinator to forward the result back to the client."
},
{
"code": null,
"e": 4549,
"s": 4358,
"text": "Read Repair Request: In case of data is not consistent across the node, a background read repair request is initiated that makes sure that the most recent data is available across the nodes."
},
{
"code": null,
"e": 4779,
"s": 4549,
"text": "Data replication is a must feature to make sure that no data is lost due to hardware or network failure. A replication strategy determines which nodes to place replicas on. Cassandra provides two different replication strategies."
},
{
"code": null,
"e": 4795,
"s": 4779,
"text": "Simple Strategy"
},
{
"code": null,
"e": 5111,
"s": 4795,
"text": "SimpleStrategy is used when you have only one data center. It places the first replica on the node selected by the partitioner. A partitioner determines how data is distributed across the nodes in the cluster (including replicas). After that, remaining replicas are placed in a clockwise direction in the Node ring."
},
{
"code": null,
"e": 5137,
"s": 5111,
"text": "Network Topology Strategy"
},
{
"code": null,
"e": 5549,
"s": 5137,
"text": "It is used when you have deployments across multiple data centers. This strategy places replicas in the same datacenter by traversing the ring clockwise until reaching the first node in another rack. This is due to the reason that sometimes failure or problem can occur in the rack. Then replicas on other nodes can provide data. This strategy is highly recommended for scalability purpose and future expansion."
},
{
"code": null,
"e": 5613,
"s": 5549,
"text": "Okay, enough theory is discussed, let’s do something practical."
},
{
"code": null,
"e": 5920,
"s": 5613,
"text": "You can download the package from Official website and run in single mode for the development purpose but it will not help you to know the true strength of Cassandra as it’d be behaving like any other database. Therefore, I am going with the docker version of it where I will set up a cluster of two nodes."
},
{
"code": null,
"e": 6141,
"s": 5920,
"text": "Note: Before you even start, make sure you set up the Docker Memory to at least 4GB otherwise the container can exit with the error code 137. It took me an hour to figure it out as this error due to low memory resources."
},
{
"code": null,
"e": 6350,
"s": 6141,
"text": "Create a folder on your machine, like I created as /Development/PetProjects/CassandraTut/data. Inside that folder, I created two sub-folders for storing data of both nodes. Once done, it will look like below:"
},
{
"code": null,
"e": 6406,
"s": 6350,
"text": "➜ data tree -a.├── node1└── node22 directories, 1 file"
},
{
"code": null,
"e": 6805,
"s": 6406,
"text": "Stay in the same folder and run the command docker pull cassandra to download the official image. If you are new to docker then you should check my posts in the Docker Series. Once downloaded, docker images the command will show it on your terminal. Make sure that docker is installed and running. Also, you have to give writing permissions to the folder where the data will be stored by Cassandra."
},
{
"code": null,
"e": 6965,
"s": 6805,
"text": "We will set up two nodes: Node1 as the main node and the Node2 as a seed node. Seeds are used during startup to discover the cluster. Let’s run the first node."
},
{
"code": null,
"e": 7211,
"s": 6965,
"text": "docker run --name cas1 -p 9042:9042 -v /Development/PetProjects/CassandraTut/data/node1:/var/lib/cassandra/data -e CASSANDRA_CLUSTER_NAME=MyCluster -e CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch -e CASSANDRA_DC=datacenter1 -d cassandra"
},
{
"code": null,
"e": 7302,
"s": 7211,
"text": "Many environment variables were self-explanatory, I will discuss CASSANDRA_ENDPOINT_SNITCH"
},
{
"code": null,
"e": 7603,
"s": 7302,
"text": "Snitches determine how Cassandra distribute replicas. This snitch is recommended for production. GossipingPropertyFileSnitch automatically updates all nodes using gossip protocol when adding new nodes and is recommended for production. Run the following command to learn about the status of the node."
},
{
"code": null,
"e": 7949,
"s": 7603,
"text": "➜ data docker exec -it cas1 nodetool statusDatacenter: datacenter1=======================Status=Up/Down|/ State=Normal/Leaving/Joining/Moving-- Address Load Tokens Owns (effective) Host ID RackUN 172.17.0.2 103.67 KiB 256 100.0% bcb57440-7303-4849-9afc-af0237587870 rack1"
},
{
"code": null,
"e": 8248,
"s": 7949,
"text": "UN tells the status that it is Up and Normal. When other nodes join, you may see the status UJ which means Up and Joining. I am using -d switch of docker run to run it in the background. Also, notice the content of the node1 folder. It creates the default system databases, something akin to MySQL."
},
{
"code": null,
"e": 8357,
"s": 8248,
"text": "➜ node1 lssystem system_auth system_distributed system_schema system_traces➜ node1"
},
{
"code": null,
"e": 8385,
"s": 8357,
"text": "Now let’s run the 2nd node:"
},
{
"code": null,
"e": 8713,
"s": 8385,
"text": "docker run --name cas2 -v /Development/PetProjects/CassandraTut/data/node2:/var/lib/cassandra/data -e CASSANDRA_SEEDS=\"$(docker inspect --format='{{ .NetworkSettings.IPAddress }}' cas1)\" -e CASSANDRA_CLUSTER_NAME=MyCluster -e CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch -e CASSANDRA_DC=datacenter1 -d cassandra:latest"
},
{
"code": null,
"e": 8999,
"s": 8713,
"text": "After setting the relevant container name and data center, you will also set CASSANDRA_SEEDS here to the IP address of the node cas1 which can fetch by using the docker inspect command. After a while when you run the nodetool status command in cas1 you should see something like below:"
},
{
"code": null,
"e": 9092,
"s": 8999,
"text": "As you can see, our second node is joining the cluster and we learned it from the status UJ."
},
{
"code": null,
"e": 9187,
"s": 9092,
"text": "If you look go the mounted volume, node2 folder you will see the system folders there as well."
},
{
"code": null,
"e": 9322,
"s": 9187,
"text": "Running commands from the terminal is irritating therefore I created a docker-compose.yaml file to run the cluster without any hassle."
},
{
"code": null,
"e": 9444,
"s": 9322,
"text": "In order to make sure that cas1 is up and running, I am making cas2 dependant of cas1 and also put a sleep of 60 seconds."
},
{
"code": null,
"e": 9733,
"s": 9444,
"text": "I was getting RPC error INFO [main] 2019-05-14 01:51:07,336 CassandraDaemon.java:556 - Not starting RPC server as requested. Use JMX (StorageService->startRPCServer()) or nodetool (enablethrift) to start it so I am calling CASSANDRA_START_RPC environment parameter too and set it to True."
},
{
"code": null,
"e": 9793,
"s": 9733,
"text": "Let’s run the docker-compose up -d to run in detached mode."
},
{
"code": null,
"e": 9898,
"s": 9793,
"text": "As you can see that the first node is not up, the second node initiation process has not started either."
},
{
"code": null,
"e": 9954,
"s": 9898,
"text": "After a while, both nodes are up with their unique IPs."
},
{
"code": null,
"e": 10033,
"s": 9954,
"text": "All Cassandra config files reside in /etc/cassandra/ folder inside containers."
},
{
"code": null,
"e": 10058,
"s": 10033,
"text": "Let’s run the CQL shell."
},
{
"code": null,
"e": 10247,
"s": 10058,
"text": "➜ CassandraTut docker exec -it cas2 cqlsh Connected to MyCluster at 127.0.0.1:9042.[cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]Use HELP for help.cqlsh>"
},
{
"code": null,
"e": 10427,
"s": 10247,
"text": "it is similar to MySQL shell. CQL, Cassandra Query Language is similar to SQL in syntax but its usage is not as similar to RDBMS systems. We will look further on it soon. Hang on!"
},
{
"code": null,
"e": 10653,
"s": 10427,
"text": "If you notice I had exposed the default Cassandra port that is 9042 in both docker run and docker composecommand. Using terminal like is not fascinating, how about using a GUI client? I am using TablePlus, a SQL/NoSQL client."
},
{
"code": null,
"e": 10708,
"s": 10653,
"text": "Once connected, you will see default system databases."
},
{
"code": null,
"e": 10910,
"s": 10708,
"text": "Let’s create a test KEYSPACE, the Cassandra version of Database, and a Table on node cas1. Do not worry, I will discuss it in details later. Right now the purpose is to tell you how data is replicated."
},
{
"code": null,
"e": 11005,
"s": 10910,
"text": "Setting Replication factor to 2, which means there will be 2 copies of data, one on each node."
},
{
"code": null,
"e": 11039,
"s": 11005,
"text": "Let’s connect to the second node."
},
{
"code": null,
"e": 11100,
"s": 11039,
"text": "Notice the port 9043. The 9042 was already assigned to cas1."
},
{
"code": null,
"e": 11188,
"s": 11100,
"text": "Lo and Behold! MyKeySpace exists here as well, it was well replicated from Cas1 to Cas2"
},
{
"code": null,
"e": 11466,
"s": 11188,
"text": "Either you make changes on Cas1 or Cas2, it will eventually be propagated. This is not similar to a typical Master/Slave concept, it is rather called Masterless as the entire system is decentralized and P2P connection is established in the ring(Does it reminds you Blockchain?)"
},
{
"code": null,
"e": 11530,
"s": 11466,
"text": "Next up is Data Modeling concepts and creating entities in CQL."
},
{
"code": null,
"e": 11896,
"s": 11530,
"text": "Cassandra is a beast and it is not possible to cover every aspect of data modeling here. Therefore I will be covering the basics to give you a little bit idea that how is it different than a typical relational database system. Despite CQL looks very much similar to SQL or MySQL based SQL, it is not SQL at all. Prepare yourself to be ready to unlearn RDBMS things."
},
{
"code": null,
"e": 11960,
"s": 11896,
"text": "Below is a little comparison between Cassandra and RDBMS world."
},
{
"code": null,
"e": 12076,
"s": 11960,
"text": "Keyspace:- It is the container collection of column families. You can think of it as a Database in the RDBMS world."
},
{
"code": null,
"e": 12257,
"s": 12076,
"text": "Column Family:- A column family is a container for an ordered collection of rows. Each row, in turn, is an ordered collection of columns. Think of it as a Table in the RDBMS world."
},
{
"code": null,
"e": 12315,
"s": 12257,
"text": "Row:- A row is the collection of columns ordered columns."
},
{
"code": null,
"e": 12371,
"s": 12315,
"text": "Column:- A column is the collection of key/value pairs."
},
{
"code": null,
"e": 12415,
"s": 12371,
"text": "RowKey:- A primary key is called a row key."
},
{
"code": null,
"e": 12552,
"s": 12415,
"text": "Compound Primary Key:- A primary key consist of multiple columns. One part of that key then called Partition Key and rest a Cluster Key."
},
{
"code": null,
"e": 13398,
"s": 12552,
"text": "Partition Key:- Data in Cassandra is spread across the nodes. The purpose of the partition key is to identify the node that has stored that particular row which is being asked for. A function, called partition, is used to compute the hash value of the partition key at the time of row is being written. For instance, node 1 has key values range from 1–10, node 2 contains 11–20 and node 3 consists of range 21–30. When a SELECT command with WHERE clause is executed, the hash value of partition key is used to find the required node, once the node is found, it then fetches the data and returns to the client. For instance, the query is SELECT * FROM users where id = 5, and suppose the hash value of partition key(which is 5 in this case) is 15, it’d be the node 2which will have that row available. Below is the pictorial representation of it."
},
{
"code": null,
"e": 13611,
"s": 13398,
"text": "Let’s come up with an example. You are working on a system that keeps information about the site users and their cities. We will create a Keyspace, called, CityInfo. You may use CQLSH or TablePlus GUI, up to you."
},
{
"code": null,
"e": 13708,
"s": 13611,
"text": "create keyspace CityInfo with replication = {'class' : 'SimpleStrategy', 'replication_factor':2}"
},
{
"code": null,
"e": 13767,
"s": 13708,
"text": "Since I have 2 nodes so I set the replication_factor to 2."
},
{
"code": null,
"e": 14298,
"s": 13767,
"text": "In RDBMS we have a facility like JOINs and writing is not cheap hence we avoid duplicates by using foreign keys in relevant tables. This is not the case in Cassandra. Cassandra is a distributed system, writing is cheap hence you are most welcome to de-normalize data where needed. This helps to retrieve data which you usually fetch via JOINs. On the other hand, data reads could be expensive because data is spanned across nodes and retrieve via partition keys. While designing models you should have the following goals in mind:"
},
{
"code": null,
"e": 15086,
"s": 14298,
"text": "Evenly spread of data in a cluster:- The primary key is the partition key if it is consist of a single column and a partition key and cluster key in case of a composite primary key. To spread data evenly you must select a column for PK which has uniqueness thus could be spread across nodes. Things like ID, Username, and email have uniqueness and will fully utilize the cluster of nodes. But if you use keys like first/last name, gender, etc then there will be very fewer choices of partition keys and despite having 100s of nodes only a few will always be used thus making a partition fat and less performant.Minimize the number of Reads:- As I mentioned, reads are expensive. If you model in a way that a single query is fetching from multiple partitions it will make the system slow."
},
{
"code": null,
"e": 15698,
"s": 15086,
"text": "Evenly spread of data in a cluster:- The primary key is the partition key if it is consist of a single column and a partition key and cluster key in case of a composite primary key. To spread data evenly you must select a column for PK which has uniqueness thus could be spread across nodes. Things like ID, Username, and email have uniqueness and will fully utilize the cluster of nodes. But if you use keys like first/last name, gender, etc then there will be very fewer choices of partition keys and despite having 100s of nodes only a few will always be used thus making a partition fat and less performant."
},
{
"code": null,
"e": 15875,
"s": 15698,
"text": "Minimize the number of Reads:- As I mentioned, reads are expensive. If you model in a way that a single query is fetching from multiple partitions it will make the system slow."
},
{
"code": null,
"e": 16138,
"s": 15875,
"text": "Therefore, unlike RDBMS where you design schema first and get the liberty of creating queries based on your requirements, this is not the case for Cassandra. You must know the queries in advance which are required in the system and then design model accordingly."
},
{
"code": null,
"e": 16272,
"s": 16138,
"text": "We have a system where users of different cities visit a website. The management has asked to come up with the following information:"
},
{
"code": null,
"e": 16332,
"s": 16272,
"text": "List of all usersList of all cities.List of users by cities"
},
{
"code": null,
"e": 16350,
"s": 16332,
"text": "List of all users"
},
{
"code": null,
"e": 16370,
"s": 16350,
"text": "List of all cities."
},
{
"code": null,
"e": 16394,
"s": 16370,
"text": "List of users by cities"
},
{
"code": null,
"e": 16431,
"s": 16394,
"text": "Let’s create the cities table first."
},
{
"code": null,
"e": 16504,
"s": 16431,
"text": "CREATE TABLE cities ( id int, name text, country text, PRIMARY KEY(id));"
},
{
"code": null,
"e": 16515,
"s": 16504,
"text": "then users"
},
{
"code": null,
"e": 16595,
"s": 16515,
"text": "CREATE TABLE users ( username text, name text, age int, PRIMARY KEY(username));"
},
{
"code": null,
"e": 16619,
"s": 16595,
"text": "Inserting a few cities."
},
{
"code": null,
"e": 16882,
"s": 16619,
"text": "INSERT INTO cities(id,name,country) VALUES (1,'Karachi','Pakistan');INSERT INTO cities(id,name,country) VALUES (2,'Lahore','Pakistan');INSERT INTO cities(id,name,country) VALUES (3,'Dubai','UAE');INSERT INTO cities(id,name,country) VALUES (4,'Berlin','Germany');"
},
{
"code": null,
"e": 16908,
"s": 16882,
"text": "And inserting a few users"
},
{
"code": null,
"e": 17121,
"s": 16908,
"text": "INSERT INTO users(username,name,age) VALUES ('aali24','Ali Amin',34);INSERT INTO users(username,name,age) VALUES ('jack01','Jack David',23);INSERT INTO users(username,name,age) VALUES ('ninopk','Nina Rehman',34);"
},
{
"code": null,
"e": 17419,
"s": 17121,
"text": "These insertions fulfill our first two requirements but what about the 3rd one? In RDBMS world we would have used city_id as an FK in users table and a JOIN would easily return the data but this is Cassandra, we can’t do this, what is left for us create another table that would satisfy our needs."
},
{
"code": null,
"e": 17520,
"s": 17419,
"text": "CREATE TABLE users_by_cities ( username text, name text, city text, age int, PRIMARY KEY(city,age));"
},
{
"code": null,
"e": 17698,
"s": 17520,
"text": "This primary key has two components: First becomes partition key and the second becomes cluster key. It will look up w.r.t city and all the records are clustered/grouped by age."
},
{
"code": null,
"e": 17724,
"s": 17698,
"text": "Insert a few records now:"
},
{
"code": null,
"e": 18012,
"s": 17724,
"text": "INSERT INTO users_by_cities(username,name,city,age) VALUES ('aali24','Ali Amin','Karachi',34);INSERT INTO users_by_cities(username,name,city, age) VALUES ('jack01','Jack David','Berlin',23);INSERT INTO users_by_cities(username,name,city, age) VALUES ('ninopk','Nina Rehman','Lahore',34);"
},
{
"code": null,
"e": 18177,
"s": 18012,
"text": "Normally these insertions in two tables will be done in a go from an “Add User” interface, from CQL side you can do something like this to add a user’s information."
},
{
"code": null,
"e": 18372,
"s": 18177,
"text": "BEGIN BATCHINSERT into users(username,name,age) VALUES('raziz12','Rashid Aziz',34);INSERT INTO users_by_cities(username,name,city, age) VALUES ('raziz12','Rashid Aziz','Karachi',30);APPLY BATCH;"
},
{
"code": null,
"e": 18562,
"s": 18372,
"text": "Before I move further, I would like to remind you about the hashed token I discussed earlier. First, run the EXPAND ON command on CQL shell. Once you do that you see the results like below:"
},
{
"code": null,
"e": 18671,
"s": 18562,
"text": "Looks good, No? OK, now we are going to see the token value of our primary key. It returns the below result:"
},
{
"code": null,
"e": 19020,
"s": 18671,
"text": "cqlsh:cityinfo> select token(username) from users;@ Row 1------------------------+---------------------- system.token(username) | -7905752472182359000@ Row 2------------------------+---------------------- system.token(username) | 2621513098312339776@ Row 3------------------------+---------------------- system.token(username) | 6013687671608201304"
},
{
"code": null,
"e": 19310,
"s": 19020,
"text": "Make sense, tokens are unique because the usernames are unique. These tokens will spread across nodes. When the user runs the command SELECT * FROM users where username = 'raziz12', it will pick the node based on this token value. I already showed this in pictorial form a few lines above."
},
{
"code": null,
"e": 19377,
"s": 19310,
"text": "The query below shows the token values from users_by_cities table."
},
{
"code": null,
"e": 20108,
"s": 19377,
"text": "cqlsh:cityinfo> select token(username),username,city from users_by_cities;@ Row 1------------------------+---------------------- system.token(username) | 2621513098312339776 username | jack01 city | Berlin@ Row 2------------------------+---------------------- system.token(username) | 6013687671608201304 username | ninopk city | Lahore@ Row 3------------------------+---------------------- system.token(username) | -882788003101376442 username | raziz12 city | Karachi@ Row 4------------------------+---------------------- system.token(username) | -7905752472182359000 username | aali24 city | Karachi"
},
{
"code": null,
"e": 20185,
"s": 20108,
"text": "Select * from users_by_cities where city = 'Karachi'; returns the following:"
},
{
"code": null,
"e": 20435,
"s": 20185,
"text": "cqlsh:cityinfo> select * from users_by_cities where city = 'Karachi';@ Row 1----------+------------- city | Karachi username | aali24 name | Ali Amin@ Row 2----------+------------- city | Karachi username | raziz12 name | Rashid Aziz"
},
{
"code": null,
"e": 20533,
"s": 20435,
"text": "The model also serves the query select * from users_by_cities where city = 'Karachi' and age = 34"
},
{
"code": null,
"e": 20596,
"s": 20533,
"text": "But what if you want to pick a record based on name the field?"
},
{
"code": null,
"e": 20651,
"s": 20596,
"text": "SELECT * from users_by_cities where name = 'Ali Amin';"
},
{
"code": null,
"e": 20682,
"s": 20651,
"text": "You’d get the following error."
},
{
"code": null,
"e": 20917,
"s": 20682,
"text": "Error from server: code=2200 [Invalid query] message=\"Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability"
},
{
"code": null,
"e": 21271,
"s": 20917,
"text": "It is because no partition key was mentioned, Cassandra is asking to hunt the required name in ALL nodes, yes ALL nodes and imagine if nodes are 10 or 100, it’d take time to return the data. Hence it is not suggested. If you want to find something w.r.t field, either create another table(highly recommended) or create a secondary index(not recommended)"
},
{
"code": null,
"e": 21607,
"s": 21271,
"text": "The data is partitioned by city, on lookup, one node responds with the token of the city, once the node is discovered, it fetches all the record in that partition for the users belong to the city of Karachi. Something similar could be visualized about the clustering of data related to Karachi. The data is clustered against agecolumn."
},
{
"code": null,
"e": 21712,
"s": 21607,
"text": "So for a partition holding records of all Karachiites, you will be seeing clusters of records w.r.t age."
},
{
"code": null,
"e": 21905,
"s": 21712,
"text": "Your head must be spinning and would be missing your beloved MySQL but I am telling you that this is something worth learning, I am learning too and I just scratched the surface of this beast."
},
{
"code": null,
"e": 22163,
"s": 21905,
"text": "You’d be wondering that title of the post mentions Python but so far no Python code written at all, I hear you. It was necessary to prepare a ground because you will just be executing queries in your Python app. The main work is somewhere else, right above."
},
{
"code": null,
"e": 22258,
"s": 22163,
"text": "OK before I move to development, I discussed that Cassandra initially wrote data in Commitlog."
},
{
"code": null,
"e": 22534,
"s": 22258,
"text": "The path of Cassandra CommitLog can be obtained from /etc/cassandra/cassandra.yaml which is /var/lib/cassandra/commitlog here it creates log file w.r.t timestamp. It is not as readable but when I searched a few inserted record then found a few traces. Check the screen below:"
},
{
"code": null,
"e": 22639,
"s": 22534,
"text": "You can find traces of jack01, aali, and ninopk here. You also find text related to repairing mechanism."
},
{
"code": null,
"e": 22727,
"s": 22639,
"text": "SSTables are found in /var/lib/cassandra/data/<keyspacename> .In my case it is cityinfo"
},
{
"code": null,
"e": 22889,
"s": 22727,
"text": "For every table/Column Family it generates manifest.json files, a few *.db and a few other types of file, below are the files of the table users_by_cities table."
},
{
"code": null,
"e": 24179,
"s": 22889,
"text": "./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/manifest.json./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-CompressionInfo.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Data.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Digest.crc32./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Filter.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Index.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Statistics.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-Summary.db./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/md-1-big-TOC.txt./users_by_cities-62cea5f0788e11e9b568e709cd27ef9f/snapshots/truncated-1558089482008-users_by_cities/schema.cql"
},
{
"code": null,
"e": 24213,
"s": 24179,
"text": "You can learn more about it here."
},
{
"code": null,
"e": 24389,
"s": 24213,
"text": "Alright, so, first of all, we’d need to install the driver. I am out the docker shell as I’d be accessing it from my host machine. Run the command pip install cassandra-driver"
},
{
"code": null,
"e": 24434,
"s": 24389,
"text": "It takes a while during building the driver:"
},
{
"code": null,
"e": 24925,
"s": 24434,
"text": "Requirement already satisfied: six>=1.9 in /anaconda3/anaconda/lib/python3.6/site-packages (from cassandra-driver) (1.11.0)Building wheels for collected packages: cassandra-driver Building wheel for cassandra-driver (setup.py) ... done Stored in directory: /Users/AdnanAhmad/Library/Caches/pip/wheels/df/f4/40/941c98128d60f08d2f628b04a7a1b10006655aac3803e0e227Successfully built cassandra-driverInstalling collected packages: cassandra-driverSuccessfully installed cassandra-driver-3.17.1"
},
{
"code": null,
"e": 25043,
"s": 24925,
"text": "Below is the code connecting to the Cassandra Cluster within Docker from the Python script running out of the Docker."
},
{
"code": null,
"e": 25364,
"s": 25043,
"text": "from cassandra.cluster import Clusterif __name__ == \"__main__\": cluster = Cluster(['0.0.0.0'],port=9042) session = cluster.connect('cityinfo',wait_for_all_pools=True) session.execute('USE cityinfo') rows = session.execute('SELECT * FROM users') for row in rows: print(row.age,row.name,row.username)"
},
{
"code": null,
"e": 25395,
"s": 25364,
"text": "The following output returned:"
},
{
"code": null,
"e": 25535,
"s": 25395,
"text": "➜ CassandraTut python cassandra_connect.py34 Ali Amin aali2434 Rashid Aziz raziz1223 Jack David jack0134 Nina Rehman ninopk➜ CassandraTut"
},
{
"code": null,
"e": 25568,
"s": 25535,
"text": "You can learn more about it here"
},
{
"code": null,
"e": 25777,
"s": 25568,
"text": "So in this post, you learned a bit about Cassandra and how to use CQL and connecting it in your Python scripts. Leave your comment below for comments, correction or feedback. As always, the code is on Github."
}
] |
Which is faster, Python threads or processes? Some insightful examples | by James Fulton | Towards Data Science
|
If you are reading this, you have likely been trying to work out what the difference is between threads and processes in Python, and when you should use each. In order to explain some of the key differences, I’m going to show some example functions, and analyse how long they take to run using both threads and processes. Importantly, I’ll talk about why threads and processes have the different timings in each case.
I’m going to be using Dask to run the example functions using threads and processes. More details on how to do this with Dask are at the bottom of the article. For now, I’m going to focus on the differences between threads and processes.
Let’s start with a simple function, just a Python for-loop. It takes an argument n which is an integer of how many repeats in the loop.
def basic_python_loop(n): """Runs simple native Python loop which is memory light and involves no data input or output.""" mydict = {} for i in range(n): mydict[i%10] = i return None
This function only creates a 10 item dictionary, so uses very little memory, and it isn’t very demanding on the CPU. Your computer will actually spend most of its time interpreting the Python code, rather than running it.
The plot below shows the times taken to execute the function basic_python_loop(n=10_000_000) 16 times. For comparison, running this function just once took about 0.8 seconds.
In the figure, each of the 16 calls to the function are assigned a task number 1–16. The orange shaded bar shows when each function call started and when it finished. For example, task 8 in the left panel started ~5 seconds after the start of the computation, and ran until 5.6 seconds. The blue bar at the top shows the entire time required to complete all 16 function calls.
The three panels in the figure time the functions using a simple loop, using multi-threading and using parallel processing.
The full 16-part calculation takes the same length of time using threads as it takes using a loop. And interestingly, each of the individual tasks takes a lot longer using threads. This is because of the global interpreter lock (GIL). In Python, only one thread can read the code at once. This is a core feature of the Python language, but most other programming languages do not have this limitation. This means that other articles you read about multi-threading may not apply to Python.
In Python, threads work like a team of cooks sharing a single recipe book. Let’s say they have 3 dishes to prepare (3 threads), and there are 3 cooks (3 cores on your computer). A cook will read one line from the recipe, and go and complete it. Once they have completed the step they join the line to read their next step. If the steps in the recipe are short (like they are in a basic Python for-loop), the cooks will complete them very quickly and so will spend most of their time just waiting for their turn to read the recipe book. So each recipe takes longer to make than if a cook could have sole access to the book.
The 16-tasks shown above were run using 3 threads, this means there are 3 function calls (3 recipes) being handled at once. Since the steps are simple (like accessing a dictionary), the threads spend most of their time waiting to read the Python code. So although we are simultaneously running 3 function calls, each one takes 3 times longer to complete. So there is no benefit to using multi-threading here!
In the figure, you can see that processes were about 3 times faster than using a loop or using multi-threading to complete all 16 tasks. Each individual task took the same length of time when run using processes as it did using loops. This is because each process has its own GIL, so processes do not lock each other out like threads.
In Python, parallel processing is like a team of cooks, but every cook has their own kitchen and recipe book.
In this function we load a randomly chosen CSV from a directory. All CSVs in the directory are the same size.
def load_csv(): """Load, but do not return, a CSV file.""" # Choose a random CSV from the directory file = np.random.choice(glob.glob(f"{temp_dir}/*.csv")) df = pd.read_csv(file) return None
Threads and processes took about as long as each other, and both were faster than using a loop. In this function, unlike the previous one, each task completed by threads takes the same amount of time as when completed by the loop. But why don’t threads get slowed down by the GIL here?
In this function, most of the time is spent running the line pd.read_csv(file). This function causes Python to run a large chunk of C code to load the data from file. When running this C code, a thread releases the Python interpreter so that other threads can read the Python code, and it won’t need to read the Python code again until it has finished loading. This means that the threads don’t lock each other out as much as in the previous example. They aren’t all fighting to read the code at once.
Most of the functions in NumPy, scipy, and pandas are written in C and so they also cause threads to release the GIL and avoid locking each other out.
In the recipe-cook analogy, this is like having an step in the recipe which says “knead the dough for 5 minutes”. The instruction is quick to read, but takes a long time to complete.
This next function uses NumPy to create a random array and find its inverse. Basically, it is just a computationally heavy calculation.
def numpy_cpu_heavy_function(n): """Runs a CPU intensive calculation, but involves no data input or output.""" x = np.linalg.inv(np.random.normal(0, 1, (n,n))) return None
The timings for this function are shown below, usingn=2000 so that the array is of shape 2000x2000.
Strangely, we didn’t get much of a speedup using either threads or processes. But why? in the previous examples we got a 3 times speed-up since the computer used has 3 cores. This is because NumPy itself uses multi-threading and uses multiple cores. This means when you try to run many of these NumPy functions in parallel, using using threads or processes, you are limited by computing power. Each core is trying to recruit additional cores to run its NumPy calculation. So once all of your cores are running at 100% speed, there is no way to get more computing power out of them.
So far, the functions we have used have either had no input arguments, or else the input argument is just a single integer. A key difference between processes and threads is shown when we have sizeable inputs or outputs.
def transfer_data(x): """Transfer data into and out of a function.""" return x*2
In the function above, we will pass in an array x and return the array doubled. In the results shown belowx was an array of dimensions 10,000x1000 and was 80 MB in memory.
In this case, threads completed the task in 0.36 seconds, and the loop took 0.51 seconds, but processes took over 14 times longer. This is because processes each have their own separate pool of memory. When we pass the array x into the function, and run it using processes, x must be copied into each process from the main Python session. This took about 3.5 seconds. Once the array was copied, the processes could double the array very quickly, but then it took another 3.5 seconds to copy the doubled arrays back to the main session. Contrary to this, threads share the same memory space with the main Python session, so there is no need to copy the array across and back again.
In the cook analogy, processes are like 3 cooks each with their own recipe books and own kitchens. The kitchens are in separate locations, so if we want the cooks to run some recipes, we need to carry the the ingredients to them, then they can cook the dish, and we need to go and collect the dishes. Sometimes it is easier to use threads and have them cook the dishes in the same kitchen, even if that means they have to read from the same recipe book.
Let’s summarise:
The GIL means that only one thread can read the Python code at once. This means multiple threads can lock each other out.
Using external calls to C code, like in NumPy, SciPy, and pandas functions means threads will release the GIL while they run these functions. This means threads are less like to have to wait for a chance to read the code.
Processes each have their own memory pool. This means it is slow to copy large amounts of data into them, or out of them. For example when running functions on large input arrays or DataFrames.
Threads share the same memory as the main Python session, so there is no need to copy data to or from them.
These lead to some rules of thumb for speeding up calculations.
First of all, on data transfer. If your functions take in or return large chunks of data, use threads; otherwise you will waste too much time transferring data. However, ask yourself, do you really need to have data as an argument, could you load data inside the function? If so, then you could still use processes.
Next on Python loops. If your function must use simple native Python loops, then use processes. However, ask yourself, could these loops be replaced with NumPy array operations? If so you could still use threads.
If you are using computationally expensive NumPy/etc operations, then you may not gain much by using threads or processes.
Thoroughly covering Dask in this article would make it too long, so instead, I’ll cover the essential parts, and link to a notebook, so that these plots are reproduceable.
If you are interested, I also have a Dask course on DataCamp where I cover Dask more thoroughly with interactive videos and exercises. The first chapter of that course is free, takes about 30 minutes, and covers all the Dask used below and in the notebooks.
We can use Dask to run calculations using threads or processes. First we import Dask, and use the dask.delayed function to create a list of lazily evaluated results.
import daskn = 10_000_000lazy_results= []for i in range(16): lazy_results.append(dask.delayed(basic_python_loop)(n))
Note that the function basic_python_loop hasn’t actually been run yet since it is lazily evaluated. Instead, only the instructions to run it have been stored.
We can run the calculation using multi-threading like:
results = dask.compute(lazy_results, scheduler='threads')
Or can run the calculation using multi-processing like:
results = dask.compute(lazy_results, scheduler='processes')
These are the simplest methods, but in the experiments for this article, I wanted more control over the number of threads and processes used. To do this, you can create a client which sets up a pool of processes and/or threads which you use to complete the computation.
For example, to create and use a pool of 3 processes, you can use:
process_client = Client( processes=True, n_workers=3, threads_per_worker=1)results = process_client.compute(lazy_results)
I took a lot of inspiration from Brendan Fortuner’s medium post from a few years ago. In fact a lot of what I’ve done here recreates his examples, but I wanted to go a little deeper than what is in the original article he wrote.
medium.com
If you are using native Python loops a lot in your code, then you should definitely be using Numba. It can speed up these loops to speeds approaching that of C. Best of all, if you use Numba correctly (see notebook) you can set it so that your loop functions do not lock the GIL. This means you can use your Numba loop functions, which are already much faster, and run them in parallel with multi-threading.
towardsdatascience.com
Finally, the rules of thumb for using threads and processes, that we arrived at in this article, are quite similar to the Dask best practices described here.
|
[
{
"code": null,
"e": 464,
"s": 46,
"text": "If you are reading this, you have likely been trying to work out what the difference is between threads and processes in Python, and when you should use each. In order to explain some of the key differences, I’m going to show some example functions, and analyse how long they take to run using both threads and processes. Importantly, I’ll talk about why threads and processes have the different timings in each case."
},
{
"code": null,
"e": 702,
"s": 464,
"text": "I’m going to be using Dask to run the example functions using threads and processes. More details on how to do this with Dask are at the bottom of the article. For now, I’m going to focus on the differences between threads and processes."
},
{
"code": null,
"e": 838,
"s": 702,
"text": "Let’s start with a simple function, just a Python for-loop. It takes an argument n which is an integer of how many repeats in the loop."
},
{
"code": null,
"e": 1044,
"s": 838,
"text": "def basic_python_loop(n): \"\"\"Runs simple native Python loop which is memory light and involves no data input or output.\"\"\" mydict = {} for i in range(n): mydict[i%10] = i return None"
},
{
"code": null,
"e": 1266,
"s": 1044,
"text": "This function only creates a 10 item dictionary, so uses very little memory, and it isn’t very demanding on the CPU. Your computer will actually spend most of its time interpreting the Python code, rather than running it."
},
{
"code": null,
"e": 1441,
"s": 1266,
"text": "The plot below shows the times taken to execute the function basic_python_loop(n=10_000_000) 16 times. For comparison, running this function just once took about 0.8 seconds."
},
{
"code": null,
"e": 1818,
"s": 1441,
"text": "In the figure, each of the 16 calls to the function are assigned a task number 1–16. The orange shaded bar shows when each function call started and when it finished. For example, task 8 in the left panel started ~5 seconds after the start of the computation, and ran until 5.6 seconds. The blue bar at the top shows the entire time required to complete all 16 function calls."
},
{
"code": null,
"e": 1942,
"s": 1818,
"text": "The three panels in the figure time the functions using a simple loop, using multi-threading and using parallel processing."
},
{
"code": null,
"e": 2431,
"s": 1942,
"text": "The full 16-part calculation takes the same length of time using threads as it takes using a loop. And interestingly, each of the individual tasks takes a lot longer using threads. This is because of the global interpreter lock (GIL). In Python, only one thread can read the code at once. This is a core feature of the Python language, but most other programming languages do not have this limitation. This means that other articles you read about multi-threading may not apply to Python."
},
{
"code": null,
"e": 3054,
"s": 2431,
"text": "In Python, threads work like a team of cooks sharing a single recipe book. Let’s say they have 3 dishes to prepare (3 threads), and there are 3 cooks (3 cores on your computer). A cook will read one line from the recipe, and go and complete it. Once they have completed the step they join the line to read their next step. If the steps in the recipe are short (like they are in a basic Python for-loop), the cooks will complete them very quickly and so will spend most of their time just waiting for their turn to read the recipe book. So each recipe takes longer to make than if a cook could have sole access to the book."
},
{
"code": null,
"e": 3463,
"s": 3054,
"text": "The 16-tasks shown above were run using 3 threads, this means there are 3 function calls (3 recipes) being handled at once. Since the steps are simple (like accessing a dictionary), the threads spend most of their time waiting to read the Python code. So although we are simultaneously running 3 function calls, each one takes 3 times longer to complete. So there is no benefit to using multi-threading here!"
},
{
"code": null,
"e": 3798,
"s": 3463,
"text": "In the figure, you can see that processes were about 3 times faster than using a loop or using multi-threading to complete all 16 tasks. Each individual task took the same length of time when run using processes as it did using loops. This is because each process has its own GIL, so processes do not lock each other out like threads."
},
{
"code": null,
"e": 3908,
"s": 3798,
"text": "In Python, parallel processing is like a team of cooks, but every cook has their own kitchen and recipe book."
},
{
"code": null,
"e": 4018,
"s": 3908,
"text": "In this function we load a randomly chosen CSV from a directory. All CSVs in the directory are the same size."
},
{
"code": null,
"e": 4224,
"s": 4018,
"text": "def load_csv(): \"\"\"Load, but do not return, a CSV file.\"\"\" # Choose a random CSV from the directory file = np.random.choice(glob.glob(f\"{temp_dir}/*.csv\")) df = pd.read_csv(file) return None"
},
{
"code": null,
"e": 4510,
"s": 4224,
"text": "Threads and processes took about as long as each other, and both were faster than using a loop. In this function, unlike the previous one, each task completed by threads takes the same amount of time as when completed by the loop. But why don’t threads get slowed down by the GIL here?"
},
{
"code": null,
"e": 5012,
"s": 4510,
"text": "In this function, most of the time is spent running the line pd.read_csv(file). This function causes Python to run a large chunk of C code to load the data from file. When running this C code, a thread releases the Python interpreter so that other threads can read the Python code, and it won’t need to read the Python code again until it has finished loading. This means that the threads don’t lock each other out as much as in the previous example. They aren’t all fighting to read the code at once."
},
{
"code": null,
"e": 5163,
"s": 5012,
"text": "Most of the functions in NumPy, scipy, and pandas are written in C and so they also cause threads to release the GIL and avoid locking each other out."
},
{
"code": null,
"e": 5346,
"s": 5163,
"text": "In the recipe-cook analogy, this is like having an step in the recipe which says “knead the dough for 5 minutes”. The instruction is quick to read, but takes a long time to complete."
},
{
"code": null,
"e": 5482,
"s": 5346,
"text": "This next function uses NumPy to create a random array and find its inverse. Basically, it is just a computationally heavy calculation."
},
{
"code": null,
"e": 5667,
"s": 5482,
"text": "def numpy_cpu_heavy_function(n): \"\"\"Runs a CPU intensive calculation, but involves no data input or output.\"\"\" x = np.linalg.inv(np.random.normal(0, 1, (n,n))) return None"
},
{
"code": null,
"e": 5767,
"s": 5667,
"text": "The timings for this function are shown below, usingn=2000 so that the array is of shape 2000x2000."
},
{
"code": null,
"e": 6349,
"s": 5767,
"text": "Strangely, we didn’t get much of a speedup using either threads or processes. But why? in the previous examples we got a 3 times speed-up since the computer used has 3 cores. This is because NumPy itself uses multi-threading and uses multiple cores. This means when you try to run many of these NumPy functions in parallel, using using threads or processes, you are limited by computing power. Each core is trying to recruit additional cores to run its NumPy calculation. So once all of your cores are running at 100% speed, there is no way to get more computing power out of them."
},
{
"code": null,
"e": 6570,
"s": 6349,
"text": "So far, the functions we have used have either had no input arguments, or else the input argument is just a single integer. A key difference between processes and threads is shown when we have sizeable inputs or outputs."
},
{
"code": null,
"e": 6657,
"s": 6570,
"text": "def transfer_data(x): \"\"\"Transfer data into and out of a function.\"\"\" return x*2"
},
{
"code": null,
"e": 6829,
"s": 6657,
"text": "In the function above, we will pass in an array x and return the array doubled. In the results shown belowx was an array of dimensions 10,000x1000 and was 80 MB in memory."
},
{
"code": null,
"e": 7510,
"s": 6829,
"text": "In this case, threads completed the task in 0.36 seconds, and the loop took 0.51 seconds, but processes took over 14 times longer. This is because processes each have their own separate pool of memory. When we pass the array x into the function, and run it using processes, x must be copied into each process from the main Python session. This took about 3.5 seconds. Once the array was copied, the processes could double the array very quickly, but then it took another 3.5 seconds to copy the doubled arrays back to the main session. Contrary to this, threads share the same memory space with the main Python session, so there is no need to copy the array across and back again."
},
{
"code": null,
"e": 7964,
"s": 7510,
"text": "In the cook analogy, processes are like 3 cooks each with their own recipe books and own kitchens. The kitchens are in separate locations, so if we want the cooks to run some recipes, we need to carry the the ingredients to them, then they can cook the dish, and we need to go and collect the dishes. Sometimes it is easier to use threads and have them cook the dishes in the same kitchen, even if that means they have to read from the same recipe book."
},
{
"code": null,
"e": 7981,
"s": 7964,
"text": "Let’s summarise:"
},
{
"code": null,
"e": 8103,
"s": 7981,
"text": "The GIL means that only one thread can read the Python code at once. This means multiple threads can lock each other out."
},
{
"code": null,
"e": 8325,
"s": 8103,
"text": "Using external calls to C code, like in NumPy, SciPy, and pandas functions means threads will release the GIL while they run these functions. This means threads are less like to have to wait for a chance to read the code."
},
{
"code": null,
"e": 8519,
"s": 8325,
"text": "Processes each have their own memory pool. This means it is slow to copy large amounts of data into them, or out of them. For example when running functions on large input arrays or DataFrames."
},
{
"code": null,
"e": 8627,
"s": 8519,
"text": "Threads share the same memory as the main Python session, so there is no need to copy data to or from them."
},
{
"code": null,
"e": 8691,
"s": 8627,
"text": "These lead to some rules of thumb for speeding up calculations."
},
{
"code": null,
"e": 9007,
"s": 8691,
"text": "First of all, on data transfer. If your functions take in or return large chunks of data, use threads; otherwise you will waste too much time transferring data. However, ask yourself, do you really need to have data as an argument, could you load data inside the function? If so, then you could still use processes."
},
{
"code": null,
"e": 9220,
"s": 9007,
"text": "Next on Python loops. If your function must use simple native Python loops, then use processes. However, ask yourself, could these loops be replaced with NumPy array operations? If so you could still use threads."
},
{
"code": null,
"e": 9343,
"s": 9220,
"text": "If you are using computationally expensive NumPy/etc operations, then you may not gain much by using threads or processes."
},
{
"code": null,
"e": 9515,
"s": 9343,
"text": "Thoroughly covering Dask in this article would make it too long, so instead, I’ll cover the essential parts, and link to a notebook, so that these plots are reproduceable."
},
{
"code": null,
"e": 9773,
"s": 9515,
"text": "If you are interested, I also have a Dask course on DataCamp where I cover Dask more thoroughly with interactive videos and exercises. The first chapter of that course is free, takes about 30 minutes, and covers all the Dask used below and in the notebooks."
},
{
"code": null,
"e": 9939,
"s": 9773,
"text": "We can use Dask to run calculations using threads or processes. First we import Dask, and use the dask.delayed function to create a list of lazily evaluated results."
},
{
"code": null,
"e": 10059,
"s": 9939,
"text": "import daskn = 10_000_000lazy_results= []for i in range(16): lazy_results.append(dask.delayed(basic_python_loop)(n))"
},
{
"code": null,
"e": 10218,
"s": 10059,
"text": "Note that the function basic_python_loop hasn’t actually been run yet since it is lazily evaluated. Instead, only the instructions to run it have been stored."
},
{
"code": null,
"e": 10273,
"s": 10218,
"text": "We can run the calculation using multi-threading like:"
},
{
"code": null,
"e": 10331,
"s": 10273,
"text": "results = dask.compute(lazy_results, scheduler='threads')"
},
{
"code": null,
"e": 10387,
"s": 10331,
"text": "Or can run the calculation using multi-processing like:"
},
{
"code": null,
"e": 10447,
"s": 10387,
"text": "results = dask.compute(lazy_results, scheduler='processes')"
},
{
"code": null,
"e": 10717,
"s": 10447,
"text": "These are the simplest methods, but in the experiments for this article, I wanted more control over the number of threads and processes used. To do this, you can create a client which sets up a pool of processes and/or threads which you use to complete the computation."
},
{
"code": null,
"e": 10784,
"s": 10717,
"text": "For example, to create and use a pool of 3 processes, you can use:"
},
{
"code": null,
"e": 10917,
"s": 10784,
"text": "process_client = Client( processes=True, n_workers=3, threads_per_worker=1)results = process_client.compute(lazy_results)"
},
{
"code": null,
"e": 11146,
"s": 10917,
"text": "I took a lot of inspiration from Brendan Fortuner’s medium post from a few years ago. In fact a lot of what I’ve done here recreates his examples, but I wanted to go a little deeper than what is in the original article he wrote."
},
{
"code": null,
"e": 11157,
"s": 11146,
"text": "medium.com"
},
{
"code": null,
"e": 11565,
"s": 11157,
"text": "If you are using native Python loops a lot in your code, then you should definitely be using Numba. It can speed up these loops to speeds approaching that of C. Best of all, if you use Numba correctly (see notebook) you can set it so that your loop functions do not lock the GIL. This means you can use your Numba loop functions, which are already much faster, and run them in parallel with multi-threading."
},
{
"code": null,
"e": 11588,
"s": 11565,
"text": "towardsdatascience.com"
}
] |
Java lang.Long.toBinaryString() method with Examples - GeeksforGeeks
|
05 Dec, 2018
The java.lang.Long.toBinaryString() method returns a string representation of the long argument as an unsigned integer in base 2. It accepts an argument in Long data-type and returns the corresponding binary string.
Syntax:
public static String toBinaryString(long num)
Parameters : The function accepts a single mandatory parameter:
num - This parameter specifies the number to be converted to binary string.
It is of Long data-type.
Return Value: This function returns the string representation of the unsigned Long value represented by the argument in binary (base 2).
Examples:
Input : 10
Output : 1010
Input : 9
Output : 1001
Program 1 : The program below demonstrates the working of function.
// Java program to demonstrate// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { long l = 10; // returns the string representation of the unsigned long value // represented by the argument in binary (base 2) System.out.println("Binary is " + Long.toBinaryString(l)); l = 20987752; System.out.println("Binary is " + Long.toBinaryString(l)); }}
Output:
Binary is 1010
Binary is 1010000000011111101101000
Program 2: The program below demonstrates the working function when a negative number is passed.
// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // conversion of a negative number to Binary long l = -13; System.out.println("Binary is " + Long.toBinaryString(l)); }}
Output:
Binary is 1111111111111111111111111111111111111111111111111111111111110011
Errors and Exceptions: Whenever a decimal number or a string is passed as an argument, it returns an error message which says “incompatible types”.
Program 3: The program below demonstrates the working function when a string number is passed.
// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // error message thrown when a string is passed System.out.println("Binary is " + Long.toBinaryString("10")); }}
Output:
prog.java:12: error: incompatible types: String cannot be converted to long
System.out.println("Binary is " + Long.toBinaryString("10"));
Program 4: The program below demonstrates the working function when a decimal is passed.
// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // error message thrown when a decimal is passed System.out.println("Binary is " + Long.toBinaryString(10.25)); }}
Output:
prog.java:12: error: incompatible types: possible lossy conversion from double to long
System.out.println("Binary is " + Long.toBinaryString(10.25));
Java-Functions
Java-lang package
java-Long
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 24231,
"s": 24015,
"text": "The java.lang.Long.toBinaryString() method returns a string representation of the long argument as an unsigned integer in base 2. It accepts an argument in Long data-type and returns the corresponding binary string."
},
{
"code": null,
"e": 24239,
"s": 24231,
"text": "Syntax:"
},
{
"code": null,
"e": 24454,
"s": 24239,
"text": "public static String toBinaryString(long num)\n\nParameters : The function accepts a single mandatory parameter: \nnum - This parameter specifies the number to be converted to binary string. \nIt is of Long data-type.\n"
},
{
"code": null,
"e": 24591,
"s": 24454,
"text": "Return Value: This function returns the string representation of the unsigned Long value represented by the argument in binary (base 2)."
},
{
"code": null,
"e": 24601,
"s": 24591,
"text": "Examples:"
},
{
"code": null,
"e": 24655,
"s": 24601,
"text": "Input : 10 \nOutput : 1010 \n\nInput : 9\nOutput : 1001 \n"
},
{
"code": null,
"e": 24723,
"s": 24655,
"text": "Program 1 : The program below demonstrates the working of function."
},
{
"code": "// Java program to demonstrate// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { long l = 10; // returns the string representation of the unsigned long value // represented by the argument in binary (base 2) System.out.println(\"Binary is \" + Long.toBinaryString(l)); l = 20987752; System.out.println(\"Binary is \" + Long.toBinaryString(l)); }}",
"e": 25212,
"s": 24723,
"text": null
},
{
"code": null,
"e": 25220,
"s": 25212,
"text": "Output:"
},
{
"code": null,
"e": 25272,
"s": 25220,
"text": "Binary is 1010\nBinary is 1010000000011111101101000\n"
},
{
"code": null,
"e": 25369,
"s": 25272,
"text": "Program 2: The program below demonstrates the working function when a negative number is passed."
},
{
"code": "// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // conversion of a negative number to Binary long l = -13; System.out.println(\"Binary is \" + Long.toBinaryString(l)); }}",
"e": 25701,
"s": 25369,
"text": null
},
{
"code": null,
"e": 25709,
"s": 25701,
"text": "Output:"
},
{
"code": null,
"e": 25785,
"s": 25709,
"text": "Binary is 1111111111111111111111111111111111111111111111111111111111110011\n"
},
{
"code": null,
"e": 25933,
"s": 25785,
"text": "Errors and Exceptions: Whenever a decimal number or a string is passed as an argument, it returns an error message which says “incompatible types”."
},
{
"code": null,
"e": 26028,
"s": 25933,
"text": "Program 3: The program below demonstrates the working function when a string number is passed."
},
{
"code": "// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // error message thrown when a string is passed System.out.println(\"Binary is \" + Long.toBinaryString(\"10\")); }}",
"e": 26347,
"s": 26028,
"text": null
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Output:"
},
{
"code": null,
"e": 26497,
"s": 26355,
"text": "prog.java:12: error: incompatible types: String cannot be converted to long\n System.out.println(\"Binary is \" + Long.toBinaryString(\"10\"));"
},
{
"code": null,
"e": 26586,
"s": 26497,
"text": "Program 4: The program below demonstrates the working function when a decimal is passed."
},
{
"code": "// Java program to demonstrate overflow// of java.lang.Long.toBinaryString() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // error message thrown when a decimal is passed System.out.println(\"Binary is \" + Long.toBinaryString(10.25)); }}",
"e": 26907,
"s": 26586,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26907,
"text": "Output:"
},
{
"code": null,
"e": 27069,
"s": 26915,
"text": "prog.java:12: error: incompatible types: possible lossy conversion from double to long\n System.out.println(\"Binary is \" + Long.toBinaryString(10.25));"
},
{
"code": null,
"e": 27084,
"s": 27069,
"text": "Java-Functions"
},
{
"code": null,
"e": 27102,
"s": 27084,
"text": "Java-lang package"
},
{
"code": null,
"e": 27112,
"s": 27102,
"text": "java-Long"
},
{
"code": null,
"e": 27122,
"s": 27112,
"text": "java-math"
},
{
"code": null,
"e": 27127,
"s": 27122,
"text": "Java"
},
{
"code": null,
"e": 27132,
"s": 27127,
"text": "Java"
},
{
"code": null,
"e": 27230,
"s": 27132,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27239,
"s": 27230,
"text": "Comments"
},
{
"code": null,
"e": 27252,
"s": 27239,
"text": "Old Comments"
},
{
"code": null,
"e": 27303,
"s": 27252,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27333,
"s": 27303,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27364,
"s": 27333,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27396,
"s": 27364,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27415,
"s": 27396,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27433,
"s": 27415,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27465,
"s": 27433,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27485,
"s": 27465,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27509,
"s": 27485,
"text": "Singleton Class in Java"
}
] |
Powershell - Measure-Command Cmdlet
|
Measure-Command cmdlet is used to meaure the time taken by script or command.
In these example, we're see the Measure-Command cmdlet in action.
In this example, we'll show how to measure time of Get-EventLog command to log an event in PowerShell event log.
Measure-Command { Get-EventLog "Windows PowerShell" }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 50
Ticks : 506776
TotalDays : 5.86546296296296E-07
TotalHours : 1.40771111111111E-05
TotalMinutes : 0.000844626666666667
TotalSeconds : 0.0506776
TotalMilliseconds : 50.6776
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2112,
"s": 2034,
"text": "Measure-Command cmdlet is used to meaure the time taken by script or command."
},
{
"code": null,
"e": 2178,
"s": 2112,
"text": "In these example, we're see the Measure-Command cmdlet in action."
},
{
"code": null,
"e": 2291,
"s": 2178,
"text": "In this example, we'll show how to measure time of Get-EventLog command to log an event in PowerShell event log."
},
{
"code": null,
"e": 2345,
"s": 2291,
"text": "Measure-Command { Get-EventLog \"Windows PowerShell\" }"
},
{
"code": null,
"e": 2666,
"s": 2345,
"text": "Days : 0\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 50\nTicks : 506776\nTotalDays : 5.86546296296296E-07\nTotalHours : 1.40771111111111E-05\nTotalMinutes : 0.000844626666666667\nTotalSeconds : 0.0506776\nTotalMilliseconds : 50.6776 \n"
},
{
"code": null,
"e": 2701,
"s": 2666,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2722,
"s": 2701,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2757,
"s": 2722,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2770,
"s": 2757,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2807,
"s": 2770,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2819,
"s": 2807,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2826,
"s": 2819,
"text": " Print"
},
{
"code": null,
"e": 2837,
"s": 2826,
"text": " Add Notes"
}
] |
What is the difference between functions and methods in JavaScript?
|
Functions and methods are the same in JavaScript, but a method is a function, which is a property of an object.
The following is an example of a function in JavaScript −
function functionname(param1, param2){
// code
}
The method is a function associated with an object. The following is an example of a method in JavaScript −
Live Demo
<html>
<head>
<script>
var employee = {
empname: "David",
department : "Finance",
id : 002,
details : function() {
return this.empname + " with Department " + this.department;
}
};
document.write(employee.details());
</script>
</head>
</html>
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "Functions and methods are the same in JavaScript, but a method is a function, which is a property of an object."
},
{
"code": null,
"e": 1232,
"s": 1174,
"text": "The following is an example of a function in JavaScript −"
},
{
"code": null,
"e": 1284,
"s": 1232,
"text": "function functionname(param1, param2){\n // code\n}"
},
{
"code": null,
"e": 1392,
"s": 1284,
"text": "The method is a function associated with an object. The following is an example of a method in JavaScript −"
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": " Live Demo"
},
{
"code": null,
"e": 1767,
"s": 1403,
"text": "<html>\n <head>\n <script>\n var employee = {\n empname: \"David\",\n department : \"Finance\",\n id : 002,\n details : function() {\n return this.empname + \" with Department \" + this.department;\n }\n };\n\n document.write(employee.details());\n </script>\n </head>\n</html>"
}
] |
HTTP Requests with axios in ReactJS
|
In this article, we are going to learn how to send and receive Http Responses with axios in a React application.
Automatic conversion of response to JSON format
Automatic conversion of response to JSON format
Easy to use and more secure
Easy to use and more secure
Setting up global HTTP interceptors
Setting up global HTTP interceptors
Simultaneous Request
Simultaneous Request
npm install axios
OR
yarn add axios
Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager.
https://jsonplaceholder.typicode.com/todos/1
Jsonplaceholder is a fake API which is used to learn the process of the sending requests.
App.jsx
import React, { useEffect, useState } from 'react';
const App = () => {
const [data, setData] = useState(null);
const [fetchData, setFetch] = useState(false);
useEffect(() => {
if (fetchData) {
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((res) => setData(res.data.title));
}
}, [fetchData]);
return (
<>
<h1>{data}</h1>
<button onClick={() => setFetch(true)}>Fetch Data</button>
</>
);
};
export default App;
In the above example, we are sending the GET request to the jsonplaceholder and accessing the data which is going to be inserted in the state as soon as the response is received.
This will produce the following result.
https://jsonplaceholder.typicode.com/todos/1
Jsonplaceholder is a fake API which is used to learn the process of the sending requests.
App.jsx
import React, { useEffect, useState } from 'react';
import './App.css';
const App = () => {
const [data, setData] = useState(null);
const [val, setVal] = useState('');
const [fetchData, setFetch] = useState(false);
useEffect(() => {
if (fetchData) {
const payload = {
method: 'POST',
body: JSON.stringify({ title: val }),
};
axios.post('https://jsonplaceholder.typicode.com/posts', payload)
.then((res) => setData(res.data.id));
}
}, [fetchData]);
return (
<>
{data && <h1>Your data is saved with Id: {data}</h1>}
<input
placeholder="Title of Post"
value={val}
onChange={(e) => setVal(e.target.value)}
/>
<button onClick={() => setFetch(true)}>Save Data</button>
</>
);
};
export default App;
In the above example, we are sending the POST request to the jsonplaceholder with the input field value in the body and displaying the response accordingly.
This will produce the following result.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "In this article, we are going to learn how to send and receive Http Responses with axios in a React application."
},
{
"code": null,
"e": 1223,
"s": 1175,
"text": "Automatic conversion of response to JSON format"
},
{
"code": null,
"e": 1271,
"s": 1223,
"text": "Automatic conversion of response to JSON format"
},
{
"code": null,
"e": 1299,
"s": 1271,
"text": "Easy to use and more secure"
},
{
"code": null,
"e": 1327,
"s": 1299,
"text": "Easy to use and more secure"
},
{
"code": null,
"e": 1363,
"s": 1327,
"text": "Setting up global HTTP interceptors"
},
{
"code": null,
"e": 1399,
"s": 1363,
"text": "Setting up global HTTP interceptors"
},
{
"code": null,
"e": 1420,
"s": 1399,
"text": "Simultaneous Request"
},
{
"code": null,
"e": 1441,
"s": 1420,
"text": "Simultaneous Request"
},
{
"code": null,
"e": 1459,
"s": 1441,
"text": "npm install axios"
},
{
"code": null,
"e": 1462,
"s": 1459,
"text": "OR"
},
{
"code": null,
"e": 1477,
"s": 1462,
"text": "yarn add axios"
},
{
"code": null,
"e": 1610,
"s": 1477,
"text": "Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager."
},
{
"code": null,
"e": 1655,
"s": 1610,
"text": "https://jsonplaceholder.typicode.com/todos/1"
},
{
"code": null,
"e": 1745,
"s": 1655,
"text": "Jsonplaceholder is a fake API which is used to learn the process of the sending requests."
},
{
"code": null,
"e": 1753,
"s": 1745,
"text": "App.jsx"
},
{
"code": null,
"e": 2252,
"s": 1753,
"text": "import React, { useEffect, useState } from 'react';\nconst App = () => {\n const [data, setData] = useState(null);\n const [fetchData, setFetch] = useState(false);\n\n useEffect(() => {\n if (fetchData) {\n axios.get('https://jsonplaceholder.typicode.com/todos/1')\n.then((res) => setData(res.data.title));\n }\n }, [fetchData]);\n return (\n <>\n <h1>{data}</h1>\n <button onClick={() => setFetch(true)}>Fetch Data</button>\n </>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 2431,
"s": 2252,
"text": "In the above example, we are sending the GET request to the jsonplaceholder and accessing the data which is going to be inserted in the state as soon as the response is received."
},
{
"code": null,
"e": 2471,
"s": 2431,
"text": "This will produce the following result."
},
{
"code": null,
"e": 2516,
"s": 2471,
"text": "https://jsonplaceholder.typicode.com/todos/1"
},
{
"code": null,
"e": 2606,
"s": 2516,
"text": "Jsonplaceholder is a fake API which is used to learn the process of the sending requests."
},
{
"code": null,
"e": 2614,
"s": 2606,
"text": "App.jsx"
},
{
"code": null,
"e": 3476,
"s": 2614,
"text": "import React, { useEffect, useState } from 'react';\nimport './App.css';\nconst App = () => {\n const [data, setData] = useState(null);\n const [val, setVal] = useState('');\n const [fetchData, setFetch] = useState(false);\n\n useEffect(() => {\n if (fetchData) {\n const payload = {\n method: 'POST',\n body: JSON.stringify({ title: val }),\n };\n axios.post('https://jsonplaceholder.typicode.com/posts', payload)\n.then((res) => setData(res.data.id));\n }\n }, [fetchData]);\n return (\n <>\n {data && <h1>Your data is saved with Id: {data}</h1>}\n <input\n placeholder=\"Title of Post\"\n value={val}\n onChange={(e) => setVal(e.target.value)}\n />\n <button onClick={() => setFetch(true)}>Save Data</button>\n </>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 3633,
"s": 3476,
"text": "In the above example, we are sending the POST request to the jsonplaceholder with the input field value in the body and displaying the response accordingly."
},
{
"code": null,
"e": 3673,
"s": 3633,
"text": "This will produce the following result."
}
] |
Python - Test if list is Palindrome - GeeksforGeeks
|
11 Oct, 2020
Given a List, check if its palindrome.
Input : test_list = [4, 5, 4] Output : True Explanation : List is same from front and rear.
Input : test_list = [4, 5, 5] Output : True Explanation : List is not same from front and rear.
Method #1: Using list slicing
In this, we extract first and reversed 2nd half of list, and then compare for equality, if found equal, then we conclude its palindrome.
Python3
# Python3 code to demonstrate working of # Test if list is Palindrome# Using list slicing # initializing listtest_list = [1, 4, 5, 4, 1] # printing original listprint("The original list is : " + str(test_list)) # Reversing the listreverse = test_list[::-1] # checking if palindromeres = test_list == reverse # printing result print("Is list Palindrome : " + str(res))
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True
Method #2 : Using reversed()
In this, we simply reverse the list and check if both original list and reversed list is similar.
Python3
# Python3 code to demonstrate working of # Test if list is Palindrome# Using reversed() # initializing listtest_list = [1, 4, 5, 4, 1] # printing original listprint("The original list is : " + str(test_list)) # reversing listrev_list = list(reversed(test_list)) # checking for Palindromeres = rev_list == test_list # printing result print("Is list Palindrome : " + str(res))
The original list is : [1, 4, 5, 4, 1]
Is list Palindrome : True
Python list-programs
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 ?
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 25687,
"s": 25647,
"text": "Given a List, check if its palindrome. "
},
{
"code": null,
"e": 25779,
"s": 25687,
"text": "Input : test_list = [4, 5, 4] Output : True Explanation : List is same from front and rear."
},
{
"code": null,
"e": 25876,
"s": 25779,
"text": "Input : test_list = [4, 5, 5] Output : True Explanation : List is not same from front and rear. "
},
{
"code": null,
"e": 25906,
"s": 25876,
"text": "Method #1: Using list slicing"
},
{
"code": null,
"e": 26043,
"s": 25906,
"text": "In this, we extract first and reversed 2nd half of list, and then compare for equality, if found equal, then we conclude its palindrome."
},
{
"code": null,
"e": 26051,
"s": 26043,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Test if list is Palindrome# Using list slicing # initializing listtest_list = [1, 4, 5, 4, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # Reversing the listreverse = test_list[::-1] # checking if palindromeres = test_list == reverse # printing result print(\"Is list Palindrome : \" + str(res))",
"e": 26424,
"s": 26051,
"text": null
},
{
"code": null,
"e": 26490,
"s": 26424,
"text": "The original list is : [1, 4, 5, 4, 1]\nIs list Palindrome : True\n"
},
{
"code": null,
"e": 26519,
"s": 26490,
"text": "Method #2 : Using reversed()"
},
{
"code": null,
"e": 26617,
"s": 26519,
"text": "In this, we simply reverse the list and check if both original list and reversed list is similar."
},
{
"code": null,
"e": 26625,
"s": 26617,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Test if list is Palindrome# Using reversed() # initializing listtest_list = [1, 4, 5, 4, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # reversing listrev_list = list(reversed(test_list)) # checking for Palindromeres = rev_list == test_list # printing result print(\"Is list Palindrome : \" + str(res))",
"e": 27005,
"s": 26625,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27005,
"text": "The original list is : [1, 4, 5, 4, 1]\nIs list Palindrome : True\n"
},
{
"code": null,
"e": 27092,
"s": 27071,
"text": "Python list-programs"
},
{
"code": null,
"e": 27099,
"s": 27092,
"text": "Python"
},
{
"code": null,
"e": 27115,
"s": 27099,
"text": "Python Programs"
},
{
"code": null,
"e": 27213,
"s": 27115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27245,
"s": 27213,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27287,
"s": 27245,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27329,
"s": 27287,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27385,
"s": 27329,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27412,
"s": 27385,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27434,
"s": 27412,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27473,
"s": 27434,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27519,
"s": 27473,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27557,
"s": 27519,
"text": "Python | Convert a list to dictionary"
}
] |
Find keys with duplicate values in dictionary in Python
|
While dealing with dictionaries, we may come across situation when there are duplicate values in the dictionary while obviously the keys remain unique. In this article we will see how we can achieve thi.
We exchange the keys with values of the dictionaries and then keep appending the values associated with a given key. This way the duplicate values get clubbed and we can see them in the resulting new dictionary.
Live Demo
dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}
print("Given Dictionary :", dictA)
k_v_exchanged = {}
for key, value in dictA.items():
if value not in k_v_exchanged:
k_v_exchanged[value] = [key]
else:
k_v_exchanged[value].append(key)
# Result
print("New Dictionary:", k_v_exchanged)
Running the above code gives us the following result −
Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}
New Dictionary: {5: ['Sun', 'Tue'], 3: ['Mon', 'Wed']}
we follow a similar approach here. Here also we create a new dictionary from the existing dictionary using set function and adding the keys with duplicate values. Finally we filter out the values where the length is greater than 1 and mark them as duplicates.
Live Demo
dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}
print("Given Dictionary :", dictA)
dictB = {}
for key, value in dictA.items():
dictB.setdefault(value, set()).add(key)
res = filter(lambda x: len(x) >1, dictB.values())
# Result
print("New Dictionary:",list(res))
Running the above code gives us the following result −
Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}
New Dictionary: [{'Tue', 'Sun'}]
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "While dealing with dictionaries, we may come across situation when there are duplicate values in the dictionary while obviously the keys remain unique. In this article we will see how we can achieve thi."
},
{
"code": null,
"e": 1478,
"s": 1266,
"text": "We exchange the keys with values of the dictionaries and then keep appending the values associated with a given key. This way the duplicate values get clubbed and we can see them in the resulting new dictionary."
},
{
"code": null,
"e": 1489,
"s": 1478,
"text": " Live Demo"
},
{
"code": null,
"e": 1795,
"s": 1489,
"text": "dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}\n\nprint(\"Given Dictionary :\", dictA)\n\nk_v_exchanged = {}\n\nfor key, value in dictA.items():\n if value not in k_v_exchanged:\n k_v_exchanged[value] = [key]\n else:\n k_v_exchanged[value].append(key)\n\n# Result\nprint(\"New Dictionary:\", k_v_exchanged)"
},
{
"code": null,
"e": 1850,
"s": 1795,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1965,
"s": 1850,
"text": "Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 3}\nNew Dictionary: {5: ['Sun', 'Tue'], 3: ['Mon', 'Wed']}"
},
{
"code": null,
"e": 2225,
"s": 1965,
"text": "we follow a similar approach here. Here also we create a new dictionary from the existing dictionary using set function and adding the keys with duplicate values. Finally we filter out the values where the length is greater than 1 and mark them as duplicates."
},
{
"code": null,
"e": 2236,
"s": 2225,
"text": " Live Demo"
},
{
"code": null,
"e": 2505,
"s": 2236,
"text": "dictA = {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}\n\nprint(\"Given Dictionary :\", dictA)\n\ndictB = {}\nfor key, value in dictA.items():\n dictB.setdefault(value, set()).add(key)\n\nres = filter(lambda x: len(x) >1, dictB.values())\n\n# Result\nprint(\"New Dictionary:\",list(res))"
},
{
"code": null,
"e": 2560,
"s": 2505,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2653,
"s": 2560,
"text": "Given Dictionary : {'Sun': 5, 'Mon': 3, 'Tue': 5, 'Wed': 4}\nNew Dictionary: [{'Tue', 'Sun'}]"
}
] |
Calculate height of Binary Tree using Inorder and Level Order Traversal - GeeksforGeeks
|
22 Jun, 2021
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it.
Example:
Input : Input: Two arrays that represent Inorder
and level order traversals of a
Binary Tree
in[] = {4, 8, 10, 12, 14, 20, 22};
level[] = {20, 8, 22, 4, 12, 10, 14};
Output : 4
The binary tree that can be constructed from the
given traversals is:
We can clearly see in the above image that the
height of the tree is 4.
The approach to calculating height is similar to the approach discussed in the post Constructing Tree from Inorder and Level Order Traversals.Let us consider the above example.in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14};In a Levelorder sequence, the first element is the root of the tree. So we know ’20’ is root for given sequences. By searching ’20’ in Inorder sequence, we can find out all elements on the left side of ‘20’ are in left subtree and elements on right are in the right subtree. So we know below structure now.
20
/ \
/ \
{4, 8, 10, 12, 14} {22}
Let us call {4, 8, 10, 12, 14} as left subarray in Inorder traversal and {22} as right subarray in Inorder traversal. In level order traversal, keys of left and right subtrees are not consecutive. So we extract all nodes from level order traversal which are in left subarray of Inorder traversal. To calculate the height of the left subtree of the root, we recur for the extracted elements from level order traversal and left subarray of inorder traversal. In the above example, we recur for the following two arrays.
// Recur for following arrays to
// calculate the height of the left subtree
In[] = {4, 8, 10, 12, 14}
level[] = {8, 4, 12, 10, 14}
Similarly, we recur for the following two arrays and calculate the height of the right subtree.
// Recur for following arrays to calculate
// height of the right subtree
In[] = {22}
level[] = {22}
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to caulate height of Binary Tree// from InOrder and LevelOrder Traversals#include <iostream>using namespace std; /* Function to find index of value in the InOrder Traversal array */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treeint getHeight(int in[], int level[], int start, int end, int& height, int n){ // Base Case if (start > end) return 0; // Get index of current root in InOrder Traversal int getIndex = search(in, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int* newLeftLevel = new int[leftCount]; int* newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == in[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == in[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate height of left Subtree if (leftCount > 0) lheight = getHeight(in, newLeftLevel, start, getIndex - 1, height, leftCount); // Recursively call to calculate height of right Subtree if (rightCount > 0) rheight = getHeight(in, newRightLevel, getIndex + 1, end, height, rightCount); // Current height height = max(lheight + 1, rheight + 1); // Delete Auxiliary arrays delete[] newRightLevel; delete[] newLeftLevel; // return height return height;} // Driver program to test above functionsint main(){ int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); int h = 0; cout << getHeight(in, level, 0, n - 1, h, n); return 0;}
// Java program to caulate height of Binary Tree// from InOrder and LevelOrder Traversalsimport java.util.*;class GFG{static int height; /* Function to find index of valuein the InOrder Traversal array */static int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treestatic int getHeight(int in[], int level[], int start, int end, int n){ // Base Case if (start > end) return 0; // Get index of current root in InOrder Traversal int getIndex = search(in, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int []newLeftLevel = new int[leftCount]; int []newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == in[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == in[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(in, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(in, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel=null; newLeftLevel=null; // return height return height;} // Driver program to test above functionspublic static void main(String[] args){ int in[] = {4, 8, 10, 12, 14, 20, 22}; int level[] = {20, 8, 22, 4, 12, 10, 14}; int n = in.length; height = 0; System.out.println(getHeight(in, level, 0, n - 1, n));}} // This code is contributed by Rajput-Ji
# Python3 program to calculate height of Binary Tree from# InOrder and LevelOrder Traversals '''Function to find the index of value in the InOrderTraversal list''' def search(arr, start, end, value): for i in range(start, end + 1): if arr[i] == value: return i return -1 '''Function to calculate the height of the Binary Tree'''def getHeight(inOrder, levelOrder, start, end, height, n): # Base Case if start > end: return 0 # Get Index of current root in InOrder Traversal getIndex = search(inOrder, start, end, levelOrder[0]) if getIndex == -1: return 0 # Count elements in Left Subtree leftCount = getIndex - start # Count elements in Right Subtree rightCount = end - getIndex # Declare two lists for left and right subtrees newLeftLevel = [None for _ in range(leftCount)] newRightLevel = [None for _ in range(rightCount)] lheight, rheight, k = 0, 0, 0 # Extract values from level order traversal list # for current left subtree for i in range(n): for j in range(start, getIndex): if levelOrder[i] == inOrder[j]: newLeftLevel[k] = levelOrder[i] k += 1 break k = 0 # Extract values from level order traversal list # for current right subtree for i in range(n): for j in range(getIndex + 1, end + 1): if levelOrder[i] == inOrder[j]: newRightLevel[k] = levelOrder[i] k += 1 break # Recursively call to calculate height # of left subtree if leftCount > 0: lheight = getHeight(inOrder, newLeftLevel, start, getIndex - 1, height, leftCount) # Recursively call to calculate height # of right subtree if rightCount > 0: rheight = getHeight(inOrder, newRightLevel, getIndex + 1, end, height, rightCount) # current height height = max(lheight + 1, rheight + 1) # return height return height # Driver Codeif __name__=='__main__': inOrder = [4, 8, 10, 12, 14, 20, 22] levelOrder = [20, 8, 22, 4, 12, 10, 14] n, h = len(inOrder), 0 print(getHeight(inOrder, levelOrder, 0, n - 1, h, n)) # This code is contributed by harshraj22
// C# program to caulate height of Binary Tree// from InOrder and LevelOrder Traversalsusing System;using System.Collections.Generic; class GFG{static int height; /* Function to find index of valuein the InOrder Traversal array */static int search(int []arr, int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treestatic int getHeight(int []In, int []level, int start, int end, int n){ // Base Case if (start > end) return 0; // Get index of current root in // InOrder Traversal int getIndex = search(In, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int []newLeftLevel = new int[leftCount]; int []newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == In[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == In[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(In, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(In, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.Max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel = null; newLeftLevel = null; // return height return height;} // Driver Codepublic static void Main(String[] args){ int []In = {4, 8, 10, 12, 14, 20, 22}; int []level = {20, 8, 22, 4, 12, 10, 14}; int n = In.Length; height = 0; Console.WriteLine(getHeight(In, level, 0, n - 1, n));}} // This code is contributed by Princi Singh
<script> //Javascript program to caulate height of Binary Tree// from InOrder and LevelOrder Traversals var height = 0; /* Function to find index of valuein the InOrder Traversal array */function search(arr, strt, end, value){ for (var i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treefunction getHeight(In, level, start, end, n){ // Base Case if (start > end) return 0; // Get index of current root in // InOrder Traversal var getIndex = search(In, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree var leftCount = getIndex - start; // Count elements in right Subtree var rightCount = end - getIndex; // Declare two arrays for left and // right subtrees var newLeftLevel = Array(leftCount); var newRightLevel = Array(rightCount); var lheight = 0, rheight = 0; var k = 0; // Extract values from level order traversal array // for current left subtree for (var i = 0; i < n; i++) { for (var j = start; j < getIndex; j++) { if (level[i] == In[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (var i = 0; i < n; i++) { for (var j = getIndex + 1; j <= end; j++) { if (level[i] == In[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(In, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(In, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel = null; newLeftLevel = null; // return height return height;} // Driver Codevar In = [4, 8, 10, 12, 14, 20, 22];var level = [20, 8, 22, 4, 12, 10, 14];var n = In.length;height = 0;document.write(getHeight(In, level, 0, n - 1, n)); </script>
Output:
4
Rajput-Ji
princi singh
Harshraj22
famously
Binary Tree
Inorder Traversal
tree-level-order
Arrays
Tree
Arrays
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Write a Program to Find the Maximum Depth or Height of a Tree
|
[
{
"code": null,
"e": 26687,
"s": 26659,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 26829,
"s": 26687,
"text": "Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. "
},
{
"code": null,
"e": 26840,
"s": 26829,
"text": "Example: "
},
{
"code": null,
"e": 27121,
"s": 26840,
"text": "Input : Input: Two arrays that represent Inorder\n and level order traversals of a \n Binary Tree\n in[] = {4, 8, 10, 12, 14, 20, 22};\n level[] = {20, 8, 22, 4, 12, 10, 14};\nOutput : 4\n\nThe binary tree that can be constructed from the \ngiven traversals is:"
},
{
"code": null,
"e": 27194,
"s": 27121,
"text": "We can clearly see in the above image that the \nheight of the tree is 4."
},
{
"code": null,
"e": 27751,
"s": 27194,
"text": "The approach to calculating height is similar to the approach discussed in the post Constructing Tree from Inorder and Level Order Traversals.Let us consider the above example.in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14};In a Levelorder sequence, the first element is the root of the tree. So we know ’20’ is root for given sequences. By searching ’20’ in Inorder sequence, we can find out all elements on the left side of ‘20’ are in left subtree and elements on right are in the right subtree. So we know below structure now. "
},
{
"code": null,
"e": 27834,
"s": 27751,
"text": " 20\n / \\\n / \\ \n {4, 8, 10, 12, 14} {22} "
},
{
"code": null,
"e": 28354,
"s": 27834,
"text": "Let us call {4, 8, 10, 12, 14} as left subarray in Inorder traversal and {22} as right subarray in Inorder traversal. In level order traversal, keys of left and right subtrees are not consecutive. So we extract all nodes from level order traversal which are in left subarray of Inorder traversal. To calculate the height of the left subtree of the root, we recur for the extracted elements from level order traversal and left subarray of inorder traversal. In the above example, we recur for the following two arrays. "
},
{
"code": null,
"e": 28491,
"s": 28354,
"text": "// Recur for following arrays to \n// calculate the height of the left subtree\nIn[] = {4, 8, 10, 12, 14}\nlevel[] = {8, 4, 12, 10, 14} "
},
{
"code": null,
"e": 28587,
"s": 28491,
"text": "Similarly, we recur for the following two arrays and calculate the height of the right subtree."
},
{
"code": null,
"e": 28692,
"s": 28587,
"text": "// Recur for following arrays to calculate\n// height of the right subtree\nIn[] = {22}\nlevel[] = {22} "
},
{
"code": null,
"e": 28745,
"s": 28692,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28749,
"s": 28745,
"text": "C++"
},
{
"code": null,
"e": 28754,
"s": 28749,
"text": "Java"
},
{
"code": null,
"e": 28762,
"s": 28754,
"text": "Python3"
},
{
"code": null,
"e": 28765,
"s": 28762,
"text": "C#"
},
{
"code": null,
"e": 28776,
"s": 28765,
"text": "Javascript"
},
{
"code": "// C++ program to caulate height of Binary Tree// from InOrder and LevelOrder Traversals#include <iostream>using namespace std; /* Function to find index of value in the InOrder Traversal array */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treeint getHeight(int in[], int level[], int start, int end, int& height, int n){ // Base Case if (start > end) return 0; // Get index of current root in InOrder Traversal int getIndex = search(in, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int* newLeftLevel = new int[leftCount]; int* newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == in[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == in[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate height of left Subtree if (leftCount > 0) lheight = getHeight(in, newLeftLevel, start, getIndex - 1, height, leftCount); // Recursively call to calculate height of right Subtree if (rightCount > 0) rheight = getHeight(in, newRightLevel, getIndex + 1, end, height, rightCount); // Current height height = max(lheight + 1, rheight + 1); // Delete Auxiliary arrays delete[] newRightLevel; delete[] newLeftLevel; // return height return height;} // Driver program to test above functionsint main(){ int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); int h = 0; cout << getHeight(in, level, 0, n - 1, h, n); return 0;}",
"e": 31312,
"s": 28776,
"text": null
},
{
"code": "// Java program to caulate height of Binary Tree// from InOrder and LevelOrder Traversalsimport java.util.*;class GFG{static int height; /* Function to find index of valuein the InOrder Traversal array */static int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treestatic int getHeight(int in[], int level[], int start, int end, int n){ // Base Case if (start > end) return 0; // Get index of current root in InOrder Traversal int getIndex = search(in, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int []newLeftLevel = new int[leftCount]; int []newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == in[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == in[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(in, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(in, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel=null; newLeftLevel=null; // return height return height;} // Driver program to test above functionspublic static void main(String[] args){ int in[] = {4, 8, 10, 12, 14, 20, 22}; int level[] = {20, 8, 22, 4, 12, 10, 14}; int n = in.length; height = 0; System.out.println(getHeight(in, level, 0, n - 1, n));}} // This code is contributed by Rajput-Ji",
"e": 33941,
"s": 31312,
"text": null
},
{
"code": "# Python3 program to calculate height of Binary Tree from# InOrder and LevelOrder Traversals '''Function to find the index of value in the InOrderTraversal list''' def search(arr, start, end, value): for i in range(start, end + 1): if arr[i] == value: return i return -1 '''Function to calculate the height of the Binary Tree'''def getHeight(inOrder, levelOrder, start, end, height, n): # Base Case if start > end: return 0 # Get Index of current root in InOrder Traversal getIndex = search(inOrder, start, end, levelOrder[0]) if getIndex == -1: return 0 # Count elements in Left Subtree leftCount = getIndex - start # Count elements in Right Subtree rightCount = end - getIndex # Declare two lists for left and right subtrees newLeftLevel = [None for _ in range(leftCount)] newRightLevel = [None for _ in range(rightCount)] lheight, rheight, k = 0, 0, 0 # Extract values from level order traversal list # for current left subtree for i in range(n): for j in range(start, getIndex): if levelOrder[i] == inOrder[j]: newLeftLevel[k] = levelOrder[i] k += 1 break k = 0 # Extract values from level order traversal list # for current right subtree for i in range(n): for j in range(getIndex + 1, end + 1): if levelOrder[i] == inOrder[j]: newRightLevel[k] = levelOrder[i] k += 1 break # Recursively call to calculate height # of left subtree if leftCount > 0: lheight = getHeight(inOrder, newLeftLevel, start, getIndex - 1, height, leftCount) # Recursively call to calculate height # of right subtree if rightCount > 0: rheight = getHeight(inOrder, newRightLevel, getIndex + 1, end, height, rightCount) # current height height = max(lheight + 1, rheight + 1) # return height return height # Driver Codeif __name__=='__main__': inOrder = [4, 8, 10, 12, 14, 20, 22] levelOrder = [20, 8, 22, 4, 12, 10, 14] n, h = len(inOrder), 0 print(getHeight(inOrder, levelOrder, 0, n - 1, h, n)) # This code is contributed by harshraj22",
"e": 36248,
"s": 33941,
"text": null
},
{
"code": "// C# program to caulate height of Binary Tree// from InOrder and LevelOrder Traversalsusing System;using System.Collections.Generic; class GFG{static int height; /* Function to find index of valuein the InOrder Traversal array */static int search(int []arr, int strt, int end, int value){ for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treestatic int getHeight(int []In, int []level, int start, int end, int n){ // Base Case if (start > end) return 0; // Get index of current root in // InOrder Traversal int getIndex = search(In, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree int leftCount = getIndex - start; // Count elements in right Subtree int rightCount = end - getIndex; // Declare two arrays for left and // right subtrees int []newLeftLevel = new int[leftCount]; int []newRightLevel = new int[rightCount]; int lheight = 0, rheight = 0; int k = 0; // Extract values from level order traversal array // for current left subtree for (int i = 0; i < n; i++) { for (int j = start; j < getIndex; j++) { if (level[i] == In[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (int i = 0; i < n; i++) { for (int j = getIndex + 1; j <= end; j++) { if (level[i] == In[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(In, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(In, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.Max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel = null; newLeftLevel = null; // return height return height;} // Driver Codepublic static void Main(String[] args){ int []In = {4, 8, 10, 12, 14, 20, 22}; int []level = {20, 8, 22, 4, 12, 10, 14}; int n = In.Length; height = 0; Console.WriteLine(getHeight(In, level, 0, n - 1, n));}} // This code is contributed by Princi Singh",
"e": 38892,
"s": 36248,
"text": null
},
{
"code": "<script> //Javascript program to caulate height of Binary Tree// from InOrder and LevelOrder Traversals var height = 0; /* Function to find index of valuein the InOrder Traversal array */function search(arr, strt, end, value){ for (var i = strt; i <= end; i++) if (arr[i] == value) return i; return -1;} // Function to calculate the height// of the Binary Treefunction getHeight(In, level, start, end, n){ // Base Case if (start > end) return 0; // Get index of current root in // InOrder Traversal var getIndex = search(In, start, end, level[0]); if (getIndex == -1) return 0; // Count elements in Left Subtree var leftCount = getIndex - start; // Count elements in right Subtree var rightCount = end - getIndex; // Declare two arrays for left and // right subtrees var newLeftLevel = Array(leftCount); var newRightLevel = Array(rightCount); var lheight = 0, rheight = 0; var k = 0; // Extract values from level order traversal array // for current left subtree for (var i = 0; i < n; i++) { for (var j = start; j < getIndex; j++) { if (level[i] == In[j]) { newLeftLevel[k] = level[i]; k++; break; } } } k = 0; // Extract values from level order traversal array // for current right subtree for (var i = 0; i < n; i++) { for (var j = getIndex + 1; j <= end; j++) { if (level[i] == In[j]) { newRightLevel[k] = level[i]; k++; break; } } } // Recursively call to calculate // height of left Subtree if (leftCount > 0) lheight = getHeight(In, newLeftLevel, start, getIndex - 1, leftCount); // Recursively call to calculate // height of right Subtree if (rightCount > 0) rheight = getHeight(In, newRightLevel, getIndex + 1, end, rightCount); // Current height height = Math.max(lheight + 1, rheight + 1); // Delete Auxiliary arrays newRightLevel = null; newLeftLevel = null; // return height return height;} // Driver Codevar In = [4, 8, 10, 12, 14, 20, 22];var level = [20, 8, 22, 4, 12, 10, 14];var n = In.length;height = 0;document.write(getHeight(In, level, 0, n - 1, n)); </script>",
"e": 41300,
"s": 38892,
"text": null
},
{
"code": null,
"e": 41310,
"s": 41300,
"text": "Output: "
},
{
"code": null,
"e": 41312,
"s": 41310,
"text": "4"
},
{
"code": null,
"e": 41324,
"s": 41314,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41337,
"s": 41324,
"text": "princi singh"
},
{
"code": null,
"e": 41348,
"s": 41337,
"text": "Harshraj22"
},
{
"code": null,
"e": 41357,
"s": 41348,
"text": "famously"
},
{
"code": null,
"e": 41369,
"s": 41357,
"text": "Binary Tree"
},
{
"code": null,
"e": 41387,
"s": 41369,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 41404,
"s": 41387,
"text": "tree-level-order"
},
{
"code": null,
"e": 41411,
"s": 41404,
"text": "Arrays"
},
{
"code": null,
"e": 41416,
"s": 41411,
"text": "Tree"
},
{
"code": null,
"e": 41423,
"s": 41416,
"text": "Arrays"
},
{
"code": null,
"e": 41428,
"s": 41423,
"text": "Tree"
},
{
"code": null,
"e": 41526,
"s": 41428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41594,
"s": 41526,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 41638,
"s": 41594,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 41686,
"s": 41638,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 41709,
"s": 41686,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 41741,
"s": 41709,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 41770,
"s": 41741,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 41805,
"s": 41770,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 41848,
"s": 41805,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 41881,
"s": 41848,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
Mastering Pandas Groupby. Understanding the Groupby Method | by Sadrach Pierre, Ph.D. | Towards Data Science
|
Pandas is a python library that provides tools for data transformation and statistical analysis. The ‘groupby’ method in pandas allows us to group large amounts of data and perform operations on these groups. In this post, we will discuss how to use the ‘groupby’ method in Pandas. For our purposes we will be using the WorldWide Corona Virus Dataset which can be found here.
Let’s get started!
First, let’s read the file called “2019-nCoV-cases-JHU.csv” into a Pandas data frame:
import pandas as pd df = pd.read_csv("2019-nCoV-cases-JHU.csv")
Next, let’s print the first five rows of data:
print(df.head())
To make things simple, let’s limit our data to only include records in the US:
df = df[df['Region'] == 'US'] #filter to only include US datadf.reset_index(inplace = True) #reset indexdel df['index'] # remove old indexprint(df.head())
We probably don’t need to consider the ‘Unassigned Location (From Diamond Princess)’ value of ‘Province’, so let’s also take that out as well:
df = df[df['Province'] != 'Unassigned Location (From Diamond Princess)']print(df.head())
Now, let’s also create a ‘State’ column by pulling the last two characters of the string values in the ‘Province’ column:
df['State'] = df['Province'].str[-2:]
We can do something similar to create a ‘County’ column. Let’s extract all characters of the string values in the ‘Province’ column excluding the last 4 characters:
df['County'] = df['Province'].str[:-4]print(df.head())
Next, let’s convert the date column into a Pandas ‘datetime’ :
df['Date'] = pd.to_datetime(df['Date'], format ='%m/%d/%Y %H:%M')
We’re now in a good position to perform some interesting ‘groupby’ operations. Let’s generate some statistics corresponding to the numerical column values, like deaths, confirmed cases, and recoveries, at the state level.
To do this, let’s first perform a ‘groupby’ on the state level:
gb = df.groupby('State')
Here, we’ve created a ‘groupby’’ object. The next thing we can do is pull a specific group. We can do this using the ‘get_group’ method. Let’s get the group corresponding to CA and set the index to be the date:
df_ca = gb.get_group('CA').set_index('Date')print(df_ca.head())
We can also iterate over the ‘groupby’ object and create a data frame containing a column for each state:
deaths = pd.DataFrame()for name, group in df.groupby('State'): if deaths.empty: deaths = group.set_index('Date')[["Deaths"]].rename(columns={"Deaths": name}) else: deaths = deaths.join(group.set_index('Date')[["Deaths"]].rename(columns={"Deaths": name}))
Let’s print the resulting data frame containing the grouped death statistics:
print(deaths.head())
Notice that this data contains a limited number of states. We can also use the describe method to get basic statics about our new data:
death_stats = deaths.describe()death_stats = death_stats.astype(int)print(death_stats)
Here, the count corresponds to the number of rows. We also have the mean, standard deviation, percentile, minimum, and maximum values for the number of deaths. Note that the newest record in this data corresponds to March 3, 2020, which was before the widespread outbreak in cases. We can define a function that automatically generates these statistics for a given numerical column:
def get_statistics(column_name): column_df = pd.DataFrame() for name, group in df.groupby('State'): if column_df.empty: column_df = group.set_index('Date')[[column_name]].rename(columns={column_name: name}) else: column_df = column_df.join(group.set_index('Date')[[column_name]].rename(columns={column_name: name})) column_df.fillna(0, inplace = True) column_stats = column_df.describe() column_stats = column_stats.astype(int) print(column_stats)
Let’s call this function with the ‘Confirmed’ column as input:
get_statistics("Confirmed")
And recovered:
get_statistics("Recovered")
We can also set the index to be the day number. Let’s create a day column and generate grouped statistics for the ‘Confirmed’ column using the day number as the index:
df['Day'] = df['Date'].dt.daydef get_statistics_day(column_name): column_df = pd.DataFrame() for name, group in df.groupby('State'): if column_df.empty: column_df = group.set_index('Day')[[column_name]].rename(columns={column_name: name}) else: column_df = column_df.join(group.set_index('Day')[[column_name]].rename(columns={column_name: name})) column_df.fillna(0, inplace = True) column_stats = column_df.describe() column_stats = column_stats.astype(int) print(column_stats)get_statistics_day("Confirmed")
These are statistics corresponding to daily confirmed cases across states. I’ll stop here but I encourage you to play around with the code and data. For example, you can try generating these statistics at the county level. All you would need to do is change ‘groupby(‘State’)’ to ‘groupby(‘County’)’.
To summarize, in this post we discussed how to use the Pandas ‘groupby’ method. We generated grouped statistics for US confirmed cases, recoveries and deaths caused by the Corona Virus. We generated these statistics using the date time values as well as day number values as indices. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 547,
"s": 171,
"text": "Pandas is a python library that provides tools for data transformation and statistical analysis. The ‘groupby’ method in pandas allows us to group large amounts of data and perform operations on these groups. In this post, we will discuss how to use the ‘groupby’ method in Pandas. For our purposes we will be using the WorldWide Corona Virus Dataset which can be found here."
},
{
"code": null,
"e": 566,
"s": 547,
"text": "Let’s get started!"
},
{
"code": null,
"e": 652,
"s": 566,
"text": "First, let’s read the file called “2019-nCoV-cases-JHU.csv” into a Pandas data frame:"
},
{
"code": null,
"e": 716,
"s": 652,
"text": "import pandas as pd df = pd.read_csv(\"2019-nCoV-cases-JHU.csv\")"
},
{
"code": null,
"e": 763,
"s": 716,
"text": "Next, let’s print the first five rows of data:"
},
{
"code": null,
"e": 780,
"s": 763,
"text": "print(df.head())"
},
{
"code": null,
"e": 859,
"s": 780,
"text": "To make things simple, let’s limit our data to only include records in the US:"
},
{
"code": null,
"e": 1014,
"s": 859,
"text": "df = df[df['Region'] == 'US'] #filter to only include US datadf.reset_index(inplace = True) #reset indexdel df['index'] # remove old indexprint(df.head())"
},
{
"code": null,
"e": 1157,
"s": 1014,
"text": "We probably don’t need to consider the ‘Unassigned Location (From Diamond Princess)’ value of ‘Province’, so let’s also take that out as well:"
},
{
"code": null,
"e": 1246,
"s": 1157,
"text": "df = df[df['Province'] != 'Unassigned Location (From Diamond Princess)']print(df.head())"
},
{
"code": null,
"e": 1368,
"s": 1246,
"text": "Now, let’s also create a ‘State’ column by pulling the last two characters of the string values in the ‘Province’ column:"
},
{
"code": null,
"e": 1406,
"s": 1368,
"text": "df['State'] = df['Province'].str[-2:]"
},
{
"code": null,
"e": 1571,
"s": 1406,
"text": "We can do something similar to create a ‘County’ column. Let’s extract all characters of the string values in the ‘Province’ column excluding the last 4 characters:"
},
{
"code": null,
"e": 1626,
"s": 1571,
"text": "df['County'] = df['Province'].str[:-4]print(df.head())"
},
{
"code": null,
"e": 1689,
"s": 1626,
"text": "Next, let’s convert the date column into a Pandas ‘datetime’ :"
},
{
"code": null,
"e": 1755,
"s": 1689,
"text": "df['Date'] = pd.to_datetime(df['Date'], format ='%m/%d/%Y %H:%M')"
},
{
"code": null,
"e": 1977,
"s": 1755,
"text": "We’re now in a good position to perform some interesting ‘groupby’ operations. Let’s generate some statistics corresponding to the numerical column values, like deaths, confirmed cases, and recoveries, at the state level."
},
{
"code": null,
"e": 2041,
"s": 1977,
"text": "To do this, let’s first perform a ‘groupby’ on the state level:"
},
{
"code": null,
"e": 2066,
"s": 2041,
"text": "gb = df.groupby('State')"
},
{
"code": null,
"e": 2277,
"s": 2066,
"text": "Here, we’ve created a ‘groupby’’ object. The next thing we can do is pull a specific group. We can do this using the ‘get_group’ method. Let’s get the group corresponding to CA and set the index to be the date:"
},
{
"code": null,
"e": 2341,
"s": 2277,
"text": "df_ca = gb.get_group('CA').set_index('Date')print(df_ca.head())"
},
{
"code": null,
"e": 2447,
"s": 2341,
"text": "We can also iterate over the ‘groupby’ object and create a data frame containing a column for each state:"
},
{
"code": null,
"e": 2722,
"s": 2447,
"text": "deaths = pd.DataFrame()for name, group in df.groupby('State'): if deaths.empty: deaths = group.set_index('Date')[[\"Deaths\"]].rename(columns={\"Deaths\": name}) else: deaths = deaths.join(group.set_index('Date')[[\"Deaths\"]].rename(columns={\"Deaths\": name}))"
},
{
"code": null,
"e": 2800,
"s": 2722,
"text": "Let’s print the resulting data frame containing the grouped death statistics:"
},
{
"code": null,
"e": 2821,
"s": 2800,
"text": "print(deaths.head())"
},
{
"code": null,
"e": 2957,
"s": 2821,
"text": "Notice that this data contains a limited number of states. We can also use the describe method to get basic statics about our new data:"
},
{
"code": null,
"e": 3044,
"s": 2957,
"text": "death_stats = deaths.describe()death_stats = death_stats.astype(int)print(death_stats)"
},
{
"code": null,
"e": 3427,
"s": 3044,
"text": "Here, the count corresponds to the number of rows. We also have the mean, standard deviation, percentile, minimum, and maximum values for the number of deaths. Note that the newest record in this data corresponds to March 3, 2020, which was before the widespread outbreak in cases. We can define a function that automatically generates these statistics for a given numerical column:"
},
{
"code": null,
"e": 3941,
"s": 3427,
"text": "def get_statistics(column_name): column_df = pd.DataFrame() for name, group in df.groupby('State'): if column_df.empty: column_df = group.set_index('Date')[[column_name]].rename(columns={column_name: name}) else: column_df = column_df.join(group.set_index('Date')[[column_name]].rename(columns={column_name: name})) column_df.fillna(0, inplace = True) column_stats = column_df.describe() column_stats = column_stats.astype(int) print(column_stats)"
},
{
"code": null,
"e": 4004,
"s": 3941,
"text": "Let’s call this function with the ‘Confirmed’ column as input:"
},
{
"code": null,
"e": 4032,
"s": 4004,
"text": "get_statistics(\"Confirmed\")"
},
{
"code": null,
"e": 4047,
"s": 4032,
"text": "And recovered:"
},
{
"code": null,
"e": 4075,
"s": 4047,
"text": "get_statistics(\"Recovered\")"
},
{
"code": null,
"e": 4243,
"s": 4075,
"text": "We can also set the index to be the day number. Let’s create a day column and generate grouped statistics for the ‘Confirmed’ column using the day number as the index:"
},
{
"code": null,
"e": 4819,
"s": 4243,
"text": "df['Day'] = df['Date'].dt.daydef get_statistics_day(column_name): column_df = pd.DataFrame() for name, group in df.groupby('State'): if column_df.empty: column_df = group.set_index('Day')[[column_name]].rename(columns={column_name: name}) else: column_df = column_df.join(group.set_index('Day')[[column_name]].rename(columns={column_name: name})) column_df.fillna(0, inplace = True) column_stats = column_df.describe() column_stats = column_stats.astype(int) print(column_stats)get_statistics_day(\"Confirmed\")"
},
{
"code": null,
"e": 5120,
"s": 4819,
"text": "These are statistics corresponding to daily confirmed cases across states. I’ll stop here but I encourage you to play around with the code and data. For example, you can try generating these statistics at the county level. All you would need to do is change ‘groupby(‘State’)’ to ‘groupby(‘County’)’."
}
] |
Puzzle 17 | (Ratio of Boys and Girls in a Country where people want only boys)
|
11 May, 2021
In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country?
Solution:Assumptions: Probability of having a boy or girl is same. Also, the probability of next kid being a boy doesn’t depend on history.
The problem can be solved by counting expected number of girls before a baby boy is born.
Let NG be the expected no. of girls before a boy is born
Let p be the probability that a child is girl and (1-p)
be probability that a child is boy.
NG can be written as sum of following infinite series.
NG = 0*(1-p) + 1*p*(1-p) + 2*p*p*(1-p) + 3*p*p*p*(1-p) + 4*p*p*p*p*(1-p) +.....
Putting p = 1/2 and (1-p) = 1/2 in above formula.
NG = 0*(1/2) + 1*(1/2)2 + 2*(1/2)3 + 3*(1/2)4 + 4*(1/2)5 + ...
1/2*NG = 0*(1/2)2 + 1*(1/2)3 + 2*(1/2)4 + 3*(1/2)5 + 4*(1/2)6 + ...
NG - NG/2 = 1*(1/2)2 + 1*(1/2)3 + 1*(1/2)4 + 1*(1/2)5 + 1*(1/2)6 + ...
Using sum formula of infinite geometrical progression with
ratio less than 1
NG/2 = (1/4)/(1-1/2) = 1/2
NG = 1
So Expected Number of number of girls = 1
Since the expected number of girls is 1 and there is always a baby boy, the expected ratio of boys and girls is 50:50
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VirajD
rtrjjadhav001
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 21 | (3 Ants and Triangle)
Puzzle 24 | (10 Coins Puzzle)
Container with Most Water
Puzzle | Set 35 (2 Eggs and 100 Floors)
Puzzle 31 | (Minimum cut Puzzle)
Puzzle | Heaven and Hell
Puzzle | 3 cuts to cut round cake into 8 equal pieces
Puzzle 27 | (Hourglasses Puzzle)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 198,
"s": 54,
"text": "In a country, all families want a boy. They keep having babies till a boy is born. What is the expected ratio of boys and girls in the country?"
},
{
"code": null,
"e": 342,
"s": 202,
"text": "Solution:Assumptions: Probability of having a boy or girl is same. Also, the probability of next kid being a boy doesn’t depend on history."
},
{
"code": null,
"e": 432,
"s": 342,
"text": "The problem can be solved by counting expected number of girls before a baby boy is born."
},
{
"code": null,
"e": 1099,
"s": 432,
"text": "\nLet NG be the expected no. of girls before a boy is born\n\nLet p be the probability that a child is girl and (1-p)\nbe probability that a child is boy.\n\nNG can be written as sum of following infinite series.\n\nNG = 0*(1-p) + 1*p*(1-p) + 2*p*p*(1-p) + 3*p*p*p*(1-p) + 4*p*p*p*p*(1-p) +.....\n\nPutting p = 1/2 and (1-p) = 1/2 in above formula.\n\nNG = 0*(1/2) + 1*(1/2)2 + 2*(1/2)3 + 3*(1/2)4 + 4*(1/2)5 + ...\n1/2*NG = 0*(1/2)2 + 1*(1/2)3 + 2*(1/2)4 + 3*(1/2)5 + 4*(1/2)6 + ...\n\nNG - NG/2 = 1*(1/2)2 + 1*(1/2)3 + 1*(1/2)4 + 1*(1/2)5 + 1*(1/2)6 + ...\n\nUsing sum formula of infinite geometrical progression with\nratio less than 1\nNG/2 = (1/4)/(1-1/2) = 1/2\n\nNG = 1\n"
},
{
"code": null,
"e": 1141,
"s": 1099,
"text": "So Expected Number of number of girls = 1"
},
{
"code": null,
"e": 1259,
"s": 1141,
"text": "Since the expected number of girls is 1 and there is always a baby boy, the expected ratio of boys and girls is 50:50"
},
{
"code": null,
"e": 1383,
"s": 1259,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 1390,
"s": 1383,
"text": "VirajD"
},
{
"code": null,
"e": 1404,
"s": 1390,
"text": "rtrjjadhav001"
},
{
"code": null,
"e": 1412,
"s": 1404,
"text": "Puzzles"
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Puzzles"
},
{
"code": null,
"e": 1518,
"s": 1420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1550,
"s": 1518,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 1602,
"s": 1550,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 1636,
"s": 1602,
"text": "Puzzle 21 | (3 Ants and Triangle)"
},
{
"code": null,
"e": 1666,
"s": 1636,
"text": "Puzzle 24 | (10 Coins Puzzle)"
},
{
"code": null,
"e": 1692,
"s": 1666,
"text": "Container with Most Water"
},
{
"code": null,
"e": 1732,
"s": 1692,
"text": "Puzzle | Set 35 (2 Eggs and 100 Floors)"
},
{
"code": null,
"e": 1765,
"s": 1732,
"text": "Puzzle 31 | (Minimum cut Puzzle)"
},
{
"code": null,
"e": 1790,
"s": 1765,
"text": "Puzzle | Heaven and Hell"
},
{
"code": null,
"e": 1844,
"s": 1790,
"text": "Puzzle | 3 cuts to cut round cake into 8 equal pieces"
}
] |
Efficient ways to compare a variable with multiple values
|
16 Jul, 2021
In this article, we will discuss the ways to compare a variable with values.
Method 1: The idea is to compare each variable individually to all the multiple values at a time.
Program 1:
C++
Java
Python3
C#
Javascript
// C++ program to compare one variable// with multiple variable#include <iostream>using namespace std; // Driver Codeint main(){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { cout << "Vowel"; } // Otherwise Consonant else { cout << "Consonant"; } return 0;}
// Java program to compare one variable// with multiple variableimport java.util.*; class GFG{ // Driver Codepublic static void main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { System.out.print("Vowel"); } // Otherwise Consonant else { System.out.print("Consonant"); } }} // This code is contributed by Rajput-Ji
# Python program to compare one variable# with multiple variable # Driver Codeif __name__ == '__main__': # Variable to be compared character = 'a'; # Compare the given variable # with vowel using or operator # Check for vowel if (character == ('a' or 'e' or 'i' or 'o' or 'u')): print("Vowel"); # Otherwise Consonant else: print("Consonant"); # This code contributed by shikhasingrajput
// C# program to compare one variable// with multiple variableusing System; class GFG{ // Driver Codepublic static void Main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { Console.Write("Vowel"); } // Otherwise Consonant else { Console.Write("Consonant"); }}} // This code is contributed by 29AjayKumar
<script> // Javascript program to compare one variable// with multiple variable // Variable to be comparedvar character = 'a'; // Compare the given variable// with vowel using || operator // Check for vowelif (character == ('a'. charCodeAt(0) || 'e'. charCodeAt(0) || 'i'. charCodeAt(0) || 'o'. charCodeAt(0) || 'u'. charCodeAt(0))){ document.write("Vowel");} // Otherwise Consonantelse{ document.write("Consonant");} // This code is contributed by SoumikMondal </script>
Consonant
Explanation:The above code gives the Wrong Answer or error as comparing variable in the above way is incorrect and it forced to code in the below way:
C++
Java
Python3
C#
Javascript
// C++ program to compare one variable// with multiple variable#include <iostream>using namespace std; // Driver Codeint main(){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel individually // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { cout << "Vowel"; } // Otherwise Consonant else { cout << "Consonant"; } return 0;}
// Java program to compare// one variable with multiple// variableimport java.util.*;class GFG{ // Driver Codepublic static void main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { System.out.print("Vowel"); } // Otherwise Consonant else { System.out.print("Consonant"); }}} // This code is contributed by 29AjayKumar
# Python3 program to compare# one variable with multiple# variable # Driver Codeif __name__ == '__main__': # Variable to be compared character = 'a'; # Compare the given variable # with vowel using or operator # Check for vowel if (character == 'a' or character == 'e' or character == 'i' or character == 'o' or character == 'u'): print("Vowel"); # Otherwise Consonant else: print("Consonant"); # This code contributed by Princi Singh
// C# program to compare// one variable with multiple// variableusing System;class GFG{ // Driver Codepublic static void Main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { Console.Write("Vowel"); } // Otherwise Consonant else { Console.Write("Consonant"); }}} // This code is contributed by gauravrajput1
<script> // javascript program to compare one variable// with multiple variable // Driver Code function checkCharacter(character){ // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { document.write("Vowel"); } // Otherwise Consonant else { document.write("Consonant"); }} // Driver Code checkCharacter('a'); // This code is contributed by bunnyram19.</script>
Vowel
Method 2 – using Bitmasking: Another approach is to check among multiple groups of values and then create a bitmask of the values and then check for that bit to be set.
Program 2:
C++
Java
Python3
C#
Javascript
// C++ program to compare a value// with multiple values#include <iostream>using namespace std; // Driver Codeint main(){ // Create bitmasks unsigned group_1 = (1 << 1) | (1 << 2) | (1 << 3); unsigned group_2 = (1 << 4) | (1 << 5) | (1 << 6); unsigned group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created bitmask if ((1 << value_to_check) & group_1) { cout << "found a match in group 1"; } if ((1 << value_to_check) & group_2) { cout << "found a match in group 2"; } if ((1 << value_to_check) & group_3) { cout << "found a match in group 3"; } return 0;}
// Java program to compare a value// with multiple valuesimport java.util.*;class GFG{ // Driver Codepublic static void main(String[] args){ // Create bitmasks int group_1 = (1 << 1) | (1 << 2) | (1 << 3); int group_2 = (1 << 4) | (1 << 5) | (1 << 6); int group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created bitmask if (((1 << value_to_check) & group_1) > 0) { System.out.print("found a match " + "in group 1"); } if (((1 << value_to_check) & group_2) > 0) { System.out.print("found a match " + "in group 2"); } if (((1 << value_to_check) & group_3) > 0) { System.out.print("found a match " + "in group 3"); }}} // This code is contributed by shikhasingrajput
# Python3 program to compare a value# with multiple values # Driver Codeif __name__ == '__main__': # Create bitmasks group_1 = (1 << 1) | (1 << 2) | (1 << 3) group_2 = (1 << 4) | (1 << 5) | (1 << 6) group_3 = (1 << 7) | (1 << 8) | (1 << 9) # Values to be checked value_to_check = 9 # Checking with created bitmask if (((1 << value_to_check) & group_1) > 0): print("found a match " + "in group 1") if (((1 << value_to_check) & group_2) > 0): print("found a match " + "in group 2") if (((1 << value_to_check) & group_3) > 0): print("found a match " + "in group 3") # This code is contributed by gauravrajput1
// C# program to compare a value// with multiple valuesusing System;class GFG{ // Driver Codepublic static void Main(String[] args){ // Create bitmasks int group_1 = (1 << 1) | (1 << 2) | (1 << 3); int group_2 = (1 << 4) | (1 << 5) | (1 << 6); int group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created // bitmask if (((1 << value_to_check) & group_1) > 0) { Console.Write("found a match " + "in group 1"); } if (((1 << value_to_check) & group_2) > 0) { Console.Write("found a match " + "in group 2"); } if (((1 << value_to_check) & group_3) > 0) { Console.Write("found a match " + "in group 3"); }}} // This code is contributed by gauravrajput1
<script> // JavaScript program to compare a value// with multiple values // Create bitmasks let group_1 = (1 << 1) | (1 << 2) | (1 << 3); let group_2 = (1 << 4) | (1 << 5) | (1 << 6); let group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked let value_to_check = 9; // Checking with created bitmask if (((1 << value_to_check) & group_1) > 0) { document.write("found a match " + "in group 1"); } if (((1 << value_to_check) & group_2) > 0) { document.write("found a match " + "in group 2"); } if (((1 << value_to_check) & group_3) > 0) { document.write("found a match " + "in group 3"); } // This code is contributed by unknown2108 </script>
found a match in group 3
Note: This approach works best for values that don’t exceed the natural size of your CPU. It would typically be 64 in modern times. The general solution to this problem using Template from C++11. Below is the program for the same:
Program 3:
C++
Python3
C#
// C++ program for comparing variable// with multiples variable#include <algorithm>#include <initializer_list>#include <iostream>using namespace std; template <typename T> // Function that checks given variable// v in the list lst[]bool is_in(const T& v, std::initializer_list<T> lst){ return (std::find(std::begin(lst), std::end(lst), v) != std::end(lst));} // Driver Codeint main(){ // Number to be compared int num = 10; // Compare with multiple variables if (is_in(num, { 1, 2, 3 })) cout << "Found in group" << endl; else cout << "Not in group" << endl; // Character to be compared char c = 'a'; // Compare with multiple variables if (is_in(c, { 'x', 'a', 'c' })) cout << "Found in group" << endl; else cout << "Not in group" << endl; return 0;}
# Python program for above approachimport math # Function that checks given variable# v in the list lst[]def is_in(v, lst): return v in lst # Driver Code # Number to be comparednum = 10 # Compare with multiple variablesif (is_in(num, [1, 2, 3] )): print("Found in group")else: print("Not in group") # Character to be comparedc = 'a' # Compare with multiple variablesif (is_in(c, ['x', 'a', 'c'] )): print("Found in group")else: print("Not in group") #This code is contributed by shubhamsingh10
// C# program for the above approachusing System;using System.Linq; public static class Extensions{ // Function that checks given variable // v in the list lst[] public static bool is_in<T>(this T[] array, T target) { return array.Contains(target); }} class GFG{ // Driver Codestatic public void Main (){ // Number to be compared int num = 10; int [] arr = { 1, 2, 3 }; // Compare with multiple variables if (arr.is_in(num)) Console.WriteLine("Found in group"); else Console.WriteLine("Not in group"); // Character to be compared char c = 'a'; char[] arr1 = { 'x', 'a', 'c' }; // Compare with multiple variables if (arr1.is_in(c)) Console.WriteLine("Found in group"); else Console.WriteLine("Not in group");}} // This code is contributed by shubhamsingh10
Not in group
Found in group
Note: It is not very efficient though when not used with primitive types. For std::string it will produce an error. This task became really easy with C++17, as it comes with Fold Expression. This is generally called Folding which helps to express the same idea with less code and it works well with any data type. Here, “||” operator to reduce all the Boolean results to a single one which is only False if all the comparison results False. Below is the program for the same:
Program 4:
C++
// C++ program for comparing variable// with multiple variables#include <algorithm>#include <initializer_list>#include <iostream>#include <string>using namespace std; template <typename First, typename... T> // Function that checks given variable// first in the list t[]bool is_in(First&& first, T&&... t){ return ((first == t) || ...);} // Driver Codeint main(){ // Number to be compared int num = 10; // Compare using template if (is_in(num, 1, 2, 3)) cout << "Found in group" << endl; else cout << "Not in group" << endl; // String to be compared string c = "abc"; // Compare using template if (is_in(c, "xyz", "bhy", "abc")) cout << "Found in group" << endl; else cout << "Not in group" << endl; return 0;}
Output:
29AjayKumar
GauravRajput1
princi singh
shikhasingrajput
Rajput-Ji
bunnyram19
SoumikMondal
unknown2108
SHUBHAMSINGH10
C-Variable Declaration and Scope
Articles
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "In this article, we will discuss the ways to compare a variable with values."
},
{
"code": null,
"e": 203,
"s": 105,
"text": "Method 1: The idea is to compare each variable individually to all the multiple values at a time."
},
{
"code": null,
"e": 214,
"s": 203,
"text": "Program 1:"
},
{
"code": null,
"e": 218,
"s": 214,
"text": "C++"
},
{
"code": null,
"e": 223,
"s": 218,
"text": "Java"
},
{
"code": null,
"e": 231,
"s": 223,
"text": "Python3"
},
{
"code": null,
"e": 234,
"s": 231,
"text": "C#"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "Javascript"
},
{
"code": "// C++ program to compare one variable// with multiple variable#include <iostream>using namespace std; // Driver Codeint main(){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { cout << \"Vowel\"; } // Otherwise Consonant else { cout << \"Consonant\"; } return 0;}",
"e": 723,
"s": 245,
"text": null
},
{
"code": "// Java program to compare one variable// with multiple variableimport java.util.*; class GFG{ // Driver Codepublic static void main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { System.out.print(\"Vowel\"); } // Otherwise Consonant else { System.out.print(\"Consonant\"); } }} // This code is contributed by Rajput-Ji",
"e": 1268,
"s": 723,
"text": null
},
{
"code": "# Python program to compare one variable# with multiple variable # Driver Codeif __name__ == '__main__': # Variable to be compared character = 'a'; # Compare the given variable # with vowel using or operator # Check for vowel if (character == ('a' or 'e' or 'i' or 'o' or 'u')): print(\"Vowel\"); # Otherwise Consonant else: print(\"Consonant\"); # This code contributed by shikhasingrajput",
"e": 1698,
"s": 1268,
"text": null
},
{
"code": "// C# program to compare one variable// with multiple variableusing System; class GFG{ // Driver Codepublic static void Main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == ('a' || 'e' || 'i' || 'o' || 'u')) { Console.Write(\"Vowel\"); } // Otherwise Consonant else { Console.Write(\"Consonant\"); }}} // This code is contributed by 29AjayKumar",
"e": 2230,
"s": 1698,
"text": null
},
{
"code": "<script> // Javascript program to compare one variable// with multiple variable // Variable to be comparedvar character = 'a'; // Compare the given variable// with vowel using || operator // Check for vowelif (character == ('a'. charCodeAt(0) || 'e'. charCodeAt(0) || 'i'. charCodeAt(0) || 'o'. charCodeAt(0) || 'u'. charCodeAt(0))){ document.write(\"Vowel\");} // Otherwise Consonantelse{ document.write(\"Consonant\");} // This code is contributed by SoumikMondal </script>",
"e": 2781,
"s": 2230,
"text": null
},
{
"code": null,
"e": 2791,
"s": 2781,
"text": "Consonant"
},
{
"code": null,
"e": 2942,
"s": 2791,
"text": "Explanation:The above code gives the Wrong Answer or error as comparing variable in the above way is incorrect and it forced to code in the below way:"
},
{
"code": null,
"e": 2946,
"s": 2942,
"text": "C++"
},
{
"code": null,
"e": 2951,
"s": 2946,
"text": "Java"
},
{
"code": null,
"e": 2959,
"s": 2951,
"text": "Python3"
},
{
"code": null,
"e": 2962,
"s": 2959,
"text": "C#"
},
{
"code": null,
"e": 2973,
"s": 2962,
"text": "Javascript"
},
{
"code": "// C++ program to compare one variable// with multiple variable#include <iostream>using namespace std; // Driver Codeint main(){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel individually // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { cout << \"Vowel\"; } // Otherwise Consonant else { cout << \"Consonant\"; } return 0;}",
"e": 3493,
"s": 2973,
"text": null
},
{
"code": "// Java program to compare// one variable with multiple// variableimport java.util.*;class GFG{ // Driver Codepublic static void main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { System.out.print(\"Vowel\"); } // Otherwise Consonant else { System.out.print(\"Consonant\"); }}} // This code is contributed by 29AjayKumar",
"e": 4045,
"s": 3493,
"text": null
},
{
"code": "# Python3 program to compare# one variable with multiple# variable # Driver Codeif __name__ == '__main__': # Variable to be compared character = 'a'; # Compare the given variable # with vowel using or operator # Check for vowel if (character == 'a' or character == 'e' or character == 'i' or character == 'o' or character == 'u'): print(\"Vowel\"); # Otherwise Consonant else: print(\"Consonant\"); # This code contributed by Princi Singh",
"e": 4552,
"s": 4045,
"text": null
},
{
"code": "// C# program to compare// one variable with multiple// variableusing System;class GFG{ // Driver Codepublic static void Main(String[] args){ // Variable to be compared char character = 'a'; // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { Console.Write(\"Vowel\"); } // Otherwise Consonant else { Console.Write(\"Consonant\"); }}} // This code is contributed by gauravrajput1",
"e": 5092,
"s": 4552,
"text": null
},
{
"code": "<script> // javascript program to compare one variable// with multiple variable // Driver Code function checkCharacter(character){ // Compare the given variable // with vowel using || operator // Check for vowel if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { document.write(\"Vowel\"); } // Otherwise Consonant else { document.write(\"Consonant\"); }} // Driver Code checkCharacter('a'); // This code is contributed by bunnyram19.</script>",
"e": 5640,
"s": 5092,
"text": null
},
{
"code": null,
"e": 5646,
"s": 5640,
"text": "Vowel"
},
{
"code": null,
"e": 5815,
"s": 5646,
"text": "Method 2 – using Bitmasking: Another approach is to check among multiple groups of values and then create a bitmask of the values and then check for that bit to be set."
},
{
"code": null,
"e": 5826,
"s": 5815,
"text": "Program 2:"
},
{
"code": null,
"e": 5830,
"s": 5826,
"text": "C++"
},
{
"code": null,
"e": 5835,
"s": 5830,
"text": "Java"
},
{
"code": null,
"e": 5843,
"s": 5835,
"text": "Python3"
},
{
"code": null,
"e": 5846,
"s": 5843,
"text": "C#"
},
{
"code": null,
"e": 5857,
"s": 5846,
"text": "Javascript"
},
{
"code": "// C++ program to compare a value// with multiple values#include <iostream>using namespace std; // Driver Codeint main(){ // Create bitmasks unsigned group_1 = (1 << 1) | (1 << 2) | (1 << 3); unsigned group_2 = (1 << 4) | (1 << 5) | (1 << 6); unsigned group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created bitmask if ((1 << value_to_check) & group_1) { cout << \"found a match in group 1\"; } if ((1 << value_to_check) & group_2) { cout << \"found a match in group 2\"; } if ((1 << value_to_check) & group_3) { cout << \"found a match in group 3\"; } return 0;}",
"e": 6561,
"s": 5857,
"text": null
},
{
"code": "// Java program to compare a value// with multiple valuesimport java.util.*;class GFG{ // Driver Codepublic static void main(String[] args){ // Create bitmasks int group_1 = (1 << 1) | (1 << 2) | (1 << 3); int group_2 = (1 << 4) | (1 << 5) | (1 << 6); int group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created bitmask if (((1 << value_to_check) & group_1) > 0) { System.out.print(\"found a match \" + \"in group 1\"); } if (((1 << value_to_check) & group_2) > 0) { System.out.print(\"found a match \" + \"in group 2\"); } if (((1 << value_to_check) & group_3) > 0) { System.out.print(\"found a match \" + \"in group 3\"); }}} // This code is contributed by shikhasingrajput",
"e": 7505,
"s": 6561,
"text": null
},
{
"code": "# Python3 program to compare a value# with multiple values # Driver Codeif __name__ == '__main__': # Create bitmasks group_1 = (1 << 1) | (1 << 2) | (1 << 3) group_2 = (1 << 4) | (1 << 5) | (1 << 6) group_3 = (1 << 7) | (1 << 8) | (1 << 9) # Values to be checked value_to_check = 9 # Checking with created bitmask if (((1 << value_to_check) & group_1) > 0): print(\"found a match \" + \"in group 1\") if (((1 << value_to_check) & group_2) > 0): print(\"found a match \" + \"in group 2\") if (((1 << value_to_check) & group_3) > 0): print(\"found a match \" + \"in group 3\") # This code is contributed by gauravrajput1",
"e": 8180,
"s": 7505,
"text": null
},
{
"code": "// C# program to compare a value// with multiple valuesusing System;class GFG{ // Driver Codepublic static void Main(String[] args){ // Create bitmasks int group_1 = (1 << 1) | (1 << 2) | (1 << 3); int group_2 = (1 << 4) | (1 << 5) | (1 << 6); int group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked int value_to_check = 9; // Checking with created // bitmask if (((1 << value_to_check) & group_1) > 0) { Console.Write(\"found a match \" + \"in group 1\"); } if (((1 << value_to_check) & group_2) > 0) { Console.Write(\"found a match \" + \"in group 2\"); } if (((1 << value_to_check) & group_3) > 0) { Console.Write(\"found a match \" + \"in group 3\"); }}} // This code is contributed by gauravrajput1",
"e": 9076,
"s": 8180,
"text": null
},
{
"code": "<script> // JavaScript program to compare a value// with multiple values // Create bitmasks let group_1 = (1 << 1) | (1 << 2) | (1 << 3); let group_2 = (1 << 4) | (1 << 5) | (1 << 6); let group_3 = (1 << 7) | (1 << 8) | (1 << 9); // Values to be checked let value_to_check = 9; // Checking with created bitmask if (((1 << value_to_check) & group_1) > 0) { document.write(\"found a match \" + \"in group 1\"); } if (((1 << value_to_check) & group_2) > 0) { document.write(\"found a match \" + \"in group 2\"); } if (((1 << value_to_check) & group_3) > 0) { document.write(\"found a match \" + \"in group 3\"); } // This code is contributed by unknown2108 </script>",
"e": 9949,
"s": 9076,
"text": null
},
{
"code": null,
"e": 9974,
"s": 9949,
"text": "found a match in group 3"
},
{
"code": null,
"e": 10205,
"s": 9974,
"text": "Note: This approach works best for values that don’t exceed the natural size of your CPU. It would typically be 64 in modern times. The general solution to this problem using Template from C++11. Below is the program for the same:"
},
{
"code": null,
"e": 10216,
"s": 10205,
"text": "Program 3:"
},
{
"code": null,
"e": 10220,
"s": 10216,
"text": "C++"
},
{
"code": null,
"e": 10228,
"s": 10220,
"text": "Python3"
},
{
"code": null,
"e": 10231,
"s": 10228,
"text": "C#"
},
{
"code": "// C++ program for comparing variable// with multiples variable#include <algorithm>#include <initializer_list>#include <iostream>using namespace std; template <typename T> // Function that checks given variable// v in the list lst[]bool is_in(const T& v, std::initializer_list<T> lst){ return (std::find(std::begin(lst), std::end(lst), v) != std::end(lst));} // Driver Codeint main(){ // Number to be compared int num = 10; // Compare with multiple variables if (is_in(num, { 1, 2, 3 })) cout << \"Found in group\" << endl; else cout << \"Not in group\" << endl; // Character to be compared char c = 'a'; // Compare with multiple variables if (is_in(c, { 'x', 'a', 'c' })) cout << \"Found in group\" << endl; else cout << \"Not in group\" << endl; return 0;}",
"e": 11092,
"s": 10231,
"text": null
},
{
"code": "# Python program for above approachimport math # Function that checks given variable# v in the list lst[]def is_in(v, lst): return v in lst # Driver Code # Number to be comparednum = 10 # Compare with multiple variablesif (is_in(num, [1, 2, 3] )): print(\"Found in group\")else: print(\"Not in group\") # Character to be comparedc = 'a' # Compare with multiple variablesif (is_in(c, ['x', 'a', 'c'] )): print(\"Found in group\")else: print(\"Not in group\") #This code is contributed by shubhamsingh10",
"e": 11603,
"s": 11092,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Linq; public static class Extensions{ // Function that checks given variable // v in the list lst[] public static bool is_in<T>(this T[] array, T target) { return array.Contains(target); }} class GFG{ // Driver Codestatic public void Main (){ // Number to be compared int num = 10; int [] arr = { 1, 2, 3 }; // Compare with multiple variables if (arr.is_in(num)) Console.WriteLine(\"Found in group\"); else Console.WriteLine(\"Not in group\"); // Character to be compared char c = 'a'; char[] arr1 = { 'x', 'a', 'c' }; // Compare with multiple variables if (arr1.is_in(c)) Console.WriteLine(\"Found in group\"); else Console.WriteLine(\"Not in group\");}} // This code is contributed by shubhamsingh10",
"e": 12501,
"s": 11603,
"text": null
},
{
"code": null,
"e": 12529,
"s": 12501,
"text": "Not in group\nFound in group"
},
{
"code": null,
"e": 13005,
"s": 12529,
"text": "Note: It is not very efficient though when not used with primitive types. For std::string it will produce an error. This task became really easy with C++17, as it comes with Fold Expression. This is generally called Folding which helps to express the same idea with less code and it works well with any data type. Here, “||” operator to reduce all the Boolean results to a single one which is only False if all the comparison results False. Below is the program for the same:"
},
{
"code": null,
"e": 13016,
"s": 13005,
"text": "Program 4:"
},
{
"code": null,
"e": 13020,
"s": 13016,
"text": "C++"
},
{
"code": "// C++ program for comparing variable// with multiple variables#include <algorithm>#include <initializer_list>#include <iostream>#include <string>using namespace std; template <typename First, typename... T> // Function that checks given variable// first in the list t[]bool is_in(First&& first, T&&... t){ return ((first == t) || ...);} // Driver Codeint main(){ // Number to be compared int num = 10; // Compare using template if (is_in(num, 1, 2, 3)) cout << \"Found in group\" << endl; else cout << \"Not in group\" << endl; // String to be compared string c = \"abc\"; // Compare using template if (is_in(c, \"xyz\", \"bhy\", \"abc\")) cout << \"Found in group\" << endl; else cout << \"Not in group\" << endl; return 0;}",
"e": 13799,
"s": 13020,
"text": null
},
{
"code": null,
"e": 13809,
"s": 13799,
"text": "Output: "
},
{
"code": null,
"e": 13823,
"s": 13811,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13837,
"s": 13823,
"text": "GauravRajput1"
},
{
"code": null,
"e": 13850,
"s": 13837,
"text": "princi singh"
},
{
"code": null,
"e": 13867,
"s": 13850,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 13877,
"s": 13867,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13888,
"s": 13877,
"text": "bunnyram19"
},
{
"code": null,
"e": 13901,
"s": 13888,
"text": "SoumikMondal"
},
{
"code": null,
"e": 13913,
"s": 13901,
"text": "unknown2108"
},
{
"code": null,
"e": 13928,
"s": 13913,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 13961,
"s": 13928,
"text": "C-Variable Declaration and Scope"
},
{
"code": null,
"e": 13970,
"s": 13961,
"text": "Articles"
},
{
"code": null,
"e": 13974,
"s": 13970,
"text": "C++"
},
{
"code": null,
"e": 13987,
"s": 13974,
"text": "C++ Programs"
},
{
"code": null,
"e": 13991,
"s": 13987,
"text": "CPP"
},
{
"code": null,
"e": 14089,
"s": 13991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14115,
"s": 14089,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 14162,
"s": 14115,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 14183,
"s": 14162,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 14219,
"s": 14183,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 14262,
"s": 14219,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 14280,
"s": 14262,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 14323,
"s": 14280,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 14369,
"s": 14323,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 14392,
"s": 14369,
"text": "std::sort() in C++ STL"
}
] |
How to implement user defined Shared Pointers in C++
|
28 Oct, 2020
Shared Pointers : A std::shared_ptr is a container for raw pointers. It is a reference counting ownership model i.e. it maintains the reference count of its contained pointer in cooperation with all copies of the std::shared_ptr. So, the counter is incremented each time a new pointer points to the resource and decremented when destructor of the object is called.Reference Counting : It is a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources.An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of std::shared_ptr have been deleted.When to use: We should use shared_ptr when we want to assign one raw pointer to multiple owners.For more information and details about shared and other smart pointers, please read here. User Defined Implementation of Shared pointers:Program:
CPP
#include <iostream>using namespace std; // Class representing a reference counter classclass Counter{public: // Constructor Counter() : m_counter(0){}; Counter(const Counter&) = delete; Counter& operator=(const Counter&) = delete; // Destructor ~Counter() {} void reset() { m_counter = 0; } unsigned int get() { return m_counter; } // Overload post/pre increment void operator++() { m_counter++; } void operator++(int) { m_counter++; } // Overload post/pre decrement void operator--() { m_counter--; } void operator--(int) { m_counter--; } // Overloading << operator friend ostream& operator<<(ostream& os, const Counter& counter) { os << "Counter Value : " << counter.m_counter << endl; return os; } private: unsigned int m_counter{};}; // Class representing a shared pointertemplate <typename T> class Shared_ptr{public: // Constructor explicit Shared_ptr(T* ptr = nullptr) { m_ptr = ptr; m_counter = new Counter(); if (ptr) { (*m_counter)++; } } // Copy constructor Shared_ptr(Shared_ptr<T>& sp) { m_ptr = sp.m_ptr; m_counter = sp.m_counter; (*m_counter)++; } // Reference count unsigned int use_count() { return m_counter->get(); } // Get the pointer T* get() { return m_ptr; } // Overload * operator T& operator*() { return *m_ptr; } // Overload -> operator T* operator->() { return m_ptr; } // Destructor ~Shared_ptr() { (*m_counter)--; if (m_counter->get() == 0) { delete m_counter; delete m_ptr; } } friend ostream& operator<<(ostream& os, Shared_ptr<T>& sp) { os << "Address pointed : " << sp.get() << endl; os << *(sp.m_counter) << endl; return os; } private: // Reference counter Counter* m_counter; // Shared pointer T* m_ptr;}; int main(){ // ptr1 pointing to an integer. Shared_ptr<int> ptr1(new int(151)); cout << "--- Shared pointers ptr1 ---\n"; *ptr1 = 100; cout << " ptr1's value now: " << *ptr1 << endl; cout << ptr1; { // ptr2 pointing to same integer // which ptr1 is pointing to // Shared pointer reference counter // should have increased now to 2. Shared_ptr<int> ptr2 = ptr1; cout << "--- Shared pointers ptr1, ptr2 ---\n"; cout << ptr1; cout << ptr2; { // ptr3 pointing to same integer // which ptr1 and ptr2 are pointing to. // Shared pointer reference counter // should have increased now to 3. Shared_ptr<int> ptr3(ptr2); cout << "--- Shared pointers ptr1, ptr2, ptr3 " "---\n"; cout << ptr1; cout << ptr2; cout << ptr3; } // ptr3 is out of scope. // It would have been destructed. // So shared pointer reference counter // should have decreased now to 2. cout << "--- Shared pointers ptr1, ptr2 ---\n"; cout << ptr1; cout << ptr2; } // ptr2 is out of scope. // It would have been destructed. // So shared pointer reference counter // should have decreased now to 1. cout << "--- Shared pointers ptr1 ---\n"; cout << ptr1; return 0;}
--- Shared pointers ptr1 ---
Address pointed : 0x1cbde70
Counter Value : 1
--- Shared pointers ptr1, ptr2 ---
Address pointed : 0x1cbde70
Counter Value : 2
Address pointed : 0x1cbde70
Counter Value : 2
--- Shared pointers ptr1, ptr2, ptr3 ---
Address pointed : 0x1cbde70
Counter Value : 3
Address pointed : 0x1cbde70
Counter Value : 3
Address pointed : 0x1cbde70
Counter Value : 3
--- Shared pointers ptr1, ptr2 ---
Address pointed : 0x1cbde70
Counter Value : 2
Address pointed : 0x1cbde70
Counter Value : 2
--- Shared pointers ptr1 ---
Address pointed : 0x1cbde70
Counter Value : 1
prakashgibbi
vipugpta
C Basics
cpp-pointer
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 1009,
"s": 52,
"text": "Shared Pointers : A std::shared_ptr is a container for raw pointers. It is a reference counting ownership model i.e. it maintains the reference count of its contained pointer in cooperation with all copies of the std::shared_ptr. So, the counter is incremented each time a new pointer points to the resource and decremented when destructor of the object is called.Reference Counting : It is a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources.An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of std::shared_ptr have been deleted.When to use: We should use shared_ptr when we want to assign one raw pointer to multiple owners.For more information and details about shared and other smart pointers, please read here. User Defined Implementation of Shared pointers:Program: "
},
{
"code": null,
"e": 1013,
"s": 1009,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; // Class representing a reference counter classclass Counter{public: // Constructor Counter() : m_counter(0){}; Counter(const Counter&) = delete; Counter& operator=(const Counter&) = delete; // Destructor ~Counter() {} void reset() { m_counter = 0; } unsigned int get() { return m_counter; } // Overload post/pre increment void operator++() { m_counter++; } void operator++(int) { m_counter++; } // Overload post/pre decrement void operator--() { m_counter--; } void operator--(int) { m_counter--; } // Overloading << operator friend ostream& operator<<(ostream& os, const Counter& counter) { os << \"Counter Value : \" << counter.m_counter << endl; return os; } private: unsigned int m_counter{};}; // Class representing a shared pointertemplate <typename T> class Shared_ptr{public: // Constructor explicit Shared_ptr(T* ptr = nullptr) { m_ptr = ptr; m_counter = new Counter(); if (ptr) { (*m_counter)++; } } // Copy constructor Shared_ptr(Shared_ptr<T>& sp) { m_ptr = sp.m_ptr; m_counter = sp.m_counter; (*m_counter)++; } // Reference count unsigned int use_count() { return m_counter->get(); } // Get the pointer T* get() { return m_ptr; } // Overload * operator T& operator*() { return *m_ptr; } // Overload -> operator T* operator->() { return m_ptr; } // Destructor ~Shared_ptr() { (*m_counter)--; if (m_counter->get() == 0) { delete m_counter; delete m_ptr; } } friend ostream& operator<<(ostream& os, Shared_ptr<T>& sp) { os << \"Address pointed : \" << sp.get() << endl; os << *(sp.m_counter) << endl; return os; } private: // Reference counter Counter* m_counter; // Shared pointer T* m_ptr;}; int main(){ // ptr1 pointing to an integer. Shared_ptr<int> ptr1(new int(151)); cout << \"--- Shared pointers ptr1 ---\\n\"; *ptr1 = 100; cout << \" ptr1's value now: \" << *ptr1 << endl; cout << ptr1; { // ptr2 pointing to same integer // which ptr1 is pointing to // Shared pointer reference counter // should have increased now to 2. Shared_ptr<int> ptr2 = ptr1; cout << \"--- Shared pointers ptr1, ptr2 ---\\n\"; cout << ptr1; cout << ptr2; { // ptr3 pointing to same integer // which ptr1 and ptr2 are pointing to. // Shared pointer reference counter // should have increased now to 3. Shared_ptr<int> ptr3(ptr2); cout << \"--- Shared pointers ptr1, ptr2, ptr3 \" \"---\\n\"; cout << ptr1; cout << ptr2; cout << ptr3; } // ptr3 is out of scope. // It would have been destructed. // So shared pointer reference counter // should have decreased now to 2. cout << \"--- Shared pointers ptr1, ptr2 ---\\n\"; cout << ptr1; cout << ptr2; } // ptr2 is out of scope. // It would have been destructed. // So shared pointer reference counter // should have decreased now to 1. cout << \"--- Shared pointers ptr1 ---\\n\"; cout << ptr1; return 0;}",
"e": 4559,
"s": 1013,
"text": null
},
{
"code": null,
"e": 5152,
"s": 4559,
"text": "--- Shared pointers ptr1 ---\nAddress pointed : 0x1cbde70\nCounter Value : 1\n\n--- Shared pointers ptr1, ptr2 ---\nAddress pointed : 0x1cbde70\nCounter Value : 2\n\nAddress pointed : 0x1cbde70\nCounter Value : 2\n\n--- Shared pointers ptr1, ptr2, ptr3 ---\nAddress pointed : 0x1cbde70\nCounter Value : 3\n\nAddress pointed : 0x1cbde70\nCounter Value : 3\n\nAddress pointed : 0x1cbde70\nCounter Value : 3\n\n--- Shared pointers ptr1, ptr2 ---\nAddress pointed : 0x1cbde70\nCounter Value : 2\n\nAddress pointed : 0x1cbde70\nCounter Value : 2\n\n--- Shared pointers ptr1 ---\nAddress pointed : 0x1cbde70\nCounter Value : 1\n\n"
},
{
"code": null,
"e": 5167,
"s": 5154,
"text": "prakashgibbi"
},
{
"code": null,
"e": 5176,
"s": 5167,
"text": "vipugpta"
},
{
"code": null,
"e": 5185,
"s": 5176,
"text": "C Basics"
},
{
"code": null,
"e": 5197,
"s": 5185,
"text": "cpp-pointer"
},
{
"code": null,
"e": 5201,
"s": 5197,
"text": "C++"
},
{
"code": null,
"e": 5205,
"s": 5201,
"text": "CPP"
},
{
"code": null,
"e": 5303,
"s": 5205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5327,
"s": 5303,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 5347,
"s": 5327,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5380,
"s": 5347,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 5424,
"s": 5380,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5449,
"s": 5424,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5494,
"s": 5449,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5542,
"s": 5494,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5559,
"s": 5542,
"text": "std::find in C++"
},
{
"code": null,
"e": 5603,
"s": 5559,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Python | sympy.expand() method
|
12 Jun, 2019
With the help of sympy.expand() method, we can expand the mathematical expressions in the form of variables by using sympy.expand() method.
Syntax : sympy.expand(expression)Return : Return mathematical expression.
Example #1 :In this example we can see that by using sympy.expand() method, we can get the mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol.
# import sympyfrom sympy import expand, symbols x, y = symbols('x y')gfg_exp = x + y # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2) print(exp)
Output :
x**2 + 2*x*y + y**2
Example #2 :
# import sympyfrom sympy import expand, symbols x, y, z = symbols('x y z')gfg_exp = x + y + z # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2) print(exp)
Output :
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "With the help of sympy.expand() method, we can expand the mathematical expressions in the form of variables by using sympy.expand() method."
},
{
"code": null,
"e": 242,
"s": 168,
"text": "Syntax : sympy.expand(expression)Return : Return mathematical expression."
},
{
"code": null,
"e": 440,
"s": 242,
"text": "Example #1 :In this example we can see that by using sympy.expand() method, we can get the mathematical expression with variables. Here we use symbols() method also to declare a variable as symbol."
},
{
"code": "# import sympyfrom sympy import expand, symbols x, y = symbols('x y')gfg_exp = x + y # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2) print(exp)",
"e": 597,
"s": 440,
"text": null
},
{
"code": null,
"e": 606,
"s": 597,
"text": "Output :"
},
{
"code": null,
"e": 626,
"s": 606,
"text": "x**2 + 2*x*y + y**2"
},
{
"code": null,
"e": 639,
"s": 626,
"text": "Example #2 :"
},
{
"code": "# import sympyfrom sympy import expand, symbols x, y, z = symbols('x y z')gfg_exp = x + y + z # Use sympy.expand() methodexp = sympy.expand(gfg_exp**2) print(exp)",
"e": 805,
"s": 639,
"text": null
},
{
"code": null,
"e": 814,
"s": 805,
"text": "Output :"
},
{
"code": null,
"e": 857,
"s": 814,
"text": "x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2"
},
{
"code": null,
"e": 863,
"s": 857,
"text": "SymPy"
},
{
"code": null,
"e": 870,
"s": 863,
"text": "Python"
}
] |
vector::empty() and vector::size() in C++ STL
|
09 Jun, 2022
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
The empty() function is used to check if the vector container is empty or not.Syntax :
vectorname.empty()
Parameters :
No parameters are passed.
Returns :
True, if vector is empty
False, Otherwise
Examples:
Input : myvector = 1, 2, 3, 4, 5
myvector.empty();
Output : False
Input : myvector = {}
myvector.empty();
Output : True
Time Complexity – Constant O(1)
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{}; if (myvector.empty()) { cout << "True"; } else { cout << "False"; } return 0;}
True
Application : Given a list of integers, find the sum of all the integers.
Input : 1, 5, 6, 3, 9, 2
Output : 26
Explanation - 1+5+6+3+9+2 = 26
Algorithm1. Check if the vector is empty, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the vector is empty. 3. Print the final value of the variable.
CPP
// CPP program to illustrate// Application of empty() function#include <iostream>#include <vector>using namespace std; int main(){ int sum = 0; vector<int> myvector{ 1, 5, 6, 3, 9, 2 }; while (!myvector.empty()) { sum = sum + myvector.back(); myvector.pop_back(); } cout << sum; return 0;}
26
size() function is used to return the size of the vector container or the number of elements in the vector container.Syntax :
vectorname.size()
Parameters :
No parameters are passed.
Returns :
Number of elements in the container.
Examples:
Input : myvector = 1, 2, 3, 4, 5
myvector.size();
Output : 5
Input : myvector = {}
myvector.size();
Output : 0
Time Complexity – Constant O(1)
Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed.
CPP
// CPP program to illustrate// Implementation of size() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; cout << myvector.size(); return 0;}
5
Why is empty() preferred over size()empty() function is often said to be preferred over the size() function due to some of these points-
empty() function does not use any comparison operators, thus it is more convenient to useempty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size().
empty() function does not use any comparison operators, thus it is more convenient to use
empty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size().
Application : Given a list of integers, find the sum of all the integers.
Input : 1, 5, 6, 3, 9, 2
Output : 26
Explanation - 1+5+6+3+9+2 = 26
Algorithm1. Check if the size of the vector is 0, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the size of the vector becomes 0. 3. Print the final value of the variable.
CPP
// CPP program to illustrate// Application of size() function#include <iostream>#include <vector>using namespace std; int main(){ int sum = 0; vector<int> myvector{ 1, 5, 6, 3, 9, 2 }; while (myvector.size() > 0) { sum = sum + myvector.back(); myvector.pop_back(); } cout << sum; return 0;}
26
We are required to be careful while using size().
For example, consider the following program:
C++
#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { "Geeks", "For", "Geeks" }; for (int i = 0 ; i <= vec.size() - 1 ; i++) cout << vec[i] << ' '; return 0;}
Geeks For Geeks
The above program works fine but now let us consider the following program:
C++
#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { "Geeks", "For", "Geeks" }; vec.clear(); for (int i = 0; i <= vec.size() - 1; i++) cout << vec[i] << ' '; cout << "Geeks For Geeks"; return 0;}
Output:
Segmentation Fault SIGEGV
By compiling the above program, we get Segmentation Fault (SIGSEGV) because the return type of size() is size_t which is an alias for unsigned long int.-> unsigned long int var = 0;-> cout << var – 1; // This will be equal to 18446744073709551615-> vector<data_type> vec;-> cout << vec.size() – 1; // This will also be equal to 18446744073709551615
so we are looping from i = 0 to i = 18446744073709551615 in the above program
Now consider the scenario where we are deleting elements from our initialized container and after a sequence of operations our container becomes empty and lastly, we are printing contents of our container using the above method. Definitely, it will lead to Segmentation Fault (SIGSEGV).
How to fix it?
It is advisable to typecast container.size() to integer type in order to avoid Segmentation Fault (SIGSEGV).
C++
#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { "Geeks", "For", "Geeks" }; // Clearing the vector // Now size is equal to 0 vec.clear(); // Typecasting vec.size() to int for (int i = 0; i < (int)vec.size() - 1; i++) cout << vec[i] << ' '; cout << "Geeks For Geeks"; return 0;} // This code is contributed by Bhuwanesh Nainwal
Geeks For Geeks
sunilpanda20022002
bhuwanesh
utkarshgupta110092
CPP-Library
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Virtual Function in C++
C++ Data Types
Templates in C++ with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 249,
"s": 52,
"text": "Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. "
},
{
"code": null,
"e": 337,
"s": 249,
"text": "The empty() function is used to check if the vector container is empty or not.Syntax : "
},
{
"code": null,
"e": 447,
"s": 337,
"text": "vectorname.empty()\nParameters :\nNo parameters are passed.\nReturns :\nTrue, if vector is empty\nFalse, Otherwise"
},
{
"code": null,
"e": 458,
"s": 447,
"text": "Examples: "
},
{
"code": null,
"e": 599,
"s": 458,
"text": "Input : myvector = 1, 2, 3, 4, 5\n myvector.empty();\nOutput : False\n\nInput : myvector = {}\n myvector.empty();\nOutput : True"
},
{
"code": null,
"e": 631,
"s": 599,
"text": "Time Complexity – Constant O(1)"
},
{
"code": null,
"e": 737,
"s": 631,
"text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed."
},
{
"code": null,
"e": 741,
"s": 737,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{}; if (myvector.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}",
"e": 1013,
"s": 741,
"text": null
},
{
"code": null,
"e": 1018,
"s": 1013,
"text": "True"
},
{
"code": null,
"e": 1093,
"s": 1018,
"text": "Application : Given a list of integers, find the sum of all the integers. "
},
{
"code": null,
"e": 1163,
"s": 1093,
"text": "Input : 1, 5, 6, 3, 9, 2\nOutput : 26\nExplanation - 1+5+6+3+9+2 = 26"
},
{
"code": null,
"e": 1380,
"s": 1163,
"text": "Algorithm1. Check if the vector is empty, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the vector is empty. 3. Print the final value of the variable."
},
{
"code": null,
"e": 1384,
"s": 1380,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of empty() function#include <iostream>#include <vector>using namespace std; int main(){ int sum = 0; vector<int> myvector{ 1, 5, 6, 3, 9, 2 }; while (!myvector.empty()) { sum = sum + myvector.back(); myvector.pop_back(); } cout << sum; return 0;}",
"e": 1709,
"s": 1384,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1709,
"text": "26"
},
{
"code": null,
"e": 1839,
"s": 1712,
"text": "size() function is used to return the size of the vector container or the number of elements in the vector container.Syntax : "
},
{
"code": null,
"e": 1943,
"s": 1839,
"text": "vectorname.size()\nParameters :\nNo parameters are passed.\nReturns :\nNumber of elements in the container."
},
{
"code": null,
"e": 1954,
"s": 1943,
"text": "Examples: "
},
{
"code": null,
"e": 2086,
"s": 1954,
"text": "Input : myvector = 1, 2, 3, 4, 5\n myvector.size();\nOutput : 5\n\nInput : myvector = {}\n myvector.size();\nOutput : 0"
},
{
"code": null,
"e": 2118,
"s": 2086,
"text": "Time Complexity – Constant O(1)"
},
{
"code": null,
"e": 2224,
"s": 2118,
"text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed."
},
{
"code": null,
"e": 2228,
"s": 2224,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of size() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector{ 1, 2, 3, 4, 5 }; cout << myvector.size(); return 0;}",
"e": 2445,
"s": 2228,
"text": null
},
{
"code": null,
"e": 2447,
"s": 2445,
"text": "5"
},
{
"code": null,
"e": 2585,
"s": 2447,
"text": "Why is empty() preferred over size()empty() function is often said to be preferred over the size() function due to some of these points- "
},
{
"code": null,
"e": 2853,
"s": 2585,
"text": "empty() function does not use any comparison operators, thus it is more convenient to useempty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size()."
},
{
"code": null,
"e": 2943,
"s": 2853,
"text": "empty() function does not use any comparison operators, thus it is more convenient to use"
},
{
"code": null,
"e": 3122,
"s": 2943,
"text": "empty() function is implemented in constant time, regardless of container type, whereas some implementations of size() function require O(n) time complexity such as list::size()."
},
{
"code": null,
"e": 3197,
"s": 3122,
"text": "Application : Given a list of integers, find the sum of all the integers. "
},
{
"code": null,
"e": 3267,
"s": 3197,
"text": "Input : 1, 5, 6, 3, 9, 2\nOutput : 26\nExplanation - 1+5+6+3+9+2 = 26"
},
{
"code": null,
"e": 3505,
"s": 3267,
"text": "Algorithm1. Check if the size of the vector is 0, if not add the back element to a variable initialized as 0, and pop the back element. 2. Repeat this step until the size of the vector becomes 0. 3. Print the final value of the variable."
},
{
"code": null,
"e": 3509,
"s": 3505,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of size() function#include <iostream>#include <vector>using namespace std; int main(){ int sum = 0; vector<int> myvector{ 1, 5, 6, 3, 9, 2 }; while (myvector.size() > 0) { sum = sum + myvector.back(); myvector.pop_back(); } cout << sum; return 0;}",
"e": 3832,
"s": 3509,
"text": null
},
{
"code": null,
"e": 3835,
"s": 3832,
"text": "26"
},
{
"code": null,
"e": 3885,
"s": 3835,
"text": "We are required to be careful while using size()."
},
{
"code": null,
"e": 3930,
"s": 3885,
"text": "For example, consider the following program:"
},
{
"code": null,
"e": 3934,
"s": 3930,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { \"Geeks\", \"For\", \"Geeks\" }; for (int i = 0 ; i <= vec.size() - 1 ; i++) cout << vec[i] << ' '; return 0;}",
"e": 4180,
"s": 3934,
"text": null
},
{
"code": null,
"e": 4197,
"s": 4180,
"text": "Geeks For Geeks "
},
{
"code": null,
"e": 4273,
"s": 4197,
"text": "The above program works fine but now let us consider the following program:"
},
{
"code": null,
"e": 4277,
"s": 4273,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { \"Geeks\", \"For\", \"Geeks\" }; vec.clear(); for (int i = 0; i <= vec.size() - 1; i++) cout << vec[i] << ' '; cout << \"Geeks For Geeks\"; return 0;}",
"e": 4568,
"s": 4277,
"text": null
},
{
"code": null,
"e": 4576,
"s": 4568,
"text": "Output:"
},
{
"code": null,
"e": 4602,
"s": 4576,
"text": "Segmentation Fault SIGEGV"
},
{
"code": null,
"e": 4953,
"s": 4602,
"text": "By compiling the above program, we get Segmentation Fault (SIGSEGV) because the return type of size() is size_t which is an alias for unsigned long int.-> unsigned long int var = 0;-> cout << var – 1; // This will be equal to 18446744073709551615-> vector<data_type> vec;-> cout << vec.size() – 1; // This will also be equal to 18446744073709551615"
},
{
"code": null,
"e": 5031,
"s": 4953,
"text": "so we are looping from i = 0 to i = 18446744073709551615 in the above program"
},
{
"code": null,
"e": 5318,
"s": 5031,
"text": "Now consider the scenario where we are deleting elements from our initialized container and after a sequence of operations our container becomes empty and lastly, we are printing contents of our container using the above method. Definitely, it will lead to Segmentation Fault (SIGSEGV)."
},
{
"code": null,
"e": 5333,
"s": 5318,
"text": "How to fix it?"
},
{
"code": null,
"e": 5442,
"s": 5333,
"text": "It is advisable to typecast container.size() to integer type in order to avoid Segmentation Fault (SIGSEGV)."
},
{
"code": null,
"e": 5446,
"s": 5442,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ // Initializing a vector of string type vector<string> vec = { \"Geeks\", \"For\", \"Geeks\" }; // Clearing the vector // Now size is equal to 0 vec.clear(); // Typecasting vec.size() to int for (int i = 0; i < (int)vec.size() - 1; i++) cout << vec[i] << ' '; cout << \"Geeks For Geeks\"; return 0;} // This code is contributed by Bhuwanesh Nainwal",
"e": 5898,
"s": 5446,
"text": null
},
{
"code": null,
"e": 5914,
"s": 5898,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 5933,
"s": 5914,
"text": "sunilpanda20022002"
},
{
"code": null,
"e": 5943,
"s": 5933,
"text": "bhuwanesh"
},
{
"code": null,
"e": 5962,
"s": 5943,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 5974,
"s": 5962,
"text": "CPP-Library"
},
{
"code": null,
"e": 5985,
"s": 5974,
"text": "cpp-vector"
},
{
"code": null,
"e": 5989,
"s": 5985,
"text": "STL"
},
{
"code": null,
"e": 5993,
"s": 5989,
"text": "C++"
},
{
"code": null,
"e": 5997,
"s": 5993,
"text": "STL"
},
{
"code": null,
"e": 6001,
"s": 5997,
"text": "CPP"
},
{
"code": null,
"e": 6099,
"s": 6001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6142,
"s": 6099,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6167,
"s": 6142,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 6201,
"s": 6167,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 6218,
"s": 6201,
"text": "Substring in C++"
},
{
"code": null,
"e": 6242,
"s": 6218,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 6296,
"s": 6242,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6320,
"s": 6296,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 6344,
"s": 6320,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 6359,
"s": 6344,
"text": "C++ Data Types"
}
] |
Make all strings from a given array equal by replacing minimum number of characters
|
08 Jun, 2021
Given an array of equal-length strings arr[], the task is to make all the strings of the array equal by replacing any character of a string with any other character, minimum number of times.
Examples:
Input: arr[] = { “west”, “east”, “wait” } Output: 3 Explanation: Replacing arr[0][1] with ‘a’ modifies arr[] to { “west”, “east”, “wait” }. Replacing arr[1][0] with ‘w’ modifies arr[] to { “wast”, “wast”, “wait” }. Replacing arr[2][2] with ‘s’ modifies arr[] to { “wast”, “wast”, “wast” }. Therefore, the required output is 3.
Input: arr[] = { “abcd”, “bcde”, “cdef” } Output: 8
Approach: The problem can be solved using Hashing. Follow the steps below to solve the problem:
Initialize a 2D array, say hash[][], where hash[i][j] stores the frequency of the character i present at the jth index of all the strings.
Traverse the array arr[] using variable i. For every ith string encountered, count the frequency of each distinct character of the string and store it into the hash[][] array.
Initialize a variable, say cntMinOp, to store the minimum count of operations required to make all the strings of the array equal.
Traverse the array hash[][] using variable i. For every ith column encountered, calculate the sum of the column, say Sum, the maximum element in the column, say Max, and update cntMinOp += (Sum – Max).
Finally, print the value of cntMinOp.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum count of// operations required to make all strings// equal by replacing characters of stringsint minOperation(string arr[], int N){ // Stores minimum count of operations // required to make all strings equal int cntMinOP = 0; // Stores length of the string int M = arr[0].length(); // hash[i][j]: Stores frequency of character // i present at j-th index of all strings int hash[256][M]; // Initialize hash[][] to 0 memset(hash, 0, sizeof(hash)); // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate over characters of // current string for (int j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i][j]][j]++; } } // Traverse hash[][] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codeint main(){ string arr[] = { "abcd", "bcde", "cdef" }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << minOperation(arr, N) << "\n";}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the minimum count of// operations required to make all Strings// equal by replacing characters of Stringsstatic int minOperation(String arr[], int N){ // Stores minimum count of operations // required to make all Strings equal int cntMinOP = 0; // Stores length of the String int M = arr[0].length(); // hash[i][j]: Stores frequency of character // i present at j-th index of all Strings int [][]hash = new int[256][M]; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate over characters of // current String for (int j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i].charAt(j)][j]++; } } // Traverse hash[][] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = Math.max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codepublic static void main(String[] args){ String arr[] = { "abcd", "bcde", "cdef" }; int N = arr.length; // Function call System.out.print(minOperation(arr, N)+ "\n");}} // This code is contributed by shikhasingrajput
# Python program to implement# the above approach # Function to find the minimum count of# operations required to make all Strings# equal by replacing characters of Stringsdef minOperation(arr, N): # Stores minimum count of operations # required to make all Strings equal cntMinOP = 0; # Stores length of the String M = len(arr[0]); # hash[i][j]: Stores frequency of character # i present at j-th index of all Strings hash = [[0 for i in range(M)] for j in range(256)]; # Traverse the array arr for i in range(N): # Iterate over characters of # current String for j in range(M): # Update frequency of # arr[i][j] hash[ord(arr[i][j])][j] += 1; # Traverse hash array for i in range(M): # Stores sum of i-th column Sum = 0; # Stores the largest element # of i-th column Max = 0; # Iterate over all possible # characters for j in range(256): # Update Sum Sum += hash[j][i]; # Update Max Max = max(Max, hash[j][i]); # Update cntMinOP cntMinOP += (Sum - Max); return cntMinOP; # Driver Codeif __name__ == '__main__': arr = ["abcd", "bcde", "cdef"]; N = len(arr); # Function call print(minOperation(arr, N)); # This code is contributed by 29AjayKumar
// C# program to implement// the above approachusing System;class GFG{ // Function to find the minimum count of// operations required to make all Strings// equal by replacing characters of Stringsstatic int minOperation(String []arr, int N){ // Stores minimum count of operations // required to make all Strings equal int cntMinOP = 0; // Stores length of the String int M = arr[0].Length; // hash[i,j]: Stores frequency of character // i present at j-th index of all Strings int [,]hash = new int[256, M]; // Traverse the array []arr for (int i = 0; i < N; i++) { // Iterate over characters of // current String for (int j = 0; j < M; j++) { // Update frequency of // arr[i,j] hash[arr[i][j], j]++; } } // Traverse hash[,] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j, i]; // Update Max Max = Math.Max(Max, hash[j, i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codepublic static void Main(String[] args){ String []arr = { "abcd", "bcde", "cdef" }; int N = arr.Length; // Function call Console.Write(minOperation(arr, N)+ "\n");}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to implement// the above approach // Function to find the minimum count of// operations required to make all strings// equal by replacing characters of stringsfunction minOperation(arr, N){ // Stores minimum count of operations // required to make all strings equal var cntMinOP = 0; // Stores length of the string var M = arr[0].length; // hash[i][j]: Stores frequency of character // i present at j-th index of all strings var hash = Array.from(Array(256), ()=>Array(M).fill(0)); // Traverse the array arr[] for (var i = 0; i < N; i++) { // Iterate over characters of // current string for (var j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i][j].charCodeAt(0)][j]++; } } // Traverse hash[][] array for (var i = 0; i < M; i++) { // Stores sum of i-th column var Sum = 0; // Stores the largest element // of i-th column var Max = 0; // Iterate over all possible // characters for (var j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = Math.max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Code var arr = ["abcd", "bcde", "cdef"];var N = arr.length; // Function calldocument.write( minOperation(arr, N) + "<br>"); </script>
8
Time Complexity:O(N * (M + 256)), where M is the length of the string Auxiliary Space:O(M + 256)
shikhasingrajput
29AjayKumar
noob2000
frequency-counting
Hash
interview-preparation
TCS-coding-questions
Arrays
Hash
Mathematical
Strings
Arrays
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "Given an array of equal-length strings arr[], the task is to make all the strings of the array equal by replacing any character of a string with any other character, minimum number of times."
},
{
"code": null,
"e": 255,
"s": 245,
"text": "Examples:"
},
{
"code": null,
"e": 582,
"s": 255,
"text": "Input: arr[] = { “west”, “east”, “wait” } Output: 3 Explanation: Replacing arr[0][1] with ‘a’ modifies arr[] to { “west”, “east”, “wait” }. Replacing arr[1][0] with ‘w’ modifies arr[] to { “wast”, “wast”, “wait” }. Replacing arr[2][2] with ‘s’ modifies arr[] to { “wast”, “wast”, “wast” }. Therefore, the required output is 3."
},
{
"code": null,
"e": 634,
"s": 582,
"text": "Input: arr[] = { “abcd”, “bcde”, “cdef” } Output: 8"
},
{
"code": null,
"e": 730,
"s": 634,
"text": "Approach: The problem can be solved using Hashing. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 869,
"s": 730,
"text": "Initialize a 2D array, say hash[][], where hash[i][j] stores the frequency of the character i present at the jth index of all the strings."
},
{
"code": null,
"e": 1045,
"s": 869,
"text": "Traverse the array arr[] using variable i. For every ith string encountered, count the frequency of each distinct character of the string and store it into the hash[][] array."
},
{
"code": null,
"e": 1176,
"s": 1045,
"text": "Initialize a variable, say cntMinOp, to store the minimum count of operations required to make all the strings of the array equal."
},
{
"code": null,
"e": 1378,
"s": 1176,
"text": "Traverse the array hash[][] using variable i. For every ith column encountered, calculate the sum of the column, say Sum, the maximum element in the column, say Max, and update cntMinOp += (Sum – Max)."
},
{
"code": null,
"e": 1416,
"s": 1378,
"text": "Finally, print the value of cntMinOp."
},
{
"code": null,
"e": 1467,
"s": 1416,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1471,
"s": 1467,
"text": "C++"
},
{
"code": null,
"e": 1476,
"s": 1471,
"text": "Java"
},
{
"code": null,
"e": 1484,
"s": 1476,
"text": "Python3"
},
{
"code": null,
"e": 1487,
"s": 1484,
"text": "C#"
},
{
"code": null,
"e": 1498,
"s": 1487,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum count of// operations required to make all strings// equal by replacing characters of stringsint minOperation(string arr[], int N){ // Stores minimum count of operations // required to make all strings equal int cntMinOP = 0; // Stores length of the string int M = arr[0].length(); // hash[i][j]: Stores frequency of character // i present at j-th index of all strings int hash[256][M]; // Initialize hash[][] to 0 memset(hash, 0, sizeof(hash)); // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate over characters of // current string for (int j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i][j]][j]++; } } // Traverse hash[][] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codeint main(){ string arr[] = { \"abcd\", \"bcde\", \"cdef\" }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << minOperation(arr, N) << \"\\n\";}",
"e": 3068,
"s": 1498,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the minimum count of// operations required to make all Strings// equal by replacing characters of Stringsstatic int minOperation(String arr[], int N){ // Stores minimum count of operations // required to make all Strings equal int cntMinOP = 0; // Stores length of the String int M = arr[0].length(); // hash[i][j]: Stores frequency of character // i present at j-th index of all Strings int [][]hash = new int[256][M]; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Iterate over characters of // current String for (int j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i].charAt(j)][j]++; } } // Traverse hash[][] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = Math.max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codepublic static void main(String[] args){ String arr[] = { \"abcd\", \"bcde\", \"cdef\" }; int N = arr.length; // Function call System.out.print(minOperation(arr, N)+ \"\\n\");}} // This code is contributed by shikhasingrajput",
"e": 4680,
"s": 3068,
"text": null
},
{
"code": "# Python program to implement# the above approach # Function to find the minimum count of# operations required to make all Strings# equal by replacing characters of Stringsdef minOperation(arr, N): # Stores minimum count of operations # required to make all Strings equal cntMinOP = 0; # Stores length of the String M = len(arr[0]); # hash[i][j]: Stores frequency of character # i present at j-th index of all Strings hash = [[0 for i in range(M)] for j in range(256)]; # Traverse the array arr for i in range(N): # Iterate over characters of # current String for j in range(M): # Update frequency of # arr[i][j] hash[ord(arr[i][j])][j] += 1; # Traverse hash array for i in range(M): # Stores sum of i-th column Sum = 0; # Stores the largest element # of i-th column Max = 0; # Iterate over all possible # characters for j in range(256): # Update Sum Sum += hash[j][i]; # Update Max Max = max(Max, hash[j][i]); # Update cntMinOP cntMinOP += (Sum - Max); return cntMinOP; # Driver Codeif __name__ == '__main__': arr = [\"abcd\", \"bcde\", \"cdef\"]; N = len(arr); # Function call print(minOperation(arr, N)); # This code is contributed by 29AjayKumar",
"e": 6083,
"s": 4680,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to find the minimum count of// operations required to make all Strings// equal by replacing characters of Stringsstatic int minOperation(String []arr, int N){ // Stores minimum count of operations // required to make all Strings equal int cntMinOP = 0; // Stores length of the String int M = arr[0].Length; // hash[i,j]: Stores frequency of character // i present at j-th index of all Strings int [,]hash = new int[256, M]; // Traverse the array []arr for (int i = 0; i < N; i++) { // Iterate over characters of // current String for (int j = 0; j < M; j++) { // Update frequency of // arr[i,j] hash[arr[i][j], j]++; } } // Traverse hash[,] array for (int i = 0; i < M; i++) { // Stores sum of i-th column int Sum = 0; // Stores the largest element // of i-th column int Max = 0; // Iterate over all possible // characters for (int j = 0; j < 256; j++) { // Update Sum Sum += hash[j, i]; // Update Max Max = Math.Max(Max, hash[j, i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Codepublic static void Main(String[] args){ String []arr = { \"abcd\", \"bcde\", \"cdef\" }; int N = arr.Length; // Function call Console.Write(minOperation(arr, N)+ \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 7664,
"s": 6083,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function to find the minimum count of// operations required to make all strings// equal by replacing characters of stringsfunction minOperation(arr, N){ // Stores minimum count of operations // required to make all strings equal var cntMinOP = 0; // Stores length of the string var M = arr[0].length; // hash[i][j]: Stores frequency of character // i present at j-th index of all strings var hash = Array.from(Array(256), ()=>Array(M).fill(0)); // Traverse the array arr[] for (var i = 0; i < N; i++) { // Iterate over characters of // current string for (var j = 0; j < M; j++) { // Update frequency of // arr[i][j] hash[arr[i][j].charCodeAt(0)][j]++; } } // Traverse hash[][] array for (var i = 0; i < M; i++) { // Stores sum of i-th column var Sum = 0; // Stores the largest element // of i-th column var Max = 0; // Iterate over all possible // characters for (var j = 0; j < 256; j++) { // Update Sum Sum += hash[j][i]; // Update Max Max = Math.max(Max, hash[j][i]); } // Update cntMinOP cntMinOP += (Sum - Max); } return cntMinOP;} // Driver Code var arr = [\"abcd\", \"bcde\", \"cdef\"];var N = arr.length; // Function calldocument.write( minOperation(arr, N) + \"<br>\"); </script>",
"e": 9155,
"s": 7664,
"text": null
},
{
"code": null,
"e": 9157,
"s": 9155,
"text": "8"
},
{
"code": null,
"e": 9256,
"s": 9159,
"text": "Time Complexity:O(N * (M + 256)), where M is the length of the string Auxiliary Space:O(M + 256)"
},
{
"code": null,
"e": 9273,
"s": 9256,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 9285,
"s": 9273,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9294,
"s": 9285,
"text": "noob2000"
},
{
"code": null,
"e": 9313,
"s": 9294,
"text": "frequency-counting"
},
{
"code": null,
"e": 9318,
"s": 9313,
"text": "Hash"
},
{
"code": null,
"e": 9340,
"s": 9318,
"text": "interview-preparation"
},
{
"code": null,
"e": 9361,
"s": 9340,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 9368,
"s": 9361,
"text": "Arrays"
},
{
"code": null,
"e": 9373,
"s": 9368,
"text": "Hash"
},
{
"code": null,
"e": 9386,
"s": 9373,
"text": "Mathematical"
},
{
"code": null,
"e": 9394,
"s": 9386,
"text": "Strings"
},
{
"code": null,
"e": 9401,
"s": 9394,
"text": "Arrays"
},
{
"code": null,
"e": 9406,
"s": 9401,
"text": "Hash"
},
{
"code": null,
"e": 9414,
"s": 9406,
"text": "Strings"
},
{
"code": null,
"e": 9427,
"s": 9414,
"text": "Mathematical"
},
{
"code": null,
"e": 9525,
"s": 9427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9593,
"s": 9525,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9637,
"s": 9593,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9669,
"s": 9637,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9717,
"s": 9669,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9731,
"s": 9717,
"text": "Linear Search"
},
{
"code": null,
"e": 9816,
"s": 9731,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 9854,
"s": 9816,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 9890,
"s": 9854,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 9921,
"s": 9890,
"text": "Hashing | Set 1 (Introduction)"
}
] |
How to join on multiple columns in Pyspark?
|
19 Dec, 2021
In this article, we will discuss how to join multiple columns in PySpark Dataframe using Python.
Let’s create the first dataframe:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()
Output:
Let’s create the second dataframe:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby"), (4, "rohith"), (5, "gnanesh")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) dataframe1.show()
Output:
we can join the multiple columns by using join() function using conditional operator
Syntax: dataframe.join(dataframe1, (dataframe.column1== dataframe1.column1) & (dataframe.column2== dataframe1.column2))
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
column1 is the first matching column in both the dataframes
column2 is the second matching column in both the dataframes
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby"), (4, "rohith"), (5, "gnanesh")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # join based on ID and name columndataframe.join(dataframe1, (dataframe.ID1 == dataframe1.ID2) & (dataframe.NAME1 == dataframe1.NAME2)).show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata = [(1, "sravan"), (2, "ojsawi"), (3, "bobby"), (4, "rohith"), (5, "gnanesh")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # join based on ID and name columndataframe.join(dataframe1, (dataframe.ID1 == dataframe1.ID2) | (dataframe.NAME1 == dataframe1.NAME2)).show()
Output:
Picked
Python-Pyspark
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": "\n19 Dec, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "In this article, we will discuss how to join multiple columns in PySpark Dataframe using Python."
},
{
"code": null,
"e": 159,
"s": 125,
"text": "Let’s create the first dataframe:"
},
{
"code": null,
"e": 167,
"s": 159,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()",
"e": 635,
"s": 167,
"text": null
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Output:"
},
{
"code": null,
"e": 678,
"s": 643,
"text": "Let’s create the second dataframe:"
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\"), (4, \"rohith\"), (5, \"gnanesh\")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) dataframe1.show()",
"e": 1201,
"s": 686,
"text": null
},
{
"code": null,
"e": 1209,
"s": 1201,
"text": "Output:"
},
{
"code": null,
"e": 1294,
"s": 1209,
"text": "we can join the multiple columns by using join() function using conditional operator"
},
{
"code": null,
"e": 1414,
"s": 1294,
"text": "Syntax: dataframe.join(dataframe1, (dataframe.column1== dataframe1.column1) & (dataframe.column2== dataframe1.column2))"
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "where, "
},
{
"code": null,
"e": 1455,
"s": 1422,
"text": "dataframe is the first dataframe"
},
{
"code": null,
"e": 1490,
"s": 1455,
"text": "dataframe1 is the second dataframe"
},
{
"code": null,
"e": 1550,
"s": 1490,
"text": "column1 is the first matching column in both the dataframes"
},
{
"code": null,
"e": 1611,
"s": 1550,
"text": "column2 is the second matching column in both the dataframes"
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\"), (4, \"rohith\"), (5, \"gnanesh\")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # join based on ID and name columndataframe.join(dataframe1, (dataframe.ID1 == dataframe1.ID2) & (dataframe.NAME1 == dataframe1.NAME2)).show()",
"e": 2488,
"s": 1619,
"text": null
},
{
"code": null,
"e": 2496,
"s": 2488,
"text": "Output:"
},
{
"code": null,
"e": 2504,
"s": 2496,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\")] # specify column namescolumns = ['ID1', 'NAME1'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # list of employee datadata = [(1, \"sravan\"), (2, \"ojsawi\"), (3, \"bobby\"), (4, \"rohith\"), (5, \"gnanesh\")] # specify column namescolumns = ['ID2', 'NAME2'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # join based on ID and name columndataframe.join(dataframe1, (dataframe.ID1 == dataframe1.ID2) | (dataframe.NAME1 == dataframe1.NAME2)).show()",
"e": 3373,
"s": 2504,
"text": null
},
{
"code": null,
"e": 3381,
"s": 3373,
"text": "Output:"
},
{
"code": null,
"e": 3388,
"s": 3381,
"text": "Picked"
},
{
"code": null,
"e": 3403,
"s": 3388,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 3410,
"s": 3403,
"text": "Python"
},
{
"code": null,
"e": 3508,
"s": 3410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3540,
"s": 3508,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3567,
"s": 3540,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3588,
"s": 3567,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3611,
"s": 3588,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3667,
"s": 3611,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3698,
"s": 3667,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3740,
"s": 3698,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3782,
"s": 3740,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3821,
"s": 3782,
"text": "Python | Get unique values from a list"
}
] |
Range Slider using Material UI in React
|
11 Feb, 2021
Material-UI is a React-based module. The Material-UI library provides users with the most efficient, effective, and user-friendly interface. For using the Range slider we need to install Material-UI. Moreover, for the custom styling, you can always refer to the API of the SVG icon component in Material-UI.
Prerequisites:
Basics of ReactJS
Already created ReactJS app
Below all the steps are described order wise to add colors to icons.
Installation:
Step 1: Before moving further, firstly we have to install the Material-UI module, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.
npm install @material-ui/core
Step 2: After installing the module, now open your App.js file which is present inside your project’s directory, under src folder, and delete the code present inside it.
Step 3: Now import React , useState ( for initial state of slider) from react and Slider from Material-UI module.
Step 4: In your app.js file, add this code snippet to import React , useState( for initial state of slider) from react and Slider from Material-UI module.
import React, { useState } from "react";
import { Slider } from "@material-ui/core";
The file structure of the project will look like:
Below is a sample program to illustrate the use of slider :
Example: Range slider for Current Temperature in the city.
Filename- src/App.js:
Javascript
//We use useState for the initial set valuesimport React, { useState } from "react";import "./App.css";//we import slider from material uiimport { Slider } from "@material-ui/core"; function App() { //Providing different values with labels const gfg = [ { value: 0, label: "0°C", }, { value: 25, label: "25°C", }, { value: 50, label: "50°C", }, { value: 100, label: "100°C", }, ]; const [val, setVal] = useState([0, 40]); const updateRange = (e, data) => { setVal(data); }; return ( <div className="App"> <h1> What is the current temperature in your City ? </h1> <div style={{ width: 500, margin: 60 }}> <span> Temperature : </span>{" "} <Slider value={val} onChange={updateRange} marks={gfg} /> </div>{" "} </div> );}export default App;
Filename- src/App.css:
CSS
body { margin: 0px;}.App { font-family: sans-serif; color: green; font-size: 16px;} span { color: red; font-size: 18px; font-weight: 13px; font-family: Verdana, Geneva, Tahoma, sans-serif; }
Output: Hence using the above-mentioned steps, we can use the Material-UI Slider to make a range slider in ReactJS.
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "Material-UI is a React-based module. The Material-UI library provides users with the most efficient, effective, and user-friendly interface. For using the Range slider we need to install Material-UI. Moreover, for the custom styling, you can always refer to the API of the SVG icon component in Material-UI."
},
{
"code": null,
"e": 351,
"s": 336,
"text": "Prerequisites:"
},
{
"code": null,
"e": 369,
"s": 351,
"text": "Basics of ReactJS"
},
{
"code": null,
"e": 397,
"s": 369,
"text": "Already created ReactJS app"
},
{
"code": null,
"e": 466,
"s": 397,
"text": "Below all the steps are described order wise to add colors to icons."
},
{
"code": null,
"e": 480,
"s": 466,
"text": "Installation:"
},
{
"code": null,
"e": 757,
"s": 480,
"text": "Step 1: Before moving further, firstly we have to install the Material-UI module, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder."
},
{
"code": null,
"e": 789,
"s": 757,
"text": "npm install @material-ui/core "
},
{
"code": null,
"e": 959,
"s": 789,
"text": "Step 2: After installing the module, now open your App.js file which is present inside your project’s directory, under src folder, and delete the code present inside it."
},
{
"code": null,
"e": 1073,
"s": 959,
"text": "Step 3: Now import React , useState ( for initial state of slider) from react and Slider from Material-UI module."
},
{
"code": null,
"e": 1229,
"s": 1073,
"text": "Step 4: In your app.js file, add this code snippet to import React , useState( for initial state of slider) from react and Slider from Material-UI module."
},
{
"code": null,
"e": 1314,
"s": 1229,
"text": "import React, { useState } from \"react\";\nimport { Slider } from \"@material-ui/core\";"
},
{
"code": null,
"e": 1364,
"s": 1314,
"text": "The file structure of the project will look like:"
},
{
"code": null,
"e": 1424,
"s": 1364,
"text": "Below is a sample program to illustrate the use of slider :"
},
{
"code": null,
"e": 1483,
"s": 1424,
"text": "Example: Range slider for Current Temperature in the city."
},
{
"code": null,
"e": 1505,
"s": 1483,
"text": "Filename- src/App.js:"
},
{
"code": null,
"e": 1516,
"s": 1505,
"text": "Javascript"
},
{
"code": "//We use useState for the initial set valuesimport React, { useState } from \"react\";import \"./App.css\";//we import slider from material uiimport { Slider } from \"@material-ui/core\"; function App() { //Providing different values with labels const gfg = [ { value: 0, label: \"0°C\", }, { value: 25, label: \"25°C\", }, { value: 50, label: \"50°C\", }, { value: 100, label: \"100°C\", }, ]; const [val, setVal] = useState([0, 40]); const updateRange = (e, data) => { setVal(data); }; return ( <div className=\"App\"> <h1> What is the current temperature in your City ? </h1> <div style={{ width: 500, margin: 60 }}> <span> Temperature : </span>{\" \"} <Slider value={val} onChange={updateRange} marks={gfg} /> </div>{\" \"} </div> );}export default App;",
"e": 2367,
"s": 1516,
"text": null
},
{
"code": null,
"e": 2390,
"s": 2367,
"text": "Filename- src/App.css:"
},
{
"code": null,
"e": 2394,
"s": 2390,
"text": "CSS"
},
{
"code": "body { margin: 0px;}.App { font-family: sans-serif; color: green; font-size: 16px;} span { color: red; font-size: 18px; font-weight: 13px; font-family: Verdana, Geneva, Tahoma, sans-serif; }",
"e": 2597,
"s": 2394,
"text": null
},
{
"code": null,
"e": 2713,
"s": 2597,
"text": "Output: Hence using the above-mentioned steps, we can use the Material-UI Slider to make a range slider in ReactJS."
},
{
"code": null,
"e": 2725,
"s": 2713,
"text": "Material-UI"
},
{
"code": null,
"e": 2741,
"s": 2725,
"text": "React-Questions"
},
{
"code": null,
"e": 2749,
"s": 2741,
"text": "ReactJS"
},
{
"code": null,
"e": 2766,
"s": 2749,
"text": "Web Technologies"
}
] |
How to Use Material Contextual ActionBar Library in Android App?
|
14 Sep, 2021
Let us first understand the two types of app bars in an android app:
The Regular AppBar
The Contextual AppBar
The Regular AppBar is just a normalized app bar that appears on the top of a page and can be well customized according to the user’s requirements. It can be used to display page topics/company names/etc., clickable icons, navigation to other pages, drawers, text fields, and various other actions. Now here lies a catch...
The regular top AppBar can be transformed anytime into a contextual action bar, which remains active until the action has been removed/completed. This transformation results in a new customized app bar, overlapping the regular app bar, until the action has terminated. Now let us have a glimpse at these images, demonstrating the two types of app bars:
Regular App Bar (Customized)
Above is just a regular app bar that has its own decorations.
Contextual Action Bar
This is a Contextual Action Bar for the selected set of item(s), having its own set of animations/additions (which are also set by the user itself!). The action bar provides a visual consistency to a page of any application. It guides the users towards the specified destination in a persistent, user-friendly way. There are multiple ways of customizing an ActionBar. In this article, we are going to create a mini-project, which very well demonstrates the use of the Material Contextual Action Bar in an Android application.
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: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello GFG!" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
We put an id to TextView widget, which we can refer to later with the id name “text_view“. The width and height of the app bar are adjusted to “wrap_content” and “match_parent” to provide a good visual appearance by resizing the widgets automatically according to their parent content(s). A random text “Hello GFG!”, sized at 30sp, is displayed at the center of the page, which will act as our action object, later.
Step 3: Create Vector Assets
Navigate to app > res > drawable. Right-click on “drawable” folder > New > Vector Asset. Choose any icon and customize according to liking, click on Next > Finish. Repeat this process one more time to create another icon of a different choice.
Step 4: Create a menu file and modify
Navigate to app > res. Right-click on res > New > Android Resource Directory.
Set Resource type to the menu. Click OK. This will create a new menu folder for you. Right-click on the menu folder > New > Menu Resource File.
Change the file name according to choice. Click OK. On the top right corner of the console, look for “Code | Split | Design“. Click on Code to modify the menu code.
Type in the following code:
XML
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/option_1" android:title="Option 1" android:icon="@drawable/ic_delete" /> <item android:id="@+id/option_2" android:title="Option 2" android:icon="@drawable/ic_baseline_share_24" /> </menu>
Note: “ic_delete” and “ic_baseline_share_24” are the vector assets created earlier (in step 3).
Step 5: Modify the MainActivity.java file, create Action Mode, generate the final output
Action Mode inside a Contextual Action Bar dedicates a specific action to be performed on a regular app bar, for example, which then transforms itself to a Contextual App Bar, as and when customized by the user itself. In other words, Action Mode temporarily changes the user interface for as long as the action is being executed. Take a look at what we are about to do now:
This here above, is the homepage of an application, with a regular app bar.
This now is a contextual app bar, transformed from the regular app bar on long-pressing the “Hello GFG!” text. Excited? Let us move on to the coding segment. Head to the already created MainActivity.java tab.
Go to the 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.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.view.ActionMode; public class MainActivity extends AppCompatActivity { private ActionMode myActMode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); textView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (myActMode != null) { return false; } myActMode = startSupportActionMode(myActModeCallback); return true; } }); } private ActionMode.Callback myActModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.example_menu, menu); mode.setTitle("Select option here"); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.option_1: Toast.makeText(MainActivity.this, "Selected Option 1", Toast.LENGTH_SHORT).show(); mode.finish(); return true; case R.id.option_2: Toast.makeText(MainActivity.this, "Selected Option 2", Toast.LENGTH_SHORT).show(); mode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { myActMode = null; } };}
Explanation:
Inside the onCreate() method, we first need a reference to our previously created text_view by accessing its id. To do this, we use:
TextView textView = findViewById(R.id.text_view);
Now we create a listener. I have created an onLongClick() listener here, which customizes the AppBar when the specified widget is long-pressed. For this, we type:
textView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(myActMode!=null){
return false;
}
myActMode=startSupportActionMode(myActModeCallback);
return true;
}
return true; signifies that the user has consumed the click listener, and does not want to activate any other click listener(s). The null check is used to verify whether the Action Mode (to be created in the next step) has already been activated so that we do not have to activate it again. For now, myActModeCallback can be well ignored.
Now we come to the important part. Using Action Mode. To do this, we create a private Action Mode variable with a user-defined name. In my case, the name is myActMode.
private ActionMode myActMode;
Moving to the next part, we have to initiate the required callback interface. To do this, we have the following callback segment.
private ActionMode.Callback myActModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.example_menu, menu);
mode.setTitle("Select option here");
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.option_1:
Toast.makeText(MainActivity.this, "Selected Option 1", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
case R.id.option_2:
Toast.makeText(MainActivity.this, "Selected Option 2", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
myActMode=null;
}
};
Since we have already created the callback functions (yet to be initialized and customized), we can pass myActModeCallback as an argument to startSupportActionMode() created in the previous step. The onCreateActionMode() is the method where we inflate our menu. To do this, we use:
mode.getMenuInflater().inflate(R.menu.example_menu, menu);
We do not need to code anything inside the onPrepareActionMode() method, since this method is called as and when the user wants to refresh the menu; certainly not the kind we want here! Coming to the next method, we of course need to tweak code into the onActionItemClicked() method, since this is the place that cares for our actions and dedicates it towards the Contextual Action Bar. Here we have:
switch (item.getItemId()) {
case R.id.option_1:
Toast.makeText(MainActivity.this, "Selected Option 1", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
case R.id.option_2:
Toast.makeText(MainActivity.this, "Selected Option 2", Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
return false;
}
I have decided to use a short Toast Message to be displayed at the bottom of the screen after an item (an icon, to be more specific) in the contextual action bar has been clicked. Of course, you can innovate new ideas too. Lastly, we arrive at the onDestroyActionMode() method, and set myActMode to null, so that the contextual app bar is closed after the action has terminated.
@Override
public void onDestroyActionMode(ActionMode mode) {
myActMode=null;
}
That was it! Now Run the android application by clicking on the button, using an Android Emulator or an external android device.
Output:
Project Link: Click Here
Blogathon-2021
Picked
Android
Blogathon
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
How to Create and Add Data to SQLite Database in Android?
How to Call or Consume External API in Spring Boot?
Re-rendering Components in ReactJS
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 123,
"s": 54,
"text": "Let us first understand the two types of app bars in an android app:"
},
{
"code": null,
"e": 142,
"s": 123,
"text": "The Regular AppBar"
},
{
"code": null,
"e": 164,
"s": 142,
"text": "The Contextual AppBar"
},
{
"code": null,
"e": 487,
"s": 164,
"text": "The Regular AppBar is just a normalized app bar that appears on the top of a page and can be well customized according to the user’s requirements. It can be used to display page topics/company names/etc., clickable icons, navigation to other pages, drawers, text fields, and various other actions. Now here lies a catch..."
},
{
"code": null,
"e": 840,
"s": 487,
"text": "The regular top AppBar can be transformed anytime into a contextual action bar, which remains active until the action has been removed/completed. This transformation results in a new customized app bar, overlapping the regular app bar, until the action has terminated. Now let us have a glimpse at these images, demonstrating the two types of app bars:"
},
{
"code": null,
"e": 869,
"s": 840,
"text": "Regular App Bar (Customized)"
},
{
"code": null,
"e": 931,
"s": 869,
"text": "Above is just a regular app bar that has its own decorations."
},
{
"code": null,
"e": 953,
"s": 931,
"text": "Contextual Action Bar"
},
{
"code": null,
"e": 1479,
"s": 953,
"text": "This is a Contextual Action Bar for the selected set of item(s), having its own set of animations/additions (which are also set by the user itself!). The action bar provides a visual consistency to a page of any application. It guides the users towards the specified destination in a persistent, user-friendly way. There are multiple ways of customizing an ActionBar. In this article, we are going to create a mini-project, which very well demonstrates the use of the Material Contextual Action Bar in an Android application."
},
{
"code": null,
"e": 1508,
"s": 1479,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1670,
"s": 1508,
"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": 1718,
"s": 1670,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1861,
"s": 1718,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1869,
"s": 1865,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello GFG!\" android:textSize=\"30sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2705,
"s": 1869,
"text": null
},
{
"code": null,
"e": 3121,
"s": 2705,
"text": "We put an id to TextView widget, which we can refer to later with the id name “text_view“. The width and height of the app bar are adjusted to “wrap_content” and “match_parent” to provide a good visual appearance by resizing the widgets automatically according to their parent content(s). A random text “Hello GFG!”, sized at 30sp, is displayed at the center of the page, which will act as our action object, later."
},
{
"code": null,
"e": 3150,
"s": 3121,
"text": "Step 3: Create Vector Assets"
},
{
"code": null,
"e": 3394,
"s": 3150,
"text": "Navigate to app > res > drawable. Right-click on “drawable” folder > New > Vector Asset. Choose any icon and customize according to liking, click on Next > Finish. Repeat this process one more time to create another icon of a different choice."
},
{
"code": null,
"e": 3432,
"s": 3394,
"text": "Step 4: Create a menu file and modify"
},
{
"code": null,
"e": 3510,
"s": 3432,
"text": "Navigate to app > res. Right-click on res > New > Android Resource Directory."
},
{
"code": null,
"e": 3654,
"s": 3510,
"text": "Set Resource type to the menu. Click OK. This will create a new menu folder for you. Right-click on the menu folder > New > Menu Resource File."
},
{
"code": null,
"e": 3819,
"s": 3654,
"text": "Change the file name according to choice. Click OK. On the top right corner of the console, look for “Code | Split | Design“. Click on Code to modify the menu code."
},
{
"code": null,
"e": 3847,
"s": 3819,
"text": "Type in the following code:"
},
{
"code": null,
"e": 3851,
"s": 3847,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/option_1\" android:title=\"Option 1\" android:icon=\"@drawable/ic_delete\" /> <item android:id=\"@+id/option_2\" android:title=\"Option 2\" android:icon=\"@drawable/ic_baseline_share_24\" /> </menu>",
"e": 4219,
"s": 3851,
"text": null
},
{
"code": null,
"e": 4315,
"s": 4219,
"text": "Note: “ic_delete” and “ic_baseline_share_24” are the vector assets created earlier (in step 3)."
},
{
"code": null,
"e": 4404,
"s": 4315,
"text": "Step 5: Modify the MainActivity.java file, create Action Mode, generate the final output"
},
{
"code": null,
"e": 4779,
"s": 4404,
"text": "Action Mode inside a Contextual Action Bar dedicates a specific action to be performed on a regular app bar, for example, which then transforms itself to a Contextual App Bar, as and when customized by the user itself. In other words, Action Mode temporarily changes the user interface for as long as the action is being executed. Take a look at what we are about to do now:"
},
{
"code": null,
"e": 4855,
"s": 4779,
"text": "This here above, is the homepage of an application, with a regular app bar."
},
{
"code": null,
"e": 5065,
"s": 4855,
"text": "This now is a contextual app bar, transformed from the regular app bar on long-pressing the “Hello GFG!” text. Excited? Let us move on to the coding segment. Head to the already created MainActivity.java tab. "
},
{
"code": null,
"e": 5255,
"s": 5065,
"text": "Go to the 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": 5260,
"s": 5255,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.view.ActionMode; public class MainActivity extends AppCompatActivity { private ActionMode myActMode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); textView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (myActMode != null) { return false; } myActMode = startSupportActionMode(myActModeCallback); return true; } }); } private ActionMode.Callback myActModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.example_menu, menu); mode.setTitle(\"Select option here\"); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.option_1: Toast.makeText(MainActivity.this, \"Selected Option 1\", Toast.LENGTH_SHORT).show(); mode.finish(); return true; case R.id.option_2: Toast.makeText(MainActivity.this, \"Selected Option 2\", Toast.LENGTH_SHORT).show(); mode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { myActMode = null; } };}",
"e": 7374,
"s": 5260,
"text": null
},
{
"code": null,
"e": 7387,
"s": 7374,
"text": "Explanation:"
},
{
"code": null,
"e": 7520,
"s": 7387,
"text": "Inside the onCreate() method, we first need a reference to our previously created text_view by accessing its id. To do this, we use:"
},
{
"code": null,
"e": 7570,
"s": 7520,
"text": "TextView textView = findViewById(R.id.text_view);"
},
{
"code": null,
"e": 7733,
"s": 7570,
"text": "Now we create a listener. I have created an onLongClick() listener here, which customizes the AppBar when the specified widget is long-pressed. For this, we type:"
},
{
"code": null,
"e": 8071,
"s": 7733,
"text": "textView.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n if(myActMode!=null){\n return false;\n }\n myActMode=startSupportActionMode(myActModeCallback);\n\n return true;\n }"
},
{
"code": null,
"e": 8410,
"s": 8071,
"text": "return true; signifies that the user has consumed the click listener, and does not want to activate any other click listener(s). The null check is used to verify whether the Action Mode (to be created in the next step) has already been activated so that we do not have to activate it again. For now, myActModeCallback can be well ignored."
},
{
"code": null,
"e": 8578,
"s": 8410,
"text": "Now we come to the important part. Using Action Mode. To do this, we create a private Action Mode variable with a user-defined name. In my case, the name is myActMode."
},
{
"code": null,
"e": 8608,
"s": 8578,
"text": "private ActionMode myActMode;"
},
{
"code": null,
"e": 8738,
"s": 8608,
"text": "Moving to the next part, we have to initiate the required callback interface. To do this, we have the following callback segment."
},
{
"code": null,
"e": 9944,
"s": 8738,
"text": "private ActionMode.Callback myActModeCallback = new ActionMode.Callback() {\n @Override\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n mode.getMenuInflater().inflate(R.menu.example_menu, menu);\n mode.setTitle(\"Select option here\");\n return true;\n }\n\n @Override\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n return false;\n }\n\n @Override\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\n switch (item.getItemId()) {\n case R.id.option_1:\n Toast.makeText(MainActivity.this, \"Selected Option 1\", Toast.LENGTH_SHORT).show();\n mode.finish();\n return true;\n case R.id.option_2:\n Toast.makeText(MainActivity.this, \"Selected Option 2\", Toast.LENGTH_SHORT).show();\n mode.finish();\n return true;\n default:\n return false;\n }\n\n }\n\n @Override\n public void onDestroyActionMode(ActionMode mode) {\n myActMode=null;\n }\n };"
},
{
"code": null,
"e": 10226,
"s": 9944,
"text": "Since we have already created the callback functions (yet to be initialized and customized), we can pass myActModeCallback as an argument to startSupportActionMode() created in the previous step. The onCreateActionMode() is the method where we inflate our menu. To do this, we use:"
},
{
"code": null,
"e": 10286,
"s": 10226,
"text": " mode.getMenuInflater().inflate(R.menu.example_menu, menu);"
},
{
"code": null,
"e": 10687,
"s": 10286,
"text": "We do not need to code anything inside the onPrepareActionMode() method, since this method is called as and when the user wants to refresh the menu; certainly not the kind we want here! Coming to the next method, we of course need to tweak code into the onActionItemClicked() method, since this is the place that cares for our actions and dedicates it towards the Contextual Action Bar. Here we have:"
},
{
"code": null,
"e": 11202,
"s": 10687,
"text": "switch (item.getItemId()) {\n case R.id.option_1:\n Toast.makeText(MainActivity.this, \"Selected Option 1\", Toast.LENGTH_SHORT).show();\n mode.finish();\n return true;\n case R.id.option_2:\n Toast.makeText(MainActivity.this, \"Selected Option 2\", Toast.LENGTH_SHORT).show();\n mode.finish();\n return true;\n default:\n return false;\n }"
},
{
"code": null,
"e": 11581,
"s": 11202,
"text": "I have decided to use a short Toast Message to be displayed at the bottom of the screen after an item (an icon, to be more specific) in the contextual action bar has been clicked. Of course, you can innovate new ideas too. Lastly, we arrive at the onDestroyActionMode() method, and set myActMode to null, so that the contextual app bar is closed after the action has terminated."
},
{
"code": null,
"e": 11688,
"s": 11581,
"text": "@Override\n public void onDestroyActionMode(ActionMode mode) {\n myActMode=null;\n }"
},
{
"code": null,
"e": 11818,
"s": 11688,
"text": "That was it! Now Run the android application by clicking on the button, using an Android Emulator or an external android device."
},
{
"code": null,
"e": 11826,
"s": 11818,
"text": "Output:"
},
{
"code": null,
"e": 11851,
"s": 11826,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 11866,
"s": 11851,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 11873,
"s": 11866,
"text": "Picked"
},
{
"code": null,
"e": 11881,
"s": 11873,
"text": "Android"
},
{
"code": null,
"e": 11891,
"s": 11881,
"text": "Blogathon"
},
{
"code": null,
"e": 11896,
"s": 11891,
"text": "Java"
},
{
"code": null,
"e": 11901,
"s": 11896,
"text": "Java"
},
{
"code": null,
"e": 11909,
"s": 11901,
"text": "Android"
},
{
"code": null,
"e": 12007,
"s": 11909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12076,
"s": 12007,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 12107,
"s": 12076,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 12150,
"s": 12107,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 12182,
"s": 12150,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 12240,
"s": 12182,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 12292,
"s": 12240,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 12327,
"s": 12292,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 12361,
"s": 12327,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 12402,
"s": 12361,
"text": "How to Connect Python with SQL Database?"
}
] |
Save and Load RData Workspace Files in R
|
16 Dec, 2021
In this article, we will discuss how to save and load R data workspace files in R programming language.
The save.image method in R is used to save the current workspace files. It is an extended version of the save method in R which is used to create a list of all the declared data objects and save them into the workspace. These files can then later be read into the corresponding saved data objects using the load() method.
Syntax:
save.image(file = “.RData”)
Arguments :
file – name of the file where the R object is saved to or read from.
Example: Saving R data workspace files
R
# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- "Geeksforgeeks!!" # saving all data to the pathsave.image("saveworkspace.RData")
These files can be loaded into the workspace using load() function.
Syntax:
Load(path)
Example: Loading R data workspace files
R
# loading the workspaceload("saveworkspace.RData")
Output:
The saveRDS and readRDS methods available in base R are basically used to provide a means to save a single R object to a connection, mostly a type of file object, and then to restore the object. The restored object may belong to a different name. This approach is different from the save and load approach, which saves and restores one or more named objects into an environment. It is used to save a single object into the workspace.
Syntax:
saveRDS(object, file = “”)
Arguments :
object – R object to serialize.
file – name of the file where the R object is saved to or read from.
Syntax:
readRDS(file)
Example: Saving and loading R data workspace
R
# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- "Geeksforgeeks!!" # saving all data to the pathsaveRDS(obj1, file = "saveworkspaceobj1.RData")print("Data object1") # loading the workspacereadRDS("saveworkspaceobj1.RData")
Output:
[1] "Data object1"
[1] 1 2 3 4 5
The save method in R writes an external representation of R objects to the specified file. These R objects can be retrieved back from the workspace using the load method.
Syntax:
save(objects, file)
Arguments :
objects- The list of the objects to be saved
file – the file name for the R objects to be saved and read from
Example: Saving and loading R data workspace
R
# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- "Geeksforgeeks!!" # saving all data to the pathsave(obj1, obj3, file ="tempworkspaceobj.RData") load("tempworkspaceobj.RData")
The RData objects are stored at the specified paths shown in the below snapshot.
Output:
anikakapoor
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "In this article, we will discuss how to save and load R data workspace files in R programming language."
},
{
"code": null,
"e": 455,
"s": 132,
"text": "The save.image method in R is used to save the current workspace files. It is an extended version of the save method in R which is used to create a list of all the declared data objects and save them into the workspace. These files can then later be read into the corresponding saved data objects using the load() method. "
},
{
"code": null,
"e": 463,
"s": 455,
"text": "Syntax:"
},
{
"code": null,
"e": 491,
"s": 463,
"text": "save.image(file = “.RData”)"
},
{
"code": null,
"e": 504,
"s": 491,
"text": "Arguments : "
},
{
"code": null,
"e": 573,
"s": 504,
"text": "file – name of the file where the R object is saved to or read from."
},
{
"code": null,
"e": 612,
"s": 573,
"text": "Example: Saving R data workspace files"
},
{
"code": null,
"e": 614,
"s": 612,
"text": "R"
},
{
"code": "# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- \"Geeksforgeeks!!\" # saving all data to the pathsave.image(\"saveworkspace.RData\")",
"e": 786,
"s": 614,
"text": null
},
{
"code": null,
"e": 855,
"s": 786,
"text": " These files can be loaded into the workspace using load() function."
},
{
"code": null,
"e": 864,
"s": 855,
"text": "Syntax: "
},
{
"code": null,
"e": 875,
"s": 864,
"text": "Load(path)"
},
{
"code": null,
"e": 916,
"s": 875,
"text": "Example: Loading R data workspace files "
},
{
"code": null,
"e": 918,
"s": 916,
"text": "R"
},
{
"code": "# loading the workspaceload(\"saveworkspace.RData\")",
"e": 969,
"s": 918,
"text": null
},
{
"code": null,
"e": 979,
"s": 969,
"text": " Output: "
},
{
"code": null,
"e": 1414,
"s": 979,
"text": "The saveRDS and readRDS methods available in base R are basically used to provide a means to save a single R object to a connection, mostly a type of file object, and then to restore the object. The restored object may belong to a different name. This approach is different from the save and load approach, which saves and restores one or more named objects into an environment. It is used to save a single object into the workspace. "
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "Syntax:"
},
{
"code": null,
"e": 1449,
"s": 1422,
"text": "saveRDS(object, file = “”)"
},
{
"code": null,
"e": 1462,
"s": 1449,
"text": "Arguments : "
},
{
"code": null,
"e": 1494,
"s": 1462,
"text": "object – R object to serialize."
},
{
"code": null,
"e": 1563,
"s": 1494,
"text": "file – name of the file where the R object is saved to or read from."
},
{
"code": null,
"e": 1572,
"s": 1563,
"text": "Syntax: "
},
{
"code": null,
"e": 1586,
"s": 1572,
"text": "readRDS(file)"
},
{
"code": null,
"e": 1633,
"s": 1586,
"text": "Example: Saving and loading R data workspace "
},
{
"code": null,
"e": 1635,
"s": 1633,
"text": "R"
},
{
"code": "# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- \"Geeksforgeeks!!\" # saving all data to the pathsaveRDS(obj1, file = \"saveworkspaceobj1.RData\")print(\"Data object1\") # loading the workspacereadRDS(\"saveworkspaceobj1.RData\")",
"e": 1900,
"s": 1635,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1900,
"text": " Output: "
},
{
"code": null,
"e": 1944,
"s": 1910,
"text": "[1] \"Data object1\" \n[1] 1 2 3 4 5"
},
{
"code": null,
"e": 2117,
"s": 1944,
"text": "The save method in R writes an external representation of R objects to the specified file. These R objects can be retrieved back from the workspace using the load method. "
},
{
"code": null,
"e": 2125,
"s": 2117,
"text": "Syntax:"
},
{
"code": null,
"e": 2145,
"s": 2125,
"text": "save(objects, file)"
},
{
"code": null,
"e": 2157,
"s": 2145,
"text": "Arguments :"
},
{
"code": null,
"e": 2202,
"s": 2157,
"text": "objects- The list of the objects to be saved"
},
{
"code": null,
"e": 2267,
"s": 2202,
"text": "file – the file name for the R objects to be saved and read from"
},
{
"code": null,
"e": 2313,
"s": 2267,
"text": "Example: Saving and loading R data workspace "
},
{
"code": null,
"e": 2315,
"s": 2313,
"text": "R"
},
{
"code": "# creating data objectsobj1 <- c(1:5) obj2 <- FALSE obj3 <- \"Geeksforgeeks!!\" # saving all data to the pathsave(obj1, obj3, file =\"tempworkspaceobj.RData\") load(\"tempworkspaceobj.RData\")",
"e": 2533,
"s": 2315,
"text": null
},
{
"code": null,
"e": 2615,
"s": 2533,
"text": " The RData objects are stored at the specified paths shown in the below snapshot."
},
{
"code": null,
"e": 2625,
"s": 2615,
"text": "Output: "
},
{
"code": null,
"e": 2639,
"s": 2627,
"text": "anikakapoor"
},
{
"code": null,
"e": 2646,
"s": 2639,
"text": "Picked"
},
{
"code": null,
"e": 2661,
"s": 2646,
"text": "R-FileHandling"
},
{
"code": null,
"e": 2672,
"s": 2661,
"text": "R Language"
},
{
"code": null,
"e": 2770,
"s": 2672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2822,
"s": 2770,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2880,
"s": 2822,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2915,
"s": 2880,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2953,
"s": 2915,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3002,
"s": 2953,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3019,
"s": 3002,
"text": "R - if statement"
},
{
"code": null,
"e": 3056,
"s": 3019,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 3099,
"s": 3056,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3136,
"s": 3099,
"text": "How to import an Excel File into R ?"
}
] |
Python | Sort Tuples in Increasing Order by any key
|
18 Dec, 2017
Given a tuple, sort the list of tuples in increasing order by any key in tuple.
Examples:
Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)]
m = 0
Output : [(1, 2), (2, 3), (2, 5), (4, 4)]
Explanation: Sorted using the 0th index key.
Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
m = 2
Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]
Explanation: Sorted using the 2nd index key
Given tuples, we need to sort them according to any given key. This can be done using sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples.
Below is the Python implementation of the above approach:
# Python code to sort a list of tuples # according to given key. # get the last key.def last(n): return n[m] # function to sort the tuple def sort(tuples): # We pass used defined function last # as a parameter. return sorted(tuples, key = last) # driver code a = [(23, 45, 20), (25, 44, 39), (89, 40, 23)]m = 2print("Sorted:"),print(sort(a))
Output:
Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]
python-tuple
Python
Sorting
Sorting
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()
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Dec, 2017"
},
{
"code": null,
"e": 132,
"s": 52,
"text": "Given a tuple, sort the list of tuples in increasing order by any key in tuple."
},
{
"code": null,
"e": 142,
"s": 132,
"text": "Examples:"
},
{
"code": null,
"e": 471,
"s": 142,
"text": "Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] \n m = 0\nOutput : [(1, 2), (2, 3), (2, 5), (4, 4)]\nExplanation: Sorted using the 0th index key.\n\nInput : [(23, 45, 20), (25, 44, 39), (89, 40, 23)]\n m = 2\nOutput : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] \nExplanation: Sorted using the 2nd index key\n"
},
{
"code": null,
"e": 694,
"s": 471,
"text": "Given tuples, we need to sort them according to any given key. This can be done using sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples."
},
{
"code": null,
"e": 752,
"s": 694,
"text": "Below is the Python implementation of the above approach:"
},
{
"code": "# Python code to sort a list of tuples # according to given key. # get the last key.def last(n): return n[m] # function to sort the tuple def sort(tuples): # We pass used defined function last # as a parameter. return sorted(tuples, key = last) # driver code a = [(23, 45, 20), (25, 44, 39), (89, 40, 23)]m = 2print(\"Sorted:\"),print(sort(a))",
"e": 1119,
"s": 752,
"text": null
},
{
"code": null,
"e": 1127,
"s": 1119,
"text": "Output:"
},
{
"code": null,
"e": 1180,
"s": 1127,
"text": "Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] \n"
},
{
"code": null,
"e": 1193,
"s": 1180,
"text": "python-tuple"
},
{
"code": null,
"e": 1200,
"s": 1193,
"text": "Python"
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Sorting"
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "Sorting"
},
{
"code": null,
"e": 1314,
"s": 1216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1332,
"s": 1314,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1374,
"s": 1332,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1396,
"s": 1374,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1431,
"s": 1396,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1457,
"s": 1431,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": "Merge Sort"
},
{
"code": null,
"e": 1490,
"s": 1468,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "QuickSort"
},
{
"code": null,
"e": 1515,
"s": 1500,
"text": "Insertion Sort"
}
] |
Minimum Cost Polygon Triangulation
|
29 Jun, 2022
A triangulation of a convex polygon is formed by drawing diagonals between non-adjacent vertices (corners) such that the diagonals never intersect. The problem is to find the cost of triangulation with the minimum cost. The cost of a triangulation is sum of the weights of its component triangles. Weight of each triangle is its perimeter (sum of lengths of all sides)See following example taken from this source.
Two triangulations of the same convex pentagon. The triangulation on the left has a cost of 8 + 2√2 + 2√5 (approximately 15.30), the one on the right has a cost of 4 + 2√2 + 4√5 (approximately 15.77).
This problem has recursive substructure. The idea is to divide the polygon into three parts: a single triangle, the sub-polygon to the left, and the sub-polygon to the right. We try all possible divisions like this and find the one that minimizes the cost of the triangle plus the cost of the triangulation of the two sub-polygons.
Let Minimum Cost of triangulation of vertices from i to j be minCost(i, j)
If j < i + 2 Then
minCost(i, j) = 0
Else
minCost(i, j) = Min { minCost(i, k) + minCost(k, j) + cost(i, k, j) }
Here k varies from 'i+1' to 'j-1'
Cost of a triangle formed by edges (i, j), (j, k) and (k, i) is
cost(i, j, k) = dist(i, j) + dist(j, k) + dist(k, i)
Following is implementation of above naive recursive formula.
C++
Java
Python3
C#
Javascript
// Recursive implementation for minimum cost convex polygon triangulation#include <iostream>#include <cmath>#define MAX 1000000.0using namespace std; // Structure of a point in 2D planestruct Point{ int x, y;}; // Utility function to find minimum of two double valuesdouble min(double x, double y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planedouble dist(Point p1, Point p2){ return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the triangledouble cost(Point points[], int i, int j, int k){ Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A recursive function to find minimum cost of polygon triangulation// The polygon is represented by points[i..j].double mTC(Point points[], int i, int j){ // There must be at least three points between i and j // (including i and j) if (j < i+2) return 0; // Initialize result as infinite double res = MAX; // Find minimum triangulation by considering all for (int k=i+1; k<j; k++) res = min(res, (mTC(points, i, k) + mTC(points, k, j) + cost(points, i, k, j))); return res;} // Driver program to test above functionsint main(){ Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; int n = sizeof(points)/sizeof(points[0]); cout << mTC(points, 0, n-1); return 0;}
// Class to store a point in the Euclidean planeclass Point{ int x, y; public Point(int x, int y) { this.x = x; this.y = y; } // Utility function to return the distance between two // vertices in a 2-dimensional plane public double dist(Point p) { // The distance between vertices `(x1, y1)` & `(x2, // y2)` is `√((x2 − x1) ^ 2 + (y2 − y1) ^ 2)` return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); }} class GFG{ // Function to calculate the weight of optimal // triangulation of a convex polygon represented by a // given set of vertices `vertices[i..j]` public static double MWT(Point[] vertices, int i, int j) { // If the polygon has less than 3 vertices, // triangulation is not possible if (j < i + 2) { return 0; } // keep track of the total weight of the minimum // weight triangulation of `MWT(i,j)` double cost = Double.MAX_VALUE; // consider all possible triangles `ikj` within the // polygon for (int k = i + 1; k <= j - 1; k++) { // The weight of a triangulation is the length // of perimeter of the triangle double weight = vertices[i].dist(vertices[j]) + vertices[j].dist(vertices[k]) + vertices[k].dist(vertices[i]); // choose the vertex `k` that leads to the // minimum total weight cost = Double.min(cost, weight + MWT(vertices, i, k) + MWT(vertices, k, j)); } return cost; } // Driver code public static void main(String[] args) { // vertices are given in clockwise order Point[] vertices = { new Point(0, 0), new Point(2, 0), new Point(2, 1), new Point(1, 2), new Point(0, 1) }; System.out.println(MWT(vertices, 0, vertices.length - 1)); }} // This code is contributed by Priiyadarshini Kumari
# Recursive implementation for minimum# cost convex polygon triangulationfrom math import sqrtMAX = 1000000.0 # A utility function to find distance# between two points in a planedef dist(p1, p2): return sqrt((p1[0] - p2[0])*(p1[0] - p2[0]) + \ (p1[1] - p2[1])*(p1[1] - p2[1])) # A utility function to find cost of# a triangle. The cost is considered# as perimeter (sum of lengths of all edges)# of the triangledef cost(points, i, j, k): p1 = points[i] p2 = points[j] p3 = points[k] return dist(p1, p2) + dist(p2, p3) + dist(p3, p1) # A recursive function to find minimum# cost of polygon triangulation# The polygon is represented by points[i..j].def mTC(points, i, j): # There must be at least three points between i and j # (including i and j) if (j < i + 2): return 0 # Initialize result as infinite res = MAX # Find minimum triangulation by considering all for k in range(i + 1, j): res = min(res, (mTC(points, i, k) + \ mTC(points, k, j) + \ cost(points, i, k, j))) return round(res, 4) # Driver codepoints = [[0, 0], [1, 0], [2, 1], [1, 2], [0, 2]]n = len(points)print(mTC(points, 0, n-1)) # This code is contributed by SHUBHAMSINGH10
using System;using System.Collections.Generic; // Class to store a point in the Euclidean planepublic class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } // Utility function to return the distance between two // vertices in a 2-dimensional plane public double dist(Point p) { // The distance between vertices `(x1, y1)` & `(x2, // y2)` is `√((x2 − x1) ^ 2 + (y2 − y1) ^ 2)` return Math.Sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); }} public class GFG { // Function to calculate the weight of optimal // triangulation of a convex polygon represented by a // given set of vertices `vertices[i..j]` public static double MWT(Point[] vertices, int i, int j) { // If the polygon has less than 3 vertices, // triangulation is not possible if (j < i + 2) { return 0; } // keep track of the total weight of the minimum // weight triangulation of `MWT(i,j)` double cost = 9999999999999.09; // consider all possible triangles `ikj` within the // polygon for (int k = i + 1; k <= j - 1; k++) { // The weight of a triangulation is the length // of perimeter of the triangle double weight = vertices[i].dist(vertices[j]) + vertices[j].dist(vertices[k]) + vertices[k].dist(vertices[i]); // choose the vertex `k` that leads to the // minimum total weight cost = Math.Min(cost, weight + MWT(vertices, i, k) + MWT(vertices, k, j)); } return Math.Round(cost,4); } // Driver code public static void Main(String[] args) { // vertices are given in clockwise order Point[] vertices = { new Point(0, 0), new Point(2, 0), new Point(2, 1), new Point(1, 2), new Point(0, 1) }; Console.WriteLine(MWT(vertices, 0, vertices.Length - 1)); }} // This code is contributed by gauravrajput1
// A JavaScript program for a// Recursive implementation for minimum cost convex polygon triangulationconst MAX = 1.79769e+308; // Utility function to find minimum of two double valuesfunction min(x, y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planefunction dist(p1, p2){ return Math.sqrt((p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the trianglefunction cost(points, i, j, k){ p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A recursive function to find minimum cost of polygon triangulation// The polygon is represented by points[i..j].function mTC(points, i, j){ // There must be at least three points between i and j // (including i and j) if (j < i+2){ return 0; } // Initialize result as infinite let res = MAX; // Find minimum triangulation by considering all for (let k=i+1; k<j; k++){ res = min(res, (mTC(points, i, k) + mTC(points, k, j) + cost(points, i, k, j))); } return res;} // Driver program to test above functions{ let points = [[0, 0], [1, 0], [2, 1], [1, 2],[0, 2]] let n = points.length; console.log(mTC(points, 0, n-1));} // The code is contributed by Nidhi Goel
Output:
15.3006
The above problem is similar to Matrix Chain Multiplication. The following is recursion tree for mTC(points[], 0, 4).
It can be easily seen in the above recursion tree that the problem has many overlapping subproblems. Since the problem has both properties: Optimal Substructure and Overlapping Subproblems, it can be efficiently solved using dynamic programming.Following is C++ implementation of dynamic programming solution.
C++
Java
Python3
C#
// A Dynamic Programming based program to find minimum cost of convex// polygon triangulation#include <iostream>#include <cmath>#define MAX 1000000.0using namespace std; // Structure of a point in 2D planestruct Point{ int x, y;}; // Utility function to find minimum of two double valuesdouble min(double x, double y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planedouble dist(Point p1, Point p2){ return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the triangledouble cost(Point points[], int i, int j, int k){ Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A Dynamic programming based function to find minimum cost for convex// polygon triangulation.double mTCDP(Point points[], int n){ // There must be at least 3 points to form a triangle if (n < 3) return 0; // table to store results of subproblems. table[i][j] stores cost of // triangulation of points from i to j. The entry table[0][n-1] stores // the final result. double table[n][n]; // Fill table using above recursive formula. Note that the table // is filled in diagonal fashion i.e., from diagonal elements to // table[0][n-1] which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i+2) table[i][j] = 0.0; else { table[i][j] = MAX; for (int k = i+1; k < j; k++) { double val = table[i][k] + table[k][j] + cost(points,i,j,k); if (table[i][j] > val) table[i][j] = val; } } } } return table[0][n-1];} // Driver program to test above functionsint main(){ Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; int n = sizeof(points)/sizeof(points[0]); cout << mTCDP(points, n); return 0;}
// A Dynamic Programming based program to find minimum cost// of convex polygon triangulationimport java.util.*; class GFG{ // Structure of a point in 2D plane static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } } // Utility function to find minimum of two double values static double min(double x, double y) { return (x <= y) ? x : y; } // A utility function to find distance between two // points in a plane static double dist(Point p1, Point p2) { return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } // A utility function to find cost of a triangle. The // cost is considered as perimeter (sum of lengths of // all edges) of the triangle static double cost(Point points[], int i, int j, int k) { Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1); } // A Dynamic programming based function to find minimum // cost for convex polygon triangulation. static double mTCDP(Point points[], int n) { // There must be at least 3 points to form a // triangle if (n < 3) return 0; // table to store results of subproblems. // table[i][j] stores cost of triangulation of // points from i to j. The entry table[0][n-1] // stores the final result. double[][] table = new double[n][n]; // Fill table using above recursive formula. Note // that the table is filled in diagonal fashion // i.e., from diagonal elements to table[0][n-1] // which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i + 2) table[i][j] = 0.0; else { table[i][j] = 1000000.0; for (int k = i + 1; k < j; k++) { double val = table[i][k] + table[k][j] + cost(points, i, j, k); if (table[i][j] > val) table[i][j] = val; } } } } return table[0][n - 1]; } // Driver program to test above functions public static void main(String[] args) { Point[] points = { new Point(0, 0), new Point(1, 0), new Point(2, 1), new Point(1, 2), new Point(0, 2) }; int n = points.length; System.out.println(mTCDP(points, n)); }} // This code is contributed by Karandeep Singh
# A Dynamic Programming based program to find minimum cost# of convex polygon triangulation import math class GFG: # Structure of a point in 2D plane class Point: x = 0 y = 0 def __init__(self, x, y): self.x = x self.y = y # Utility function to find minimum of two double values @staticmethod def min(x, y): return x if (x <= y) else y # A utility function to find distance between two # points in a plane @staticmethod def dist(p1, p2): return math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)) # A utility function to find cost of a triangle. The # cost is considered as perimeter (sum of lengths of # all edges) of the triangle @staticmethod def cost(points, i, j, k): p1 = points[i] p2 = points[j] p3 = points[k] return GFG.dist(p1, p2) + GFG.dist(p2, p3) + GFG.dist(p3, p1) # A Dynamic programming based function to find minimum # cost for convex polygon triangulation. @staticmethod def mTCDP(points, n): # There must be at least 3 points to form a # triangle if (n < 3): return 0 # table to store results of subproblems. # table[i][j] stores cost of triangulation of # points from i to j. The entry table[0][n-1] # stores the final result. table = [[0.0] * (n) for _ in range(n)] # Fill table using above recursive formula. Note # that the table is filled in diagonal fashion # i.e., from diagonal elements to table[0][n-1] # which is the result. gap = 0 while (gap < n): i = 0 j = gap while (j < n): if (j < i + 2): table[i][j] = 0.0 else: table[i][j] = 1000000.0 k = i + 1 while (k < j): val = table[i][k] + table[k][j] + \ GFG.cost(points, i, j, k) if (table[i][j] > val): table[i][j] = val k += 1 i += 1 j += 1 gap += 1 return table[0][n - 1] # Driver program to test above functionsif __name__ == "__main__": points = [GFG.Point(0, 0), GFG.Point(1, 0), GFG.Point( 2, 1), GFG.Point(1, 2), GFG.Point(0, 2)] n = len(points) print(GFG.mTCDP(points, n)) # This code is contributed by Aarti_Rathi
using System; // A Dynamic Programming based program to find minimum cost// of convex polygon triangulation // Structure of a point in 2D planepublic class Point { public int x; public int y;} public static class Globals { public const double MAX = 1000000.0; // Utility function to find minimum of two double values public static double min(double x, double y) { return (x <= y) ? x : y; } // A utility function to find distance between two // points in a plane public static double dist(Point p1, Point p2) { return Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } // A utility function to find cost of a triangle. The // cost is considered as perimeter (sum of lengths of // all edges) of the triangle public static double cost(Point[] points, int i, int j, int k) { Point p1 = points[i]; Point p2 = points[j]; Point p3 = points[k]; return (dist(p1, p2) + dist(p2, p3) + dist(p3, p1)); } // A Dynamic programming based function to find minimum // cost for convex polygon triangulation. public static double mTCDP(Point[] points, int n) { // There must be at least 3 points to form a // triangle if (n < 3) { return 0; } // table to store results of subproblems. // table[i][j] stores cost of triangulation of // points from i to j. The entry table[0][n-1] // stores the final result. double[, ] table = new double[n, n]; ; // Fill table using above recursive formula. Note // that the table is filled in diagonal fashion // i.e., from diagonal elements to table[0][n-1] // which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i + 2) { table[i, j] = 0.0; } else { table[i, j] = MAX; for (int k = i + 1; k < j; k++) { double val = table[i, k] + table[k, j] + cost(points, i, j, k); if (table[i, j] > val) { table[i, j] = val; } } } } } return table[0, n - 1]; } // Driver program to test above functions public static void Main() { Point[] points = { new Point(){ x = 0, y = 0 }, new Point(){ x = 1, y = 0 }, new Point(){ x = 2, y = 1 }, new Point(){ x = 1, y = 2 }, new Point(){ x = 0, y = 2 } }; int n = points.Length; Console.Write(mTCDP(points, n)); }} // This code is contributed by Aarti_Rathi
Output:
15.3006
Time complexity of the above dynamic programming solution is O(n3). Please note that the above implementations assume that the points of convex polygon are given in order (either clockwise or anticlockwise)Exercise: Extend the above solution to print triangulation also. For the above example, the optimal triangulation is 0 3 4, 0 1 3, and 1 2 3.Sources: http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture12.html http://www.cs.utoronto.ca/~heap/Courses/270F02/A4/chains/node2.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
kevinpretterhofer
lit2017043
SHUBHAMSINGH10
pawki
rahullilua2126
GauravRajput1
surinderdawra388
karandeep1234
classroompxico
_shinchancode
codewithshinchan
Dynamic Programming
Geometric
Dynamic Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 468,
"s": 52,
"text": "A triangulation of a convex polygon is formed by drawing diagonals between non-adjacent vertices (corners) such that the diagonals never intersect. The problem is to find the cost of triangulation with the minimum cost. The cost of a triangulation is sum of the weights of its component triangles. Weight of each triangle is its perimeter (sum of lengths of all sides)See following example taken from this source. "
},
{
"code": null,
"e": 671,
"s": 468,
"text": "Two triangulations of the same convex pentagon. The triangulation on the left has a cost of 8 + 2√2 + 2√5 (approximately 15.30), the one on the right has a cost of 4 + 2√2 + 4√5 (approximately 15.77). "
},
{
"code": null,
"e": 1004,
"s": 671,
"text": "This problem has recursive substructure. The idea is to divide the polygon into three parts: a single triangle, the sub-polygon to the left, and the sub-polygon to the right. We try all possible divisions like this and find the one that minimizes the cost of the triangle plus the cost of the triangulation of the two sub-polygons. "
},
{
"code": null,
"e": 1368,
"s": 1004,
"text": "Let Minimum Cost of triangulation of vertices from i to j be minCost(i, j)\nIf j < i + 2 Then\n minCost(i, j) = 0\nElse\n minCost(i, j) = Min { minCost(i, k) + minCost(k, j) + cost(i, k, j) }\n Here k varies from 'i+1' to 'j-1'\n\nCost of a triangle formed by edges (i, j), (j, k) and (k, i) is \n cost(i, j, k) = dist(i, j) + dist(j, k) + dist(k, i)"
},
{
"code": null,
"e": 1431,
"s": 1368,
"text": "Following is implementation of above naive recursive formula. "
},
{
"code": null,
"e": 1435,
"s": 1431,
"text": "C++"
},
{
"code": null,
"e": 1440,
"s": 1435,
"text": "Java"
},
{
"code": null,
"e": 1448,
"s": 1440,
"text": "Python3"
},
{
"code": null,
"e": 1451,
"s": 1448,
"text": "C#"
},
{
"code": null,
"e": 1462,
"s": 1451,
"text": "Javascript"
},
{
"code": "// Recursive implementation for minimum cost convex polygon triangulation#include <iostream>#include <cmath>#define MAX 1000000.0using namespace std; // Structure of a point in 2D planestruct Point{ int x, y;}; // Utility function to find minimum of two double valuesdouble min(double x, double y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planedouble dist(Point p1, Point p2){ return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the triangledouble cost(Point points[], int i, int j, int k){ Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A recursive function to find minimum cost of polygon triangulation// The polygon is represented by points[i..j].double mTC(Point points[], int i, int j){ // There must be at least three points between i and j // (including i and j) if (j < i+2) return 0; // Initialize result as infinite double res = MAX; // Find minimum triangulation by considering all for (int k=i+1; k<j; k++) res = min(res, (mTC(points, i, k) + mTC(points, k, j) + cost(points, i, k, j))); return res;} // Driver program to test above functionsint main(){ Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; int n = sizeof(points)/sizeof(points[0]); cout << mTC(points, 0, n-1); return 0;}",
"e": 3017,
"s": 1462,
"text": null
},
{
"code": "// Class to store a point in the Euclidean planeclass Point{ int x, y; public Point(int x, int y) { this.x = x; this.y = y; } // Utility function to return the distance between two // vertices in a 2-dimensional plane public double dist(Point p) { // The distance between vertices `(x1, y1)` & `(x2, // y2)` is `√((x2 − x1) ^ 2 + (y2 − y1) ^ 2)` return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); }} class GFG{ // Function to calculate the weight of optimal // triangulation of a convex polygon represented by a // given set of vertices `vertices[i..j]` public static double MWT(Point[] vertices, int i, int j) { // If the polygon has less than 3 vertices, // triangulation is not possible if (j < i + 2) { return 0; } // keep track of the total weight of the minimum // weight triangulation of `MWT(i,j)` double cost = Double.MAX_VALUE; // consider all possible triangles `ikj` within the // polygon for (int k = i + 1; k <= j - 1; k++) { // The weight of a triangulation is the length // of perimeter of the triangle double weight = vertices[i].dist(vertices[j]) + vertices[j].dist(vertices[k]) + vertices[k].dist(vertices[i]); // choose the vertex `k` that leads to the // minimum total weight cost = Double.min(cost, weight + MWT(vertices, i, k) + MWT(vertices, k, j)); } return cost; } // Driver code public static void main(String[] args) { // vertices are given in clockwise order Point[] vertices = { new Point(0, 0), new Point(2, 0), new Point(2, 1), new Point(1, 2), new Point(0, 1) }; System.out.println(MWT(vertices, 0, vertices.length - 1)); }} // This code is contributed by Priiyadarshini Kumari",
"e": 4920,
"s": 3017,
"text": null
},
{
"code": "# Recursive implementation for minimum# cost convex polygon triangulationfrom math import sqrtMAX = 1000000.0 # A utility function to find distance# between two points in a planedef dist(p1, p2): return sqrt((p1[0] - p2[0])*(p1[0] - p2[0]) + \\ (p1[1] - p2[1])*(p1[1] - p2[1])) # A utility function to find cost of# a triangle. The cost is considered# as perimeter (sum of lengths of all edges)# of the triangledef cost(points, i, j, k): p1 = points[i] p2 = points[j] p3 = points[k] return dist(p1, p2) + dist(p2, p3) + dist(p3, p1) # A recursive function to find minimum# cost of polygon triangulation# The polygon is represented by points[i..j].def mTC(points, i, j): # There must be at least three points between i and j # (including i and j) if (j < i + 2): return 0 # Initialize result as infinite res = MAX # Find minimum triangulation by considering all for k in range(i + 1, j): res = min(res, (mTC(points, i, k) + \\ mTC(points, k, j) + \\ cost(points, i, k, j))) return round(res, 4) # Driver codepoints = [[0, 0], [1, 0], [2, 1], [1, 2], [0, 2]]n = len(points)print(mTC(points, 0, n-1)) # This code is contributed by SHUBHAMSINGH10",
"e": 6200,
"s": 4920,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // Class to store a point in the Euclidean planepublic class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } // Utility function to return the distance between two // vertices in a 2-dimensional plane public double dist(Point p) { // The distance between vertices `(x1, y1)` & `(x2, // y2)` is `√((x2 − x1) ^ 2 + (y2 − y1) ^ 2)` return Math.Sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y)); }} public class GFG { // Function to calculate the weight of optimal // triangulation of a convex polygon represented by a // given set of vertices `vertices[i..j]` public static double MWT(Point[] vertices, int i, int j) { // If the polygon has less than 3 vertices, // triangulation is not possible if (j < i + 2) { return 0; } // keep track of the total weight of the minimum // weight triangulation of `MWT(i,j)` double cost = 9999999999999.09; // consider all possible triangles `ikj` within the // polygon for (int k = i + 1; k <= j - 1; k++) { // The weight of a triangulation is the length // of perimeter of the triangle double weight = vertices[i].dist(vertices[j]) + vertices[j].dist(vertices[k]) + vertices[k].dist(vertices[i]); // choose the vertex `k` that leads to the // minimum total weight cost = Math.Min(cost, weight + MWT(vertices, i, k) + MWT(vertices, k, j)); } return Math.Round(cost,4); } // Driver code public static void Main(String[] args) { // vertices are given in clockwise order Point[] vertices = { new Point(0, 0), new Point(2, 0), new Point(2, 1), new Point(1, 2), new Point(0, 1) }; Console.WriteLine(MWT(vertices, 0, vertices.Length - 1)); }} // This code is contributed by gauravrajput1",
"e": 8209,
"s": 6200,
"text": null
},
{
"code": "// A JavaScript program for a// Recursive implementation for minimum cost convex polygon triangulationconst MAX = 1.79769e+308; // Utility function to find minimum of two double valuesfunction min(x, y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planefunction dist(p1, p2){ return Math.sqrt((p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the trianglefunction cost(points, i, j, k){ p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A recursive function to find minimum cost of polygon triangulation// The polygon is represented by points[i..j].function mTC(points, i, j){ // There must be at least three points between i and j // (including i and j) if (j < i+2){ return 0; } // Initialize result as infinite let res = MAX; // Find minimum triangulation by considering all for (let k=i+1; k<j; k++){ res = min(res, (mTC(points, i, k) + mTC(points, k, j) + cost(points, i, k, j))); } return res;} // Driver program to test above functions{ let points = [[0, 0], [1, 0], [2, 1], [1, 2],[0, 2]] let n = points.length; console.log(mTC(points, 0, n-1));} // The code is contributed by Nidhi Goel",
"e": 9612,
"s": 8209,
"text": null
},
{
"code": null,
"e": 9621,
"s": 9612,
"text": "Output: "
},
{
"code": null,
"e": 9629,
"s": 9621,
"text": "15.3006"
},
{
"code": null,
"e": 9748,
"s": 9629,
"text": "The above problem is similar to Matrix Chain Multiplication. The following is recursion tree for mTC(points[], 0, 4). "
},
{
"code": null,
"e": 10059,
"s": 9748,
"text": "It can be easily seen in the above recursion tree that the problem has many overlapping subproblems. Since the problem has both properties: Optimal Substructure and Overlapping Subproblems, it can be efficiently solved using dynamic programming.Following is C++ implementation of dynamic programming solution. "
},
{
"code": null,
"e": 10063,
"s": 10059,
"text": "C++"
},
{
"code": null,
"e": 10068,
"s": 10063,
"text": "Java"
},
{
"code": null,
"e": 10076,
"s": 10068,
"text": "Python3"
},
{
"code": null,
"e": 10079,
"s": 10076,
"text": "C#"
},
{
"code": "// A Dynamic Programming based program to find minimum cost of convex// polygon triangulation#include <iostream>#include <cmath>#define MAX 1000000.0using namespace std; // Structure of a point in 2D planestruct Point{ int x, y;}; // Utility function to find minimum of two double valuesdouble min(double x, double y){ return (x <= y)? x : y;} // A utility function to find distance between two points in a planedouble dist(Point p1, Point p2){ return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));} // A utility function to find cost of a triangle. The cost is considered// as perimeter (sum of lengths of all edges) of the triangledouble cost(Point points[], int i, int j, int k){ Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1);} // A Dynamic programming based function to find minimum cost for convex// polygon triangulation.double mTCDP(Point points[], int n){ // There must be at least 3 points to form a triangle if (n < 3) return 0; // table to store results of subproblems. table[i][j] stores cost of // triangulation of points from i to j. The entry table[0][n-1] stores // the final result. double table[n][n]; // Fill table using above recursive formula. Note that the table // is filled in diagonal fashion i.e., from diagonal elements to // table[0][n-1] which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i+2) table[i][j] = 0.0; else { table[i][j] = MAX; for (int k = i+1; k < j; k++) { double val = table[i][k] + table[k][j] + cost(points,i,j,k); if (table[i][j] > val) table[i][j] = val; } } } } return table[0][n-1];} // Driver program to test above functionsint main(){ Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}}; int n = sizeof(points)/sizeof(points[0]); cout << mTCDP(points, n); return 0;}",
"e": 12181,
"s": 10079,
"text": null
},
{
"code": "// A Dynamic Programming based program to find minimum cost// of convex polygon triangulationimport java.util.*; class GFG{ // Structure of a point in 2D plane static class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } } // Utility function to find minimum of two double values static double min(double x, double y) { return (x <= y) ? x : y; } // A utility function to find distance between two // points in a plane static double dist(Point p1, Point p2) { return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } // A utility function to find cost of a triangle. The // cost is considered as perimeter (sum of lengths of // all edges) of the triangle static double cost(Point points[], int i, int j, int k) { Point p1 = points[i], p2 = points[j], p3 = points[k]; return dist(p1, p2) + dist(p2, p3) + dist(p3, p1); } // A Dynamic programming based function to find minimum // cost for convex polygon triangulation. static double mTCDP(Point points[], int n) { // There must be at least 3 points to form a // triangle if (n < 3) return 0; // table to store results of subproblems. // table[i][j] stores cost of triangulation of // points from i to j. The entry table[0][n-1] // stores the final result. double[][] table = new double[n][n]; // Fill table using above recursive formula. Note // that the table is filled in diagonal fashion // i.e., from diagonal elements to table[0][n-1] // which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i + 2) table[i][j] = 0.0; else { table[i][j] = 1000000.0; for (int k = i + 1; k < j; k++) { double val = table[i][k] + table[k][j] + cost(points, i, j, k); if (table[i][j] > val) table[i][j] = val; } } } } return table[0][n - 1]; } // Driver program to test above functions public static void main(String[] args) { Point[] points = { new Point(0, 0), new Point(1, 0), new Point(2, 1), new Point(1, 2), new Point(0, 2) }; int n = points.length; System.out.println(mTCDP(points, n)); }} // This code is contributed by Karandeep Singh",
"e": 14582,
"s": 12181,
"text": null
},
{
"code": "# A Dynamic Programming based program to find minimum cost# of convex polygon triangulation import math class GFG: # Structure of a point in 2D plane class Point: x = 0 y = 0 def __init__(self, x, y): self.x = x self.y = y # Utility function to find minimum of two double values @staticmethod def min(x, y): return x if (x <= y) else y # A utility function to find distance between two # points in a plane @staticmethod def dist(p1, p2): return math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)) # A utility function to find cost of a triangle. The # cost is considered as perimeter (sum of lengths of # all edges) of the triangle @staticmethod def cost(points, i, j, k): p1 = points[i] p2 = points[j] p3 = points[k] return GFG.dist(p1, p2) + GFG.dist(p2, p3) + GFG.dist(p3, p1) # A Dynamic programming based function to find minimum # cost for convex polygon triangulation. @staticmethod def mTCDP(points, n): # There must be at least 3 points to form a # triangle if (n < 3): return 0 # table to store results of subproblems. # table[i][j] stores cost of triangulation of # points from i to j. The entry table[0][n-1] # stores the final result. table = [[0.0] * (n) for _ in range(n)] # Fill table using above recursive formula. Note # that the table is filled in diagonal fashion # i.e., from diagonal elements to table[0][n-1] # which is the result. gap = 0 while (gap < n): i = 0 j = gap while (j < n): if (j < i + 2): table[i][j] = 0.0 else: table[i][j] = 1000000.0 k = i + 1 while (k < j): val = table[i][k] + table[k][j] + \\ GFG.cost(points, i, j, k) if (table[i][j] > val): table[i][j] = val k += 1 i += 1 j += 1 gap += 1 return table[0][n - 1] # Driver program to test above functionsif __name__ == \"__main__\": points = [GFG.Point(0, 0), GFG.Point(1, 0), GFG.Point( 2, 1), GFG.Point(1, 2), GFG.Point(0, 2)] n = len(points) print(GFG.mTCDP(points, n)) # This code is contributed by Aarti_Rathi",
"e": 17095,
"s": 14582,
"text": null
},
{
"code": "using System; // A Dynamic Programming based program to find minimum cost// of convex polygon triangulation // Structure of a point in 2D planepublic class Point { public int x; public int y;} public static class Globals { public const double MAX = 1000000.0; // Utility function to find minimum of two double values public static double min(double x, double y) { return (x <= y) ? x : y; } // A utility function to find distance between two // points in a plane public static double dist(Point p1, Point p2) { return Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)); } // A utility function to find cost of a triangle. The // cost is considered as perimeter (sum of lengths of // all edges) of the triangle public static double cost(Point[] points, int i, int j, int k) { Point p1 = points[i]; Point p2 = points[j]; Point p3 = points[k]; return (dist(p1, p2) + dist(p2, p3) + dist(p3, p1)); } // A Dynamic programming based function to find minimum // cost for convex polygon triangulation. public static double mTCDP(Point[] points, int n) { // There must be at least 3 points to form a // triangle if (n < 3) { return 0; } // table to store results of subproblems. // table[i][j] stores cost of triangulation of // points from i to j. The entry table[0][n-1] // stores the final result. double[, ] table = new double[n, n]; ; // Fill table using above recursive formula. Note // that the table is filled in diagonal fashion // i.e., from diagonal elements to table[0][n-1] // which is the result. for (int gap = 0; gap < n; gap++) { for (int i = 0, j = gap; j < n; i++, j++) { if (j < i + 2) { table[i, j] = 0.0; } else { table[i, j] = MAX; for (int k = i + 1; k < j; k++) { double val = table[i, k] + table[k, j] + cost(points, i, j, k); if (table[i, j] > val) { table[i, j] = val; } } } } } return table[0, n - 1]; } // Driver program to test above functions public static void Main() { Point[] points = { new Point(){ x = 0, y = 0 }, new Point(){ x = 1, y = 0 }, new Point(){ x = 2, y = 1 }, new Point(){ x = 1, y = 2 }, new Point(){ x = 0, y = 2 } }; int n = points.Length; Console.Write(mTCDP(points, n)); }} // This code is contributed by Aarti_Rathi",
"e": 19674,
"s": 17095,
"text": null
},
{
"code": null,
"e": 19683,
"s": 19674,
"text": "Output: "
},
{
"code": null,
"e": 19691,
"s": 19683,
"text": "15.3006"
},
{
"code": null,
"e": 20306,
"s": 19691,
"text": "Time complexity of the above dynamic programming solution is O(n3). Please note that the above implementations assume that the points of convex polygon are given in order (either clockwise or anticlockwise)Exercise: Extend the above solution to print triangulation also. For the above example, the optimal triangulation is 0 3 4, 0 1 3, and 1 2 3.Sources: http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture12.html http://www.cs.utoronto.ca/~heap/Courses/270F02/A4/chains/node2.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 20324,
"s": 20306,
"text": "kevinpretterhofer"
},
{
"code": null,
"e": 20335,
"s": 20324,
"text": "lit2017043"
},
{
"code": null,
"e": 20350,
"s": 20335,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 20356,
"s": 20350,
"text": "pawki"
},
{
"code": null,
"e": 20371,
"s": 20356,
"text": "rahullilua2126"
},
{
"code": null,
"e": 20385,
"s": 20371,
"text": "GauravRajput1"
},
{
"code": null,
"e": 20402,
"s": 20385,
"text": "surinderdawra388"
},
{
"code": null,
"e": 20416,
"s": 20402,
"text": "karandeep1234"
},
{
"code": null,
"e": 20431,
"s": 20416,
"text": "classroompxico"
},
{
"code": null,
"e": 20445,
"s": 20431,
"text": "_shinchancode"
},
{
"code": null,
"e": 20462,
"s": 20445,
"text": "codewithshinchan"
},
{
"code": null,
"e": 20482,
"s": 20462,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 20492,
"s": 20482,
"text": "Geometric"
},
{
"code": null,
"e": 20512,
"s": 20492,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 20522,
"s": 20512,
"text": "Geometric"
}
] |
PostgreSQL – REVOKE
|
17 Aug, 2021
In PostgreSQL, the REVOKE statement is used to revoke previously granted privileges on database objects through a role.
The following shows the syntax of the REVOKE statement:
Syntax:
REVOKE privilege | ALL
ON TABLE tbl_name | ALL TABLES IN SCHEMA schema_name
FROM role_name;
Let’s analyze the above syntax:
First, specify the privileges that is to be revoked. Use the ALL option to revoke all previously granted privileges.
Then, set the name of the table after the ON keyword.
Finally, specify the name of the role whose privileges is to be revoked.
Example:
First,log into the dvdrental sample database as Postgres:
psql -U postgres -d dvdrental
Now initialize a role called ‘abhishek’ with the LOGIN and PASSWORD attributes as shown below:
CREATE ROLE abhishek
LOGIN
PASSWORD 'geeks12345';
Now grat all privileges on the film table to the role ‘abhishek’ as shown below:
GRANT ALL
ON film
TO abhishek;
Now provide the SELECT privilege on the actor table to the role ‘abhishek’ as shown below:
GRANT SELECT
ON actor
TO abhishek;
Here we will revoke the SELECT privilege on the actor table from the role ‘abhishek’, as shown below:
REVOKE SELECT
ON actor
FROM abhishek;
If you wish to revoke all privileges on the film table from the role ‘abhishek’, make use of theREVOKE statement with the ALL option as shown below:
REVOKE ALL
ON film
FROM abhishek;
Output:
simranarora5sos
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "In PostgreSQL, the REVOKE statement is used to revoke previously granted privileges on database objects through a role."
},
{
"code": null,
"e": 204,
"s": 148,
"text": "The following shows the syntax of the REVOKE statement:"
},
{
"code": null,
"e": 306,
"s": 204,
"text": "Syntax: \nREVOKE privilege | ALL\nON TABLE tbl_name | ALL TABLES IN SCHEMA schema_name\nFROM role_name;"
},
{
"code": null,
"e": 338,
"s": 306,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 455,
"s": 338,
"text": "First, specify the privileges that is to be revoked. Use the ALL option to revoke all previously granted privileges."
},
{
"code": null,
"e": 509,
"s": 455,
"text": "Then, set the name of the table after the ON keyword."
},
{
"code": null,
"e": 582,
"s": 509,
"text": "Finally, specify the name of the role whose privileges is to be revoked."
},
{
"code": null,
"e": 591,
"s": 582,
"text": "Example:"
},
{
"code": null,
"e": 649,
"s": 591,
"text": "First,log into the dvdrental sample database as Postgres:"
},
{
"code": null,
"e": 679,
"s": 649,
"text": "psql -U postgres -d dvdrental"
},
{
"code": null,
"e": 774,
"s": 679,
"text": "Now initialize a role called ‘abhishek’ with the LOGIN and PASSWORD attributes as shown below:"
},
{
"code": null,
"e": 825,
"s": 774,
"text": "CREATE ROLE abhishek\nLOGIN \nPASSWORD 'geeks12345';"
},
{
"code": null,
"e": 906,
"s": 825,
"text": "Now grat all privileges on the film table to the role ‘abhishek’ as shown below:"
},
{
"code": null,
"e": 938,
"s": 906,
"text": "GRANT ALL \nON film\nTO abhishek;"
},
{
"code": null,
"e": 1029,
"s": 938,
"text": "Now provide the SELECT privilege on the actor table to the role ‘abhishek’ as shown below:"
},
{
"code": null,
"e": 1064,
"s": 1029,
"text": "GRANT SELECT\nON actor\nTO abhishek;"
},
{
"code": null,
"e": 1166,
"s": 1064,
"text": "Here we will revoke the SELECT privilege on the actor table from the role ‘abhishek’, as shown below:"
},
{
"code": null,
"e": 1204,
"s": 1166,
"text": "REVOKE SELECT\nON actor\nFROM abhishek;"
},
{
"code": null,
"e": 1353,
"s": 1204,
"text": "If you wish to revoke all privileges on the film table from the role ‘abhishek’, make use of theREVOKE statement with the ALL option as shown below:"
},
{
"code": null,
"e": 1387,
"s": 1353,
"text": "REVOKE ALL\nON film\nFROM abhishek;"
},
{
"code": null,
"e": 1395,
"s": 1387,
"text": "Output:"
},
{
"code": null,
"e": 1411,
"s": 1395,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1437,
"s": 1411,
"text": "postgreSQL-administration"
},
{
"code": null,
"e": 1448,
"s": 1437,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1546,
"s": 1448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1573,
"s": 1546,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 1605,
"s": 1573,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 1628,
"s": 1605,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 1668,
"s": 1628,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 1706,
"s": 1668,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1740,
"s": 1706,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 1764,
"s": 1740,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1819,
"s": 1764,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 1843,
"s": 1819,
"text": "PostgreSQL - Copy Table"
}
] |
Print the content of a div element using JavaScript
|
26 Jul, 2021
To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted. Then a JavaScript popup window is created and the extracted contents of the HTML div elements are written to the popup window and finally the window is printed using the JavaScript Window Print command.
Example 1: This example uses JavaScript window print command to print the content of div element.
<!DOCTYPE html><html> <head> <title> Print the content of a div </title> <!-- Script to print the content of a div --> <script> function printDiv() { var divContents = document.getElementById("GFG").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script></head> <body style="text-align:center;"> <div id="GFG" style="background-color: green;"> <h2>Geeksforgeeks</h2> <p> This is inside the div and will be printed on the screen after the click. </p> </div> <input type="button" value="click" onclick="printDiv()"> </body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Example 2: This example uses JavaScript window print command to print the content of div element.
<!DOCTYPE html><html> <head> <title> Print the content of a div </title> <!-- Script to print the content of a div --> <script> function printDiv() { var divContents = document.getElementById("GFG").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script></head> <body> <center> <div id="GFG" style="background-color: green;"> <h2>Geeksforgeeks</h2> <table border="1px"> <tr> <td>computer</td> <td>Algorithm</td> </tr> <tr> <td>Microwave</td> <td>Infrared</td> </tr> </table> </div> <p> The table is inside the div and will get printed on the click of button. </p> <input type="button" value="click" onclick="printDiv()"> </center> </body> </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 447,
"s": 53,
"text": "To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted. Then a JavaScript popup window is created and the extracted contents of the HTML div elements are written to the popup window and finally the window is printed using the JavaScript Window Print command."
},
{
"code": null,
"e": 545,
"s": 447,
"text": "Example 1: This example uses JavaScript window print command to print the content of div element."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Print the content of a div </title> <!-- Script to print the content of a div --> <script> function printDiv() { var divContents = document.getElementById(\"GFG\").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script></head> <body style=\"text-align:center;\"> <div id=\"GFG\" style=\"background-color: green;\"> <h2>Geeksforgeeks</h2> <p> This is inside the div and will be printed on the screen after the click. </p> </div> <input type=\"button\" value=\"click\" onclick=\"printDiv()\"> </body> </html> ",
"e": 1514,
"s": 545,
"text": null
},
{
"code": null,
"e": 1522,
"s": 1514,
"text": "Output:"
},
{
"code": null,
"e": 1550,
"s": 1522,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 1577,
"s": 1550,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 1675,
"s": 1577,
"text": "Example 2: This example uses JavaScript window print command to print the content of div element."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Print the content of a div </title> <!-- Script to print the content of a div --> <script> function printDiv() { var divContents = document.getElementById(\"GFG\").innerHTML; var a = window.open('', '', 'height=500, width=500'); a.document.write('<html>'); a.document.write('<body > <h1>Div contents are <br>'); a.document.write(divContents); a.document.write('</body></html>'); a.document.close(); a.print(); } </script></head> <body> <center> <div id=\"GFG\" style=\"background-color: green;\"> <h2>Geeksforgeeks</h2> <table border=\"1px\"> <tr> <td>computer</td> <td>Algorithm</td> </tr> <tr> <td>Microwave</td> <td>Infrared</td> </tr> </table> </div> <p> The table is inside the div and will get printed on the click of button. </p> <input type=\"button\" value=\"click\" onclick=\"printDiv()\"> </center> </body> </html> ",
"e": 2993,
"s": 1675,
"text": null
},
{
"code": null,
"e": 3001,
"s": 2993,
"text": "Output:"
},
{
"code": null,
"e": 3029,
"s": 3001,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 3056,
"s": 3029,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 3275,
"s": 3056,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3282,
"s": 3275,
"text": "Picked"
},
{
"code": null,
"e": 3293,
"s": 3282,
"text": "JavaScript"
},
{
"code": null,
"e": 3310,
"s": 3293,
"text": "Web Technologies"
},
{
"code": null,
"e": 3337,
"s": 3310,
"text": "Web technologies Questions"
}
] |
PostgreSQL – IF Statement
|
22 Feb, 2022
PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.
Syntax:
IF condition THEN
statements;
END IF;
The above conditional statement is a boolean expression that evaluates to either true or false.
Example 1:
In this example, we declare two variables a and b. In the body of the block, we compare the value of a and b using the comparison operator >, < and = in the boolean expressions of the IF statements.
DO $$
DECLARE
a integer := 10;
b integer := 20;
BEGIN
IF a > b THEN
RAISE NOTICE 'a is greater than b';
END IF;
IF a < b THEN
RAISE NOTICE 'a is less than b';
END IF;
IF a = b THEN
RAISE NOTICE 'a is equal to b';
END IF;
END $$;
Output:
Example 2:
DO $$
DECLARE
a integer := 10;
b integer := 10;
BEGIN
IF a > b THEN
RAISE NOTICE 'a is greater than b';
ELSIF a < b THEN
RAISE NOTICE 'a is less than b';
ELSE
RAISE NOTICE 'a is equal to b';
END IF;
END $$;
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part."
},
{
"code": null,
"e": 259,
"s": 209,
"text": "Syntax:\nIF condition THEN\n statements;\nEND IF;\n"
},
{
"code": null,
"e": 355,
"s": 259,
"text": "The above conditional statement is a boolean expression that evaluates to either true or false."
},
{
"code": null,
"e": 366,
"s": 355,
"text": "Example 1:"
},
{
"code": null,
"e": 565,
"s": 366,
"text": "In this example, we declare two variables a and b. In the body of the block, we compare the value of a and b using the comparison operator >, < and = in the boolean expressions of the IF statements."
},
{
"code": null,
"e": 826,
"s": 565,
"text": "DO $$\nDECLARE\n a integer := 10;\n b integer := 20;\nBEGIN \n IF a > b THEN\n RAISE NOTICE 'a is greater than b';\n END IF;\n\n IF a < b THEN\n RAISE NOTICE 'a is less than b';\n END IF;\n\n IF a = b THEN\n RAISE NOTICE 'a is equal to b';\n END IF;\nEND $$;\n"
},
{
"code": null,
"e": 834,
"s": 826,
"text": "Output:"
},
{
"code": null,
"e": 845,
"s": 834,
"text": "Example 2:"
},
{
"code": null,
"e": 1084,
"s": 845,
"text": "DO $$\nDECLARE\n a integer := 10;\n b integer := 10;\nBEGIN \n IF a > b THEN \n RAISE NOTICE 'a is greater than b';\n ELSIF a < b THEN\n RAISE NOTICE 'a is less than b';\n ELSE\n RAISE NOTICE 'a is equal to b';\n END IF;\nEND $$;\n"
},
{
"code": null,
"e": 1092,
"s": 1084,
"text": "Output:"
},
{
"code": null,
"e": 1113,
"s": 1092,
"text": "postgreSQL-operators"
},
{
"code": null,
"e": 1124,
"s": 1113,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1222,
"s": 1124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1249,
"s": 1222,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 1281,
"s": 1249,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 1304,
"s": 1281,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 1344,
"s": 1304,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 1382,
"s": 1344,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1416,
"s": 1382,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 1440,
"s": 1416,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1495,
"s": 1440,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 1519,
"s": 1495,
"text": "PostgreSQL - Copy Table"
}
] |
Google Cloud Platform – Introduction to BigQuery Sandbox
|
23 Apr, 2021
BigQuery sandbox gives you free access to try out BigQuery and use the UI without providing a credit card or using a billing account. It’s a quick way to get started and try out some BigQuery concepts.
To get started, click on this link and follow along with the rest of the article. If you’re a new Google Cloud user, you’ll need to create an account and a project by following the prompts.
Once a project is created, you’ll be redirected to the BigQuery console, where you’ll see Sandbox in the top left-hand corner.
If you’re a returning Google Cloud user, create a new project by selecting the Project dropdown.
Your new project may be created with a default billing account. If that’s the case, go into the Billing Account Management page and select Disable Billing. Then use the search bar within the console to head to BigQuery.
Make sure your new project is selected in the Project dropdown, and there, you will also see Sandbox in the top left-hand corner. Now that you’re in the BigQuery Sandbox, you’re ready to start querying. That’s all it takes to get set up.
Because you aren’t charged for using the BigQuery Sandbox, there are a few caveats. Mainly, any tables or views that you create will expire after 60 days. You’re also limited to 10 gigabytes of storage, and one terabyte of data process each month. Now you can easily start working with public data sets, loading in your own data, and running some queries.
BigQuery provides publicly available data sets for anyone to analyze covering a variety of data types, from historical weather to taxi trips taken in New York City. To analyze public data, just click on the Add Data button on the left-hand side to see a list of the publicly available data sets that you already have available.
As a quick example, let’s use the project sunroof public data set, so you can see how much sunlight hits your roof in a year. For this we will be using the following query:
SELECT state_name, AVG(yearly_sunlight_kwh_kw_threshold_avg) AS average_sun
FROM 'bigquery-public-data.sunroof_solar.solar_potential_by_postal_code'
GROUP BY state_name
ORDER BY average_sun DESC
IMIT 3
In this sample query, we’re averaging the amount of sunlight per US state and ordering the top three states by the highest sunlight potential. As you can see, the top three states are New Mexico, Arizona, and Nevada.
Cloud-Computing
Google Cloud Platform
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Software Testing - Web Based Testing
Floyd’s Cycle Finding Algorithm
Samsung R&D Interview Experience
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
Deutsche Bank Interview Experience (2021-22 )
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "BigQuery sandbox gives you free access to try out BigQuery and use the UI without providing a credit card or using a billing account. It’s a quick way to get started and try out some BigQuery concepts. "
},
{
"code": null,
"e": 421,
"s": 231,
"text": "To get started, click on this link and follow along with the rest of the article. If you’re a new Google Cloud user, you’ll need to create an account and a project by following the prompts."
},
{
"code": null,
"e": 548,
"s": 421,
"text": "Once a project is created, you’ll be redirected to the BigQuery console, where you’ll see Sandbox in the top left-hand corner."
},
{
"code": null,
"e": 646,
"s": 548,
"text": " If you’re a returning Google Cloud user, create a new project by selecting the Project dropdown."
},
{
"code": null,
"e": 867,
"s": 646,
"text": " Your new project may be created with a default billing account. If that’s the case, go into the Billing Account Management page and select Disable Billing. Then use the search bar within the console to head to BigQuery."
},
{
"code": null,
"e": 1106,
"s": 867,
"text": " Make sure your new project is selected in the Project dropdown, and there, you will also see Sandbox in the top left-hand corner. Now that you’re in the BigQuery Sandbox, you’re ready to start querying. That’s all it takes to get set up."
},
{
"code": null,
"e": 1463,
"s": 1106,
"text": " Because you aren’t charged for using the BigQuery Sandbox, there are a few caveats. Mainly, any tables or views that you create will expire after 60 days. You’re also limited to 10 gigabytes of storage, and one terabyte of data process each month. Now you can easily start working with public data sets, loading in your own data, and running some queries."
},
{
"code": null,
"e": 1792,
"s": 1463,
"text": " BigQuery provides publicly available data sets for anyone to analyze covering a variety of data types, from historical weather to taxi trips taken in New York City. To analyze public data, just click on the Add Data button on the left-hand side to see a list of the publicly available data sets that you already have available."
},
{
"code": null,
"e": 1965,
"s": 1792,
"text": "As a quick example, let’s use the project sunroof public data set, so you can see how much sunlight hits your roof in a year. For this we will be using the following query:"
},
{
"code": null,
"e": 2167,
"s": 1965,
"text": "SELECT state_name, AVG(yearly_sunlight_kwh_kw_threshold_avg) AS average_sun\nFROM 'bigquery-public-data.sunroof_solar.solar_potential_by_postal_code'\nGROUP BY state_name\nORDER BY average_sun DESC\nIMIT 3"
},
{
"code": null,
"e": 2385,
"s": 2167,
"text": " In this sample query, we’re averaging the amount of sunlight per US state and ordering the top three states by the highest sunlight potential. As you can see, the top three states are New Mexico, Arizona, and Nevada."
},
{
"code": null,
"e": 2401,
"s": 2385,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 2423,
"s": 2401,
"text": "Google Cloud Platform"
},
{
"code": null,
"e": 2521,
"s": 2423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2595,
"s": 2521,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 2648,
"s": 2595,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 2685,
"s": 2648,
"text": "Software Testing - Web Based Testing"
},
{
"code": null,
"e": 2717,
"s": 2685,
"text": "Floyd’s Cycle Finding Algorithm"
},
{
"code": null,
"e": 2750,
"s": 2717,
"text": "Samsung R&D Interview Experience"
},
{
"code": null,
"e": 2820,
"s": 2750,
"text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!"
},
{
"code": null,
"e": 2846,
"s": 2820,
"text": "Spring Boot - Annotations"
},
{
"code": null,
"e": 2892,
"s": 2846,
"text": "Deutsche Bank Interview Experience (2021-22 )"
},
{
"code": null,
"e": 2919,
"s": 2892,
"text": "ReactJS useNavigate() Hook"
}
] |
HTML Basics
|
22 Jun, 2022
In this article, we will see the HTML Basics by understanding all the basic stuff of HTML coding. There are various tags that we must consider and include while starting to code in HTML. These tags help in the organization and basic formatting of elements in our script or web pages. These step-by-step procedures will guide you through the process of writing HTML.
Basic HTML Document: Below mentioned are the basic HTML tags that divide the whole document into various parts like head, body, etc.
Every HTML document begins with a HTML document tag. Although this is not mandatory, it is a good convention to start the document with this below-mentioned tag. Please refer to the HTML Doctypes article for more information related to Doctypes.
<!DOCTYPE html>
<html> : Every HTML code must be enclosed between basic HTML tags. It begins with <html> and ends with </html> tag.
<head>: The head tag comes next which contains all the header information of the web page or documents like the title of the page and other miscellaneous information. This information is enclosed within the head tag which opens with <head> and ends with </head>. The contents will of this tag will be explained in the later sections of the course.
<title>: We can mention the title of a web page using the <title> tag. This is header information and hence is mentioned within the header tags. The tag begins with <title> and ends with </title>.
<body>: Next step is the most important of all the tags we have learned so far. The body tag contains the actual body of the page which will be visible to all the users. This opens with <body> and ends with </body>. All content enclosed within this tag will be shown on the web page be it writings or images or audio or videos or even links. We will see later in the section how using various tags we may insert mentioned contents into our web pages.
The whole pattern of the code will look something like the below code example.
Example: This example illustrates the HTML basic structure.
HTML
<html> <head> <!-- Information about the page --> <!--This is the comment tag--> <title>GeeksforGeeks</title></head> <body> <!--Contents of the webpage--></body> </html>
This code won’t display anything. It just shows the basic pattern of how to write the HTML code and will name the title of the page as GeeksforGeeks. <! – – comment here – – > is the comment tag in HTML and it doesn’t read the line present inside this tag.
HTML Headings: These tags help us to give headings to the content of a webpage. These tags are mainly written inside the body tag. HTML provides us with six heading tags from <h1> to <h6>. Every tag displays the heading in a different style and font size.
Most HTML heading tag that we use :-
Heading 1
Heading 2
Heading 3
Example: This example illustrates the use of 6 heading tags from <h1> to <h6> in HTML.
HTML
<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <h2>Hello GeeksforGeeks</h2> <h3>Hello GeeksforGeeks</h3> <h4>Hello GeeksforGeeks</h4> <h5>Hello GeeksforGeeks</h5> <h6>Hello GeeksforGeeks</h6></body> </html>
Output:
HTML Headings
HTML Paragraph: These tags help us to write paragraph statements on a webpage. They start with the <p> tag and ends with </p>.
HTML Break: – These tags are used for inserting a single line type break. It does not have any closing tag. In HTML the break tag is written as <br>.
Example: This example illustrates the use of the <p> tag for writing a paragraph statement in HTML.
HTML
<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> </body> </html>
Output:
HTML Paragraph
HTML Horizontal Line: The <hr> tag is used to break the page into various parts, creating horizontal margins with help of a horizontal line running from the left to right-hand side of the page. This is also an empty tag and doesn’t take any additional statements.
Example: This example illustrates the use of the <hr> tag for the horizontal line in HTML.
HTML
<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr></body> </html>
Output:
Adding horizontal line using the <hr> tag
HTML Images: The image tag is used to insert an image into our web page. The source of the image to be inserted is put inside the <img src=”source_of_image“> tag.
Image can be inserted in the image tag in two formats: –
If the image is in the same folder, then we can just write the name of the image and the format as the path.
If the image is in another folder, then we do need to mention the path of the image and the image name as well as the format of the image.
Example: This example illustrates the use of the <img> tag for inserting the images in HTML.
HTML
<html> <head> <title>GeeksforGeeks</title></head> <body> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png"></body> </html>
Output:
Adding image using <img> tag
Supported Browsers:
Google Chrome 93.0 & above
Internet Explorer 11.0
Microsoft Edge 93.0
Firefox 92.0 & above
Opera 79.0
Safari 14.1
There are also various other tags in HTML to insert links, audios, and various other formatting tags that we will be learning in the later sections.
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
HTML is the foundation of web pages and 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.
imdp
ysachin2314
bhaskargeeksforgeeks
jyotibujethiya
codingbeast12
HTML and XML
HTML-Basics
Web technologies-HTML and XML
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 419,
"s": 53,
"text": "In this article, we will see the HTML Basics by understanding all the basic stuff of HTML coding. There are various tags that we must consider and include while starting to code in HTML. These tags help in the organization and basic formatting of elements in our script or web pages. These step-by-step procedures will guide you through the process of writing HTML."
},
{
"code": null,
"e": 552,
"s": 419,
"text": "Basic HTML Document: Below mentioned are the basic HTML tags that divide the whole document into various parts like head, body, etc."
},
{
"code": null,
"e": 798,
"s": 552,
"text": "Every HTML document begins with a HTML document tag. Although this is not mandatory, it is a good convention to start the document with this below-mentioned tag. Please refer to the HTML Doctypes article for more information related to Doctypes."
},
{
"code": null,
"e": 814,
"s": 798,
"text": "<!DOCTYPE html>"
},
{
"code": null,
"e": 930,
"s": 814,
"text": "<html> : Every HTML code must be enclosed between basic HTML tags. It begins with <html> and ends with </html> tag."
},
{
"code": null,
"e": 1278,
"s": 930,
"text": "<head>: The head tag comes next which contains all the header information of the web page or documents like the title of the page and other miscellaneous information. This information is enclosed within the head tag which opens with <head> and ends with </head>. The contents will of this tag will be explained in the later sections of the course."
},
{
"code": null,
"e": 1475,
"s": 1278,
"text": "<title>: We can mention the title of a web page using the <title> tag. This is header information and hence is mentioned within the header tags. The tag begins with <title> and ends with </title>."
},
{
"code": null,
"e": 1926,
"s": 1475,
"text": "<body>: Next step is the most important of all the tags we have learned so far. The body tag contains the actual body of the page which will be visible to all the users. This opens with <body> and ends with </body>. All content enclosed within this tag will be shown on the web page be it writings or images or audio or videos or even links. We will see later in the section how using various tags we may insert mentioned contents into our web pages."
},
{
"code": null,
"e": 2005,
"s": 1926,
"text": "The whole pattern of the code will look something like the below code example."
},
{
"code": null,
"e": 2065,
"s": 2005,
"text": "Example: This example illustrates the HTML basic structure."
},
{
"code": null,
"e": 2070,
"s": 2065,
"text": "HTML"
},
{
"code": "<html> <head> <!-- Information about the page --> <!--This is the comment tag--> <title>GeeksforGeeks</title></head> <body> <!--Contents of the webpage--></body> </html>",
"e": 2257,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2514,
"s": 2257,
"text": "This code won’t display anything. It just shows the basic pattern of how to write the HTML code and will name the title of the page as GeeksforGeeks. <! – – comment here – – > is the comment tag in HTML and it doesn’t read the line present inside this tag."
},
{
"code": null,
"e": 2772,
"s": 2514,
"text": "HTML Headings: These tags help us to give headings to the content of a webpage. These tags are mainly written inside the body tag. HTML provides us with six heading tags from <h1> to <h6>. Every tag displays the heading in a different style and font size. "
},
{
"code": null,
"e": 2810,
"s": 2772,
"text": "Most HTML heading tag that we use :- "
},
{
"code": null,
"e": 2821,
"s": 2810,
"text": "Heading 1 "
},
{
"code": null,
"e": 2831,
"s": 2821,
"text": "Heading 2"
},
{
"code": null,
"e": 2842,
"s": 2831,
"text": "Heading 3 "
},
{
"code": null,
"e": 2929,
"s": 2842,
"text": "Example: This example illustrates the use of 6 heading tags from <h1> to <h6> in HTML."
},
{
"code": null,
"e": 2934,
"s": 2929,
"text": "HTML"
},
{
"code": "<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <h2>Hello GeeksforGeeks</h2> <h3>Hello GeeksforGeeks</h3> <h4>Hello GeeksforGeeks</h4> <h5>Hello GeeksforGeeks</h5> <h6>Hello GeeksforGeeks</h6></body> </html>",
"e": 3201,
"s": 2934,
"text": null
},
{
"code": null,
"e": 3209,
"s": 3201,
"text": "Output:"
},
{
"code": null,
"e": 3223,
"s": 3209,
"text": "HTML Headings"
},
{
"code": null,
"e": 3352,
"s": 3223,
"text": "HTML Paragraph: These tags help us to write paragraph statements on a webpage. They start with the <p> tag and ends with </p>. "
},
{
"code": null,
"e": 3503,
"s": 3352,
"text": "HTML Break: – These tags are used for inserting a single line type break. It does not have any closing tag. In HTML the break tag is written as <br>. "
},
{
"code": null,
"e": 3603,
"s": 3503,
"text": "Example: This example illustrates the use of the <p> tag for writing a paragraph statement in HTML."
},
{
"code": null,
"e": 3608,
"s": 3603,
"text": "HTML"
},
{
"code": "<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> </body> </html>",
"e": 3871,
"s": 3608,
"text": null
},
{
"code": null,
"e": 3879,
"s": 3871,
"text": "Output:"
},
{
"code": null,
"e": 3894,
"s": 3879,
"text": "HTML Paragraph"
},
{
"code": null,
"e": 4158,
"s": 3894,
"text": "HTML Horizontal Line: The <hr> tag is used to break the page into various parts, creating horizontal margins with help of a horizontal line running from the left to right-hand side of the page. This is also an empty tag and doesn’t take any additional statements."
},
{
"code": null,
"e": 4249,
"s": 4158,
"text": "Example: This example illustrates the use of the <hr> tag for the horizontal line in HTML."
},
{
"code": null,
"e": 4254,
"s": 4249,
"text": "HTML"
},
{
"code": "<html> <head> <title>GeeksforGeeks</title></head> <body> <h1>Hello GeeksforGeeks</h1> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr> <p> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> A Computer Science portal for geeks<br> </p> <hr></body> </html>",
"e": 4874,
"s": 4254,
"text": null
},
{
"code": null,
"e": 4882,
"s": 4874,
"text": "Output:"
},
{
"code": null,
"e": 4924,
"s": 4882,
"text": "Adding horizontal line using the <hr> tag"
},
{
"code": null,
"e": 5087,
"s": 4924,
"text": "HTML Images: The image tag is used to insert an image into our web page. The source of the image to be inserted is put inside the <img src=”source_of_image“> tag."
},
{
"code": null,
"e": 5145,
"s": 5087,
"text": "Image can be inserted in the image tag in two formats: – "
},
{
"code": null,
"e": 5255,
"s": 5145,
"text": "If the image is in the same folder, then we can just write the name of the image and the format as the path. "
},
{
"code": null,
"e": 5395,
"s": 5255,
"text": "If the image is in another folder, then we do need to mention the path of the image and the image name as well as the format of the image. "
},
{
"code": null,
"e": 5488,
"s": 5395,
"text": "Example: This example illustrates the use of the <img> tag for inserting the images in HTML."
},
{
"code": null,
"e": 5493,
"s": 5488,
"text": "HTML"
},
{
"code": "<html> <head> <title>GeeksforGeeks</title></head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Geek_logi_-low_res.png\"></body> </html>",
"e": 5661,
"s": 5493,
"text": null
},
{
"code": null,
"e": 5669,
"s": 5661,
"text": "Output:"
},
{
"code": null,
"e": 5698,
"s": 5669,
"text": "Adding image using <img> tag"
},
{
"code": null,
"e": 5718,
"s": 5698,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 5745,
"s": 5718,
"text": "Google Chrome 93.0 & above"
},
{
"code": null,
"e": 5768,
"s": 5745,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 5788,
"s": 5768,
"text": "Microsoft Edge 93.0"
},
{
"code": null,
"e": 5809,
"s": 5788,
"text": "Firefox 92.0 & above"
},
{
"code": null,
"e": 5820,
"s": 5809,
"text": "Opera 79.0"
},
{
"code": null,
"e": 5832,
"s": 5820,
"text": "Safari 14.1"
},
{
"code": null,
"e": 5981,
"s": 5832,
"text": "There are also various other tags in HTML to insert links, audios, and various other formatting tags that we will be learning in the later sections."
},
{
"code": null,
"e": 6278,
"s": 5981,
"text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6406,
"s": 6278,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6605,
"s": 6406,
"text": "HTML is the foundation of web pages and 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": 6610,
"s": 6605,
"text": "imdp"
},
{
"code": null,
"e": 6622,
"s": 6610,
"text": "ysachin2314"
},
{
"code": null,
"e": 6643,
"s": 6622,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 6658,
"s": 6643,
"text": "jyotibujethiya"
},
{
"code": null,
"e": 6672,
"s": 6658,
"text": "codingbeast12"
},
{
"code": null,
"e": 6685,
"s": 6672,
"text": "HTML and XML"
},
{
"code": null,
"e": 6697,
"s": 6685,
"text": "HTML-Basics"
},
{
"code": null,
"e": 6727,
"s": 6697,
"text": "Web technologies-HTML and XML"
},
{
"code": null,
"e": 6732,
"s": 6727,
"text": "HTML"
},
{
"code": null,
"e": 6749,
"s": 6732,
"text": "Web Technologies"
},
{
"code": null,
"e": 6754,
"s": 6749,
"text": "HTML"
},
{
"code": null,
"e": 6852,
"s": 6754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6900,
"s": 6852,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 6962,
"s": 6900,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7012,
"s": 6962,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7036,
"s": 7012,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 7089,
"s": 7036,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 7122,
"s": 7089,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 7184,
"s": 7122,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7245,
"s": 7184,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7295,
"s": 7245,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Ways to create triplets from given list
|
18 Feb, 2019
Given a list of words, write a Python program to create triplets from the given list.
Examples :
Input: [‘Geeks’, ‘for’, ‘Geeks’, ‘is’, ‘best’, ‘resource’, ‘for’, ‘study’]Output:[[‘Geeks’, ‘for’, ‘Geeks’], [‘for’, ‘Geeks’, ‘is’],[‘Geeks’, ‘is’, ‘best’], [‘is’, ‘best’, ‘resource’],[‘best’, ‘resource’, ‘for’], [‘resource’, ‘for’, ‘study’]]
Input: [‘I’, ‘am’, ‘Paras’, ‘Jain’, ‘I’, ‘Study’, ‘From’, ‘GFG’]Output:[[‘I’, ‘am’, ‘Paras’], [‘am’, ‘Paras’, ‘Jain’],[‘Paras’, ‘Jain’, ‘I’], [‘Jain’, ‘I’, ‘Study’],[‘I’, ‘Study’, ‘From’], [‘Study’, ‘From’, ‘GFG’]]
Let’s see some of the methods to do this task.
Method #1: Using List comprehension
# Python code to create triplets from list of words. # List of word initializationlist_of_words = ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo'] # Using list comprehensionList = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # printing listprint(List)
[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'],
['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'],
['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]
Method #2: Using Iteration
# Python code to create triplets from list of words. # List of word initializationlist_of_words = ['Geeks', 'for', 'Geeks', 'is', 'best', 'resource', 'for', 'study'] # Output list initializationout = [] # Finding length of listlength = len(list_of_words) # Using iterationfor z in range(0, length-2): # Creating a temp list to add 3 words temp = [] temp.append(list_of_words[z]) temp.append(list_of_words[z + 1]) temp.append(list_of_words[z + 2]) out.append(temp) # printing outputprint(out)
[['Geeks', 'for', 'Geeks'], ['for', 'Geeks', 'is'],
['Geeks', 'is', 'best'], ['is', 'best', 'resource'],
['best', 'resource', 'for'], ['resource', 'for', 'study']]
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "Given a list of words, write a Python program to create triplets from the given list."
},
{
"code": null,
"e": 125,
"s": 114,
"text": "Examples :"
},
{
"code": null,
"e": 368,
"s": 125,
"text": "Input: [‘Geeks’, ‘for’, ‘Geeks’, ‘is’, ‘best’, ‘resource’, ‘for’, ‘study’]Output:[[‘Geeks’, ‘for’, ‘Geeks’], [‘for’, ‘Geeks’, ‘is’],[‘Geeks’, ‘is’, ‘best’], [‘is’, ‘best’, ‘resource’],[‘best’, ‘resource’, ‘for’], [‘resource’, ‘for’, ‘study’]]"
},
{
"code": null,
"e": 583,
"s": 368,
"text": "Input: [‘I’, ‘am’, ‘Paras’, ‘Jain’, ‘I’, ‘Study’, ‘From’, ‘GFG’]Output:[[‘I’, ‘am’, ‘Paras’], [‘am’, ‘Paras’, ‘Jain’],[‘Paras’, ‘Jain’, ‘I’], [‘Jain’, ‘I’, ‘Study’],[‘I’, ‘Study’, ‘From’], [‘Study’, ‘From’, ‘GFG’]]"
},
{
"code": null,
"e": 630,
"s": 583,
"text": "Let’s see some of the methods to do this task."
},
{
"code": null,
"e": 666,
"s": 630,
"text": "Method #1: Using List comprehension"
},
{
"code": "# Python code to create triplets from list of words. # List of word initializationlist_of_words = ['I', 'am', 'Paras', 'Jain', 'I', 'Study', 'DS', 'Algo'] # Using list comprehensionList = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # printing listprint(List)",
"e": 972,
"s": 666,
"text": null
},
{
"code": null,
"e": 1119,
"s": 972,
"text": "[['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], \n ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'],\n ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]\n"
},
{
"code": null,
"e": 1147,
"s": 1119,
"text": " Method #2: Using Iteration"
},
{
"code": "# Python code to create triplets from list of words. # List of word initializationlist_of_words = ['Geeks', 'for', 'Geeks', 'is', 'best', 'resource', 'for', 'study'] # Output list initializationout = [] # Finding length of listlength = len(list_of_words) # Using iterationfor z in range(0, length-2): # Creating a temp list to add 3 words temp = [] temp.append(list_of_words[z]) temp.append(list_of_words[z + 1]) temp.append(list_of_words[z + 2]) out.append(temp) # printing outputprint(out)",
"e": 1678,
"s": 1147,
"text": null
},
{
"code": null,
"e": 1845,
"s": 1678,
"text": "[['Geeks', 'for', 'Geeks'], ['for', 'Geeks', 'is'],\n ['Geeks', 'is', 'best'], ['is', 'best', 'resource'],\n ['best', 'resource', 'for'], ['resource', 'for', 'study']]\n"
},
{
"code": null,
"e": 1866,
"s": 1845,
"text": "Python list-programs"
},
{
"code": null,
"e": 1878,
"s": 1866,
"text": "python-list"
},
{
"code": null,
"e": 1885,
"s": 1878,
"text": "Python"
},
{
"code": null,
"e": 1901,
"s": 1885,
"text": "Python Programs"
},
{
"code": null,
"e": 1913,
"s": 1901,
"text": "python-list"
},
{
"code": null,
"e": 2011,
"s": 1913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2029,
"s": 2011,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2071,
"s": 2029,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2093,
"s": 2071,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2128,
"s": 2093,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2154,
"s": 2128,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2197,
"s": 2154,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2258,
"s": 2219,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2296,
"s": 2258,
"text": "Python | Convert a list to dictionary"
}
] |
Web Workers in Javascript
|
04 Jun, 2019
Web workers are giving us the possibility to write multi-threaded Javascript, which does not block the DOM. Even the Asynchronous operations block the DOM to some extent. On the other side, web workers help us solve this problem, escaping the single-threaded environment and reaching a higher performance of our web pages.
In order to use:
Web workers live in their own file (Not interacting with the User Interface)
Functions are Passed By Copy
No global variables are allowed
Implementing Web Workers
/* -----------------------------Index.JS--------------------------*/ // Check if web worker functionality is available for the browser if(window.Worker){ // Creating new web worker using constructor var worker = new Worker('worker.js'); var message = 'Hello'; // Sending the message using postMessage worker.postMessage(message); // On response worker.onmessage = function(e) { console.log(e.data); }; } /* -----------------------------Worker.JS--------------------------*/ // Waits for any activity from the pageself.onmessage = function(e) { if(e.data !== undefined) { // Do work var total = e.data + ' World'; // Posting back to the page self.postMessage(total) }}// Terminate with: worker.terminate()
In the example above, the worker is doing the work of concatenating the received string with the defined one and sends it back to the main.js file without interrupting the page.
Output :'Hello World'
Web Workers does not have access to:
The Parent Object
The Window Object
The Document Object
The DOM
However, the do have access to:
The location object
The navigator object
XMLHttpRequest
The Application Cache
Spawning other web workers (Stored at the same origin as the parent page)
Importing external script using importScripts()
Common use cases:
When complex computing calculations are required
In HTML5 Games (Higher frame rate)
At any websites containing JavaScript for performance improvement
Real World Example
The following program is written for the reason to show what difference is in the behavior of our page with and without worker.
/* -----------------------------Index.JS--------------------------*/const delay = 5000; // Get element of without worker buttonconst noWorkerBtn = document.getElementById('worker--without');// Add event listener to the button itselfnoWorkerBtn.addEventListener('click', () => { // Define the starting time const start = performance.now(); // Do complex calculations while (performance.now() - start < delay); // Get the ending time const end = performance.now(); // Calculate the difference in time const resWithoutWorker = end - start; // Log the result console.log('No worker:', resWithoutWorker); }); // Define a workerconst worker = new Worker('./worker.js'); // Get element of with worker buttonconst workerBtn = document.getElementById('worker--with'); // Add event listener to the buttonworkerBtn.addEventListener('click', () => { // Send delay number worker.postMessage(delay); });// On message from workerworker.onmessage = e => { // Log the result console.log("With worker: ", e.data);}; /* -----------------------------Worker.JS--------------------------*/ // On message receivedthis.onmessage = e => { // Delay equals to data received const delay = e.data; // Define starting time const start = performance.now(); // Do the complex calculation while (performance.now() - start < delay); // Get ending time const end = performance.now(); // Calculate difference const resWithWorker = end - start; // Send result this.postMessage(end - start);};
Examples:
Output: 'No worker: 5000'
Output: 'With worker: 5000'
That’s how the page behaves without our worker code:
The animation freezes because the JavaScript is blocking the DOM.
Page behaviour without webworker
That’s how the page behaves with our worker code:
As you can see the animation in the background is not interrupted as our worker does the calculation for us. In this way, we let the DOM thread run independently.
Page behaviour with webworker
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2019"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "Web workers are giving us the possibility to write multi-threaded Javascript, which does not block the DOM. Even the Asynchronous operations block the DOM to some extent. On the other side, web workers help us solve this problem, escaping the single-threaded environment and reaching a higher performance of our web pages."
},
{
"code": null,
"e": 368,
"s": 351,
"text": "In order to use:"
},
{
"code": null,
"e": 445,
"s": 368,
"text": "Web workers live in their own file (Not interacting with the User Interface)"
},
{
"code": null,
"e": 474,
"s": 445,
"text": "Functions are Passed By Copy"
},
{
"code": null,
"e": 506,
"s": 474,
"text": "No global variables are allowed"
},
{
"code": null,
"e": 531,
"s": 506,
"text": "Implementing Web Workers"
},
{
"code": "/* -----------------------------Index.JS--------------------------*/ // Check if web worker functionality is available for the browser if(window.Worker){ // Creating new web worker using constructor var worker = new Worker('worker.js'); var message = 'Hello'; // Sending the message using postMessage worker.postMessage(message); // On response worker.onmessage = function(e) { console.log(e.data); }; } /* -----------------------------Worker.JS--------------------------*/ // Waits for any activity from the pageself.onmessage = function(e) { if(e.data !== undefined) { // Do work var total = e.data + ' World'; // Posting back to the page self.postMessage(total) }}// Terminate with: worker.terminate()",
"e": 1467,
"s": 531,
"text": null
},
{
"code": null,
"e": 1645,
"s": 1467,
"text": "In the example above, the worker is doing the work of concatenating the received string with the defined one and sends it back to the main.js file without interrupting the page."
},
{
"code": null,
"e": 1668,
"s": 1645,
"text": "Output :'Hello World'\n"
},
{
"code": null,
"e": 1705,
"s": 1668,
"text": "Web Workers does not have access to:"
},
{
"code": null,
"e": 1723,
"s": 1705,
"text": "The Parent Object"
},
{
"code": null,
"e": 1741,
"s": 1723,
"text": "The Window Object"
},
{
"code": null,
"e": 1761,
"s": 1741,
"text": "The Document Object"
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "The DOM"
},
{
"code": null,
"e": 1801,
"s": 1769,
"text": "However, the do have access to:"
},
{
"code": null,
"e": 1821,
"s": 1801,
"text": "The location object"
},
{
"code": null,
"e": 1842,
"s": 1821,
"text": "The navigator object"
},
{
"code": null,
"e": 1857,
"s": 1842,
"text": "XMLHttpRequest"
},
{
"code": null,
"e": 1879,
"s": 1857,
"text": "The Application Cache"
},
{
"code": null,
"e": 1953,
"s": 1879,
"text": "Spawning other web workers (Stored at the same origin as the parent page)"
},
{
"code": null,
"e": 2001,
"s": 1953,
"text": "Importing external script using importScripts()"
},
{
"code": null,
"e": 2019,
"s": 2001,
"text": "Common use cases:"
},
{
"code": null,
"e": 2068,
"s": 2019,
"text": "When complex computing calculations are required"
},
{
"code": null,
"e": 2103,
"s": 2068,
"text": "In HTML5 Games (Higher frame rate)"
},
{
"code": null,
"e": 2169,
"s": 2103,
"text": "At any websites containing JavaScript for performance improvement"
},
{
"code": null,
"e": 2188,
"s": 2169,
"text": "Real World Example"
},
{
"code": null,
"e": 2316,
"s": 2188,
"text": "The following program is written for the reason to show what difference is in the behavior of our page with and without worker."
},
{
"code": "/* -----------------------------Index.JS--------------------------*/const delay = 5000; // Get element of without worker buttonconst noWorkerBtn = document.getElementById('worker--without');// Add event listener to the button itselfnoWorkerBtn.addEventListener('click', () => { // Define the starting time const start = performance.now(); // Do complex calculations while (performance.now() - start < delay); // Get the ending time const end = performance.now(); // Calculate the difference in time const resWithoutWorker = end - start; // Log the result console.log('No worker:', resWithoutWorker); }); // Define a workerconst worker = new Worker('./worker.js'); // Get element of with worker buttonconst workerBtn = document.getElementById('worker--with'); // Add event listener to the buttonworkerBtn.addEventListener('click', () => { // Send delay number worker.postMessage(delay); });// On message from workerworker.onmessage = e => { // Log the result console.log(\"With worker: \", e.data);}; /* -----------------------------Worker.JS--------------------------*/ // On message receivedthis.onmessage = e => { // Delay equals to data received const delay = e.data; // Define starting time const start = performance.now(); // Do the complex calculation while (performance.now() - start < delay); // Get ending time const end = performance.now(); // Calculate difference const resWithWorker = end - start; // Send result this.postMessage(end - start);};",
"e": 3866,
"s": 2316,
"text": null
},
{
"code": null,
"e": 3876,
"s": 3866,
"text": "Examples:"
},
{
"code": null,
"e": 3932,
"s": 3876,
"text": "Output: 'No worker: 5000'\nOutput: 'With worker: 5000'\n"
},
{
"code": null,
"e": 3985,
"s": 3932,
"text": "That’s how the page behaves without our worker code:"
},
{
"code": null,
"e": 4051,
"s": 3985,
"text": "The animation freezes because the JavaScript is blocking the DOM."
},
{
"code": null,
"e": 4084,
"s": 4051,
"text": "Page behaviour without webworker"
},
{
"code": null,
"e": 4134,
"s": 4084,
"text": "That’s how the page behaves with our worker code:"
},
{
"code": null,
"e": 4297,
"s": 4134,
"text": "As you can see the animation in the background is not interrupted as our worker does the calculation for us. In this way, we let the DOM thread run independently."
},
{
"code": null,
"e": 4327,
"s": 4297,
"text": "Page behaviour with webworker"
},
{
"code": null,
"e": 4343,
"s": 4327,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4354,
"s": 4343,
"text": "JavaScript"
},
{
"code": null,
"e": 4371,
"s": 4354,
"text": "Web Technologies"
}
] |
Find the number of islands | Set 1 (Using DFS)
|
20 Jun, 2022
Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands
Example:
Input : mat[][] = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}}
Output : 5
This is a variation of the standard problem: “Counting the number of connected components in an undirected graph”.
Before we go to the problem, let us understand what is a connected component. A connected component of an undirected graph is a subgraph in which every two vertices are connected to each other by a path(s), and which is connected to no other vertices outside the subgraph. For example, the graph shown below has three connected components.
A graph where all vertices are connected with each other has exactly one connected component, consisting of the whole graph. Such a graph with only one connected component is called a Strongly Connected Graph.The problem can be easily solved by applying DFS() on each component. In each DFS() call, a component or a sub-graph is visited. We will call DFS on the next un-visited component. The number of calls to DFS() gives the number of connected components. BFS can also be used.
What is an island?
A group of connected 1s forms an island. For example, the below matrix contains 4 islands
A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we recursively call for all adjacent vertices, here we can recursively call for 8 neighbours only. We keep track of the visited 1s so that they are not visited again.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to count islands in boolean 2D matrix#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 5 // A function to check if a given// cell (row, col) can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to do DFS for a// 2D boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL]){ // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited);} // The main function that returns// count of islands in a given boolean// 2D matrixint countIslands(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count;} // Driver codeint main(){ int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << "Number of islands is: " << countIslands(M); return 0;} // This is code is contributed by rathbhupendra
// Program to count islands in boolean 2D matrix#include <stdbool.h>#include <stdio.h>#include <string.h> #define ROW 5#define COL 5 // A function to check if a given cell (row, col) can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, column number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to do DFS for a 2D boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL]){ // These arrays are used to get row and column numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited);} // The main function that returns count of islands in a given boolean// 2D matrixint countIslands(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i][j] && !visited[i][j]) // If a cell with value 1 is not { // visited yet, then new island found DFS(M, i, j, visited); // Visit all cells in this island. ++count; // and increment island count } return count;} // Driver program to test above functionint main(){ int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; printf("Number of islands is: %d\n", countIslands(M)); return 0;}
// Java program to count islands in boolean 2D matriximport java.util.*;import java.lang.*;import java.io.*; class Islands { // No of rows and columns static final int ROW = 5, COL = 5; // A function to check if a given cell (row, col) can // be included in DFS boolean isSafe(int M[][], int row, int col, boolean visited[][]) { // row number is in range, column number is in range // and value is 1 and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); } // A utility function to do DFS for a 2D boolean matrix. // It only considers the 8 neighbors as adjacent vertices void DFS(int M[][], int row, int col, boolean visited[][]) { // These arrays are used to get row and column numbers // of 8 neighbors of a given cell int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 }; int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns count of islands in a given // boolean 2D matrix int countIslands(int M[][]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited boolean visited[][] = new boolean[ROW][COL]; // Initialize count as 0 and traverse through the all cells // of given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i][j] == 1 && !visited[i][j]) // If a cell with { // value 1 is not // visited yet, then new island found, Visit all // cells in this island and increment island count DFS(M, i, j, visited); ++count; } return count; } // Driver method public static void main(String[] args) throws java.lang.Exception { int M[][] = new int[][] { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Islands I = new Islands(); System.out.println("Number of islands is: " + I.countIslands(M)); }} // Contributed by Aakash Hasija
# Program to count islands in boolean 2D matrixclass Graph: def __init__(self, row, col, g): self.ROW = row self.COL = col self.graph = g # A function to check if a given cell # (row, col) can be included in DFS def isSafe(self, i, j, visited): # row number is in range, column number # is in range and value is 1 # and not yet visited return (i >= 0 and i < self.ROW and j >= 0 and j < self.COL and not visited[i][j] and self.graph[i][j]) # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j, visited): # These arrays are used to get row and # column numbers of 8 neighbours # of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]; colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]; # Mark this cell as visited visited[i][j] = True # Recur for all connected neighbours for k in range(8): if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): self.DFS(i + rowNbr[k], j + colNbr[k], visited) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[False for j in range(self.COL)]for i in range(self.ROW)] # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if visited[i][j] == False and self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j, visited) count += 1 return count graph = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph)col = len(graph[0]) g = Graph(row, col, graph) print ("Number of islands is:")print (g.countIslands()) # This code is contributed by Neelam Yadav
// C# program to count// islands in boolean// 2D matrixusing System; class GFG { // No of rows // and columns static int ROW = 5, COL = 5; // A function to check if // a given cell (row, col) // can be included in DFS static bool isSafe(int[, ] M, int row, int col, bool[, ] visited) { // row number is in range, // column number is in range // and value is 1 and not // yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row, col] == 1 && !visited[row, col]); } // A utility function to do // DFS for a 2D boolean matrix. // It only considers the 8 // neighbors as adjacent vertices static void DFS(int[, ] M, int row, int col, bool[, ] visited) { // These arrays are used to // get row and column numbers // of 8 neighbors of a given cell int[] rowNbr = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell // as visited visited[row, col] = true; // Recur for all // connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that // returns count of islands // in a given boolean 2D matrix static int countIslands(int[, ] M) { // Make a bool array to // mark visited cells. // Initially all cells // are unvisited bool[, ] visited = new bool[ROW, COL]; // Initialize count as 0 and // traverse through the all // cells of given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i, j] == 1 && !visited[i, j]) { // If a cell with value 1 is not // visited yet, then new island // found, Visit all cells in this // island and increment island count DFS(M, i, j, visited); ++count; } return count; } // Driver Code public static void Main() { int[, ] M = new int[, ] { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Console.Write("Number of islands is: " + countIslands(M)); }} // This code is contributed// by shiv_bhakt.
<?php// Program to count islands// in boolean 2D matrix $ROW = 5;$COL = 5; // A function to check if a// given cell (row, col) can// be included in DFSfunction isSafe(&$M, $row, $col, &$visited){ global $ROW, $COL; // row number is in range, // column number is in // range and value is 1 // and not yet visited return ($row >= 0) && ($row < $ROW) && ($col >= 0) && ($col < $COL) && ($M[$row][$col] && !isset($visited[$row][$col]));} // A utility function to do DFS// for a 2D boolean matrix. It// only considers the 8 neighbours// as adjacent verticesfunction DFS(&$M, $row, $col, &$visited){ // These arrays are used to // get row and column numbers // of 8 neighbours of a given cell $rowNbr = array(-1, -1, -1, 0, 0, 1, 1, 1); $colNbr = array(-1, 0, 1, -1, 1, -1, 0, 1); // Mark this cell as visited $visited[$row][$col] = true; // Recur for all // connected neighbours for ($k = 0; $k < 8; ++$k) if (isSafe($M, $row + $rowNbr[$k], $col + $colNbr[$k], $visited)) DFS($M, $row + $rowNbr[$k], $col + $colNbr[$k], $visited);} // The main function that returns// count of islands in a given// boolean 2D matrixfunction countIslands(&$M){ global $ROW, $COL; // Make a bool array to // mark visited cells. // Initially all cells // are unvisited $visited = array(array()); // Initialize count as 0 and // traverse through the all // cells of given matrix $count = 0; for ($i = 0; $i < $ROW; ++$i) for ($j = 0; $j < $COL; ++$j) if ($M[$i][$j] && !isset($visited[$i][$j])) // If a cell with value 1 { // is not visited yet, DFS($M, $i, $j, $visited); // then new island found ++$count; // Visit all cells in this } // island and increment // island count. return $count;} // Driver Code$M = array(array(1, 1, 0, 0, 0), array(0, 1, 0, 0, 1), array(1, 0, 0, 1, 1), array(0, 0, 0, 0, 0), array(1, 0, 1, 0, 1)); echo "Number of islands is: ", countIslands($M); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to count islands in boolean 2D matrix // No of rows and columns let ROW = 5, COL = 5; // A function to check if a given cell (row, col) can // be included in DFS function isSafe(M,row,col,visited) { // row number is in range, column number is in range // and value is 1 and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); } // A utility function to do DFS for a 2D boolean matrix. // It only considers the 8 neighbors as adjacent vertices function DFS(M, row, col, visited) { // These arrays are used to get row and column numbers // of 8 neighbors of a given cell let rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]; let colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (let k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns count of islands in a given // boolean 2D matrix function countIslands(M) { // Make a bool array to mark visited cells. // Initially all cells are unvisited let visited = new Array(ROW); for(let i = 0; i < ROW; i++) { visited[i] = new Array(COL); } for(let i = 0; i < ROW; i++) { for(let j = 0; j < COL; j++) { visited[i][j] = false; } } // Initialize count as 0 and traverse through the all cells // of given matrix let count = 0; for (let i = 0; i < ROW; ++i) { for (let j = 0; j < COL; ++j) { if (M[i][j] == 1 && !visited[i][j]) { // value 1 is not // visited yet, then new island found, Visit all // cells in this island and increment island count DFS(M, i, j, visited); count++; } } } return count; } // Driver method let M = [[ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1], [1, 0, 0, 1, 1] ,[0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]; document.write("Number of islands is: " + countIslands(M)); // This code is contributed by avanitrachhadiya2155</script>
Number of islands is: 5
Time complexity: O(ROW x COL)Auxiliary Space: O(ROW x COL), due to visited matrix
Alternative solution without creating visited matrix:
C++
Java
Python3
C#
Javascript
// C++Program to count islands in boolean 2D matrix#include <bits/stdc++.h>using namespace std; // A utility function to do DFS for a 2D// boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(vector<vector<int>> &M, int i, int j, int ROW, int COL){ //Base condition //if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal }} int countIslands(vector<vector<int>> &M){ int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count;} // Driver Codeint main(){ vector<vector<int>> M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; cout << "Number of islands is: " << countIslands(M); return 0;} // This code is contributed by ajaymakvana.
// Java Program to count islands in boolean 2D matriximport java.util.*;public class Main{ // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices static void DFS(int[][] M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } static int countIslands(int[][] M) { int ROW = M.length; int COL = M[0].length; int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } // Driver code public static void main(String[] args) { int[][] M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; System.out.print("Number of islands is: " + countIslands(M)); }} // This code is contributed by suresh07.
# Program to count islands in boolean 2D matrixclass Graph: def __init__(self, row, col, graph): self.ROW = row self.COL = col self.graph = graph # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j): if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: return # mark it as visited self.graph[i][j] = -1 # Recur for 8 neighbours self.DFS(i - 1, j - 1) self.DFS(i - 1, j) self.DFS(i - 1, j + 1) self.DFS(i, j - 1) self.DFS(i, j + 1) self.DFS(i + 1, j - 1) self.DFS(i + 1, j) self.DFS(i + 1, j + 1) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j) count += 1 return count graph = [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph)col = len(graph[0]) g = Graph(row, col, graph) print("Number of islands is:", g.countIslands()) # This code is contributed by Shivam Shrey
// C# Program to count islands in boolean 2D matrixusing System;using System.Collections.Generic;class GFG { // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices static void DFS(int[,] M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i,j] != 1) { return; } if (M[i,j] == 1) { M[i,j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } static int countIslands(int[,] M) { int ROW = M.GetLength(0); int COL = M.GetLength(1); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i,j] == 1) { M[i,j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } // Driver code static void Main() { int[,] M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; Console.Write("Number of islands is: " + countIslands(M)); }} // This code is contributed by decode2207.
<script> // Javascript Program to count islands in boolean 2D matrix // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices function DFS(M, i, j, ROW, COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } function countIslands(M) { let ROW = M.length; let COL = M[0].length; let count = 0; for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } let M = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]; document.write("Number of islands is: " + countIslands(M)); // This code is contributed by divyesh072019.</script>
Number of islands is: 5
Time complexity: O(ROW x COL)Auxiliary Space: O(1), as we are not using any extra space.
Find the number of Islands | Set 2 (Using Disjoint Set)
Islands in a graph using BFS
Vishal_Khoda
ukasp
rathbhupendra
avanitrachhadiya2155
sshrey47
ajaymakvana
surinderdawra388
simmytarika5
iramkhalid24
divyesh072019
decode2207
suresh07
amartyaghoshgfg
_shinchancode
hardikkoriintern
Amazon
Citrix
D-E-Shaw
DFS
graph-connectivity
Informatica
Linkedin
Microsoft
Ola Cabs
Opera
Paytm
Samsung
Snapdeal
Streamoid Technologies
Visa
Graph
Matrix
Paytm
Amazon
Microsoft
Samsung
Snapdeal
Citrix
D-E-Shaw
Ola Cabs
Visa
Linkedin
Opera
Streamoid Technologies
Informatica
DFS
Matrix
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 199,
"s": 54,
"text": "Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands"
},
{
"code": null,
"e": 209,
"s": 199,
"text": "Example: "
},
{
"code": null,
"e": 400,
"s": 209,
"text": "Input : mat[][] = {{1, 1, 0, 0, 0},\n {0, 1, 0, 0, 1},\n {1, 0, 0, 1, 1},\n {0, 0, 0, 0, 0},\n {1, 0, 1, 0, 1}}\nOutput : 5"
},
{
"code": null,
"e": 516,
"s": 400,
"text": "This is a variation of the standard problem: “Counting the number of connected components in an undirected graph”. "
},
{
"code": null,
"e": 858,
"s": 516,
"text": "Before we go to the problem, let us understand what is a connected component. A connected component of an undirected graph is a subgraph in which every two vertices are connected to each other by a path(s), and which is connected to no other vertices outside the subgraph. For example, the graph shown below has three connected components. "
},
{
"code": null,
"e": 1342,
"s": 860,
"text": "A graph where all vertices are connected with each other has exactly one connected component, consisting of the whole graph. Such a graph with only one connected component is called a Strongly Connected Graph.The problem can be easily solved by applying DFS() on each component. In each DFS() call, a component or a sub-graph is visited. We will call DFS on the next un-visited component. The number of calls to DFS() gives the number of connected components. BFS can also be used."
},
{
"code": null,
"e": 1362,
"s": 1342,
"text": "What is an island? "
},
{
"code": null,
"e": 1453,
"s": 1362,
"text": "A group of connected 1s forms an island. For example, the below matrix contains 4 islands "
},
{
"code": null,
"e": 1708,
"s": 1453,
"text": "A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we recursively call for all adjacent vertices, here we can recursively call for 8 neighbours only. We keep track of the visited 1s so that they are not visited again. "
},
{
"code": null,
"e": 1712,
"s": 1708,
"text": "C++"
},
{
"code": null,
"e": 1714,
"s": 1712,
"text": "C"
},
{
"code": null,
"e": 1719,
"s": 1714,
"text": "Java"
},
{
"code": null,
"e": 1727,
"s": 1719,
"text": "Python3"
},
{
"code": null,
"e": 1730,
"s": 1727,
"text": "C#"
},
{
"code": null,
"e": 1734,
"s": 1730,
"text": "PHP"
},
{
"code": null,
"e": 1745,
"s": 1734,
"text": "Javascript"
},
{
"code": "// C++ Program to count islands in boolean 2D matrix#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 5 // A function to check if a given// cell (row, col) can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to do DFS for a// 2D boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL]){ // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited);} // The main function that returns// count of islands in a given boolean// 2D matrixint countIslands(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count;} // Driver codeint main(){ int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << \"Number of islands is: \" << countIslands(M); return 0;} // This is code is contributed by rathbhupendra",
"e": 4015,
"s": 1745,
"text": null
},
{
"code": "// Program to count islands in boolean 2D matrix#include <stdbool.h>#include <stdio.h>#include <string.h> #define ROW 5#define COL 5 // A function to check if a given cell (row, col) can be included in DFSint isSafe(int M[][COL], int row, int col, bool visited[][COL]){ // row number is in range, column number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]);} // A utility function to do DFS for a 2D boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(int M[][COL], int row, int col, bool visited[][COL]){ // These arrays are used to get row and column numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited);} // The main function that returns count of islands in a given boolean// 2D matrixint countIslands(int M[][COL]){ // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i][j] && !visited[i][j]) // If a cell with value 1 is not { // visited yet, then new island found DFS(M, i, j, visited); // Visit all cells in this island. ++count; // and increment island count } return count;} // Driver program to test above functionint main(){ int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; printf(\"Number of islands is: %d\\n\", countIslands(M)); return 0;}",
"e": 6185,
"s": 4015,
"text": null
},
{
"code": "// Java program to count islands in boolean 2D matriximport java.util.*;import java.lang.*;import java.io.*; class Islands { // No of rows and columns static final int ROW = 5, COL = 5; // A function to check if a given cell (row, col) can // be included in DFS boolean isSafe(int M[][], int row, int col, boolean visited[][]) { // row number is in range, column number is in range // and value is 1 and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); } // A utility function to do DFS for a 2D boolean matrix. // It only considers the 8 neighbors as adjacent vertices void DFS(int M[][], int row, int col, boolean visited[][]) { // These arrays are used to get row and column numbers // of 8 neighbors of a given cell int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 }; int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns count of islands in a given // boolean 2D matrix int countIslands(int M[][]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited boolean visited[][] = new boolean[ROW][COL]; // Initialize count as 0 and traverse through the all cells // of given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i][j] == 1 && !visited[i][j]) // If a cell with { // value 1 is not // visited yet, then new island found, Visit all // cells in this island and increment island count DFS(M, i, j, visited); ++count; } return count; } // Driver method public static void main(String[] args) throws java.lang.Exception { int M[][] = new int[][] { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Islands I = new Islands(); System.out.println(\"Number of islands is: \" + I.countIslands(M)); }} // Contributed by Aakash Hasija",
"e": 8809,
"s": 6185,
"text": null
},
{
"code": "# Program to count islands in boolean 2D matrixclass Graph: def __init__(self, row, col, g): self.ROW = row self.COL = col self.graph = g # A function to check if a given cell # (row, col) can be included in DFS def isSafe(self, i, j, visited): # row number is in range, column number # is in range and value is 1 # and not yet visited return (i >= 0 and i < self.ROW and j >= 0 and j < self.COL and not visited[i][j] and self.graph[i][j]) # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j, visited): # These arrays are used to get row and # column numbers of 8 neighbours # of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]; colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]; # Mark this cell as visited visited[i][j] = True # Recur for all connected neighbours for k in range(8): if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): self.DFS(i + rowNbr[k], j + colNbr[k], visited) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[False for j in range(self.COL)]for i in range(self.ROW)] # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if visited[i][j] == False and self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j, visited) count += 1 return count graph = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph)col = len(graph[0]) g = Graph(row, col, graph) print (\"Number of islands is:\")print (g.countIslands()) # This code is contributed by Neelam Yadav",
"e": 11117,
"s": 8809,
"text": null
},
{
"code": "// C# program to count// islands in boolean// 2D matrixusing System; class GFG { // No of rows // and columns static int ROW = 5, COL = 5; // A function to check if // a given cell (row, col) // can be included in DFS static bool isSafe(int[, ] M, int row, int col, bool[, ] visited) { // row number is in range, // column number is in range // and value is 1 and not // yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row, col] == 1 && !visited[row, col]); } // A utility function to do // DFS for a 2D boolean matrix. // It only considers the 8 // neighbors as adjacent vertices static void DFS(int[, ] M, int row, int col, bool[, ] visited) { // These arrays are used to // get row and column numbers // of 8 neighbors of a given cell int[] rowNbr = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 }; int[] colNbr = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell // as visited visited[row, col] = true; // Recur for all // connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that // returns count of islands // in a given boolean 2D matrix static int countIslands(int[, ] M) { // Make a bool array to // mark visited cells. // Initially all cells // are unvisited bool[, ] visited = new bool[ROW, COL]; // Initialize count as 0 and // traverse through the all // cells of given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) if (M[i, j] == 1 && !visited[i, j]) { // If a cell with value 1 is not // visited yet, then new island // found, Visit all cells in this // island and increment island count DFS(M, i, j, visited); ++count; } return count; } // Driver Code public static void Main() { int[, ] M = new int[, ] { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Console.Write(\"Number of islands is: \" + countIslands(M)); }} // This code is contributed// by shiv_bhakt.",
"e": 13870,
"s": 11117,
"text": null
},
{
"code": "<?php// Program to count islands// in boolean 2D matrix $ROW = 5;$COL = 5; // A function to check if a// given cell (row, col) can// be included in DFSfunction isSafe(&$M, $row, $col, &$visited){ global $ROW, $COL; // row number is in range, // column number is in // range and value is 1 // and not yet visited return ($row >= 0) && ($row < $ROW) && ($col >= 0) && ($col < $COL) && ($M[$row][$col] && !isset($visited[$row][$col]));} // A utility function to do DFS// for a 2D boolean matrix. It// only considers the 8 neighbours// as adjacent verticesfunction DFS(&$M, $row, $col, &$visited){ // These arrays are used to // get row and column numbers // of 8 neighbours of a given cell $rowNbr = array(-1, -1, -1, 0, 0, 1, 1, 1); $colNbr = array(-1, 0, 1, -1, 1, -1, 0, 1); // Mark this cell as visited $visited[$row][$col] = true; // Recur for all // connected neighbours for ($k = 0; $k < 8; ++$k) if (isSafe($M, $row + $rowNbr[$k], $col + $colNbr[$k], $visited)) DFS($M, $row + $rowNbr[$k], $col + $colNbr[$k], $visited);} // The main function that returns// count of islands in a given// boolean 2D matrixfunction countIslands(&$M){ global $ROW, $COL; // Make a bool array to // mark visited cells. // Initially all cells // are unvisited $visited = array(array()); // Initialize count as 0 and // traverse through the all // cells of given matrix $count = 0; for ($i = 0; $i < $ROW; ++$i) for ($j = 0; $j < $COL; ++$j) if ($M[$i][$j] && !isset($visited[$i][$j])) // If a cell with value 1 { // is not visited yet, DFS($M, $i, $j, $visited); // then new island found ++$count; // Visit all cells in this } // island and increment // island count. return $count;} // Driver Code$M = array(array(1, 1, 0, 0, 0), array(0, 1, 0, 0, 1), array(1, 0, 0, 1, 1), array(0, 0, 0, 0, 0), array(1, 0, 1, 0, 1)); echo \"Number of islands is: \", countIslands($M); // This code is contributed// by ChitraNayal?>",
"e": 16278,
"s": 13870,
"text": null
},
{
"code": "<script>// Javascript program to count islands in boolean 2D matrix // No of rows and columns let ROW = 5, COL = 5; // A function to check if a given cell (row, col) can // be included in DFS function isSafe(M,row,col,visited) { // row number is in range, column number is in range // and value is 1 and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); } // A utility function to do DFS for a 2D boolean matrix. // It only considers the 8 neighbors as adjacent vertices function DFS(M, row, col, visited) { // These arrays are used to get row and column numbers // of 8 neighbors of a given cell let rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]; let colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (let k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { DFS(M, row + rowNbr[k], col + colNbr[k], visited); } } } // The main function that returns count of islands in a given // boolean 2D matrix function countIslands(M) { // Make a bool array to mark visited cells. // Initially all cells are unvisited let visited = new Array(ROW); for(let i = 0; i < ROW; i++) { visited[i] = new Array(COL); } for(let i = 0; i < ROW; i++) { for(let j = 0; j < COL; j++) { visited[i][j] = false; } } // Initialize count as 0 and traverse through the all cells // of given matrix let count = 0; for (let i = 0; i < ROW; ++i) { for (let j = 0; j < COL; ++j) { if (M[i][j] == 1 && !visited[i][j]) { // value 1 is not // visited yet, then new island found, Visit all // cells in this island and increment island count DFS(M, i, j, visited); count++; } } } return count; } // Driver method let M = [[ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1], [1, 0, 0, 1, 1] ,[0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]; document.write(\"Number of islands is: \" + countIslands(M)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 18859,
"s": 16278,
"text": null
},
{
"code": null,
"e": 18883,
"s": 18859,
"text": "Number of islands is: 5"
},
{
"code": null,
"e": 18965,
"s": 18883,
"text": "Time complexity: O(ROW x COL)Auxiliary Space: O(ROW x COL), due to visited matrix"
},
{
"code": null,
"e": 19019,
"s": 18965,
"text": "Alternative solution without creating visited matrix:"
},
{
"code": null,
"e": 19023,
"s": 19019,
"text": "C++"
},
{
"code": null,
"e": 19028,
"s": 19023,
"text": "Java"
},
{
"code": null,
"e": 19036,
"s": 19028,
"text": "Python3"
},
{
"code": null,
"e": 19039,
"s": 19036,
"text": "C#"
},
{
"code": null,
"e": 19050,
"s": 19039,
"text": "Javascript"
},
{
"code": "// C++Program to count islands in boolean 2D matrix#include <bits/stdc++.h>using namespace std; // A utility function to do DFS for a 2D// boolean matrix. It only considers// the 8 neighbours as adjacent verticesvoid DFS(vector<vector<int>> &M, int i, int j, int ROW, int COL){ //Base condition //if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal }} int countIslands(vector<vector<int>> &M){ int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count;} // Driver Codeint main(){ vector<vector<int>> M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; cout << \"Number of islands is: \" << countIslands(M); return 0;} // This code is contributed by ajaymakvana.",
"e": 21462,
"s": 19050,
"text": null
},
{
"code": "// Java Program to count islands in boolean 2D matriximport java.util.*;public class Main{ // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices static void DFS(int[][] M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } static int countIslands(int[][] M) { int ROW = M.length; int COL = M[0].length; int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } // Driver code public static void main(String[] args) { int[][] M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; System.out.print(\"Number of islands is: \" + countIslands(M)); }} // This code is contributed by suresh07.",
"e": 24048,
"s": 21462,
"text": null
},
{
"code": "# Program to count islands in boolean 2D matrixclass Graph: def __init__(self, row, col, graph): self.ROW = row self.COL = col self.graph = graph # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j): if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: return # mark it as visited self.graph[i][j] = -1 # Recur for 8 neighbours self.DFS(i - 1, j - 1) self.DFS(i - 1, j) self.DFS(i - 1, j + 1) self.DFS(i, j - 1) self.DFS(i, j + 1) self.DFS(i + 1, j - 1) self.DFS(i + 1, j) self.DFS(i + 1, j + 1) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j) count += 1 return count graph = [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph)col = len(graph[0]) g = Graph(row, col, graph) print(\"Number of islands is:\", g.countIslands()) # This code is contributed by Shivam Shrey",
"e": 25703,
"s": 24048,
"text": null
},
{
"code": "// C# Program to count islands in boolean 2D matrixusing System;using System.Collections.Generic;class GFG { // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices static void DFS(int[,] M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i,j] != 1) { return; } if (M[i,j] == 1) { M[i,j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } static int countIslands(int[,] M) { int ROW = M.GetLength(0); int COL = M.GetLength(1); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i,j] == 1) { M[i,j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } // Driver code static void Main() { int[,] M = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; Console.Write(\"Number of islands is: \" + countIslands(M)); }} // This code is contributed by decode2207.",
"e": 28275,
"s": 25703,
"text": null
},
{
"code": "<script> // Javascript Program to count islands in boolean 2D matrix // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices function DFS(M, i, j, ROW, COL) { // Base condition // if i less than 0 or j less than 0 or i greater than ROW-1 or j greater than COL- or if M[i][j] != 1 then we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } function countIslands(M) { let ROW = M.length; let COL = M[0].length; let count = 0; for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) { if (M[i][j] == 1) { M[i][j] = 0; count++; DFS(M, i + 1, j, ROW, COL); //right side traversal DFS(M, i - 1, j, ROW, COL); //left side traversal DFS(M, i, j + 1, ROW, COL); //upward side traversal DFS(M, i, j - 1, ROW, COL); //downward side traversal DFS(M, i + 1, j + 1, ROW, COL); //upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); //downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); //downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); //upward-left side traversal } } } return count; } let M = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]; document.write(\"Number of islands is: \" + countIslands(M)); // This code is contributed by divyesh072019.</script>",
"e": 30724,
"s": 28275,
"text": null
},
{
"code": null,
"e": 30748,
"s": 30724,
"text": "Number of islands is: 5"
},
{
"code": null,
"e": 30838,
"s": 30748,
"text": " Time complexity: O(ROW x COL)Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 30895,
"s": 30838,
"text": "Find the number of Islands | Set 2 (Using Disjoint Set) "
},
{
"code": null,
"e": 30924,
"s": 30895,
"text": "Islands in a graph using BFS"
},
{
"code": null,
"e": 30937,
"s": 30924,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 30943,
"s": 30937,
"text": "ukasp"
},
{
"code": null,
"e": 30957,
"s": 30943,
"text": "rathbhupendra"
},
{
"code": null,
"e": 30978,
"s": 30957,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30987,
"s": 30978,
"text": "sshrey47"
},
{
"code": null,
"e": 30999,
"s": 30987,
"text": "ajaymakvana"
},
{
"code": null,
"e": 31016,
"s": 30999,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31029,
"s": 31016,
"text": "simmytarika5"
},
{
"code": null,
"e": 31042,
"s": 31029,
"text": "iramkhalid24"
},
{
"code": null,
"e": 31056,
"s": 31042,
"text": "divyesh072019"
},
{
"code": null,
"e": 31067,
"s": 31056,
"text": "decode2207"
},
{
"code": null,
"e": 31076,
"s": 31067,
"text": "suresh07"
},
{
"code": null,
"e": 31092,
"s": 31076,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 31106,
"s": 31092,
"text": "_shinchancode"
},
{
"code": null,
"e": 31123,
"s": 31106,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 31130,
"s": 31123,
"text": "Amazon"
},
{
"code": null,
"e": 31137,
"s": 31130,
"text": "Citrix"
},
{
"code": null,
"e": 31146,
"s": 31137,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 31150,
"s": 31146,
"text": "DFS"
},
{
"code": null,
"e": 31169,
"s": 31150,
"text": "graph-connectivity"
},
{
"code": null,
"e": 31181,
"s": 31169,
"text": "Informatica"
},
{
"code": null,
"e": 31190,
"s": 31181,
"text": "Linkedin"
},
{
"code": null,
"e": 31200,
"s": 31190,
"text": "Microsoft"
},
{
"code": null,
"e": 31209,
"s": 31200,
"text": "Ola Cabs"
},
{
"code": null,
"e": 31215,
"s": 31209,
"text": "Opera"
},
{
"code": null,
"e": 31221,
"s": 31215,
"text": "Paytm"
},
{
"code": null,
"e": 31229,
"s": 31221,
"text": "Samsung"
},
{
"code": null,
"e": 31238,
"s": 31229,
"text": "Snapdeal"
},
{
"code": null,
"e": 31261,
"s": 31238,
"text": "Streamoid Technologies"
},
{
"code": null,
"e": 31266,
"s": 31261,
"text": "Visa"
},
{
"code": null,
"e": 31272,
"s": 31266,
"text": "Graph"
},
{
"code": null,
"e": 31279,
"s": 31272,
"text": "Matrix"
},
{
"code": null,
"e": 31285,
"s": 31279,
"text": "Paytm"
},
{
"code": null,
"e": 31292,
"s": 31285,
"text": "Amazon"
},
{
"code": null,
"e": 31302,
"s": 31292,
"text": "Microsoft"
},
{
"code": null,
"e": 31310,
"s": 31302,
"text": "Samsung"
},
{
"code": null,
"e": 31319,
"s": 31310,
"text": "Snapdeal"
},
{
"code": null,
"e": 31326,
"s": 31319,
"text": "Citrix"
},
{
"code": null,
"e": 31335,
"s": 31326,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 31344,
"s": 31335,
"text": "Ola Cabs"
},
{
"code": null,
"e": 31349,
"s": 31344,
"text": "Visa"
},
{
"code": null,
"e": 31358,
"s": 31349,
"text": "Linkedin"
},
{
"code": null,
"e": 31364,
"s": 31358,
"text": "Opera"
},
{
"code": null,
"e": 31387,
"s": 31364,
"text": "Streamoid Technologies"
},
{
"code": null,
"e": 31399,
"s": 31387,
"text": "Informatica"
},
{
"code": null,
"e": 31403,
"s": 31399,
"text": "DFS"
},
{
"code": null,
"e": 31410,
"s": 31403,
"text": "Matrix"
},
{
"code": null,
"e": 31416,
"s": 31410,
"text": "Graph"
}
] |
Build a bidirectional text generator with XLNet | by Rostyslav Neskorozhenyi | Towards Data Science
|
Current Transformers based models, like GPT-2 or even GPT-3 show incredible achievements in the task of text-generation (prediction of the next probable word based on the previous sequence of words). These models can create long, creative and cohesive texts, but usually they can generate text only in one direction, from left to right. I was wondering if there is a way to generate text in both directions and having some start phrase (for example “text generation is cool”) to see what story will unfold around it. XLNet was the solution: due to its using of all permutations of the input sequence factorization order this model can help to generate text in any direction.
In this article we will not study in detail the internal principles of XLNet (excellent brief explanation you can find here). Instead, we’ll start experimenting right away: we will practice a little bit in masked word prediction with XLNet, try to implement top-K bidirectional generation, and then implement a more efficient approach that combines beam search and top-K sampling.
At the end of the article we will get a generator capable of creating such text based on the start phrase (which is highlighted in bold):
Following up on my initial thoughts: text generation is cool! It works great for creating blog header, title etc. You will need Word 2013
Let’s begin. We will conduct all our experiments in Google Collab Notebook (with GPU environment), which is available by this link, so the only module we will need to install is the excellent Transformers library. This library provides a simple interface to XLNet, as well as to many other transformers based models.
!pip install transformers
One of the advantages of XLNet is that this model can perfectly cope with the prediction of several related masked words while taking into account the previous context. For example, I will mention in the text that I gave you three apples, and then ask the model to tell me who now owns some apples by feeding the model a sentence with masked words: “<mask> have <mask> apples in hands”. As a result, we will see that the model perfectly understands who has apples and how many.
Before we can start communicating with the model, we need to load it, as well as load a tokenizer that processes the incoming text into a digital form understandable for the model. In the basic form, tokenization is splitting of the text into words or subwords, which then are converted to ids. Each model requires text to be tokenized in a specific way. XLNet uses SentencePiece method. You can read more about the tokenization process at the link.
Also we need to add a padding text to help XLNet with short texts as was proposed by Aman Rusia.
Predict top 5 words for each <mask> token. To make a prediction we need to feed the model with tokenized text, masked words indexes and permutation masks. Permutation masks are needed to disable input tokens to attend to masked tokens. You can read more about model parameters here.
Output:
predicted word: <mask> 0word and logits You -9.070054054260254word and logits I -10.822368621826172word and logits We -12.820359230041504word and logits Now -14.133552551269531word and logits They -14.863320350646973predicted word: <mask> 1word and logits three -23.045528411865234word and logits the -24.3369083404541word and logits these -25.59902000427246word and logits two -25.809444427490234word and logits your -25.947147369384766
Now when we know how to predict masked words with XLNet it’s time to create a top-k bidirectional text generator. Its work principles are simple. We will create a loop and at each iteration the model will predict top-k tokens for a masked word on the right or on the left side of start phrase. After that we add random token from topK to the start phrase and repeat iteration for n times.
Output:
• 1 1 User reviews and says:? The text generation is cool for me to see and the font size seems right
Not too impressive. There is a lot of repetitions and whole text looks meaningless. But we will find a better solution.
As we can see, it is still quite difficult for the model to generate text right-to-left. We often get a word that does not fit into the context well, which leads to an even less suitable next word. As a result, the generated text becomes incoherent.
We can increase the chances of finding connected word sequences by generating words not by one on each side of the starting phrase, but by creating a certain number of beams of word sequences and choosing one of the most probable beams of a certain length.
Thus, we get some kind of combination of top-k sampling and beam search. The principle of the resulting method is shown in the diagram.
The bidirectional generation process consists of n iterations. I split each iteration into four steps for better understanding:
In the first step, we get a start phrase and generate right-to-left on its left side a certain number of beams of a certain length (at each stage of beam search, we select next token candidates with top-K sampling).
In the second step, we take a random beam from the top-K most probable beams and add it to the start phrase.
The resulting new phrase serves as a start phrase for the third step, in which we generate a certain number of beams on the right side of the new start phrase.
In the fourth step, we take a random beam from the top-k beams obtained in the third step and add that beam to the new starting phrase. The resulting phrase serves as the starting point for the next iteration.
I hope that the description was clear enough and the diagram will help you figure it out. The main thing is that, based on my experiments, this method in most cases allows you to generate quite coherent text bidirectionally.
Let’s implement the method in code. Firstly we will create a function that will take tokenized start sentence, a sequence of token candidates with their probabilities and generate next n probable sequences of token candidates on the right or on the left side. We will use this function iteratively, so generated token sequences from previous iteration will serve as input on the next iteration.
Now we will create beam_gen function that will generate a list of token beams of given length (depth) using token candidates proposed by candidates_gen.
beam_gen function will return final beams list sorted by probability.
Let’s gather all parts together in a bi_gen function. bi_gen will be able to generate text left-to-right (parameter direction=’right’), right-to-left (parameter direction=’left’), or in both directions (parameter direction=’both’)
If both directions are selected, generator will work in the following way: generate n_tokens on the left side, after that — n tokens in the right side, then again n tokens on the left side and so on. It will repeat number of times, that is saved in iterations parameter.
We will separately indicate in first_sample_size parameter the number of candidates in the first stage of beam search. This number can be higher than the number of candidates in the next stages (specified in the variable sample_size), since it is important to get enough candidates for the first token, on which all subsequent sequences will be based. According to my observations, this approach increases the likelihood of generating a coherent and reasonably probable sequence of tokens.
We will use high temperature parameter to lower model confidence in its top token choices. This allows to make the generation more varied and not get stuck with the most likely repeating sequences of tokens.
And finally we will try our bidirectional text generator with start phrase “text generation is cool”.
The resulting text:
Follow the trend: Graphic design is cool, text generation is cool, data manipulation and algorithms are cool, etc.
It’s also starting to seem somewhat like we are embarking into a new world largely controlled by artificial intelligence based on its ability over a long period to manipulate, manage and adapt our daily lives.
The entire previous paragraph was generated by our new text generator. The text is pretty convincing, isn’t it? Therefore, please accept my congratulations. We have created almost the first of its kind transformers based bidirectional text generator. And while it still makes a lot of mistakes, it can be used to create a lot of interesting and fun stories that will grow around any phrase that comes to your mind.
|
[
{
"code": null,
"e": 847,
"s": 172,
"text": "Current Transformers based models, like GPT-2 or even GPT-3 show incredible achievements in the task of text-generation (prediction of the next probable word based on the previous sequence of words). These models can create long, creative and cohesive texts, but usually they can generate text only in one direction, from left to right. I was wondering if there is a way to generate text in both directions and having some start phrase (for example “text generation is cool”) to see what story will unfold around it. XLNet was the solution: due to its using of all permutations of the input sequence factorization order this model can help to generate text in any direction."
},
{
"code": null,
"e": 1228,
"s": 847,
"text": "In this article we will not study in detail the internal principles of XLNet (excellent brief explanation you can find here). Instead, we’ll start experimenting right away: we will practice a little bit in masked word prediction with XLNet, try to implement top-K bidirectional generation, and then implement a more efficient approach that combines beam search and top-K sampling."
},
{
"code": null,
"e": 1366,
"s": 1228,
"text": "At the end of the article we will get a generator capable of creating such text based on the start phrase (which is highlighted in bold):"
},
{
"code": null,
"e": 1504,
"s": 1366,
"text": "Following up on my initial thoughts: text generation is cool! It works great for creating blog header, title etc. You will need Word 2013"
},
{
"code": null,
"e": 1821,
"s": 1504,
"text": "Let’s begin. We will conduct all our experiments in Google Collab Notebook (with GPU environment), which is available by this link, so the only module we will need to install is the excellent Transformers library. This library provides a simple interface to XLNet, as well as to many other transformers based models."
},
{
"code": null,
"e": 1847,
"s": 1821,
"text": "!pip install transformers"
},
{
"code": null,
"e": 2325,
"s": 1847,
"text": "One of the advantages of XLNet is that this model can perfectly cope with the prediction of several related masked words while taking into account the previous context. For example, I will mention in the text that I gave you three apples, and then ask the model to tell me who now owns some apples by feeding the model a sentence with masked words: “<mask> have <mask> apples in hands”. As a result, we will see that the model perfectly understands who has apples and how many."
},
{
"code": null,
"e": 2775,
"s": 2325,
"text": "Before we can start communicating with the model, we need to load it, as well as load a tokenizer that processes the incoming text into a digital form understandable for the model. In the basic form, tokenization is splitting of the text into words or subwords, which then are converted to ids. Each model requires text to be tokenized in a specific way. XLNet uses SentencePiece method. You can read more about the tokenization process at the link."
},
{
"code": null,
"e": 2872,
"s": 2775,
"text": "Also we need to add a padding text to help XLNet with short texts as was proposed by Aman Rusia."
},
{
"code": null,
"e": 3155,
"s": 2872,
"text": "Predict top 5 words for each <mask> token. To make a prediction we need to feed the model with tokenized text, masked words indexes and permutation masks. Permutation masks are needed to disable input tokens to attend to masked tokens. You can read more about model parameters here."
},
{
"code": null,
"e": 3163,
"s": 3155,
"text": "Output:"
},
{
"code": null,
"e": 3601,
"s": 3163,
"text": "predicted word: <mask> 0word and logits You -9.070054054260254word and logits I -10.822368621826172word and logits We -12.820359230041504word and logits Now -14.133552551269531word and logits They -14.863320350646973predicted word: <mask> 1word and logits three -23.045528411865234word and logits the -24.3369083404541word and logits these -25.59902000427246word and logits two -25.809444427490234word and logits your -25.947147369384766"
},
{
"code": null,
"e": 3990,
"s": 3601,
"text": "Now when we know how to predict masked words with XLNet it’s time to create a top-k bidirectional text generator. Its work principles are simple. We will create a loop and at each iteration the model will predict top-k tokens for a masked word on the right or on the left side of start phrase. After that we add random token from topK to the start phrase and repeat iteration for n times."
},
{
"code": null,
"e": 3998,
"s": 3990,
"text": "Output:"
},
{
"code": null,
"e": 4100,
"s": 3998,
"text": "• 1 1 User reviews and says:? The text generation is cool for me to see and the font size seems right"
},
{
"code": null,
"e": 4220,
"s": 4100,
"text": "Not too impressive. There is a lot of repetitions and whole text looks meaningless. But we will find a better solution."
},
{
"code": null,
"e": 4470,
"s": 4220,
"text": "As we can see, it is still quite difficult for the model to generate text right-to-left. We often get a word that does not fit into the context well, which leads to an even less suitable next word. As a result, the generated text becomes incoherent."
},
{
"code": null,
"e": 4727,
"s": 4470,
"text": "We can increase the chances of finding connected word sequences by generating words not by one on each side of the starting phrase, but by creating a certain number of beams of word sequences and choosing one of the most probable beams of a certain length."
},
{
"code": null,
"e": 4863,
"s": 4727,
"text": "Thus, we get some kind of combination of top-k sampling and beam search. The principle of the resulting method is shown in the diagram."
},
{
"code": null,
"e": 4991,
"s": 4863,
"text": "The bidirectional generation process consists of n iterations. I split each iteration into four steps for better understanding:"
},
{
"code": null,
"e": 5207,
"s": 4991,
"text": "In the first step, we get a start phrase and generate right-to-left on its left side a certain number of beams of a certain length (at each stage of beam search, we select next token candidates with top-K sampling)."
},
{
"code": null,
"e": 5316,
"s": 5207,
"text": "In the second step, we take a random beam from the top-K most probable beams and add it to the start phrase."
},
{
"code": null,
"e": 5476,
"s": 5316,
"text": "The resulting new phrase serves as a start phrase for the third step, in which we generate a certain number of beams on the right side of the new start phrase."
},
{
"code": null,
"e": 5686,
"s": 5476,
"text": "In the fourth step, we take a random beam from the top-k beams obtained in the third step and add that beam to the new starting phrase. The resulting phrase serves as the starting point for the next iteration."
},
{
"code": null,
"e": 5911,
"s": 5686,
"text": "I hope that the description was clear enough and the diagram will help you figure it out. The main thing is that, based on my experiments, this method in most cases allows you to generate quite coherent text bidirectionally."
},
{
"code": null,
"e": 6306,
"s": 5911,
"text": "Let’s implement the method in code. Firstly we will create a function that will take tokenized start sentence, a sequence of token candidates with their probabilities and generate next n probable sequences of token candidates on the right or on the left side. We will use this function iteratively, so generated token sequences from previous iteration will serve as input on the next iteration."
},
{
"code": null,
"e": 6459,
"s": 6306,
"text": "Now we will create beam_gen function that will generate a list of token beams of given length (depth) using token candidates proposed by candidates_gen."
},
{
"code": null,
"e": 6529,
"s": 6459,
"text": "beam_gen function will return final beams list sorted by probability."
},
{
"code": null,
"e": 6760,
"s": 6529,
"text": "Let’s gather all parts together in a bi_gen function. bi_gen will be able to generate text left-to-right (parameter direction=’right’), right-to-left (parameter direction=’left’), or in both directions (parameter direction=’both’)"
},
{
"code": null,
"e": 7031,
"s": 6760,
"text": "If both directions are selected, generator will work in the following way: generate n_tokens on the left side, after that — n tokens in the right side, then again n tokens on the left side and so on. It will repeat number of times, that is saved in iterations parameter."
},
{
"code": null,
"e": 7521,
"s": 7031,
"text": "We will separately indicate in first_sample_size parameter the number of candidates in the first stage of beam search. This number can be higher than the number of candidates in the next stages (specified in the variable sample_size), since it is important to get enough candidates for the first token, on which all subsequent sequences will be based. According to my observations, this approach increases the likelihood of generating a coherent and reasonably probable sequence of tokens."
},
{
"code": null,
"e": 7729,
"s": 7521,
"text": "We will use high temperature parameter to lower model confidence in its top token choices. This allows to make the generation more varied and not get stuck with the most likely repeating sequences of tokens."
},
{
"code": null,
"e": 7831,
"s": 7729,
"text": "And finally we will try our bidirectional text generator with start phrase “text generation is cool”."
},
{
"code": null,
"e": 7851,
"s": 7831,
"text": "The resulting text:"
},
{
"code": null,
"e": 7966,
"s": 7851,
"text": "Follow the trend: Graphic design is cool, text generation is cool, data manipulation and algorithms are cool, etc."
},
{
"code": null,
"e": 8176,
"s": 7966,
"text": "It’s also starting to seem somewhat like we are embarking into a new world largely controlled by artificial intelligence based on its ability over a long period to manipulate, manage and adapt our daily lives."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.