title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to prevent Reflection to break a Singleton Class Pattern?
|
A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create multiple instance of a class by modifying the constructor scope. See the example below β
Live Demo
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Tester {
public static void main(String[] args) throws
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
A a = A.getInstance();
A b = null;
Constructor<?>[] constructors = A.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//make the private constructor as public
constructor.setAccessible(true);
b = (A) constructor.newInstance();
break;
}
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
class A implements Serializable {
private static A a;
private A(){}
public static A getInstance(){
if(a == null){
a = new A();
}
return a;
}
}
705927765
366712642
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation β
Create A using Enum instead of Class.
Live Demo
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
public class Tester {
public static void main(String[] args) throws
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
A a = A.INSTANCE;
A b = A.INSTANCE;
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
enum A implements Serializable {
INSTANCE;
}
705927765
705927765
|
[
{
"code": null,
"e": 1424,
"s": 1062,
"text": "A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create multiple instance of a class by modifying the constructor scope. See the example below β"
},
{
"code": null,
"e": 1435,
"s": 1424,
"text": " Live Demo"
},
{
"code": null,
"e": 2340,
"s": 1435,
"text": "import java.io.Serializable;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class Tester {\n public static void main(String[] args) throws\n InstantiationException, IllegalAccessException,\n\n IllegalArgumentException, InvocationTargetException{\n A a = A.getInstance();\n A b = null;\n\n Constructor<?>[] constructors = A.class.getDeclaredConstructors();\n\n for (Constructor constructor : constructors) {\n //make the private constructor as public\n constructor.setAccessible(true);\n b = (A) constructor.newInstance();\n break;\n }\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n}\n\nclass A implements Serializable {\n private static A a;\n private A(){}\n\n public static A getInstance(){\n if(a == null){\n a = new A();\n }\n return a;\n }\n}"
},
{
"code": null,
"e": 2360,
"s": 2340,
"text": "705927765\n366712642"
},
{
"code": null,
"e": 2473,
"s": 2360,
"text": "Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation β"
},
{
"code": null,
"e": 2511,
"s": 2473,
"text": "Create A using Enum instead of Class."
},
{
"code": null,
"e": 2522,
"s": 2511,
"text": " Live Demo"
},
{
"code": null,
"e": 2967,
"s": 2522,
"text": "import java.io.Serializable;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class Tester {\n public static void main(String[] args) throws\n InstantiationException, IllegalAccessException,\n IllegalArgumentException, InvocationTargetException{\n\n A a = A.INSTANCE;\n A b = A.INSTANCE;\n\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n}\nenum A implements Serializable {\n INSTANCE;\n}"
},
{
"code": null,
"e": 2987,
"s": 2967,
"text": "705927765\n705927765"
}
] |
Java program to merge two or more files alternatively into third file
|
Assume we have three files as β
output1.txt
Hello how are you
output2.txt
Welcome to Tutorialspoint
output3.txt
We provide simply easy learning
Following Java example merges the contents of the above three files alternatively into a single file β
import java.util.Scanner;
public class MergingFiles {
public static void main(String args[]) throws IOException {
Scanner sc1 = new Scanner(new File("D://input1.txt"));
Scanner sc2 = new Scanner(new File("D://input2.txt"));
Scanner sc3 = new Scanner(new File("D://input3.txt"));
FileWriter writer = new FileWriter("D://result.txt");
String str[] = new String[3];
while (sc1.hasNextLine()||sc2.hasNextLine()||sc3.hasNextLine()) {
str[0] = sc1.nextLine();
str[1] = sc2.nextLine();
str[2] = sc3.nextLine();
}
writer.append(str[0]+"\n");
writer.append(str[1]+"\n");
writer.append(str[2]+"\n");
writer.flush();
System.out.println("Contents added ");
}
}
Contents added
If the above three files are in the same directly you can rewrite the sample program as β
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MergingFiles {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\\example");
//List of all files and directories
File filesList[] = directoryPath.listFiles();
Scanner sc = null;
FileWriter writer = new FileWriter("D://output.txt");
for(File file : filesList) {
sc = new Scanner(file);
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
writer.append(input+"\n");
}
writer.flush();
}
System.out.println("Contents added ");
}
}
Contents added
|
[
{
"code": null,
"e": 1094,
"s": 1062,
"text": "Assume we have three files as β"
},
{
"code": null,
"e": 1106,
"s": 1094,
"text": "output1.txt"
},
{
"code": null,
"e": 1124,
"s": 1106,
"text": "Hello how are you"
},
{
"code": null,
"e": 1136,
"s": 1124,
"text": "output2.txt"
},
{
"code": null,
"e": 1162,
"s": 1136,
"text": "Welcome to Tutorialspoint"
},
{
"code": null,
"e": 1174,
"s": 1162,
"text": "output3.txt"
},
{
"code": null,
"e": 1206,
"s": 1174,
"text": "We provide simply easy learning"
},
{
"code": null,
"e": 1309,
"s": 1206,
"text": "Following Java example merges the contents of the above three files alternatively into a single file β"
},
{
"code": null,
"e": 2063,
"s": 1309,
"text": "import java.util.Scanner;\npublic class MergingFiles {\n public static void main(String args[]) throws IOException {\n Scanner sc1 = new Scanner(new File(\"D://input1.txt\"));\n Scanner sc2 = new Scanner(new File(\"D://input2.txt\"));\n Scanner sc3 = new Scanner(new File(\"D://input3.txt\"));\n FileWriter writer = new FileWriter(\"D://result.txt\");\n String str[] = new String[3];\n while (sc1.hasNextLine()||sc2.hasNextLine()||sc3.hasNextLine()) {\n str[0] = sc1.nextLine();\n str[1] = sc2.nextLine();\n str[2] = sc3.nextLine();\n }\n writer.append(str[0]+\"\\n\");\n writer.append(str[1]+\"\\n\");\n writer.append(str[2]+\"\\n\");\n writer.flush();\n System.out.println(\"Contents added \");\n }\n}"
},
{
"code": null,
"e": 2078,
"s": 2063,
"text": "Contents added"
},
{
"code": null,
"e": 2168,
"s": 2078,
"text": "If the above three files are in the same directly you can rewrite the sample program as β"
},
{
"code": null,
"e": 2981,
"s": 2168,
"text": "import java.io.File;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Scanner;\npublic class MergingFiles {\n public static void main(String args[]) throws IOException {\n //Creating a File object for directory\n File directoryPath = new File(\"D:\\\\example\");\n //List of all files and directories\n File filesList[] = directoryPath.listFiles();\n Scanner sc = null;\n FileWriter writer = new FileWriter(\"D://output.txt\");\n for(File file : filesList) {\n sc = new Scanner(file);\n String input;\n StringBuffer sb = new StringBuffer();\n while (sc.hasNextLine()) {\n input = sc.nextLine();\n writer.append(input+\"\\n\");\n }\n writer.flush();\n }\n System.out.println(\"Contents added \");\n }\n}"
},
{
"code": null,
"e": 2996,
"s": 2981,
"text": "Contents added"
}
] |
Empowering Docker using Tkinter GUI | by Kasper SchΓΈn Henriksen | Towards Data Science
|
In several cases, it can be useful to create a Graphical User Interface (GUI) that can be accessed in Docker, for instance when developing machine learning applications where visualizing image and video is desired. However, several steps are required to be able to view the GUI at the host machine. In this article, we will use Tkinter to create a simple GUI in Python which can be accessed through Docker.
In this article, we will cover several steps. The first two steps are necessary to run a Tkinter GUI application in Docker. The other steps are optional and are used to gain extra information of how to enhance the development phase using Tkinter and Docker. The steps are:
Create very simple application using Tkinter.Create a simple Docker image and run a Tkinter application in the Docker container.Simplify Docker run command using shell script. (Optional)Allow continuous development of GUI. (Optional)
Create very simple application using Tkinter.
Create a simple Docker image and run a Tkinter application in the Docker container.
Simplify Docker run command using shell script. (Optional)
Allow continuous development of GUI. (Optional)
This article has only been tested with Linux and may not work for other OS. You should also already have installed Docker.
Below, an overview of the directory structure is presented. These files will be used for this article and you can therefore create them beforehand.
app/ββ tkinter_app.pyDockerfilerun.sh (optional)
Since the goal of this article is to demonstrate how a GUI can be accessed through Docker, a simple window is created as presented below. This GUI contains text and a button to quit the application.
To create this simple application, the code below is utilized.
Afterwards, a Dockerfile should be created and contain the following code. In this Dockerfile, we set the base of the Docker image to a slim version of Python 3.8.12. Afterwards, we update the package information and install Tkinter. The last two lines run the command /app/tkinter_app.py with Python.
In the same directory as the Dockerfile, the following command should be executed to build the Docker image:
docker build -t tkinter_in_docker .
The command above builds a Docker image with the name tkinter_in_docker.
Now that the Docker image has been built, we can run a Docker container of the Docker image. To do this, it requires permission granting, which can have some safety issues. In this article, we will go with a safe approach. However, other approaches exist which are even safer, which are covered here. In this article, we will input our own user credentials by using the following command:
# Read the above before pastingdocker run -u=$(id -u $USER):$(id -g $USER) \ -e DISPLAY=$DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ -v $(pwd)/app:/app \ --rm \ tkinter_in_docker
In the above, -u is used to set the name of the user, -e to set the display, the first -v creates a volume in X11-unix to provide display, the second -v creates another volume where the Docker container can access our Tkinter application, and lastly we use --rm to automatically remove the container after usage.
The previous complex Docker run command as presented above, can be simplified by creating a simple bash file as following:
To make the shell script executable, you can run the command below:
chmod +x ./run.sh
Now you will be able to run it simply by using the command:
./run.sh
In our scenario, we have a single file for the application tkinter_app.py and there is therefore little to no reason for running it manually inside a Docker container using Python. However, for larger applications it might be desired to run individual scripts within the Docker environment instead of running the same one each time.
To allow continuous development, follow the next steps:
Comment line 11 and 12 in your Dockerfile to prevent Docker from automatically running tkinter_app.py.
Use the following Docker build command to rebuild the image with the new changes:
docker build -t tkinter_in_docker .
To run and interact with the Docker container, use the following command:
# Read "Running Docker Container" before running this commanddocker run -u=$(id -u $USER):$(id -g $USER) \ -e DISPLAY=$DISPLAY \ -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ -v $(pwd)/app:/app \ --rm \ -it \ tkinter_in_docker \ /bin/bash
The above command is based on the previous Docker run command. -it is added to get an interactive terminal in the Docker environment, and /bin/bash is added to run it using Bash. If desired, you can replace the above command with the command in the shell script, which was previously covered.
Navigate to the application directory which is located in /app/.
Use the command to run the application:
python tkinter_app.py
Since we have setup a shared volume through our Docker run command, we are now able to locally use an IDE and continuously change our application without the necessity of restarting the Docker container.
Note: To detach the Docker container (exit the docker container), press Ctrl+D.
In this article you developed a simple GUI application using Tkinter which you were able to run through Docker. This is a powerful skill to acquire, especially within the field of data science, due to the vast possibilities of running interactive isolated GUI environments. Now you should be able to further develop your own application.
This is my first article on Medium and feedback is therefore more than appreciated.
|
[
{
"code": null,
"e": 579,
"s": 172,
"text": "In several cases, it can be useful to create a Graphical User Interface (GUI) that can be accessed in Docker, for instance when developing machine learning applications where visualizing image and video is desired. However, several steps are required to be able to view the GUI at the host machine. In this article, we will use Tkinter to create a simple GUI in Python which can be accessed through Docker."
},
{
"code": null,
"e": 852,
"s": 579,
"text": "In this article, we will cover several steps. The first two steps are necessary to run a Tkinter GUI application in Docker. The other steps are optional and are used to gain extra information of how to enhance the development phase using Tkinter and Docker. The steps are:"
},
{
"code": null,
"e": 1086,
"s": 852,
"text": "Create very simple application using Tkinter.Create a simple Docker image and run a Tkinter application in the Docker container.Simplify Docker run command using shell script. (Optional)Allow continuous development of GUI. (Optional)"
},
{
"code": null,
"e": 1132,
"s": 1086,
"text": "Create very simple application using Tkinter."
},
{
"code": null,
"e": 1216,
"s": 1132,
"text": "Create a simple Docker image and run a Tkinter application in the Docker container."
},
{
"code": null,
"e": 1275,
"s": 1216,
"text": "Simplify Docker run command using shell script. (Optional)"
},
{
"code": null,
"e": 1323,
"s": 1275,
"text": "Allow continuous development of GUI. (Optional)"
},
{
"code": null,
"e": 1446,
"s": 1323,
"text": "This article has only been tested with Linux and may not work for other OS. You should also already have installed Docker."
},
{
"code": null,
"e": 1594,
"s": 1446,
"text": "Below, an overview of the directory structure is presented. These files will be used for this article and you can therefore create them beforehand."
},
{
"code": null,
"e": 1643,
"s": 1594,
"text": "app/ββ tkinter_app.pyDockerfilerun.sh (optional)"
},
{
"code": null,
"e": 1842,
"s": 1643,
"text": "Since the goal of this article is to demonstrate how a GUI can be accessed through Docker, a simple window is created as presented below. This GUI contains text and a button to quit the application."
},
{
"code": null,
"e": 1905,
"s": 1842,
"text": "To create this simple application, the code below is utilized."
},
{
"code": null,
"e": 2207,
"s": 1905,
"text": "Afterwards, a Dockerfile should be created and contain the following code. In this Dockerfile, we set the base of the Docker image to a slim version of Python 3.8.12. Afterwards, we update the package information and install Tkinter. The last two lines run the command /app/tkinter_app.py with Python."
},
{
"code": null,
"e": 2316,
"s": 2207,
"text": "In the same directory as the Dockerfile, the following command should be executed to build the Docker image:"
},
{
"code": null,
"e": 2352,
"s": 2316,
"text": "docker build -t tkinter_in_docker ."
},
{
"code": null,
"e": 2425,
"s": 2352,
"text": "The command above builds a Docker image with the name tkinter_in_docker."
},
{
"code": null,
"e": 2814,
"s": 2425,
"text": "Now that the Docker image has been built, we can run a Docker container of the Docker image. To do this, it requires permission granting, which can have some safety issues. In this article, we will go with a safe approach. However, other approaches exist which are even safer, which are covered here. In this article, we will input our own user credentials by using the following command:"
},
{
"code": null,
"e": 3047,
"s": 2814,
"text": "# Read the above before pastingdocker run -u=$(id -u $USER):$(id -g $USER) \\ -e DISPLAY=$DISPLAY \\ -v /tmp/.X11-unix:/tmp/.X11-unix:rw \\ -v $(pwd)/app:/app \\ --rm \\ tkinter_in_docker"
},
{
"code": null,
"e": 3360,
"s": 3047,
"text": "In the above, -u is used to set the name of the user, -e to set the display, the first -v creates a volume in X11-unix to provide display, the second -v creates another volume where the Docker container can access our Tkinter application, and lastly we use --rm to automatically remove the container after usage."
},
{
"code": null,
"e": 3483,
"s": 3360,
"text": "The previous complex Docker run command as presented above, can be simplified by creating a simple bash file as following:"
},
{
"code": null,
"e": 3551,
"s": 3483,
"text": "To make the shell script executable, you can run the command below:"
},
{
"code": null,
"e": 3569,
"s": 3551,
"text": "chmod +x ./run.sh"
},
{
"code": null,
"e": 3629,
"s": 3569,
"text": "Now you will be able to run it simply by using the command:"
},
{
"code": null,
"e": 3638,
"s": 3629,
"text": "./run.sh"
},
{
"code": null,
"e": 3971,
"s": 3638,
"text": "In our scenario, we have a single file for the application tkinter_app.py and there is therefore little to no reason for running it manually inside a Docker container using Python. However, for larger applications it might be desired to run individual scripts within the Docker environment instead of running the same one each time."
},
{
"code": null,
"e": 4027,
"s": 3971,
"text": "To allow continuous development, follow the next steps:"
},
{
"code": null,
"e": 4130,
"s": 4027,
"text": "Comment line 11 and 12 in your Dockerfile to prevent Docker from automatically running tkinter_app.py."
},
{
"code": null,
"e": 4212,
"s": 4130,
"text": "Use the following Docker build command to rebuild the image with the new changes:"
},
{
"code": null,
"e": 4248,
"s": 4212,
"text": "docker build -t tkinter_in_docker ."
},
{
"code": null,
"e": 4322,
"s": 4248,
"text": "To run and interact with the Docker container, use the following command:"
},
{
"code": null,
"e": 4623,
"s": 4322,
"text": "# Read \"Running Docker Container\" before running this commanddocker run -u=$(id -u $USER):$(id -g $USER) \\ -e DISPLAY=$DISPLAY \\ -v /tmp/.X11-unix:/tmp/.X11-unix:rw \\ -v $(pwd)/app:/app \\ --rm \\ -it \\ tkinter_in_docker \\ /bin/bash"
},
{
"code": null,
"e": 4916,
"s": 4623,
"text": "The above command is based on the previous Docker run command. -it is added to get an interactive terminal in the Docker environment, and /bin/bash is added to run it using Bash. If desired, you can replace the above command with the command in the shell script, which was previously covered."
},
{
"code": null,
"e": 4981,
"s": 4916,
"text": "Navigate to the application directory which is located in /app/."
},
{
"code": null,
"e": 5021,
"s": 4981,
"text": "Use the command to run the application:"
},
{
"code": null,
"e": 5043,
"s": 5021,
"text": "python tkinter_app.py"
},
{
"code": null,
"e": 5247,
"s": 5043,
"text": "Since we have setup a shared volume through our Docker run command, we are now able to locally use an IDE and continuously change our application without the necessity of restarting the Docker container."
},
{
"code": null,
"e": 5327,
"s": 5247,
"text": "Note: To detach the Docker container (exit the docker container), press Ctrl+D."
},
{
"code": null,
"e": 5665,
"s": 5327,
"text": "In this article you developed a simple GUI application using Tkinter which you were able to run through Docker. This is a powerful skill to acquire, especially within the field of data science, due to the vast possibilities of running interactive isolated GUI environments. Now you should be able to further develop your own application."
}
] |
Calculate the CGPA and CGPA % of marks obtained by a Student in N subjects - GeeksforGeeks
|
10 Nov, 2021
Given an array arr[] of size N which contains the marks of a student in N subjects, the task is to calculate the CGPA and the CGPA percentage of the student. Note: Consider all marks to be out of 100, for each subject.
CGPA(Cumulative Grade Point Average) is the systematic arrangement in the educational stream to get an average of grade points.
Examples:
Input: arr[] = {90, 80, 70, 80, 90} Output: CGPA = 8.2, Percentage = 77.89 Explanation: The grade in each subject respectively out of 10 is {9, 8, 7, 8, 9}. The CGPA is the average of all the grades = (9 + 8 + 7 + 8 + 9) / 5 = 8.2 The percentage of this CGPA is 77.89.
Input: arr[] = {90, 90, 90, 80, 85} Output: CGPA = 8.7, Percentage = 82.65
Approach: In this article, the CGPA is calculated on a scale of 10.
Input the array from the user containing the marks of the student in N subjects.
Since the scale is on 10, divide marks in every subject by 10 to find the GPA of the student in each subject.
The average of all the GPAβs yield the overall CGPA of the student.
After finding the CGPA, the CGPA percentage can be calculated by the formula:
CGPA% = CGPA * 9.5
This is a general formula for a scale of 10. However, if the entire calculation is made on a scale of 4, this 9.5 is thereby multiplied by 2.5 and the CGPA percentage is found by multiplying with 23.75.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to calculate the CGPA// and CGPA percentage of a student#include<bits/stdc++.h>using namespace std; double CgpaCalc(double marks[], int n){ // Variable to store the grades in // every subject double grade[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for(int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver codeint main(){ int n = 5; double marks[] = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); cout << "CGPA = "; printf("%.1f\n", cgpa); cout << "CGPA Percentage = "; printf("%.2f", cgpa * 9.5);} // This code is contributed by Bhupendra_Singh
// Java program to calculate the CGPA// and CGPA percentage of a student import java.util.Scanner;class CGPA { public static double CgpaCalc(double[] marks, int n) { // Variable to store the grades in // every subject double grade[] = new double[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for (int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for (int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa; } // Driver code public static void main(String args[]) { int n = 5; double[] marks = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); System.out.println( "CGPA = " + cgpa); System.out.println( "CGPA Percentage = " + String.format("%.2f", cgpa * 9.5)); }}
# Python3 program to calculate the CGPA# and CGPA percentage of a studentdef CgpaCalc(marks, n): # Variable to store the grades in # every subject grade = [0] * n # Variables to store CGPA and the # sum of all the grades Sum = 0 # Computing the grades for i in range(n): grade[i] = (marks[i] / 10) # Computing the sum of grades for i in range(n): Sum += grade[i] # Computing the CGPA cgpa = Sum / n return cgpa # Driver coden = 5marks = [ 90, 80, 70, 80, 90 ] cgpa = CgpaCalc(marks, n) print("CGPA = ", '%.1f' % cgpa)print("CGPA Percentage = ", '%.2f' % (cgpa * 9.5)) # This code is contributed by divyeshrabadiya07
// C# program to calculate the CGPA// and CGPA percentage of a studentusing System; class GFG{ public static double CgpaCalc(double[] marks, int n){ // Variable to store the grades in // every subject double []grade = new double[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for(int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver codepublic static void Main(String []args){ int n = 5; double[] marks = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); Console.WriteLine("CGPA = " + cgpa); Console.WriteLine("CGPA Percentage = {0:F2}", cgpa * 9.5);}} // This code is contributed by Amit Katiyar
<script> // Javascript program to calculate the CGPA// and CGPA percentage of a student function CgpaCalc( marks, n){ // Variable to store the grades in // every subject let grade = Array.from({length: n}, (_, i) => 0); // Variables to store CGPA and the // sum of all the grades let cgpa, sum = 0; // Computing the grades for(let i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(let i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver Code let n = 5; let marks = [ 90, 80, 70, 80, 90 ]; let cgpa = CgpaCalc(marks, n); document.write( "CGPA = " + cgpa + "<br/>"); document.write( "CGPA Percentage = " + (cgpa * 9.5).toFixed(2)); </script>
CGPA = 8.2
CGPA Percentage = 77.90
Time Complexity: O(n)
Auxiliary Space: O(n)
bgangwar59
amit143katiyar
divyeshrabadiya07
code_hunt
subham348
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 24159,
"s": 24131,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24378,
"s": 24159,
"text": "Given an array arr[] of size N which contains the marks of a student in N subjects, the task is to calculate the CGPA and the CGPA percentage of the student. Note: Consider all marks to be out of 100, for each subject."
},
{
"code": null,
"e": 24506,
"s": 24378,
"text": "CGPA(Cumulative Grade Point Average) is the systematic arrangement in the educational stream to get an average of grade points."
},
{
"code": null,
"e": 24516,
"s": 24506,
"text": "Examples:"
},
{
"code": null,
"e": 24785,
"s": 24516,
"text": "Input: arr[] = {90, 80, 70, 80, 90} Output: CGPA = 8.2, Percentage = 77.89 Explanation: The grade in each subject respectively out of 10 is {9, 8, 7, 8, 9}. The CGPA is the average of all the grades = (9 + 8 + 7 + 8 + 9) / 5 = 8.2 The percentage of this CGPA is 77.89."
},
{
"code": null,
"e": 24860,
"s": 24785,
"text": "Input: arr[] = {90, 90, 90, 80, 85} Output: CGPA = 8.7, Percentage = 82.65"
},
{
"code": null,
"e": 24928,
"s": 24860,
"text": "Approach: In this article, the CGPA is calculated on a scale of 10."
},
{
"code": null,
"e": 25009,
"s": 24928,
"text": "Input the array from the user containing the marks of the student in N subjects."
},
{
"code": null,
"e": 25119,
"s": 25009,
"text": "Since the scale is on 10, divide marks in every subject by 10 to find the GPA of the student in each subject."
},
{
"code": null,
"e": 25187,
"s": 25119,
"text": "The average of all the GPAβs yield the overall CGPA of the student."
},
{
"code": null,
"e": 25265,
"s": 25187,
"text": "After finding the CGPA, the CGPA percentage can be calculated by the formula:"
},
{
"code": null,
"e": 25284,
"s": 25265,
"text": "CGPA% = CGPA * 9.5"
},
{
"code": null,
"e": 25487,
"s": 25284,
"text": "This is a general formula for a scale of 10. However, if the entire calculation is made on a scale of 4, this 9.5 is thereby multiplied by 2.5 and the CGPA percentage is found by multiplying with 23.75."
},
{
"code": null,
"e": 25538,
"s": 25487,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25542,
"s": 25538,
"text": "C++"
},
{
"code": null,
"e": 25547,
"s": 25542,
"text": "Java"
},
{
"code": null,
"e": 25555,
"s": 25547,
"text": "Python3"
},
{
"code": null,
"e": 25558,
"s": 25555,
"text": "C#"
},
{
"code": null,
"e": 25569,
"s": 25558,
"text": "Javascript"
},
{
"code": "// C++ program to calculate the CGPA// and CGPA percentage of a student#include<bits/stdc++.h>using namespace std; double CgpaCalc(double marks[], int n){ // Variable to store the grades in // every subject double grade[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for(int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver codeint main(){ int n = 5; double marks[] = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); cout << \"CGPA = \"; printf(\"%.1f\\n\", cgpa); cout << \"CGPA Percentage = \"; printf(\"%.2f\", cgpa * 9.5);} // This code is contributed by Bhupendra_Singh",
"e": 26449,
"s": 25569,
"text": null
},
{
"code": "// Java program to calculate the CGPA// and CGPA percentage of a student import java.util.Scanner;class CGPA { public static double CgpaCalc(double[] marks, int n) { // Variable to store the grades in // every subject double grade[] = new double[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for (int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for (int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa; } // Driver code public static void main(String args[]) { int n = 5; double[] marks = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); System.out.println( \"CGPA = \" + cgpa); System.out.println( \"CGPA Percentage = \" + String.format(\"%.2f\", cgpa * 9.5)); }}",
"e": 27498,
"s": 26449,
"text": null
},
{
"code": "# Python3 program to calculate the CGPA# and CGPA percentage of a studentdef CgpaCalc(marks, n): # Variable to store the grades in # every subject grade = [0] * n # Variables to store CGPA and the # sum of all the grades Sum = 0 # Computing the grades for i in range(n): grade[i] = (marks[i] / 10) # Computing the sum of grades for i in range(n): Sum += grade[i] # Computing the CGPA cgpa = Sum / n return cgpa # Driver coden = 5marks = [ 90, 80, 70, 80, 90 ] cgpa = CgpaCalc(marks, n) print(\"CGPA = \", '%.1f' % cgpa)print(\"CGPA Percentage = \", '%.2f' % (cgpa * 9.5)) # This code is contributed by divyeshrabadiya07",
"e": 28189,
"s": 27498,
"text": null
},
{
"code": "// C# program to calculate the CGPA// and CGPA percentage of a studentusing System; class GFG{ public static double CgpaCalc(double[] marks, int n){ // Variable to store the grades in // every subject double []grade = new double[n]; // Variables to store CGPA and the // sum of all the grades double cgpa, sum = 0; // Computing the grades for(int i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(int i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver codepublic static void Main(String []args){ int n = 5; double[] marks = { 90, 80, 70, 80, 90 }; double cgpa = CgpaCalc(marks, n); Console.WriteLine(\"CGPA = \" + cgpa); Console.WriteLine(\"CGPA Percentage = {0:F2}\", cgpa * 9.5);}} // This code is contributed by Amit Katiyar",
"e": 29141,
"s": 28189,
"text": null
},
{
"code": "<script> // Javascript program to calculate the CGPA// and CGPA percentage of a student function CgpaCalc( marks, n){ // Variable to store the grades in // every subject let grade = Array.from({length: n}, (_, i) => 0); // Variables to store CGPA and the // sum of all the grades let cgpa, sum = 0; // Computing the grades for(let i = 0; i < n; i++) { grade[i] = (marks[i] / 10); } // Computing the sum of grades for(let i = 0; i < n; i++) { sum += grade[i]; } // Computing the CGPA cgpa = sum / n; return cgpa;} // Driver Code let n = 5; let marks = [ 90, 80, 70, 80, 90 ]; let cgpa = CgpaCalc(marks, n); document.write( \"CGPA = \" + cgpa + \"<br/>\"); document.write( \"CGPA Percentage = \" + (cgpa * 9.5).toFixed(2)); </script>",
"e": 30028,
"s": 29141,
"text": null
},
{
"code": null,
"e": 30063,
"s": 30028,
"text": "CGPA = 8.2\nCGPA Percentage = 77.90"
},
{
"code": null,
"e": 30085,
"s": 30063,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 30107,
"s": 30085,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 30118,
"s": 30107,
"text": "bgangwar59"
},
{
"code": null,
"e": 30133,
"s": 30118,
"text": "amit143katiyar"
},
{
"code": null,
"e": 30151,
"s": 30133,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30161,
"s": 30151,
"text": "code_hunt"
},
{
"code": null,
"e": 30171,
"s": 30161,
"text": "subham348"
},
{
"code": null,
"e": 30184,
"s": 30171,
"text": "Mathematical"
},
{
"code": null,
"e": 30203,
"s": 30184,
"text": "School Programming"
},
{
"code": null,
"e": 30216,
"s": 30203,
"text": "Mathematical"
},
{
"code": null,
"e": 30314,
"s": 30216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30323,
"s": 30314,
"text": "Comments"
},
{
"code": null,
"e": 30336,
"s": 30323,
"text": "Old Comments"
},
{
"code": null,
"e": 30360,
"s": 30336,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 30374,
"s": 30360,
"text": "Prime Numbers"
},
{
"code": null,
"e": 30417,
"s": 30374,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30458,
"s": 30417,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 30503,
"s": 30458,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 30521,
"s": 30503,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30537,
"s": 30521,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30562,
"s": 30537,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30581,
"s": 30562,
"text": "Inheritance in C++"
}
] |
Build Python Packages Without Publishing | by Max Reynolds | Towards Data Science
|
Packages in Python allow for seamless distribution of python modules. When we use pip install, we are often downloading a publicly available package from PyPI. Local packages can also be useful for code organization and re-use, allowing you to simply import a module without having to navigate to its directory or re-write code. In this demonstration, we will be building and accessing a basic Python package.
Letβs create two simple modules and package them. We will then use this package to write a simple app that prompts a user to select a .jpg image from their computer to be gray-scaled.
ui.py
#ui.pyfrom tkinter import filedialogfrom tkinter import Tkdef get_image_file(): Tk().withdraw() filename = filedialog.askopenfilename(title = "Select file",filetypes = [("jpeg files","*.jpg")]) return filename
image_edits.py
#image_edits.pyfrom cv2 import imread, COLOR_RGB2GRAY, cvtColor, imwriteimport osdef write_grayscale_image(filepath): original_image = imread(filepath) grayed_image = cvtColor(original_image, COLOR_RGB2GRAY) grayed_filename=os.path.join(os.path.split(filepath)[0],'grayed_'+os.path.split(filepath)[1]) print(grayed_filename) imwrite(grayed_filename, grayed_image) #export grayscaled image return grayed_filename
Create a blank __init__.py file, which will be used by Python to recognize this as a package.
$ touch __init__.py
At this point, our file structure should look like this:
dir/ image_pkg/ ui.py image_edits.py __init__.py
Next, create a setup.py file outside of your package directory
setup.py
import setuptoolssetuptools.setup(name='examplepackage',version='0.1',description='An example package',url='#',author='max',install_requires=['opencv-python'],author_email='',packages=setuptools.find_packages(),zip_safe=False)
Note that packages not included in the python standard library should be included in install_requires. Our file structure should now look like:
dir/ image_pkg/ ui.py image_edits.py __init__.py setup.py
If you are using virtual environments (generally good practice for Python development), create and activate your environment.
$ python3 -m venv myenv$ source myenv/bin/activate
Install wheel.
$ pip install wheel
Install the package into your environment.
$ pip install .
Our package has been created, and we can now use it from anywhere. Letβs create a simple app which incorporates our package contents.
main.py
#main.pyfrom image_pkg.ui import get_image_filefrom image_pkg.image_edits import write_grayscale_imagewrite_grayscale_image(get_image_file())
We have now built and implemented a basic python package! More information regarding package distribution, licensing, and installation can be found in the documentation.
towardsdatascience.com
towardsdatascience.co
Registering for Medium supports my work.
|
[
{
"code": null,
"e": 582,
"s": 172,
"text": "Packages in Python allow for seamless distribution of python modules. When we use pip install, we are often downloading a publicly available package from PyPI. Local packages can also be useful for code organization and re-use, allowing you to simply import a module without having to navigate to its directory or re-write code. In this demonstration, we will be building and accessing a basic Python package."
},
{
"code": null,
"e": 766,
"s": 582,
"text": "Letβs create two simple modules and package them. We will then use this package to write a simple app that prompts a user to select a .jpg image from their computer to be gray-scaled."
},
{
"code": null,
"e": 772,
"s": 766,
"text": "ui.py"
},
{
"code": null,
"e": 992,
"s": 772,
"text": "#ui.pyfrom tkinter import filedialogfrom tkinter import Tkdef get_image_file(): Tk().withdraw() filename = filedialog.askopenfilename(title = \"Select file\",filetypes = [(\"jpeg files\",\"*.jpg\")]) return filename"
},
{
"code": null,
"e": 1007,
"s": 992,
"text": "image_edits.py"
},
{
"code": null,
"e": 1437,
"s": 1007,
"text": "#image_edits.pyfrom cv2 import imread, COLOR_RGB2GRAY, cvtColor, imwriteimport osdef write_grayscale_image(filepath): original_image = imread(filepath) grayed_image = cvtColor(original_image, COLOR_RGB2GRAY) grayed_filename=os.path.join(os.path.split(filepath)[0],'grayed_'+os.path.split(filepath)[1]) print(grayed_filename) imwrite(grayed_filename, grayed_image) #export grayscaled image return grayed_filename"
},
{
"code": null,
"e": 1531,
"s": 1437,
"text": "Create a blank __init__.py file, which will be used by Python to recognize this as a package."
},
{
"code": null,
"e": 1551,
"s": 1531,
"text": "$ touch __init__.py"
},
{
"code": null,
"e": 1608,
"s": 1551,
"text": "At this point, our file structure should look like this:"
},
{
"code": null,
"e": 1699,
"s": 1608,
"text": "dir/ image_pkg/ ui.py image_edits.py __init__.py"
},
{
"code": null,
"e": 1762,
"s": 1699,
"text": "Next, create a setup.py file outside of your package directory"
},
{
"code": null,
"e": 1771,
"s": 1762,
"text": "setup.py"
},
{
"code": null,
"e": 1998,
"s": 1771,
"text": "import setuptoolssetuptools.setup(name='examplepackage',version='0.1',description='An example package',url='#',author='max',install_requires=['opencv-python'],author_email='',packages=setuptools.find_packages(),zip_safe=False)"
},
{
"code": null,
"e": 2142,
"s": 1998,
"text": "Note that packages not included in the python standard library should be included in install_requires. Our file structure should now look like:"
},
{
"code": null,
"e": 2245,
"s": 2142,
"text": "dir/ image_pkg/ ui.py image_edits.py __init__.py setup.py"
},
{
"code": null,
"e": 2371,
"s": 2245,
"text": "If you are using virtual environments (generally good practice for Python development), create and activate your environment."
},
{
"code": null,
"e": 2422,
"s": 2371,
"text": "$ python3 -m venv myenv$ source myenv/bin/activate"
},
{
"code": null,
"e": 2437,
"s": 2422,
"text": "Install wheel."
},
{
"code": null,
"e": 2457,
"s": 2437,
"text": "$ pip install wheel"
},
{
"code": null,
"e": 2500,
"s": 2457,
"text": "Install the package into your environment."
},
{
"code": null,
"e": 2516,
"s": 2500,
"text": "$ pip install ."
},
{
"code": null,
"e": 2650,
"s": 2516,
"text": "Our package has been created, and we can now use it from anywhere. Letβs create a simple app which incorporates our package contents."
},
{
"code": null,
"e": 2658,
"s": 2650,
"text": "main.py"
},
{
"code": null,
"e": 2800,
"s": 2658,
"text": "#main.pyfrom image_pkg.ui import get_image_filefrom image_pkg.image_edits import write_grayscale_imagewrite_grayscale_image(get_image_file())"
},
{
"code": null,
"e": 2970,
"s": 2800,
"text": "We have now built and implemented a basic python package! More information regarding package distribution, licensing, and installation can be found in the documentation."
},
{
"code": null,
"e": 2993,
"s": 2970,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3015,
"s": 2993,
"text": "towardsdatascience.co"
}
] |
How many types of Result Sets are there in JDBC What are they?
|
There are two types of result sets namely, forward only and, bidirectional.
Forward only ResultSet: The ResultSet object whose cursor moves only in one direction is known as forward only ResultSet. By default, JDBC result sets are forward-only result sets.
You can move the cursor of the forward only ResultSets using the next() method of the ResultSet interface. It moves the pointer to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position it returns false, else it returns true.
Therefore, using this method in the while loop you can iterate the contents of the ResultSet object.
while(rs.next()){
}
Assume we have a table named dataset with content as shown below:
+--------------+-----------+
| mobile_brand | unit_sale |
+--------------+-----------+
| Iphone | 3000 |
| Samsung | 4000 |
| Nokia | 5000 |
| Vivo | 1500 |
+--------------+-----------+
The following example retrieves all the records of the Dataset table and prints the results:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingData {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from Dataset");
System.out.println("Contents of the table");
while(rs.next()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
}
}
}
Connection established......
Contents of the table
Brand: Iphone, Sale: 3000
Brand: Samsung, Sale: 4000
Brand: Nokia, Sale: 5000
Brand: Vivo, Sale: 1500
Bidirectional ResultSet: A bi-directional ResultSet object is the one whose cursor moves in both forward and backward directions.
The createStatement() method of the Connection interface has a variant which accepts two integer values representing the result set type and the concurrency type.
Statement createStatement(int resultSetType, int resultSetConcurrency)
To create a bi-directional result set you need to pass the type as ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to this method as:
//Creating a Statement object
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Following example demonstrates the creation of bi-directional ResultSet. Here we trying to created a bi-directional ResultSet object which retrieves the data from the table name dataset and, we are trying to print rows of the dataset table from last to first using the previous() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BidirectionalResultSet {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from Dataset");
rs.afterLast();
System.out.println("Contents of the table");
while(rs.previous()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
}
}
}
Connection established......
Contents of the table
Brand: Vivo, Sale: 1500
Brand: Nokia, Sale: 5000
Brand: Samsung, Sale: 4000
Brand: IPhone, Sale: 3000
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "There are two types of result sets namely, forward only and, bidirectional."
},
{
"code": null,
"e": 1319,
"s": 1138,
"text": "Forward only ResultSet: The ResultSet object whose cursor moves only in one direction is known as forward only ResultSet. By default, JDBC result sets are forward-only result sets."
},
{
"code": null,
"e": 1617,
"s": 1319,
"text": "You can move the cursor of the forward only ResultSets using the next() method of the ResultSet interface. It moves the pointer to the next row from the current position. This method returns a boolean value. If there are no rows next to its current position it returns false, else it returns true."
},
{
"code": null,
"e": 1718,
"s": 1617,
"text": "Therefore, using this method in the while loop you can iterate the contents of the ResultSet object."
},
{
"code": null,
"e": 1738,
"s": 1718,
"text": "while(rs.next()){\n}"
},
{
"code": null,
"e": 1804,
"s": 1738,
"text": "Assume we have a table named dataset with content as shown below:"
},
{
"code": null,
"e": 2036,
"s": 1804,
"text": "+--------------+-----------+\n| mobile_brand | unit_sale |\n+--------------+-----------+\n| Iphone | 3000 |\n| Samsung | 4000 |\n| Nokia | 5000 |\n| Vivo | 1500 |\n+--------------+-----------+"
},
{
"code": null,
"e": 2129,
"s": 2036,
"text": "The following example retrieves all the records of the Dataset table and prints the results:"
},
{
"code": null,
"e": 3091,
"s": 2129,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class RetrievingData {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/TestDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from Dataset\");\n System.out.println(\"Contents of the table\");\n while(rs.next()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n }\n }\n}"
},
{
"code": null,
"e": 3244,
"s": 3091,
"text": "Connection established......\nContents of the table\nBrand: Iphone, Sale: 3000\nBrand: Samsung, Sale: 4000\nBrand: Nokia, Sale: 5000\nBrand: Vivo, Sale: 1500"
},
{
"code": null,
"e": 3374,
"s": 3244,
"text": "Bidirectional ResultSet: A bi-directional ResultSet object is the one whose cursor moves in both forward and backward directions."
},
{
"code": null,
"e": 3537,
"s": 3374,
"text": "The createStatement() method of the Connection interface has a variant which accepts two integer values representing the result set type and the concurrency type."
},
{
"code": null,
"e": 3608,
"s": 3537,
"text": "Statement createStatement(int resultSetType, int resultSetConcurrency)"
},
{
"code": null,
"e": 3792,
"s": 3608,
"text": "To create a bi-directional result set you need to pass the type as ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to this method as:"
},
{
"code": null,
"e": 3921,
"s": 3792,
"text": "//Creating a Statement object\nStatement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,\nResultSet.CONCUR_UPDATABLE);"
},
{
"code": null,
"e": 4209,
"s": 3921,
"text": "Following example demonstrates the creation of bi-directional ResultSet. Here we trying to created a bi-directional ResultSet object which retrieves the data from the table name dataset and, we are trying to print rows of the dataset table from last to first using the previous() method."
},
{
"code": null,
"e": 5270,
"s": 4209,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class BidirectionalResultSet {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/TestDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,\n ResultSet.CONCUR_UPDATABLE);\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from Dataset\");\n rs.afterLast();\n System.out.println(\"Contents of the table\");\n while(rs.previous()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n }\n }\n}"
},
{
"code": null,
"e": 5423,
"s": 5270,
"text": "Connection established......\nContents of the table\nBrand: Vivo, Sale: 1500\nBrand: Nokia, Sale: 5000\nBrand: Samsung, Sale: 4000\nBrand: IPhone, Sale: 3000"
}
] |
Advantages of vector over array in C++ - GeeksforGeeks
|
30 Oct, 2018
We have already discussed arrays and vectors. In this post, we will discuss advantages of vector over normal array.
Advantages of Vector over arrays :
Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++.Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << "Size of Array " << sizeof(array) / sizeof(array[0]) << "\n"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << "Size of vector Before Removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; v.erase(v.begin() + 2); // Remove 3rd element cout << "\nSize of vector After removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; return 0;}Output:Size of Array 100
Size of vector Before Removal=5
1 2 3 4 5
Size of vector After removal=4
1 2 4 5
Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}Size of array cannot be determined if dynamically allocated whereas Size of the vector can be determined in O(1) time.When arrays are passed to a function, a separate parameter for size is also passed whereas in case of passing a vector to a function, there is no such need as vector maintains variables which keeps track of size of container at all times.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << "Size of array= "; cout << sizeof(arr) / sizeof(*arr) << "\n"; // Pointer cannot be used to get size of // block pointed by it return 0;}Output:Size of array= 2
When array becomes full and new elements are inserted; no reallocation is done implicitly whereas When vector becomes larger than its capacity, reallocation is done implicitly.Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << "*(array + " << i << ") : "; cout << *(array + i) << endl; } return 0;}Output:warning: address of local variable 'arr' returned [-Wreturn-local-addr]
Segmentation Fault (SIGSEGV)
// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << " "; return 0;}Output:1 2 3 4 5 6 7 8 9 10
Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << "vector get:\n"; for (auto it : get) cout << it << " "; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}Output:vector get:
1 2 3 4 5 6 7 8 9 10
error: invalid array assignment
copyArr=arr;
Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++.
Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}
#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}
Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << "Size of Array " << sizeof(array) / sizeof(array[0]) << "\n"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << "Size of vector Before Removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; v.erase(v.begin() + 2); // Remove 3rd element cout << "\nSize of vector After removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; return 0;}Output:Size of Array 100
Size of vector Before Removal=5
1 2 3 4 5
Size of vector After removal=4
1 2 4 5
#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << "Size of Array " << sizeof(array) / sizeof(array[0]) << "\n"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << "Size of vector Before Removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; v.erase(v.begin() + 2); // Remove 3rd element cout << "\nSize of vector After removal=" << v.size() << "\n"; // Output Values of vector for (auto it : v) cout << it << " "; return 0;}
Output:
Size of Array 100
Size of vector Before Removal=5
1 2 3 4 5
Size of vector After removal=4
1 2 4 5
Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}
#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}
Size of array cannot be determined if dynamically allocated whereas Size of the vector can be determined in O(1) time.
When arrays are passed to a function, a separate parameter for size is also passed whereas in case of passing a vector to a function, there is no such need as vector maintains variables which keeps track of size of container at all times.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << "Size of array= "; cout << sizeof(arr) / sizeof(*arr) << "\n"; // Pointer cannot be used to get size of // block pointed by it return 0;}Output:Size of array= 2
#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << "Size of array= "; cout << sizeof(arr) / sizeof(*arr) << "\n"; // Pointer cannot be used to get size of // block pointed by it return 0;}
Output:
Size of array= 2
When array becomes full and new elements are inserted; no reallocation is done implicitly whereas When vector becomes larger than its capacity, reallocation is done implicitly.
Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << "*(array + " << i << ") : "; cout << *(array + i) << endl; } return 0;}Output:warning: address of local variable 'arr' returned [-Wreturn-local-addr]
Segmentation Fault (SIGSEGV)
// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << " "; return 0;}Output:1 2 3 4 5 6 7 8 9 10
// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << "*(array + " << i << ") : "; cout << *(array + i) << endl; } return 0;}
Output:
warning: address of local variable 'arr' returned [-Wreturn-local-addr]
Segmentation Fault (SIGSEGV)
// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << " "; return 0;}
Output:
1 2 3 4 5 6 7 8 9 10
Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << "vector get:\n"; for (auto it : get) cout << it << " "; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}Output:vector get:
1 2 3 4 5 6 7 8 9 10
error: invalid array assignment
copyArr=arr;
#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << "vector get:\n"; for (auto it : get) cout << it << " "; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}
Output:
vector get:
1 2 3 4 5 6 7 8 9 10
error: invalid array assignment
copyArr=arr;
nikhil_jsk
cpp-array
cpp-vector
Arrays
Data Structures
Difference Between
Data Structures
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Difference between Stack and Queue Data Structures
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
What is Competitive Programming and How to Prepare for It?
Data Structures | Linked List | Question 1
|
[
{
"code": null,
"e": 26177,
"s": 26149,
"text": "\n30 Oct, 2018"
},
{
"code": null,
"e": 26293,
"s": 26177,
"text": "We have already discussed arrays and vectors. In this post, we will discuss advantages of vector over normal array."
},
{
"code": null,
"e": 26328,
"s": 26293,
"text": "Advantages of Vector over arrays :"
},
{
"code": null,
"e": 31013,
"s": 26328,
"text": "Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++.Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << \"Size of Array \" << sizeof(array) / sizeof(array[0]) << \"\\n\"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << \"Size of vector Before Removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; v.erase(v.begin() + 2); // Remove 3rd element cout << \"\\nSize of vector After removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; return 0;}Output:Size of Array 100\nSize of vector Before Removal=5\n1 2 3 4 5 \nSize of vector After removal=4\n1 2 4 5\nArrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}Size of array cannot be determined if dynamically allocated whereas Size of the vector can be determined in O(1) time.When arrays are passed to a function, a separate parameter for size is also passed whereas in case of passing a vector to a function, there is no such need as vector maintains variables which keeps track of size of container at all times.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << \"Size of array= \"; cout << sizeof(arr) / sizeof(*arr) << \"\\n\"; // Pointer cannot be used to get size of // block pointed by it return 0;}Output:Size of array= 2\nWhen array becomes full and new elements are inserted; no reallocation is done implicitly whereas When vector becomes larger than its capacity, reallocation is done implicitly.Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << \"*(array + \" << i << \") : \"; cout << *(array + i) << endl; } return 0;}Output:warning: address of local variable 'arr' returned [-Wreturn-local-addr]\nSegmentation Fault (SIGSEGV)\n// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << \" \"; return 0;}Output:1 2 3 4 5 6 7 8 9 10 \nArrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << \"vector get:\\n\"; for (auto it : get) cout << it << \" \"; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}Output:vector get:\n1 2 3 4 5 6 7 8 9 10\n\nerror: invalid array assignment\n copyArr=arr;\n"
},
{
"code": null,
"e": 31142,
"s": 31013,
"text": "Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++."
},
{
"code": null,
"e": 31516,
"s": 31142,
"text": "Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation int* arr = new int[100]; // Dynamic Implementation vector<int> v; // Vector's Implementation return 0;}",
"e": 31731,
"s": 31516,
"text": null
},
{
"code": null,
"e": 32680,
"s": 31731,
"text": "Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << \"Size of Array \" << sizeof(array) / sizeof(array[0]) << \"\\n\"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << \"Size of vector Before Removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; v.erase(v.begin() + 2); // Remove 3rd element cout << \"\\nSize of vector After removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; return 0;}Output:Size of Array 100\nSize of vector Before Removal=5\n1 2 3 4 5 \nSize of vector After removal=4\n1 2 4 5\n"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ int array[100]; // Static Implementation cout << \"Size of Array \" << sizeof(array) / sizeof(array[0]) << \"\\n\"; vector<int> v; // Vector's Implementation // Inserting Values in Vector v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); cout << \"Size of vector Before Removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; v.erase(v.begin() + 2); // Remove 3rd element cout << \"\\nSize of vector After removal=\" << v.size() << \"\\n\"; // Output Values of vector for (auto it : v) cout << it << \" \"; return 0;}",
"e": 33394,
"s": 32680,
"text": null
},
{
"code": null,
"e": 33402,
"s": 33394,
"text": "Output:"
},
{
"code": null,
"e": 33503,
"s": 33402,
"text": "Size of Array 100\nSize of vector Before Removal=5\n1 2 3 4 5 \nSize of vector After removal=4\n1 2 4 5\n"
},
{
"code": null,
"e": 33884,
"s": 33503,
"text": "Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation delete[] arr; // array Explicitly deallocated vector<int> v; // Automatic deallocation when variable goes out of scope return 0;}",
"e": 34137,
"s": 33884,
"text": null
},
{
"code": null,
"e": 34256,
"s": 34137,
"text": "Size of array cannot be determined if dynamically allocated whereas Size of the vector can be determined in O(1) time."
},
{
"code": null,
"e": 34790,
"s": 34256,
"text": "When arrays are passed to a function, a separate parameter for size is also passed whereas in case of passing a vector to a function, there is no such need as vector maintains variables which keeps track of size of container at all times.#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << \"Size of array= \"; cout << sizeof(arr) / sizeof(*arr) << \"\\n\"; // Pointer cannot be used to get size of // block pointed by it return 0;}Output:Size of array= 2\n"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ int* arr = new int[100]; // Dynamic Implementation cout << \"Size of array= \"; cout << sizeof(arr) / sizeof(*arr) << \"\\n\"; // Pointer cannot be used to get size of // block pointed by it return 0;}",
"e": 35062,
"s": 34790,
"text": null
},
{
"code": null,
"e": 35070,
"s": 35062,
"text": "Output:"
},
{
"code": null,
"e": 35088,
"s": 35070,
"text": "Size of array= 2\n"
},
{
"code": null,
"e": 35265,
"s": 35088,
"text": "When array becomes full and new elements are inserted; no reallocation is done implicitly whereas When vector becomes larger than its capacity, reallocation is done implicitly."
},
{
"code": null,
"e": 36614,
"s": 35265,
"text": "Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function.// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << \"*(array + \" << i << \") : \"; cout << *(array + i) << endl; } return 0;}Output:warning: address of local variable 'arr' returned [-Wreturn-local-addr]\nSegmentation Fault (SIGSEGV)\n// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << \" \"; return 0;}Output:1 2 3 4 5 6 7 8 9 10 \n"
},
{
"code": "// Program to demonstrate arrays cannot be returned#include <bits/stdc++.h>using namespace std; int* getValues(){ int arr[10]; // Array defined locally for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; return arr; // returning pointer to array} // main functionint main(){ int* array; // pointer of int type array = getValues(); // Call function to get arr for (int i = 0; i < 10; i++) { // Printing Values cout << \"*(array + \" << i << \") : \"; cout << *(array + i) << endl; } return 0;}",
"e": 37182,
"s": 36614,
"text": null
},
{
"code": null,
"e": 37190,
"s": 37182,
"text": "Output:"
},
{
"code": null,
"e": 37292,
"s": 37190,
"text": "warning: address of local variable 'arr' returned [-Wreturn-local-addr]\nSegmentation Fault (SIGSEGV)\n"
},
{
"code": "// Program to demonstrate vector can be returned#include <bits/stdc++.h>using namespace std; // Function returning vectorvector<int> getValues(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) // Inserting values in Vector v.push_back(i + 1); return v; // returning pointer to array} // main functionint main(){ vector<int> get; get = getValues(); // Call function to get v // Output Values of vector for (auto it : get) cout << it << \" \"; return 0;}",
"e": 37818,
"s": 37292,
"text": null
},
{
"code": null,
"e": 37826,
"s": 37818,
"text": "Output:"
},
{
"code": null,
"e": 37849,
"s": 37826,
"text": "1 2 3 4 5 6 7 8 9 10 \n"
},
{
"code": null,
"e": 38530,
"s": 37849,
"text": "Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << \"vector get:\\n\"; for (auto it : get) cout << it << \" \"; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}Output:vector get:\n1 2 3 4 5 6 7 8 9 10\n\nerror: invalid array assignment\n copyArr=arr;\n"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // main functionint main(){ vector<int> v; // Vector defined locally for (int i = 0; i < 10; i++) v.push_back(i + 1); vector<int> get; get = v; // Copying vector v into vector get cout << \"vector get:\\n\"; for (auto it : get) cout << it << \" \"; int arr[10]; for (int i = 0; i < 10; i++) // Putting Values in array arr[i] = i + 1; int copyArr[10]; copyArr = arr; // Error return 0;}",
"e": 39025,
"s": 38530,
"text": null
},
{
"code": null,
"e": 39033,
"s": 39025,
"text": "Output:"
},
{
"code": null,
"e": 39117,
"s": 39033,
"text": "vector get:\n1 2 3 4 5 6 7 8 9 10\n\nerror: invalid array assignment\n copyArr=arr;\n"
},
{
"code": null,
"e": 39128,
"s": 39117,
"text": "nikhil_jsk"
},
{
"code": null,
"e": 39138,
"s": 39128,
"text": "cpp-array"
},
{
"code": null,
"e": 39149,
"s": 39138,
"text": "cpp-vector"
},
{
"code": null,
"e": 39156,
"s": 39149,
"text": "Arrays"
},
{
"code": null,
"e": 39172,
"s": 39156,
"text": "Data Structures"
},
{
"code": null,
"e": 39191,
"s": 39172,
"text": "Difference Between"
},
{
"code": null,
"e": 39207,
"s": 39191,
"text": "Data Structures"
},
{
"code": null,
"e": 39214,
"s": 39207,
"text": "Arrays"
},
{
"code": null,
"e": 39312,
"s": 39214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39343,
"s": 39312,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 39381,
"s": 39343,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 39406,
"s": 39381,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 39427,
"s": 39406,
"text": "Next Greater Element"
},
{
"code": null,
"e": 39485,
"s": 39427,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 39536,
"s": 39485,
"text": "Difference between Stack and Queue Data Structures"
},
{
"code": null,
"e": 39579,
"s": 39536,
"text": "Data Structures | Linked List | Question 5"
},
{
"code": null,
"e": 39626,
"s": 39579,
"text": "Data Structures | Tree Traversals | Question 4"
},
{
"code": null,
"e": 39685,
"s": 39626,
"text": "What is Competitive Programming and How to Prepare for It?"
}
] |
K-Means Clustering in SAS. What is Clustering? | by Dhilip Subramanian | Towards Data Science
|
What is Clustering?
βClustering is the process of dividing the datasets into groups, consisting of similar data-pointsβ. Clustering is a type of unsupervised machine learning, which is used when you have unlabeled data.
Letβs understand in the real scenario,
Group of diners sitting in a restaurant. Letβs say two tables in the restaurant called T1 and T2. People in Table T1 might be related to each other, or maybe a group of family members or colleagues or anything.
In a similar way, people in table T2 might be related to each other or maybe a group of colleagues or anything. But, when comparing people sitting in table T1 and people sitting in table T2, they are entirely different and not at all related to each other.
Clustering also works in the same way. Data points in one cluster are entirely different from data points in another cluster. All the points in the same cluster are either the same or related to each other.
Another good example is the Netflix movie recommendation.
Netflix recommends movies based on the history of the userβs watch. Whatever people watched; similar films related to it will be shown. Clustering algorithm generates all of these recommended lists.
Clustering can be used for segmentation and many other applications. It has different techniques. One of the most popular, simple and interesting algorithms is K -Means Clustering.
K-Means is a clustering algorithm whose main goal is to group similar elements or data points into a cluster. βKβ in K-means represents the number of clusters.
K-means clustering steps:
Distance measure will determine the similarity between two elements and it will influence the shape of the clusters. Normally, Euclidean distance will be used in K-Means Clustering
The Euclidean distance is the βordinaryβ straight line. It is the distance between two points in Euclidean space.
How does K-Means Algorithm work?
Letβs take two data points. Assume K =2. Then, it will take two random centroids anywhere in the data and based on that it will draw a line in the middle. One centroid represents in red and another one in yellow. Then all the data points towards the yellow centroid classified into yellow. All the data points towards the red centroid classified as a red. This is the first iteration step.
Next step, it calculates the distance from the centroid to data points by using the Euclidean method. And both red and yellow centroid points moves into new points by calculating the mean of all the points.
Again, it draws a new line between new centroid points. Automatically, all the points falling towards the red centroid will be recognized as a red group and yellow centroid will be recognized as a yellow group.
Again the same step will be repeated with new points and it will calculate new centroids. We can clearly see that data points has been moved to different groups.
It keeps on going until centroid movements become almost negligible. Then, it becomes cluster 1 and cluster 2. Here, the output Y label will give 0βs and 1βs. 0βs represent cluster 1 and 1 represent cluster 2. If it is three clusters, then it gives 0, 1 and 2.
Letβs take a famous IRIS datasets. Checking the dataset by using proc means
/* Checking the contents of the datasets */proc means data=work.iris N Nmiss mean median max min;run;
It has 150 observations and 5 variables. No missing values or outliers detected. We will use only four variables namely sepal_length, sepal_width, petal_length and petal_width. The datasets in βcmβ. βTargetβ variable can be dropped as it is a category variable.
A small introduction about Iris flower data set. This is a multivariate data set and it was introduced by the British statistician and biologist Ronald Fisher in 1936 for his research paper. Below picture about sepal and petal.
It would be interesting to get to know the data set before analyzing it.
/* Dropping the variable target and stored the dataset in the name of IRIS1 */data iris1; set work.iris; drop target;run;
Prior to running cluster analysis, we need to standardize all the analysis variables (real numeric variables) to a mean of zero and standard deviation of one (converted to z-scores). Here, our datasets are already standardized one.
/* Perfoming Cluster Analysis */ods graphics on;proc cluster data = iris1 method = centroid ccc print=15 outtree=Tree;var sepal_length--petal_width;run;ods graphics off;
The METHOD => specification determines the clustering method used by the procedure. Here, we are using the CENTROID method. CCC β Cubic Clustering Criterion β It helps to find out the optimum cluster point.
Need to find out the optimum clusters.
The first three eigenvalues account for about 99.48% of the total variance, hence, it suggests to go with three clusters. However, it can be cross-checked in the ccc plot.
If we see from the cluster history, there are 15 observations (as we have given in our code print = 15)
From the above CCC plot, it can be seen that elbow has dropped at three. Hence, the optimum cluster would be 3. βOptimum cluster can be found in Elbow method in Pythonβ
In order to categorize each observation out of 150 observations into three clusters, we can use proc tree. ncl = 3 (our optimum cluster is 3).
/* Retaining 3 clusters */proc tree noprint ncl=3 out=out;copy sepal_length--petal_width;run;
150 observations divided into three clusters.
Creating scatterplot by using proc candisc and proc sgplot
/* To create a Scatterplot */proc candisc out = can;class cluster;var petal_width: sepal_length:;run;proc sgplot data = can;title "Cluster Analysis for IRIS datasets";scatter y = can2 x = can1 / group = cluster;run;
We can see that our analysis clearly separates three clusters. Cluster 1 is blue, Cluster 2 is red and Cluster 3 is green.
Advantage and Disadvantage of K-means Clustering
Advantage:
1) Practically work well even some assumptions are broken.
2) Simple, easy to implement.
3) Easy to interpret the clustering results.
4) Fast and efficient in terms of computational cost.
Disadvantage:
1) Uniform effect often produces clusters with relatively uniform size even if the input data have different cluster size.
2) Different densities may work poorly with clusters.
3) Sensitive to outliers.
4) K value needs to be known before K-means clustering.
Entire SAS code available in my GIT https://github.com/sdhilip200/IRIS-datasets
If you find any mistakes or improvement required, please feel free to comment.
|
[
{
"code": null,
"e": 66,
"s": 46,
"text": "What is Clustering?"
},
{
"code": null,
"e": 266,
"s": 66,
"text": "βClustering is the process of dividing the datasets into groups, consisting of similar data-pointsβ. Clustering is a type of unsupervised machine learning, which is used when you have unlabeled data."
},
{
"code": null,
"e": 305,
"s": 266,
"text": "Letβs understand in the real scenario,"
},
{
"code": null,
"e": 516,
"s": 305,
"text": "Group of diners sitting in a restaurant. Letβs say two tables in the restaurant called T1 and T2. People in Table T1 might be related to each other, or maybe a group of family members or colleagues or anything."
},
{
"code": null,
"e": 773,
"s": 516,
"text": "In a similar way, people in table T2 might be related to each other or maybe a group of colleagues or anything. But, when comparing people sitting in table T1 and people sitting in table T2, they are entirely different and not at all related to each other."
},
{
"code": null,
"e": 980,
"s": 773,
"text": "Clustering also works in the same way. Data points in one cluster are entirely different from data points in another cluster. All the points in the same cluster are either the same or related to each other."
},
{
"code": null,
"e": 1038,
"s": 980,
"text": "Another good example is the Netflix movie recommendation."
},
{
"code": null,
"e": 1237,
"s": 1038,
"text": "Netflix recommends movies based on the history of the userβs watch. Whatever people watched; similar films related to it will be shown. Clustering algorithm generates all of these recommended lists."
},
{
"code": null,
"e": 1418,
"s": 1237,
"text": "Clustering can be used for segmentation and many other applications. It has different techniques. One of the most popular, simple and interesting algorithms is K -Means Clustering."
},
{
"code": null,
"e": 1578,
"s": 1418,
"text": "K-Means is a clustering algorithm whose main goal is to group similar elements or data points into a cluster. βKβ in K-means represents the number of clusters."
},
{
"code": null,
"e": 1604,
"s": 1578,
"text": "K-means clustering steps:"
},
{
"code": null,
"e": 1785,
"s": 1604,
"text": "Distance measure will determine the similarity between two elements and it will influence the shape of the clusters. Normally, Euclidean distance will be used in K-Means Clustering"
},
{
"code": null,
"e": 1899,
"s": 1785,
"text": "The Euclidean distance is the βordinaryβ straight line. It is the distance between two points in Euclidean space."
},
{
"code": null,
"e": 1932,
"s": 1899,
"text": "How does K-Means Algorithm work?"
},
{
"code": null,
"e": 2322,
"s": 1932,
"text": "Letβs take two data points. Assume K =2. Then, it will take two random centroids anywhere in the data and based on that it will draw a line in the middle. One centroid represents in red and another one in yellow. Then all the data points towards the yellow centroid classified into yellow. All the data points towards the red centroid classified as a red. This is the first iteration step."
},
{
"code": null,
"e": 2529,
"s": 2322,
"text": "Next step, it calculates the distance from the centroid to data points by using the Euclidean method. And both red and yellow centroid points moves into new points by calculating the mean of all the points."
},
{
"code": null,
"e": 2740,
"s": 2529,
"text": "Again, it draws a new line between new centroid points. Automatically, all the points falling towards the red centroid will be recognized as a red group and yellow centroid will be recognized as a yellow group."
},
{
"code": null,
"e": 2902,
"s": 2740,
"text": "Again the same step will be repeated with new points and it will calculate new centroids. We can clearly see that data points has been moved to different groups."
},
{
"code": null,
"e": 3163,
"s": 2902,
"text": "It keeps on going until centroid movements become almost negligible. Then, it becomes cluster 1 and cluster 2. Here, the output Y label will give 0βs and 1βs. 0βs represent cluster 1 and 1 represent cluster 2. If it is three clusters, then it gives 0, 1 and 2."
},
{
"code": null,
"e": 3239,
"s": 3163,
"text": "Letβs take a famous IRIS datasets. Checking the dataset by using proc means"
},
{
"code": null,
"e": 3341,
"s": 3239,
"text": "/* Checking the contents of the datasets */proc means data=work.iris N Nmiss mean median max min;run;"
},
{
"code": null,
"e": 3603,
"s": 3341,
"text": "It has 150 observations and 5 variables. No missing values or outliers detected. We will use only four variables namely sepal_length, sepal_width, petal_length and petal_width. The datasets in βcmβ. βTargetβ variable can be dropped as it is a category variable."
},
{
"code": null,
"e": 3831,
"s": 3603,
"text": "A small introduction about Iris flower data set. This is a multivariate data set and it was introduced by the British statistician and biologist Ronald Fisher in 1936 for his research paper. Below picture about sepal and petal."
},
{
"code": null,
"e": 3904,
"s": 3831,
"text": "It would be interesting to get to know the data set before analyzing it."
},
{
"code": null,
"e": 4032,
"s": 3904,
"text": "/* Dropping the variable target and stored the dataset in the name of IRIS1 */data iris1; set work.iris; drop target;run;"
},
{
"code": null,
"e": 4264,
"s": 4032,
"text": "Prior to running cluster analysis, we need to standardize all the analysis variables (real numeric variables) to a mean of zero and standard deviation of one (converted to z-scores). Here, our datasets are already standardized one."
},
{
"code": null,
"e": 4434,
"s": 4264,
"text": "/* Perfoming Cluster Analysis */ods graphics on;proc cluster data = iris1 method = centroid ccc print=15 outtree=Tree;var sepal_length--petal_width;run;ods graphics off;"
},
{
"code": null,
"e": 4642,
"s": 4434,
"text": "The METHOD => specification determines the clustering method used by the procedure. Here, we are using the CENTROID method. CCC β Cubic Clustering Criterion β It helps to find out the optimum cluster point."
},
{
"code": null,
"e": 4681,
"s": 4642,
"text": "Need to find out the optimum clusters."
},
{
"code": null,
"e": 4853,
"s": 4681,
"text": "The first three eigenvalues account for about 99.48% of the total variance, hence, it suggests to go with three clusters. However, it can be cross-checked in the ccc plot."
},
{
"code": null,
"e": 4957,
"s": 4853,
"text": "If we see from the cluster history, there are 15 observations (as we have given in our code print = 15)"
},
{
"code": null,
"e": 5126,
"s": 4957,
"text": "From the above CCC plot, it can be seen that elbow has dropped at three. Hence, the optimum cluster would be 3. βOptimum cluster can be found in Elbow method in Pythonβ"
},
{
"code": null,
"e": 5269,
"s": 5126,
"text": "In order to categorize each observation out of 150 observations into three clusters, we can use proc tree. ncl = 3 (our optimum cluster is 3)."
},
{
"code": null,
"e": 5363,
"s": 5269,
"text": "/* Retaining 3 clusters */proc tree noprint ncl=3 out=out;copy sepal_length--petal_width;run;"
},
{
"code": null,
"e": 5409,
"s": 5363,
"text": "150 observations divided into three clusters."
},
{
"code": null,
"e": 5468,
"s": 5409,
"text": "Creating scatterplot by using proc candisc and proc sgplot"
},
{
"code": null,
"e": 5684,
"s": 5468,
"text": "/* To create a Scatterplot */proc candisc out = can;class cluster;var petal_width: sepal_length:;run;proc sgplot data = can;title \"Cluster Analysis for IRIS datasets\";scatter y = can2 x = can1 / group = cluster;run;"
},
{
"code": null,
"e": 5807,
"s": 5684,
"text": "We can see that our analysis clearly separates three clusters. Cluster 1 is blue, Cluster 2 is red and Cluster 3 is green."
},
{
"code": null,
"e": 5856,
"s": 5807,
"text": "Advantage and Disadvantage of K-means Clustering"
},
{
"code": null,
"e": 5867,
"s": 5856,
"text": "Advantage:"
},
{
"code": null,
"e": 5926,
"s": 5867,
"text": "1) Practically work well even some assumptions are broken."
},
{
"code": null,
"e": 5956,
"s": 5926,
"text": "2) Simple, easy to implement."
},
{
"code": null,
"e": 6001,
"s": 5956,
"text": "3) Easy to interpret the clustering results."
},
{
"code": null,
"e": 6055,
"s": 6001,
"text": "4) Fast and efficient in terms of computational cost."
},
{
"code": null,
"e": 6069,
"s": 6055,
"text": "Disadvantage:"
},
{
"code": null,
"e": 6192,
"s": 6069,
"text": "1) Uniform effect often produces clusters with relatively uniform size even if the input data have different cluster size."
},
{
"code": null,
"e": 6246,
"s": 6192,
"text": "2) Different densities may work poorly with clusters."
},
{
"code": null,
"e": 6272,
"s": 6246,
"text": "3) Sensitive to outliers."
},
{
"code": null,
"e": 6328,
"s": 6272,
"text": "4) K value needs to be known before K-means clustering."
},
{
"code": null,
"e": 6408,
"s": 6328,
"text": "Entire SAS code available in my GIT https://github.com/sdhilip200/IRIS-datasets"
}
] |
Find minimum possible size of array with given rules for removing elements - GeeksforGeeks
|
16 Sep, 2021
Given an array of numbers and a constant k, minimize size of array with following rules for removing elements.
Exactly three elements can be removed at one go.
The removed three elements must be adjacent in array, i.e., arr[i], arr[i+1], arr[i+2]. And the second element must be k greater than first and third element must be k greater than second, i.e., arr[i+1] β arr[i] = k and arr[i+2]-arr[i+1] = k.
Example:
Input: arr[] = {2, 3, 4, 5, 6, 4}, k = 1
Output: 0
We can actually remove all elements.
First remove 4, 5, 6 => We get {2, 3, 4}
Now remove 2, 3, 4 => We get empty array {}
Input: arr[] = {2, 3, 4, 7, 6, 4}, k = 1
Output: 3
We can only remove 2 3 4
Source: https://code.google.com/codejam/contest/4214486/dashboard#s=p2We strongly recommend you to minimize your browser and try this yourself first. For every element arr[i] there are two possibilities. 1) Either the element is not removed. 2) OR element is removed (if it follows rules of removal). When an element is removed, there are again two possibilities. .....a) It may be removed directly, i.e., initial arr[i+1] is arr[i]+k and arr[i+2] is arr[i] + 2*k. .....b) There exist x and y such that arr[x] β arr[i] = k, arr[y] β arr[x] = k, and subarrays βarr[i+1...x-1]β & βarr[x+1...y-1]β can be completely removed.
Below is recursive algorithm based on above idea.
// Returns size of minimum possible size of arr[low..high]
// after removing elements according to given rules
findMinSize(arr[], low, high, k)
// If there are less than 3 elements in arr[low..high]
1) If high-low+1 < 3, return high-low+1
// Consider the case when 'arr[low]' is not considered as
// part of any triplet to be removed. Initialize result
// using this case
2) result = 1 + findMinSize(arr, low+1, high)
// Case when 'arr[low]' is part of some triplet and removed
// Try all possible triplets that have arr[low]
3) For all i from low+1 to high
For all j from i+1 to high
Update result if all of the following conditions are met
a) arr[i] - arr[low] = k
b) arr[j] - arr[i] = k
c) findMinSize(arr, low+1, i-1, k) returns 0
d) findMinSize(arr, i+1, j-1, k) also returns 0
e) Result calculated for this triplet (low, i, j)
is smaller than existing result.
4) Return result
The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array dp[][] to store results of the subproblems. Below is Dynamic Programming based solution
Below is the implementation of above idea. The implementation is memoization based, i.e., it is recursive and uses a lookup table dp[][] to check if a subproblem is already solved or not.
C++
Java
Python3
C#
Javascript
// C++ program to find size of minimum possible array after// removing elements according to given rules#include <bits/stdc++.h>using namespace std;#define MAX 1000 // dp[i][j] denotes the minimum number of elements left in// the subarray arr[i..j].int dp[MAX][MAX]; int minSizeRec(int arr[], int low, int high, int k){ // If already evaluated if (dp[low][high] != -1) return dp[low][high]; // If size of array is less than 3 if ( (high-low + 1) < 3) return high-low +1; // Initialize result as the case when first element is // separated (not removed using given rules) int res = 1 + minSizeRec(arr, low+1, high, k); // Now consider all cases when first element forms a triplet // and removed. Check for all possible triplets (low, i, j) for (int i = low+1; i<=high-1; i++) { for (int j = i+1; j <= high; j++ ) { // Check if this triplet follows the given rules of // removal. And elements between 'low' and 'i' , and // between 'i' and 'j' can be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2*k) && minSizeRec(arr, low+1, i-1, k) == 0 && minSizeRec(arr, i+1, j-1, k) == 0) { res = min(res, minSizeRec(arr, j+1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res);} // This function mainly initializes dp table and calls// recursive function minSizeRecint minSize(int arr[], int n, int k){ memset(dp, -1, sizeof(dp)); return minSizeRec(arr, 0, n-1, k);} // Driver program to test above functionint main(){ int arr[] = {2, 3, 4, 5, 6, 4}; int n = sizeof(arr)/sizeof(arr[0]); int k = 1; cout << minSize(arr, n, k) << endl; return 0;}
// Java program to find size of// minimum possible array after// removing elements according// to given rulesclass GFG{ static int MAX = 1000; // dp[i][j] denotes the minimum // number of elements left in // the subarray arr[i..j]. static int dp[][] = new int[MAX][MAX]; static int minSizeRec(int arr[], int low, int high, int k) { // If already evaluated if (dp[low][high] != -1) { return dp[low][high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) int res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (int i = low + 1; i <= high - 1; i++) { for (int j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec static int minSize(int arr[], int n, int k) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i][j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } // Driver code public static void main(String[] args) { int arr[] = {2, 3, 4, 5, 6, 4}; int n = arr.length; int k = 1; System.out.println(minSize(arr, n, k)); }} // This code is contributed by 29AjayKumar
# Python3 program to find size of# minimum possible array after# removing elements according to given rulesMAX=1000 dp=[[-1 for i in range(MAX)] for i in range(MAX)]# dp[i][j] denotes the minimum number of elements left in# the subarray arr[i..j]. def minSizeRec(arr,low,high,k): # If already evaluated if dp[low][high] != -1: return dp[low][high] # If size of array is less than 3 if (high-low + 1) < 3: return (high-low + 1) # Initialize result as the case when first element is # separated (not removed using given rules) res = 1 + minSizeRec(arr, low+1, high, k) # Now consider all cases when # first element forms a triplet # and removed. Check for all possible # triplets (low, i, j) for i in range(low+1,high): for j in range(i+1,high+1): # Check if this triplet follows the given rules of # removal. And elements between 'low' and 'i' , and # between 'i' and 'j' can be recursively removed. if (arr[i]==(arr[low]+k) and arr[j] == (arr[low] + 2*k) and minSizeRec(arr, low+1, i-1, k) == 0 and minSizeRec(arr, i+1, j-1, k) == 0): res=min(res,minSizeRec(arr,j+1,high,k) ) # Insert value in table and return result dp[low][high] = res return res # This function mainly initializes dp table and calls# recursive function minSizeRecdef minSize(arr,n,k): dp=[[-1 for i in range(MAX)] for i in range(MAX)] return minSizeRec(arr, 0, n-1, k) # Driver program to test above functionif __name__=='__main__': arr=[2, 3, 4, 5, 6, 4] n=len(arr) k=1 print(minSize(arr,n,k)) # this code is contributed by sahilshelangia
// C# program to find size of// minimum possible array after// removing elements according// to given rulesusing System; class GFG{ static int MAX = 1000; // dp[i,j] denotes the minimum // number of elements left in // the subarray arr[i..j]. static int [,]dp = new int[MAX, MAX]; static int minSizeRec(int []arr, int low, int high, int k) { // If already evaluated if (dp[low, high] != -1) { return dp[low, high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) int res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (int i = low + 1; i <= high - 1; i++) { for (int j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.Min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low, high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec static int minSize(int []arr, int n, int k) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i, j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } // Driver code public static void Main(String[] args) { int []arr = {2, 3, 4, 5, 6, 4}; int n = arr.Length; int k = 1; Console.WriteLine(minSize(arr, n, k)); }} // This code contributed by Rajput-Ji
<script> // Javascript program to find size of // minimum possible array after // removing elements according // to given rules let MAX = 1000; // dp[i][j] denotes the minimum // number of elements left in // the subarray arr[i..j]. let dp = new Array(MAX); for(let i = 0; i < MAX; i++) { dp[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { dp[i][j] = 0; } } function minSizeRec(arr, low, high, k) { // If already evaluated if (dp[low][high] != -1) { return dp[low][high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) let res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (let i = low + 1; i <= high - 1; i++) { for (let j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec function minSize(arr, n, k) { for (let i = 0; i < MAX; i++) { for (let j = 0; j < MAX; j++) { dp[i][j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } let arr = [2, 3, 4, 5, 6, 4]; let n = arr.length; let k = 1; document.write(minSize(arr, n, k)); // This code is contributed by mukesh07.</script>
Output:
0
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sahilshelangia
29AjayKumar
Rajput-Ji
mukesh07
sweetyty
sagartomar9927
surinderdawra388
simmytarika5
Google code jam
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Strategy for a Game | DP-31
Maximum sum such that no two elements are adjacent
Maximum Subarray Sum using Divide and Conquer algorithm
Min Cost Path | DP-6
Weighted Job Scheduling
Optimal Binary Search Tree | DP-24
Binomial Coefficient | DP-9
3 Different ways to print Fibonacci series in Java
Greedy approach vs Dynamic programming
|
[
{
"code": null,
"e": 24696,
"s": 24668,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 24808,
"s": 24696,
"text": "Given an array of numbers and a constant k, minimize size of array with following rules for removing elements. "
},
{
"code": null,
"e": 24857,
"s": 24808,
"text": "Exactly three elements can be removed at one go."
},
{
"code": null,
"e": 25101,
"s": 24857,
"text": "The removed three elements must be adjacent in array, i.e., arr[i], arr[i+1], arr[i+2]. And the second element must be k greater than first and third element must be k greater than second, i.e., arr[i+1] β arr[i] = k and arr[i+2]-arr[i+1] = k."
},
{
"code": null,
"e": 25111,
"s": 25101,
"text": "Example: "
},
{
"code": null,
"e": 25365,
"s": 25111,
"text": "Input: arr[] = {2, 3, 4, 5, 6, 4}, k = 1\nOutput: 0\nWe can actually remove all elements. \nFirst remove 4, 5, 6 => We get {2, 3, 4}\nNow remove 2, 3, 4 => We get empty array {}\n\nInput: arr[] = {2, 3, 4, 7, 6, 4}, k = 1\nOutput: 3\nWe can only remove 2 3 4"
},
{
"code": null,
"e": 25987,
"s": 25365,
"text": "Source: https://code.google.com/codejam/contest/4214486/dashboard#s=p2We strongly recommend you to minimize your browser and try this yourself first. For every element arr[i] there are two possibilities. 1) Either the element is not removed. 2) OR element is removed (if it follows rules of removal). When an element is removed, there are again two possibilities. .....a) It may be removed directly, i.e., initial arr[i+1] is arr[i]+k and arr[i+2] is arr[i] + 2*k. .....b) There exist x and y such that arr[x] β arr[i] = k, arr[y] β arr[x] = k, and subarrays βarr[i+1...x-1]β & βarr[x+1...y-1]β can be completely removed."
},
{
"code": null,
"e": 26039,
"s": 25987,
"text": "Below is recursive algorithm based on above idea. "
},
{
"code": null,
"e": 26980,
"s": 26039,
"text": "// Returns size of minimum possible size of arr[low..high]\n// after removing elements according to given rules\nfindMinSize(arr[], low, high, k)\n\n// If there are less than 3 elements in arr[low..high]\n1) If high-low+1 < 3, return high-low+1\n\n// Consider the case when 'arr[low]' is not considered as\n// part of any triplet to be removed. Initialize result \n// using this case\n2) result = 1 + findMinSize(arr, low+1, high)\n\n// Case when 'arr[low]' is part of some triplet and removed\n// Try all possible triplets that have arr[low]\n3) For all i from low+1 to high\n For all j from i+1 to high\n Update result if all of the following conditions are met\n a) arr[i] - arr[low] = k \n b) arr[j] - arr[i] = k\n c) findMinSize(arr, low+1, i-1, k) returns 0\n d) findMinSize(arr, i+1, j-1, k) also returns 0\n e) Result calculated for this triplet (low, i, j)\n is smaller than existing result.\n\n4) Return result"
},
{
"code": null,
"e": 27457,
"s": 26980,
"text": "The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array dp[][] to store results of the subproblems. Below is Dynamic Programming based solution"
},
{
"code": null,
"e": 27646,
"s": 27457,
"text": "Below is the implementation of above idea. The implementation is memoization based, i.e., it is recursive and uses a lookup table dp[][] to check if a subproblem is already solved or not. "
},
{
"code": null,
"e": 27650,
"s": 27646,
"text": "C++"
},
{
"code": null,
"e": 27655,
"s": 27650,
"text": "Java"
},
{
"code": null,
"e": 27663,
"s": 27655,
"text": "Python3"
},
{
"code": null,
"e": 27666,
"s": 27663,
"text": "C#"
},
{
"code": null,
"e": 27677,
"s": 27666,
"text": "Javascript"
},
{
"code": "// C++ program to find size of minimum possible array after// removing elements according to given rules#include <bits/stdc++.h>using namespace std;#define MAX 1000 // dp[i][j] denotes the minimum number of elements left in// the subarray arr[i..j].int dp[MAX][MAX]; int minSizeRec(int arr[], int low, int high, int k){ // If already evaluated if (dp[low][high] != -1) return dp[low][high]; // If size of array is less than 3 if ( (high-low + 1) < 3) return high-low +1; // Initialize result as the case when first element is // separated (not removed using given rules) int res = 1 + minSizeRec(arr, low+1, high, k); // Now consider all cases when first element forms a triplet // and removed. Check for all possible triplets (low, i, j) for (int i = low+1; i<=high-1; i++) { for (int j = i+1; j <= high; j++ ) { // Check if this triplet follows the given rules of // removal. And elements between 'low' and 'i' , and // between 'i' and 'j' can be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2*k) && minSizeRec(arr, low+1, i-1, k) == 0 && minSizeRec(arr, i+1, j-1, k) == 0) { res = min(res, minSizeRec(arr, j+1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res);} // This function mainly initializes dp table and calls// recursive function minSizeRecint minSize(int arr[], int n, int k){ memset(dp, -1, sizeof(dp)); return minSizeRec(arr, 0, n-1, k);} // Driver program to test above functionint main(){ int arr[] = {2, 3, 4, 5, 6, 4}; int n = sizeof(arr)/sizeof(arr[0]); int k = 1; cout << minSize(arr, n, k) << endl; return 0;}",
"e": 29508,
"s": 27677,
"text": null
},
{
"code": "// Java program to find size of// minimum possible array after// removing elements according// to given rulesclass GFG{ static int MAX = 1000; // dp[i][j] denotes the minimum // number of elements left in // the subarray arr[i..j]. static int dp[][] = new int[MAX][MAX]; static int minSizeRec(int arr[], int low, int high, int k) { // If already evaluated if (dp[low][high] != -1) { return dp[low][high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) int res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (int i = low + 1; i <= high - 1; i++) { for (int j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec static int minSize(int arr[], int n, int k) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i][j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } // Driver code public static void main(String[] args) { int arr[] = {2, 3, 4, 5, 6, 4}; int n = arr.length; int k = 1; System.out.println(minSize(arr, n, k)); }} // This code is contributed by 29AjayKumar",
"e": 31916,
"s": 29508,
"text": null
},
{
"code": "# Python3 program to find size of# minimum possible array after# removing elements according to given rulesMAX=1000 dp=[[-1 for i in range(MAX)] for i in range(MAX)]# dp[i][j] denotes the minimum number of elements left in# the subarray arr[i..j]. def minSizeRec(arr,low,high,k): # If already evaluated if dp[low][high] != -1: return dp[low][high] # If size of array is less than 3 if (high-low + 1) < 3: return (high-low + 1) # Initialize result as the case when first element is # separated (not removed using given rules) res = 1 + minSizeRec(arr, low+1, high, k) # Now consider all cases when # first element forms a triplet # and removed. Check for all possible # triplets (low, i, j) for i in range(low+1,high): for j in range(i+1,high+1): # Check if this triplet follows the given rules of # removal. And elements between 'low' and 'i' , and # between 'i' and 'j' can be recursively removed. if (arr[i]==(arr[low]+k) and arr[j] == (arr[low] + 2*k) and minSizeRec(arr, low+1, i-1, k) == 0 and minSizeRec(arr, i+1, j-1, k) == 0): res=min(res,minSizeRec(arr,j+1,high,k) ) # Insert value in table and return result dp[low][high] = res return res # This function mainly initializes dp table and calls# recursive function minSizeRecdef minSize(arr,n,k): dp=[[-1 for i in range(MAX)] for i in range(MAX)] return minSizeRec(arr, 0, n-1, k) # Driver program to test above functionif __name__=='__main__': arr=[2, 3, 4, 5, 6, 4] n=len(arr) k=1 print(minSize(arr,n,k)) # this code is contributed by sahilshelangia ",
"e": 33671,
"s": 31916,
"text": null
},
{
"code": "// C# program to find size of// minimum possible array after// removing elements according// to given rulesusing System; class GFG{ static int MAX = 1000; // dp[i,j] denotes the minimum // number of elements left in // the subarray arr[i..j]. static int [,]dp = new int[MAX, MAX]; static int minSizeRec(int []arr, int low, int high, int k) { // If already evaluated if (dp[low, high] != -1) { return dp[low, high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) int res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (int i = low + 1; i <= high - 1; i++) { for (int j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.Min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low, high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec static int minSize(int []arr, int n, int k) { for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { dp[i, j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } // Driver code public static void Main(String[] args) { int []arr = {2, 3, 4, 5, 6, 4}; int n = arr.Length; int k = 1; Console.WriteLine(minSize(arr, n, k)); }} // This code contributed by Rajput-Ji",
"e": 36083,
"s": 33671,
"text": null
},
{
"code": "<script> // Javascript program to find size of // minimum possible array after // removing elements according // to given rules let MAX = 1000; // dp[i][j] denotes the minimum // number of elements left in // the subarray arr[i..j]. let dp = new Array(MAX); for(let i = 0; i < MAX; i++) { dp[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { dp[i][j] = 0; } } function minSizeRec(arr, low, high, k) { // If already evaluated if (dp[low][high] != -1) { return dp[low][high]; } // If size of array is less than 3 if ((high - low + 1) < 3) { return high - low + 1; } // Initialize result as the // case when first element is // separated (not removed // using given rules) let res = 1 + minSizeRec(arr, low + 1, high, k); // Now consider all cases when // first element forms a triplet // and removed. Check for all // possible triplets (low, i, j) for (let i = low + 1; i <= high - 1; i++) { for (let j = i + 1; j <= high; j++) { // Check if this triplet // follows the given rules of // removal. And elements // between 'low' and 'i' , and // between 'i' and 'j' can // be recursively removed. if (arr[i] == (arr[low] + k) && arr[j] == (arr[low] + 2 * k) && minSizeRec(arr, low + 1, i - 1, k) == 0 && minSizeRec(arr, i + 1, j - 1, k) == 0) { res = Math.min(res, minSizeRec(arr, j + 1, high, k)); } } } // Insert value in table and return result return (dp[low][high] = res); } // This function mainly initializes // dp table and calls recursive // function minSizeRec function minSize(arr, n, k) { for (let i = 0; i < MAX; i++) { for (let j = 0; j < MAX; j++) { dp[i][j] = -1; } } return minSizeRec(arr, 0, n - 1, k); } let arr = [2, 3, 4, 5, 6, 4]; let n = arr.length; let k = 1; document.write(minSize(arr, n, k)); // This code is contributed by mukesh07.</script>",
"e": 38505,
"s": 36083,
"text": null
},
{
"code": null,
"e": 38513,
"s": 38505,
"text": "Output:"
},
{
"code": null,
"e": 38515,
"s": 38513,
"text": "0"
},
{
"code": null,
"e": 38682,
"s": 38515,
"text": "This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 38697,
"s": 38682,
"text": "sahilshelangia"
},
{
"code": null,
"e": 38709,
"s": 38697,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38719,
"s": 38709,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38728,
"s": 38719,
"text": "mukesh07"
},
{
"code": null,
"e": 38737,
"s": 38728,
"text": "sweetyty"
},
{
"code": null,
"e": 38752,
"s": 38737,
"text": "sagartomar9927"
},
{
"code": null,
"e": 38769,
"s": 38752,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38782,
"s": 38769,
"text": "simmytarika5"
},
{
"code": null,
"e": 38798,
"s": 38782,
"text": "Google code jam"
},
{
"code": null,
"e": 38818,
"s": 38798,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38838,
"s": 38818,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38936,
"s": 38838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38945,
"s": 38936,
"text": "Comments"
},
{
"code": null,
"e": 38958,
"s": 38945,
"text": "Old Comments"
},
{
"code": null,
"e": 39018,
"s": 38958,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 39054,
"s": 39018,
"text": "Optimal Strategy for a Game | DP-31"
},
{
"code": null,
"e": 39105,
"s": 39054,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 39161,
"s": 39105,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 39182,
"s": 39161,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 39206,
"s": 39182,
"text": "Weighted Job Scheduling"
},
{
"code": null,
"e": 39241,
"s": 39206,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 39269,
"s": 39241,
"text": "Binomial Coefficient | DP-9"
},
{
"code": null,
"e": 39320,
"s": 39269,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
Angular ng Bootstrap Popover Component - GeeksforGeeks
|
06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.
In this article we will know how to use Popover in angular ng bootstrap. Popover is used to make a button that will be pop out by clicking on it.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html make a popover component.
Serve the app using ng serve.
Example 1: In this example, we are making a popover with its placement to top.
app.component.html
<button id='gfg' type="button" class="btn btn-success" placement="top" ngbPopover="Angular ng bootstrap" popoverTitle="GeeksforGeeks"> Click here</button>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.css
#gfg{ margin-left: 100px; margin-top: 150px}
Output:
Example 2: In this example, we are making a popover with its placement to bottom, right, left.
app.component.html
<button id='gfg' type="button" class="btn btn-primary" placement="bottom" ngbPopover="Angular ng bootstrap" popoverTitle="GeeksforGeeks"> Click here</button> <button id='gfg' type="button" class="btn btn-warning" placement="right" ngbPopover="Angular ng bootstrap" popoverTitle="GeeksforGeeks"> Click here</button> <button id='gfg' type="button" class="btn btn-danger" placement="left" ngbPopover="Angular ng bootstrap" popoverTitle="GeeksforGeeks"> Click here</button>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.css
#gfg{ margin-left: 100px; margin-top: 150px}
Output:
Reference: https://ng-bootstrap.github.io/#/components/popover/examples
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 26538,
"s": 26354,
"text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites."
},
{
"code": null,
"e": 26684,
"s": 26538,
"text": "In this article we will know how to use Popover in angular ng bootstrap. Popover is used to make a button that will be pop out by clicking on it."
},
{
"code": null,
"e": 26705,
"s": 26684,
"text": "Installation syntax:"
},
{
"code": null,
"e": 26739,
"s": 26705,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 26749,
"s": 26739,
"text": "Approach:"
},
{
"code": null,
"e": 26824,
"s": 26749,
"text": "First, install the angular ng bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 26946,
"s": 26824,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 27029,
"s": 26946,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n"
},
{
"code": null,
"e": 27077,
"s": 27029,
"text": "In app.component.html make a popover component."
},
{
"code": null,
"e": 27107,
"s": 27077,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 27188,
"s": 27109,
"text": "Example 1: In this example, we are making a popover with its placement to top."
},
{
"code": null,
"e": 27207,
"s": 27188,
"text": "app.component.html"
},
{
"code": "<button id='gfg' type=\"button\" class=\"btn btn-success\" placement=\"top\" ngbPopover=\"Angular ng bootstrap\" popoverTitle=\"GeeksforGeeks\"> Click here</button>",
"e": 27379,
"s": 27207,
"text": null
},
{
"code": null,
"e": 27393,
"s": 27379,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 27996,
"s": 27393,
"text": null
},
{
"code": null,
"e": 28014,
"s": 27996,
"text": "app.component.css"
},
{
"code": "#gfg{ margin-left: 100px; margin-top: 150px}",
"e": 28065,
"s": 28014,
"text": null
},
{
"code": null,
"e": 28073,
"s": 28065,
"text": "Output:"
},
{
"code": null,
"e": 28168,
"s": 28073,
"text": "Example 2: In this example, we are making a popover with its placement to bottom, right, left."
},
{
"code": null,
"e": 28187,
"s": 28168,
"text": "app.component.html"
},
{
"code": "<button id='gfg' type=\"button\" class=\"btn btn-primary\" placement=\"bottom\" ngbPopover=\"Angular ng bootstrap\" popoverTitle=\"GeeksforGeeks\"> Click here</button> <button id='gfg' type=\"button\" class=\"btn btn-warning\" placement=\"right\" ngbPopover=\"Angular ng bootstrap\" popoverTitle=\"GeeksforGeeks\"> Click here</button> <button id='gfg' type=\"button\" class=\"btn btn-danger\" placement=\"left\" ngbPopover=\"Angular ng bootstrap\" popoverTitle=\"GeeksforGeeks\"> Click here</button>",
"e": 28757,
"s": 28187,
"text": null
},
{
"code": null,
"e": 28771,
"s": 28757,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 29376,
"s": 28771,
"text": null
},
{
"code": null,
"e": 29394,
"s": 29376,
"text": "app.component.css"
},
{
"code": "#gfg{ margin-left: 100px; margin-top: 150px}",
"e": 29445,
"s": 29394,
"text": null
},
{
"code": null,
"e": 29453,
"s": 29445,
"text": "Output:"
},
{
"code": null,
"e": 29525,
"s": 29453,
"text": "Reference: https://ng-bootstrap.github.io/#/components/popover/examples"
},
{
"code": null,
"e": 29546,
"s": 29525,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 29556,
"s": 29546,
"text": "AngularJS"
},
{
"code": null,
"e": 29573,
"s": 29556,
"text": "Web Technologies"
},
{
"code": null,
"e": 29671,
"s": 29573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29706,
"s": 29671,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29741,
"s": 29706,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29765,
"s": 29741,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29800,
"s": 29765,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29853,
"s": 29800,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29893,
"s": 29853,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29926,
"s": 29893,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29971,
"s": 29926,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30014,
"s": 29971,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Merge k Sorted Lists in Python
|
Suppose we have some lists, these are sorted. We have to merge these lists into one list. To solve this, we will use the heap data structure. So if the lists are [1,4,5], [1,3,4], [2,6], then the final list will be [1,1,2,3,4,4,5,6].
To solve this, we will follow these steps β
make one heap
make one heap
for each linked list l in lists βif is in not 0, then insert I into a heap
for each linked list l in lists β
if is in not 0, then insert I into a heap
if is in not 0, then insert I into a heap
res := null and res_next := null
res := null and res_next := null
Do one infinite loop βtemp := min of heapif heap has no element, then return resif res is 0, thenres := temp, res_next := temptemp := next element of tempif temp is not zero, then insert temp into heapnext of res := nullotherwise βnext of res_next := temp, temp := next of temp, res_next := next of res_nextif temp is not null, then insert temp into heapnext of res_next := null
Do one infinite loop β
temp := min of heap
temp := min of heap
if heap has no element, then return res
if heap has no element, then return res
if res is 0, thenres := temp, res_next := temptemp := next element of tempif temp is not zero, then insert temp into heapnext of res := null
if res is 0, then
res := temp, res_next := temp
res := temp, res_next := temp
temp := next element of temp
temp := next element of temp
if temp is not zero, then insert temp into heap
if temp is not zero, then insert temp into heap
next of res := null
next of res := null
otherwise βnext of res_next := temp, temp := next of temp, res_next := next of res_nextif temp is not null, then insert temp into heapnext of res_next := null
otherwise β
next of res_next := temp, temp := next of temp, res_next := next of res_next
next of res_next := temp, temp := next of temp, res_next := next of res_next
if temp is not null, then insert temp into heap
if temp is not null, then insert temp into heap
next of res_next := null
next of res_next := null
Let us see the following implementation to get a better understanding β
Live Demo
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Heap:
def __init__(self):
self.arr = []
def print_heap(self):
res = " "
for i in self.arr:
res += str(i.val) + " "
print(res)
def getVal(self,i):
return self.arr[i].val
def parent(self,i):
return (i-1)//2
def left(self,i):
return (2*i + 1)
def right(self,i):
return (2*i + 2)
def insert(self,value):
self.arr.append(value)
n = len(self.arr)-1
i = n
while i != 0 and
self.arr[i].val<self.arr[self.parent(i)].val:
self.arr[i],self.arr[self.parent(i)] = self.arr[self.parent(i)],self.arr[i]
i = self.parent(i)
def heapify(self,i):
left = self.left(i)
right = self.right(i)
smallest = i
n= len(self.arr)
if left<n and self.getVal(left)<self.getVal(smallest): smallest = left
if right <n and self.getVal(right)<self.getVal(smallest): smallest = right
if smallest!=i:
self.arr[i],self.arr[smallest] = self.arr[smallest],self.arr[i]
self.heapify(smallest)
def extractMin(self):
n = len(self.arr)
if n==0:
return '#'
if n== 1:
temp =self.arr[0]
self.arr.pop()
return temp
root = self.arr[0]
self.arr[0] = self.arr[-1]
self.arr.pop()
self.heapify(0)
return root
class Solution(object):
def mergeKLists(self, lists):
heap = Heap()
for i in lists:
if i:
heap.insert(i)
res = None
res_next = None
while True:
temp = heap.extractMin()
if temp == "#":
return res
if not res:
res = temp
res_next = temp
temp = temp.next
if temp:
heap.insert(temp)
res.next = None
else:
res_next.next = temp
temp = temp.next
res_next=res_next.next
if temp:
heap.insert(temp)
res_next.next = None
ob = Solution()
lists = [[1,4,5],[1,3,4],[2,6]]
lls = []
for ll in lists:
l = make_list(ll)
lls.append(l)
print_list(ob.mergeKLists(lls))
[[1,4,5],[1,3,4],[2,6]]
[1, 1, 2, 3, 4, 4, 5, 6, ]
|
[
{
"code": null,
"e": 1296,
"s": 1062,
"text": "Suppose we have some lists, these are sorted. We have to merge these lists into one list. To solve this, we will use the heap data structure. So if the lists are [1,4,5], [1,3,4], [2,6], then the final list will be [1,1,2,3,4,4,5,6]."
},
{
"code": null,
"e": 1340,
"s": 1296,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1354,
"s": 1340,
"text": "make one heap"
},
{
"code": null,
"e": 1368,
"s": 1354,
"text": "make one heap"
},
{
"code": null,
"e": 1443,
"s": 1368,
"text": "for each linked list l in lists βif is in not 0, then insert I into a heap"
},
{
"code": null,
"e": 1477,
"s": 1443,
"text": "for each linked list l in lists β"
},
{
"code": null,
"e": 1519,
"s": 1477,
"text": "if is in not 0, then insert I into a heap"
},
{
"code": null,
"e": 1561,
"s": 1519,
"text": "if is in not 0, then insert I into a heap"
},
{
"code": null,
"e": 1594,
"s": 1561,
"text": "res := null and res_next := null"
},
{
"code": null,
"e": 1627,
"s": 1594,
"text": "res := null and res_next := null"
},
{
"code": null,
"e": 2006,
"s": 1627,
"text": "Do one infinite loop βtemp := min of heapif heap has no element, then return resif res is 0, thenres := temp, res_next := temptemp := next element of tempif temp is not zero, then insert temp into heapnext of res := nullotherwise βnext of res_next := temp, temp := next of temp, res_next := next of res_nextif temp is not null, then insert temp into heapnext of res_next := null"
},
{
"code": null,
"e": 2029,
"s": 2006,
"text": "Do one infinite loop β"
},
{
"code": null,
"e": 2049,
"s": 2029,
"text": "temp := min of heap"
},
{
"code": null,
"e": 2069,
"s": 2049,
"text": "temp := min of heap"
},
{
"code": null,
"e": 2109,
"s": 2069,
"text": "if heap has no element, then return res"
},
{
"code": null,
"e": 2149,
"s": 2109,
"text": "if heap has no element, then return res"
},
{
"code": null,
"e": 2290,
"s": 2149,
"text": "if res is 0, thenres := temp, res_next := temptemp := next element of tempif temp is not zero, then insert temp into heapnext of res := null"
},
{
"code": null,
"e": 2308,
"s": 2290,
"text": "if res is 0, then"
},
{
"code": null,
"e": 2338,
"s": 2308,
"text": "res := temp, res_next := temp"
},
{
"code": null,
"e": 2368,
"s": 2338,
"text": "res := temp, res_next := temp"
},
{
"code": null,
"e": 2397,
"s": 2368,
"text": "temp := next element of temp"
},
{
"code": null,
"e": 2426,
"s": 2397,
"text": "temp := next element of temp"
},
{
"code": null,
"e": 2474,
"s": 2426,
"text": "if temp is not zero, then insert temp into heap"
},
{
"code": null,
"e": 2522,
"s": 2474,
"text": "if temp is not zero, then insert temp into heap"
},
{
"code": null,
"e": 2542,
"s": 2522,
"text": "next of res := null"
},
{
"code": null,
"e": 2562,
"s": 2542,
"text": "next of res := null"
},
{
"code": null,
"e": 2721,
"s": 2562,
"text": "otherwise βnext of res_next := temp, temp := next of temp, res_next := next of res_nextif temp is not null, then insert temp into heapnext of res_next := null"
},
{
"code": null,
"e": 2733,
"s": 2721,
"text": "otherwise β"
},
{
"code": null,
"e": 2810,
"s": 2733,
"text": "next of res_next := temp, temp := next of temp, res_next := next of res_next"
},
{
"code": null,
"e": 2887,
"s": 2810,
"text": "next of res_next := temp, temp := next of temp, res_next := next of res_next"
},
{
"code": null,
"e": 2935,
"s": 2887,
"text": "if temp is not null, then insert temp into heap"
},
{
"code": null,
"e": 2983,
"s": 2935,
"text": "if temp is not null, then insert temp into heap"
},
{
"code": null,
"e": 3008,
"s": 2983,
"text": "next of res_next := null"
},
{
"code": null,
"e": 3033,
"s": 3008,
"text": "next of res_next := null"
},
{
"code": null,
"e": 3105,
"s": 3033,
"text": "Let us see the following implementation to get a better understanding β"
},
{
"code": null,
"e": 3116,
"s": 3105,
"text": " Live Demo"
},
{
"code": null,
"e": 5677,
"s": 3116,
"text": "class ListNode:\n def __init__(self, data, next = None):\n self.val = data\n self.next = next\ndef make_list(elements):\n head = ListNode(elements[0])\n for element in elements[1:]:\n ptr = head\n while ptr.next:\n ptr = ptr.next\n ptr.next = ListNode(element)\n return head\ndef print_list(head):\n ptr = head\n print('[', end = \"\")\n while ptr:\n print(ptr.val, end = \", \")\n ptr = ptr.next\n print(']')\nclass Heap:\n def __init__(self):\n self.arr = []\n def print_heap(self):\n res = \" \"\n for i in self.arr:\n res += str(i.val) + \" \"\n print(res)\n def getVal(self,i):\n return self.arr[i].val\n def parent(self,i):\n return (i-1)//2\n def left(self,i):\n return (2*i + 1)\n def right(self,i):\n return (2*i + 2)\n def insert(self,value):\n self.arr.append(value)\n n = len(self.arr)-1\n i = n\n while i != 0 and\nself.arr[i].val<self.arr[self.parent(i)].val:\n self.arr[i],self.arr[self.parent(i)] = self.arr[self.parent(i)],self.arr[i]\n i = self.parent(i)\n def heapify(self,i):\n left = self.left(i)\n right = self.right(i)\n smallest = i\n n= len(self.arr)\n if left<n and self.getVal(left)<self.getVal(smallest): smallest = left\n if right <n and self.getVal(right)<self.getVal(smallest): smallest = right\n if smallest!=i:\n self.arr[i],self.arr[smallest] = self.arr[smallest],self.arr[i]\n self.heapify(smallest)\n def extractMin(self):\n n = len(self.arr)\n if n==0:\n return '#'\n if n== 1:\n temp =self.arr[0]\n self.arr.pop()\n return temp\n root = self.arr[0]\n self.arr[0] = self.arr[-1]\n self.arr.pop()\n self.heapify(0)\n return root\nclass Solution(object):\n def mergeKLists(self, lists):\n heap = Heap()\n for i in lists:\n if i:\n heap.insert(i)\n res = None\n res_next = None\n while True:\n temp = heap.extractMin()\n if temp == \"#\":\n return res\n if not res:\n res = temp\n res_next = temp\n temp = temp.next\n if temp:\n heap.insert(temp)\n res.next = None\n else:\n res_next.next = temp\n temp = temp.next\n res_next=res_next.next\n if temp:\n heap.insert(temp)\n res_next.next = None\nob = Solution()\nlists = [[1,4,5],[1,3,4],[2,6]]\nlls = []\nfor ll in lists:\n l = make_list(ll)\n lls.append(l)\nprint_list(ob.mergeKLists(lls))"
},
{
"code": null,
"e": 5701,
"s": 5677,
"text": "[[1,4,5],[1,3,4],[2,6]]"
},
{
"code": null,
"e": 5728,
"s": 5701,
"text": "[1, 1, 2, 3, 4, 4, 5, 6, ]"
}
] |
How to install Scala on Windows? - GeeksforGeeks
|
05 Oct, 2021
Prerequisite: Introduction to Scala Before, we start with the process of Installing Scala on our System, we must have first-hand knowledge of What the Scala Language is and what it actually does? Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides the Javascript runtimes. Scala is highly influenced by Java and some other programming langauges like Lisp, Haskell, Pizza etc.Scala is a very compatible language and thus can very easily be installed into the Windows. The most basic requirement is that we must have Java 1.8 or a greater version installed on our computer.
Verifying Java Packages:The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them. Just go to the Command line(For Windows, search for cmd in the Run dialog( + R).Now run the following command:
java -version
Once this command is executed the output will show the java version and the output will be as follows:In case we are not having the SDK installed then download the latest version according to the computer requirements from oracle.com and just proceed with the installation.
Downloading Scala:Before starting with the installation process, you need to download it. For that, all versions of Scala for Windows are available on scala-lang.orgDownload the Scala and follow the further instructions for the installation of Scala.
Beginning with the Installation:
Getting Started:
Getting done with the Userβs License Agreement:
Move on to Installing
Installation Process:
Finished Installation:
After completing the installation process, any IDE or text editor can be used to write Scala Codes and Run them on the IDE or the Command prompt with the use of command:
scalac file_name.Scala
scala class_name
Hereβs a sample Program to begin with the use of Scala Programming:Letβs consider a simple Hello World Program.
// Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println("Hello World!") } }
how-to-install
Scala-Basics
How To
Installation Guide
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
How to Install FFmpeg on Windows?
How to integrate Git Bash with Visual Studio Code?
How to Install Anaconda on Windows?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26596,
"s": 25561,
"text": "Prerequisite: Introduction to Scala Before, we start with the process of Installing Scala on our System, we must have first-hand knowledge of What the Scala Language is and what it actually does? Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides the Javascript runtimes. Scala is highly influenced by Java and some other programming langauges like Lisp, Haskell, Pizza etc.Scala is a very compatible language and thus can very easily be installed into the Windows. The most basic requirement is that we must have Java 1.8 or a greater version installed on our computer."
},
{
"code": null,
"e": 26906,
"s": 26596,
"text": "Verifying Java Packages:The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them. Just go to the Command line(For Windows, search for cmd in the Run dialog( + R).Now run the following command:"
},
{
"code": null,
"e": 26921,
"s": 26906,
"text": "java -version "
},
{
"code": null,
"e": 27195,
"s": 26921,
"text": "Once this command is executed the output will show the java version and the output will be as follows:In case we are not having the SDK installed then download the latest version according to the computer requirements from oracle.com and just proceed with the installation."
},
{
"code": null,
"e": 27446,
"s": 27195,
"text": "Downloading Scala:Before starting with the installation process, you need to download it. For that, all versions of Scala for Windows are available on scala-lang.orgDownload the Scala and follow the further instructions for the installation of Scala."
},
{
"code": null,
"e": 27479,
"s": 27446,
"text": "Beginning with the Installation:"
},
{
"code": null,
"e": 27496,
"s": 27479,
"text": "Getting Started:"
},
{
"code": null,
"e": 27544,
"s": 27496,
"text": "Getting done with the Userβs License Agreement:"
},
{
"code": null,
"e": 27566,
"s": 27544,
"text": "Move on to Installing"
},
{
"code": null,
"e": 27588,
"s": 27566,
"text": "Installation Process:"
},
{
"code": null,
"e": 27611,
"s": 27588,
"text": "Finished Installation:"
},
{
"code": null,
"e": 27781,
"s": 27611,
"text": "After completing the installation process, any IDE or text editor can be used to write Scala Codes and Run them on the IDE or the Command prompt with the use of command:"
},
{
"code": null,
"e": 27821,
"s": 27781,
"text": "scalac file_name.Scala\nscala class_name"
},
{
"code": null,
"e": 27933,
"s": 27821,
"text": "Hereβs a sample Program to begin with the use of Scala Programming:Letβs consider a simple Hello World Program."
},
{
"code": "// Scala program to print Hello World! object Geeks { // Main Method def main(args: Array[String]) { // prints Hello World println(\"Hello World!\") } } ",
"e": 28122,
"s": 27933,
"text": null
},
{
"code": null,
"e": 28137,
"s": 28122,
"text": "how-to-install"
},
{
"code": null,
"e": 28150,
"s": 28137,
"text": "Scala-Basics"
},
{
"code": null,
"e": 28157,
"s": 28150,
"text": "How To"
},
{
"code": null,
"e": 28176,
"s": 28157,
"text": "Installation Guide"
},
{
"code": null,
"e": 28182,
"s": 28176,
"text": "Scala"
},
{
"code": null,
"e": 28280,
"s": 28182,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28307,
"s": 28280,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 28355,
"s": 28307,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28389,
"s": 28355,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28440,
"s": 28389,
"text": "How to integrate Git Bash with Visual Studio Code?"
},
{
"code": null,
"e": 28476,
"s": 28440,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 28509,
"s": 28476,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28543,
"s": 28509,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28579,
"s": 28543,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 28614,
"s": 28579,
"text": "How to Install Pygame on Windows ?"
}
] |
Outlier Detection: An ETL Tutorial with Spark | by Edward Elson Kosasih | Towards Data Science
|
Part of the Industry 4.0 framework is to make sure that manufacturers have more visibility over whatβs going on with their machines in the factory floors. This is why Industry 4.0 works tightly with Internet of Things. IoT allows large scale real-time data collection from sensors that are installed in production equipment possible. Nevertheless, having good Data Collection Agents alone isnβt sufficient. We need an automated way of extracting, analyzing and summarizing information from the large data stream, since itβs impossible for humans to do it manually. In big data terminology, this process is often referred to as ETL (Extract-Transform-Load).
Today, weβll discuss one family of algorithm that I have personally seen to be useful in the industry: outlier detection. The idea is to find any abnormal measurements from the data stream and highlight them to the domain experts e.g. process engineers. I will share an implementation of a basic anomaly detection algorithm in Spark. I could have done the same tutorial with pythonβs pandas-dataframe, but unfortunately once we deal with big dataset (whose size is way larger than memory space), the latter is no longer suitable.
In this post, Iβll use scala as my choice of programming language. I personally like to use scala when I write codes for production. Python is faster to write, hence useful for prototyping. However, itsβ lack of static typing could make things more difficult to debug. On the other hand, scala is more similar to Java, albeit less verbose (it runs on JVM too). But letβs leave this pro-and-cons debate for another session.
This is a simple dummy dataset that I use. Suppose we have data stream from 2 sensors. How can we automatically capture the two anomalous dots that are present below?
The model that we use finds region of values whose probability of occurrence are low under the distribution that has been fitted to the observed data. We assume that our sensors are unimodal gaussian in nature. With that, we can calculate the two thresholds that are six sigma away from the distributionβs mean.
Visually, the thresholds are fitted in this manner. Any measurements above the Upper Limit (around 25) or below the Lower Limit (around 15) are deemed as outliers.
Now to implement this in Spark, we first import all of the library dependencies.
import org.apache.spark.sql.{Column, SQLContext}import org.apache.spark.{SparkConf, SparkContext}import org.apache.spark.sql.types._import org.apache.spark.sql.functions._
We need to wrap all of our functions inside an object with a main function (This might remind you of Java). We can actually write this in a different style, one that looks more like a script. Scala has an interpreter called REPL that allows programmers to execute codes line-by-line. Nevertheless in production itβs good to keep things organized in this manner.
/** * Sample Anomaly Detection with Spark */object AnomalyDetection { def main(args: Array[String]): Unit = { // the rest of the functions go here }}
Now if youβre running spark in Windows, you might stumble upon some exceptions saying that the program failed to locate the winutil binary. In that case, you need to download the winutils.exe (this is how to do it) and set the following system property inside your code.
System.setProperty("hadoop.home.dir", "C:/winutil/")
Next, we need to configure spark, sparkContext and sqlContext. If we use HBase (a NoSQL database) with ZooKeeper, weβll need to configure the spark.hbase.host parameter to point the corresponding host address.
/** Configure Spark */val conf = new SparkConf() .setAppName("anomalyDetection") .setMaster("local[8]")conf.set("spark.hbase.host", "zookeeper.default.svc.cluster.local")val sc = new SparkContext(conf)sc.setLogLevel("WARN")val sqlContext = new SQLContext(sc)
We now assume that our data comes in a csv format. It has also been saved in a file called test.csv. We first specify the data schema explicitly. Note than in production, data could also be obtained from a database and message broker (e.g. MQTT, Kafka etc...).
/** read csv */val customSchema = StructType(Array( StructField("sensorId", StringType, true), StructField("values", DoubleType, true)))
Then, we read the csv file into a Spark DataFrame. Here we can see that there are only two columns: sensorId and values.
// load datasetval df = sqlContext.read .format("com.databricks.spark.csv") .option("header", "true") .schema(customSchema) .load("test.csv")df.printSchema()
root | β sensorId: string (nullable = true) | β values: double (nullable = true)
We would like to calculate the distribution profile for each sensorID, particularly the Upper and Lower Outlier Thresholds. To do that, we need to group the dataframe by sensorId, followed by aggregating each sensor dataβs mean and standard deviation accordingly. We can then create 2 new columns, one for each outlier threshold.
// calculate statisticsval statsDF = df .groupBy("sensorId") .agg(mean("values").as("mean"), stddev("values").as("stddev")) .withColumn("UpperLimit", col("mean") + col("stddev")*3) .withColumn("LowerLimit", col("mean") - col("stddev")*3)statsDF.printSchema()
root | β sensorId: string (nullable = true) | β mean: double (nullable = true) | β stddev: double (nullable = false) | β UpperLimit: double (nullable = true) | β LowerLimit: double (nullable = true)
We would now like to find which sensor readings are anomalous in the original dataframe. Since the information live in two different dataframes, we need to join them using the sensorId column as a common index.
// join the two dataframeval joinDF = df.join(statsDF, usingColumns = Seq("sensorId"))
Lastly, we can filter rows whose values lie beyond the range enclosed by the outlier thresholds. Voila! We managed to capture the two anomalous points.
// outlierDetectionval detectOutlier = (values: Column, UpperLimit: Column, LowerLimit: Column) => { // outliers are points lying below LowerLimit or above upperLimit (values < LowerLimit) or (values > UpperLimit)}val outlierDF = joinDF .withColumn("isOutlier", detectOutlier(col("values"), col("UpperLimit"), col("LowerLimit"))) .filter(col("isOutlier"))outlierDF.show()
(Optional) We could also write output dataframe into another table (or csv file) for further processing. This completes the whole ETL process.
outlierDF .repartition(1) .write.format("com.databricks.spark.csv") .save("result")
The above method outputs a folder called result, with the following files inside it. Normally data will be split into multiple csvs (each with a different part name). But since we have repartitioned the dataframe into 1, all data is collected into one partition (or file).
The final step is to close the sparkContext.
// close sparkContextsc.stop()
Spark comes with a web interface (by default in port 4040) that could be used to see how the ETL process runs. I find this useful, especially in identifying bottleneck functions.
We have seen how a typical ETL pipeline with Spark works, using anomaly detection as the main transformation process. Note that some of the procedures used here is not suitable for production. For example, CSV input and output are not encouraged. Normally we would use Hadoop Distributed File System (HDFS) instead. The latter could be wrapped under a database too e.g. HBase. Nonetheless, the main programming paradigm stays the same.
|
[
{
"code": null,
"e": 829,
"s": 172,
"text": "Part of the Industry 4.0 framework is to make sure that manufacturers have more visibility over whatβs going on with their machines in the factory floors. This is why Industry 4.0 works tightly with Internet of Things. IoT allows large scale real-time data collection from sensors that are installed in production equipment possible. Nevertheless, having good Data Collection Agents alone isnβt sufficient. We need an automated way of extracting, analyzing and summarizing information from the large data stream, since itβs impossible for humans to do it manually. In big data terminology, this process is often referred to as ETL (Extract-Transform-Load)."
},
{
"code": null,
"e": 1359,
"s": 829,
"text": "Today, weβll discuss one family of algorithm that I have personally seen to be useful in the industry: outlier detection. The idea is to find any abnormal measurements from the data stream and highlight them to the domain experts e.g. process engineers. I will share an implementation of a basic anomaly detection algorithm in Spark. I could have done the same tutorial with pythonβs pandas-dataframe, but unfortunately once we deal with big dataset (whose size is way larger than memory space), the latter is no longer suitable."
},
{
"code": null,
"e": 1782,
"s": 1359,
"text": "In this post, Iβll use scala as my choice of programming language. I personally like to use scala when I write codes for production. Python is faster to write, hence useful for prototyping. However, itsβ lack of static typing could make things more difficult to debug. On the other hand, scala is more similar to Java, albeit less verbose (it runs on JVM too). But letβs leave this pro-and-cons debate for another session."
},
{
"code": null,
"e": 1949,
"s": 1782,
"text": "This is a simple dummy dataset that I use. Suppose we have data stream from 2 sensors. How can we automatically capture the two anomalous dots that are present below?"
},
{
"code": null,
"e": 2261,
"s": 1949,
"text": "The model that we use finds region of values whose probability of occurrence are low under the distribution that has been fitted to the observed data. We assume that our sensors are unimodal gaussian in nature. With that, we can calculate the two thresholds that are six sigma away from the distributionβs mean."
},
{
"code": null,
"e": 2425,
"s": 2261,
"text": "Visually, the thresholds are fitted in this manner. Any measurements above the Upper Limit (around 25) or below the Lower Limit (around 15) are deemed as outliers."
},
{
"code": null,
"e": 2506,
"s": 2425,
"text": "Now to implement this in Spark, we first import all of the library dependencies."
},
{
"code": null,
"e": 2678,
"s": 2506,
"text": "import org.apache.spark.sql.{Column, SQLContext}import org.apache.spark.{SparkConf, SparkContext}import org.apache.spark.sql.types._import org.apache.spark.sql.functions._"
},
{
"code": null,
"e": 3040,
"s": 2678,
"text": "We need to wrap all of our functions inside an object with a main function (This might remind you of Java). We can actually write this in a different style, one that looks more like a script. Scala has an interpreter called REPL that allows programmers to execute codes line-by-line. Nevertheless in production itβs good to keep things organized in this manner."
},
{
"code": null,
"e": 3203,
"s": 3040,
"text": "/** * Sample Anomaly Detection with Spark */object AnomalyDetection { def main(args: Array[String]): Unit = { // the rest of the functions go here }}"
},
{
"code": null,
"e": 3474,
"s": 3203,
"text": "Now if youβre running spark in Windows, you might stumble upon some exceptions saying that the program failed to locate the winutil binary. In that case, you need to download the winutils.exe (this is how to do it) and set the following system property inside your code."
},
{
"code": null,
"e": 3527,
"s": 3474,
"text": "System.setProperty(\"hadoop.home.dir\", \"C:/winutil/\")"
},
{
"code": null,
"e": 3737,
"s": 3527,
"text": "Next, we need to configure spark, sparkContext and sqlContext. If we use HBase (a NoSQL database) with ZooKeeper, weβll need to configure the spark.hbase.host parameter to point the corresponding host address."
},
{
"code": null,
"e": 3998,
"s": 3737,
"text": "/** Configure Spark */val conf = new SparkConf() .setAppName(\"anomalyDetection\") .setMaster(\"local[8]\")conf.set(\"spark.hbase.host\", \"zookeeper.default.svc.cluster.local\")val sc = new SparkContext(conf)sc.setLogLevel(\"WARN\")val sqlContext = new SQLContext(sc)"
},
{
"code": null,
"e": 4259,
"s": 3998,
"text": "We now assume that our data comes in a csv format. It has also been saved in a file called test.csv. We first specify the data schema explicitly. Note than in production, data could also be obtained from a database and message broker (e.g. MQTT, Kafka etc...)."
},
{
"code": null,
"e": 4398,
"s": 4259,
"text": "/** read csv */val customSchema = StructType(Array( StructField(\"sensorId\", StringType, true), StructField(\"values\", DoubleType, true)))"
},
{
"code": null,
"e": 4519,
"s": 4398,
"text": "Then, we read the csv file into a Spark DataFrame. Here we can see that there are only two columns: sensorId and values."
},
{
"code": null,
"e": 4681,
"s": 4519,
"text": "// load datasetval df = sqlContext.read .format(\"com.databricks.spark.csv\") .option(\"header\", \"true\") .schema(customSchema) .load(\"test.csv\")df.printSchema()"
},
{
"code": null,
"e": 4762,
"s": 4681,
"text": "root | β sensorId: string (nullable = true) | β values: double (nullable = true)"
},
{
"code": null,
"e": 5092,
"s": 4762,
"text": "We would like to calculate the distribution profile for each sensorID, particularly the Upper and Lower Outlier Thresholds. To do that, we need to group the dataframe by sensorId, followed by aggregating each sensor dataβs mean and standard deviation accordingly. We can then create 2 new columns, one for each outlier threshold."
},
{
"code": null,
"e": 5355,
"s": 5092,
"text": "// calculate statisticsval statsDF = df .groupBy(\"sensorId\") .agg(mean(\"values\").as(\"mean\"), stddev(\"values\").as(\"stddev\")) .withColumn(\"UpperLimit\", col(\"mean\") + col(\"stddev\")*3) .withColumn(\"LowerLimit\", col(\"mean\") - col(\"stddev\")*3)statsDF.printSchema()"
},
{
"code": null,
"e": 5554,
"s": 5355,
"text": "root | β sensorId: string (nullable = true) | β mean: double (nullable = true) | β stddev: double (nullable = false) | β UpperLimit: double (nullable = true) | β LowerLimit: double (nullable = true)"
},
{
"code": null,
"e": 5765,
"s": 5554,
"text": "We would now like to find which sensor readings are anomalous in the original dataframe. Since the information live in two different dataframes, we need to join them using the sensorId column as a common index."
},
{
"code": null,
"e": 5852,
"s": 5765,
"text": "// join the two dataframeval joinDF = df.join(statsDF, usingColumns = Seq(\"sensorId\"))"
},
{
"code": null,
"e": 6004,
"s": 5852,
"text": "Lastly, we can filter rows whose values lie beyond the range enclosed by the outlier thresholds. Voila! We managed to capture the two anomalous points."
},
{
"code": null,
"e": 6380,
"s": 6004,
"text": "// outlierDetectionval detectOutlier = (values: Column, UpperLimit: Column, LowerLimit: Column) => { // outliers are points lying below LowerLimit or above upperLimit (values < LowerLimit) or (values > UpperLimit)}val outlierDF = joinDF .withColumn(\"isOutlier\", detectOutlier(col(\"values\"), col(\"UpperLimit\"), col(\"LowerLimit\"))) .filter(col(\"isOutlier\"))outlierDF.show()"
},
{
"code": null,
"e": 6523,
"s": 6380,
"text": "(Optional) We could also write output dataframe into another table (or csv file) for further processing. This completes the whole ETL process."
},
{
"code": null,
"e": 6610,
"s": 6523,
"text": "outlierDF .repartition(1) .write.format(\"com.databricks.spark.csv\") .save(\"result\")"
},
{
"code": null,
"e": 6883,
"s": 6610,
"text": "The above method outputs a folder called result, with the following files inside it. Normally data will be split into multiple csvs (each with a different part name). But since we have repartitioned the dataframe into 1, all data is collected into one partition (or file)."
},
{
"code": null,
"e": 6928,
"s": 6883,
"text": "The final step is to close the sparkContext."
},
{
"code": null,
"e": 6959,
"s": 6928,
"text": "// close sparkContextsc.stop()"
},
{
"code": null,
"e": 7138,
"s": 6959,
"text": "Spark comes with a web interface (by default in port 4040) that could be used to see how the ETL process runs. I find this useful, especially in identifying bottleneck functions."
}
] |
Comparator naturalOrder() method in Java with examples - GeeksforGeeks
|
29 Apr, 2019
The naturalOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null.
Syntax:
static <T extends Comparable<T>>
Comparator<T> naturalOrder()
Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the natural ordering on Comparable objects.
Below programs illustrate naturalOrder() method:Program 1:
// Java program to demonstrate// Comparator.naturalOrder() method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<Integer> values = Arrays.asList(212, 324, 435, 566, 133, 100, 121); // naturalOrder is a static method values.sort(Comparator.naturalOrder()); // print sorted number based on natural order System.out.println(values); }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Comparator.naturalOrder() method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<String> stringList = Arrays.asList("Aman", "Kajal", "Joyita", "Das"); System.out.println("Before sorting:"); stringList.forEach(System.out::println); stringList.sort(Comparator.naturalOrder()); System.out.println("\nAfter sorting:"); stringList.forEach(System.out::println); }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#naturalOrder()
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 24192,
"s": 23948,
"text": "The naturalOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null."
},
{
"code": null,
"e": 24200,
"s": 24192,
"text": "Syntax:"
},
{
"code": null,
"e": 24268,
"s": 24200,
"text": "static <T extends Comparable<T>> \n Comparator<T> naturalOrder()\n"
},
{
"code": null,
"e": 24309,
"s": 24268,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 24413,
"s": 24309,
"text": "Return value: This method returns a comparator that imposes the natural ordering on Comparable objects."
},
{
"code": null,
"e": 24472,
"s": 24413,
"text": "Below programs illustrate naturalOrder() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Comparator.naturalOrder() method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<Integer> values = Arrays.asList(212, 324, 435, 566, 133, 100, 121); // naturalOrder is a static method values.sort(Comparator.naturalOrder()); // print sorted number based on natural order System.out.println(values); }}",
"e": 25017,
"s": 24472,
"text": null
},
{
"code": null,
"e": 25077,
"s": 25017,
"text": "The output printed on console of IDE is shown below.Output:"
},
{
"code": null,
"e": 25088,
"s": 25077,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Comparator.naturalOrder() method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<String> stringList = Arrays.asList(\"Aman\", \"Kajal\", \"Joyita\", \"Das\"); System.out.println(\"Before sorting:\"); stringList.forEach(System.out::println); stringList.sort(Comparator.naturalOrder()); System.out.println(\"\\nAfter sorting:\"); stringList.forEach(System.out::println); }}",
"e": 25671,
"s": 25088,
"text": null
},
{
"code": null,
"e": 25724,
"s": 25671,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 25820,
"s": 25724,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#naturalOrder()"
},
{
"code": null,
"e": 25840,
"s": 25820,
"text": "Java - util package"
},
{
"code": null,
"e": 25856,
"s": 25840,
"text": "Java-Comparator"
},
{
"code": null,
"e": 25871,
"s": 25856,
"text": "Java-Functions"
},
{
"code": null,
"e": 25876,
"s": 25871,
"text": "Java"
},
{
"code": null,
"e": 25881,
"s": 25876,
"text": "Java"
},
{
"code": null,
"e": 25979,
"s": 25881,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25988,
"s": 25979,
"text": "Comments"
},
{
"code": null,
"e": 26001,
"s": 25988,
"text": "Old Comments"
},
{
"code": null,
"e": 26047,
"s": 26001,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26068,
"s": 26047,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26083,
"s": 26068,
"text": "Stream In Java"
},
{
"code": null,
"e": 26100,
"s": 26083,
"text": "Generics in Java"
},
{
"code": null,
"e": 26119,
"s": 26100,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26149,
"s": 26119,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26192,
"s": 26149,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26221,
"s": 26192,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26237,
"s": 26221,
"text": "Strings in Java"
}
] |
CopyOnWriteArrayList remove() method in Java with Examples - GeeksforGeeks
|
06 Jan, 2020
The remove()method of CopyOnArrayList in Javais used to remove the element in the list.
Syntax:
1. public E remove(int index)
2. public boolean remove(Object o)
The remove(int index) method of CopyOnArrayList in Java is used to remove the element at the specified position in the list.
Syntax:
public E remove(int index)
Parameters: This method accepts a mandatory parameter index which specifies the position of the element.
Return Type: This method returns the list after deleting the specified element.
Exception: This method throws ArrayIndexOutOfBounds exception if specified index is out of range i.e index is less than 0 or greater than or equal to the size of the list.
Below programs illustrate the remove(int index) method of CopyOnArrayList in Java:
Program 1: This program involves CopyOnArrayList remove(int index) of Integer type
// Java Program to illustrate CopyOnArrayList// remove(int index) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<Integer> ArrLis1 = new CopyOnWriteArrayList<Integer>(); // Add elements ArrLis1.add(63); ArrLis1.add(54); ArrLis1.add(81); ArrLis1.add(96); // print CopyOnWriteArrayList System.out.println("CopyOnWriteArrayList: " + ArrLis1); ArrLis1.remove(2); // check using function System.out.println(ArrLis1); }}
CopyOnWriteArrayList: [63, 54, 81, 96]
[63, 54, 96]
Program 2: This program involves CopyOnArrayList remove(int index) of String type
// Java Program to illustrate CopyOnArrayList// remove(int index) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<String> ArrLis1 = new CopyOnWriteArrayList<String>(); // Add elements ArrLis1.add("geeks"); ArrLis1.add("gfg"); ArrLis1.add("programming"); // print CopyOnWriteArrayList System.out.println("CopyOnWriteArrayList: " + ArrLis1); ArrLis1.remove(0); // check using function System.out.println(ArrLis1); }}
CopyOnWriteArrayList: [geeks, gfg, programming]
[gfg, programming]
The remove(Object o) method of CopyOnArrayList in Java is used to removes the first occurrence of specified element, if it is present in the list.
Syntax:
public boolean remove(Object o)
Parameters: This method accepts a mandatory parameter o, the element which is to be removed from the list, if present.
Return Type: This method returns true if specified element is present in the list, else false.
Below programs illustrate the remove(Object o) method of CopyOnArrayList in Java:
Program 1: This program involves CopyOnArrayList remove(Object o) of Integer type
// Java Program to illustrate CopyOnArrayList// remove(Object o) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<Integer> ArrLis1 = new CopyOnWriteArrayList<Integer>(); // Add elements ArrLis1.add(11); ArrLis1.add(22); ArrLis1.add(33); ArrLis1.add(22); ArrLis1.add(44); // print CopyOnWriteArrayList System.out.println("CopyOnWriteArrayList: " + ArrLis1); ArrLis1.remove(new Integer(22)); // check using function System.out.println(ArrLis1); }}
CopyOnWriteArrayList: [11, 22, 33, 22, 44]
[11, 33, 22, 44]
Program 2: This program involves CopyOnArrayList remove(Object o) of String type
// Java Program to illustrate CopyOnArrayList// remove(Object o) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<String> ArrLis1 = new CopyOnWriteArrayList<String>(); // Add elements ArrLis1.add("geeks"); ArrLis1.add("gfg"); ArrLis1.add("programming"); // print CopyOnWriteArrayList System.out.println("CopyOnWriteArrayList: " + ArrLis1); ArrLis1.remove("gfg"); // check using function System.out.println(ArrLis1); }}
CopyOnWriteArrayList: [geeks, gfg, programming]
[geeks, programming]
nidhi_biet
Java-CopyOnWriteArrayList
Java-Functions
Picked
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
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
|
[
{
"code": null,
"e": 24099,
"s": 24071,
"text": "\n06 Jan, 2020"
},
{
"code": null,
"e": 24187,
"s": 24099,
"text": "The remove()method of CopyOnArrayList in Javais used to remove the element in the list."
},
{
"code": null,
"e": 24195,
"s": 24187,
"text": "Syntax:"
},
{
"code": null,
"e": 24261,
"s": 24195,
"text": "1. public E remove(int index)\n2. public boolean remove(Object o)\n"
},
{
"code": null,
"e": 24386,
"s": 24261,
"text": "The remove(int index) method of CopyOnArrayList in Java is used to remove the element at the specified position in the list."
},
{
"code": null,
"e": 24394,
"s": 24386,
"text": "Syntax:"
},
{
"code": null,
"e": 24422,
"s": 24394,
"text": "public E remove(int index)\n"
},
{
"code": null,
"e": 24527,
"s": 24422,
"text": "Parameters: This method accepts a mandatory parameter index which specifies the position of the element."
},
{
"code": null,
"e": 24607,
"s": 24527,
"text": "Return Type: This method returns the list after deleting the specified element."
},
{
"code": null,
"e": 24779,
"s": 24607,
"text": "Exception: This method throws ArrayIndexOutOfBounds exception if specified index is out of range i.e index is less than 0 or greater than or equal to the size of the list."
},
{
"code": null,
"e": 24862,
"s": 24779,
"text": "Below programs illustrate the remove(int index) method of CopyOnArrayList in Java:"
},
{
"code": null,
"e": 24945,
"s": 24862,
"text": "Program 1: This program involves CopyOnArrayList remove(int index) of Integer type"
},
{
"code": "// Java Program to illustrate CopyOnArrayList// remove(int index) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<Integer> ArrLis1 = new CopyOnWriteArrayList<Integer>(); // Add elements ArrLis1.add(63); ArrLis1.add(54); ArrLis1.add(81); ArrLis1.add(96); // print CopyOnWriteArrayList System.out.println(\"CopyOnWriteArrayList: \" + ArrLis1); ArrLis1.remove(2); // check using function System.out.println(ArrLis1); }}",
"e": 25600,
"s": 24945,
"text": null
},
{
"code": null,
"e": 25653,
"s": 25600,
"text": "CopyOnWriteArrayList: [63, 54, 81, 96]\n[63, 54, 96]\n"
},
{
"code": null,
"e": 25735,
"s": 25653,
"text": "Program 2: This program involves CopyOnArrayList remove(int index) of String type"
},
{
"code": "// Java Program to illustrate CopyOnArrayList// remove(int index) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<String> ArrLis1 = new CopyOnWriteArrayList<String>(); // Add elements ArrLis1.add(\"geeks\"); ArrLis1.add(\"gfg\"); ArrLis1.add(\"programming\"); // print CopyOnWriteArrayList System.out.println(\"CopyOnWriteArrayList: \" + ArrLis1); ArrLis1.remove(0); // check using function System.out.println(ArrLis1); }}",
"e": 26383,
"s": 25735,
"text": null
},
{
"code": null,
"e": 26451,
"s": 26383,
"text": "CopyOnWriteArrayList: [geeks, gfg, programming]\n[gfg, programming]\n"
},
{
"code": null,
"e": 26598,
"s": 26451,
"text": "The remove(Object o) method of CopyOnArrayList in Java is used to removes the first occurrence of specified element, if it is present in the list."
},
{
"code": null,
"e": 26606,
"s": 26598,
"text": "Syntax:"
},
{
"code": null,
"e": 26639,
"s": 26606,
"text": "public boolean remove(Object o)\n"
},
{
"code": null,
"e": 26758,
"s": 26639,
"text": "Parameters: This method accepts a mandatory parameter o, the element which is to be removed from the list, if present."
},
{
"code": null,
"e": 26853,
"s": 26758,
"text": "Return Type: This method returns true if specified element is present in the list, else false."
},
{
"code": null,
"e": 26935,
"s": 26853,
"text": "Below programs illustrate the remove(Object o) method of CopyOnArrayList in Java:"
},
{
"code": null,
"e": 27017,
"s": 26935,
"text": "Program 1: This program involves CopyOnArrayList remove(Object o) of Integer type"
},
{
"code": "// Java Program to illustrate CopyOnArrayList// remove(Object o) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<Integer> ArrLis1 = new CopyOnWriteArrayList<Integer>(); // Add elements ArrLis1.add(11); ArrLis1.add(22); ArrLis1.add(33); ArrLis1.add(22); ArrLis1.add(44); // print CopyOnWriteArrayList System.out.println(\"CopyOnWriteArrayList: \" + ArrLis1); ArrLis1.remove(new Integer(22)); // check using function System.out.println(ArrLis1); }}",
"e": 27709,
"s": 27017,
"text": null
},
{
"code": null,
"e": 27770,
"s": 27709,
"text": "CopyOnWriteArrayList: [11, 22, 33, 22, 44]\n[11, 33, 22, 44]\n"
},
{
"code": null,
"e": 27851,
"s": 27770,
"text": "Program 2: This program involves CopyOnArrayList remove(Object o) of String type"
},
{
"code": "// Java Program to illustrate CopyOnArrayList// remove(Object o) method import java.util.concurrent.CopyOnWriteArrayList;import java.util.*; public class GFG { public static void main(String[] args) { CopyOnWriteArrayList<String> ArrLis1 = new CopyOnWriteArrayList<String>(); // Add elements ArrLis1.add(\"geeks\"); ArrLis1.add(\"gfg\"); ArrLis1.add(\"programming\"); // print CopyOnWriteArrayList System.out.println(\"CopyOnWriteArrayList: \" + ArrLis1); ArrLis1.remove(\"gfg\"); // check using function System.out.println(ArrLis1); }}",
"e": 28502,
"s": 27851,
"text": null
},
{
"code": null,
"e": 28572,
"s": 28502,
"text": "CopyOnWriteArrayList: [geeks, gfg, programming]\n[geeks, programming]\n"
},
{
"code": null,
"e": 28583,
"s": 28572,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28609,
"s": 28583,
"text": "Java-CopyOnWriteArrayList"
},
{
"code": null,
"e": 28624,
"s": 28609,
"text": "Java-Functions"
},
{
"code": null,
"e": 28631,
"s": 28624,
"text": "Picked"
},
{
"code": null,
"e": 28636,
"s": 28631,
"text": "Java"
},
{
"code": null,
"e": 28641,
"s": 28636,
"text": "Java"
},
{
"code": null,
"e": 28739,
"s": 28641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28748,
"s": 28739,
"text": "Comments"
},
{
"code": null,
"e": 28761,
"s": 28748,
"text": "Old Comments"
},
{
"code": null,
"e": 28812,
"s": 28761,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28842,
"s": 28812,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28873,
"s": 28842,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28892,
"s": 28873,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28924,
"s": 28892,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28942,
"s": 28924,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28974,
"s": 28942,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28998,
"s": 28974,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29017,
"s": 28998,
"text": "LinkedList in Java"
}
] |
Confidence Intervals Explained Simply for Data Scientists | by Rahul Agarwal | Towards Data Science
|
Recently, I got asked about how to explain confidence intervals in simple terms to a layperson. I found that it is hard to do that.
Confidence Intervals are always a headache to explain even to someone who knows about them, let alone someone who doesnβt understand statistics.
I went to Wikipedia to find something and here is the definition:
In statistics, a confidence interval (CI) is a type of estimate computed from the statistics of the observed data. This proposes a range of plausible values for an unknown parameter. The interval has an associated confidence level that the true parameter is in the proposed range. This is more clearly stated as: the confidence level represents the probability that the unknown parameter lies in the stated interval. The level of confidence can be chosen by the investigator. In general terms, a confidence interval for an unknown parameter is based on sampling the distribution of a corresponding estimator. [1]
And my first thought was that might be they have written it like this so that nobody could understand it. The problem here lies with a lot of terminology and language that statisticians enjoy to employ.
This post is about explaining confidence intervals in an easy to understand way without all that pretentiousness.
Letβs start by creating a real-life scenario.
Imagine you want to find the mean height of all the people in a particular US state.
You could go to each person in that particular state and ask for their height, or you can do the smarter thing by taking a sample of 1000 people in the state.
Then you can use the mean of their heights (Estimated Mean) to estimate the average of heights in the state(True Mean)
This is all well and good, but you being the true data scientist, are not satisfied. The estimated mean is just a single number, and you want to have a range where the true mean could lie.
Why do we want a range? Because in real life, we are concerned about the confidence of our estimates.
Typically even if I ask you to guess the height of people in the particular US state, you are more inclined to say something like: βI believe it is between 6 foot to 6 Foot 2 Inchβ rather than a point estimate like βIts 6 foot 2.2345 inchesβ.
We humans also like to attach a level of confidence when we give estimates. Have you ever said β βI am 90% confidentβ.
In this particular example, I can be more confident about the statement- βI believe it is between 5 foot to 7 Footβ than βI believe it is between 6 foot to 6 Foot 2 Inchβ as the first range is a superset of the second one.
So how do we get this range and quantify a confidence value?
To understand how we will calculate the confidence intervals, we need to understand the Central Limit Theorem.
Central Limit Theorem: The Central Limit Theorem(CLT) simply states that if you have a population with mean ΞΌ and standard deviation Ο, and take random samples from the population, then the distribution of the sample means will be approximately normally distributed with mean as the population mean and estimated standard deviation s/βn where s is the standard deviation of the sample and n is the number of observations in the sample.
So knowing all this, you become curious. We already have a sample of 1000 people in the US state. Can we apply CLT?
We know that the mean of the sampling distribution is equal to the population mean(which we donβt know and want to estimate)and the sample deviation of the sampling distribution is given by Ο/βn( i.e., the standard deviation of the sample divided by the number of observations in the sample)
Now, you want to find intervals on the X-axis that contains the true population mean.
So what do we do? We cast a net from the value we know.
To get such ranges/intervals, we go 1.96 standard deviations away from Xbar, the sample mean in both directions. And this range is the 95% confidence interval.
Now, when I say that I estimate the true mean to be Xbar (The sample Mean) with a confidence interval of [Xbar-1.96SD, Xbar+1.96SD], I am saying that:
That this is an interval constructed using a certain procedure. Were this procedure to be repeated on numerous samples, the fraction of calculated confidence intervals (which would differ for each sample) that encompass the true population parameter would tend toward 95%
When you take 99% CI, you essentially increase the proportion and thus cast a wider net with three standard deviations.
Here Xbar is the sample mean(mean of the 1000 heights sample you took).
Z is the no of standard deviations away from the sample mean(1.96 for 95%, 2.576 for 99%) β level of confidence you want.
s is the standard deviation in the sample.
n is the size of the sample.
Each line in the figure above is one such experiment where the dot signifies the sample mean, and the line signifies the range. The dotted line in this figure is the true population mean.
See how some of these intervals donβt contain the true population mean, and almost all of them(95%) do include the true population mean.
As we said, Z is the no of standard deviations away from the sample mean(1.96 for 95%, 2.576 for 99%) β level of confidence you want.
You can go for any arbitrary level of confidence. Say, for example, you want 90% confidence. You can get that by using the idea that the shaded area inside the normal curve needs to be 0.90.
import scipy.stats as stp = 0.9 + (1-0.9)/2Z = st.norm.ppf(p, loc=0, scale=1)print(Z)----------------------------------------------------------1.6448536269514722
If you want to learn more about hypothesis testing, confidence intervals, and statistical inference methods for numerical and categorical data, Mine CΜ§etinkaya-Rundel teaches Inferential Statistics course on coursera, and it cannot get simpler than this one. She is a great instructor and explains the fundamentals of Statistical inference nicely.
Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz
Also, a small disclaimer β There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
|
[
{
"code": null,
"e": 304,
"s": 172,
"text": "Recently, I got asked about how to explain confidence intervals in simple terms to a layperson. I found that it is hard to do that."
},
{
"code": null,
"e": 449,
"s": 304,
"text": "Confidence Intervals are always a headache to explain even to someone who knows about them, let alone someone who doesnβt understand statistics."
},
{
"code": null,
"e": 515,
"s": 449,
"text": "I went to Wikipedia to find something and here is the definition:"
},
{
"code": null,
"e": 1128,
"s": 515,
"text": "In statistics, a confidence interval (CI) is a type of estimate computed from the statistics of the observed data. This proposes a range of plausible values for an unknown parameter. The interval has an associated confidence level that the true parameter is in the proposed range. This is more clearly stated as: the confidence level represents the probability that the unknown parameter lies in the stated interval. The level of confidence can be chosen by the investigator. In general terms, a confidence interval for an unknown parameter is based on sampling the distribution of a corresponding estimator. [1]"
},
{
"code": null,
"e": 1331,
"s": 1128,
"text": "And my first thought was that might be they have written it like this so that nobody could understand it. The problem here lies with a lot of terminology and language that statisticians enjoy to employ."
},
{
"code": null,
"e": 1445,
"s": 1331,
"text": "This post is about explaining confidence intervals in an easy to understand way without all that pretentiousness."
},
{
"code": null,
"e": 1491,
"s": 1445,
"text": "Letβs start by creating a real-life scenario."
},
{
"code": null,
"e": 1576,
"s": 1491,
"text": "Imagine you want to find the mean height of all the people in a particular US state."
},
{
"code": null,
"e": 1735,
"s": 1576,
"text": "You could go to each person in that particular state and ask for their height, or you can do the smarter thing by taking a sample of 1000 people in the state."
},
{
"code": null,
"e": 1854,
"s": 1735,
"text": "Then you can use the mean of their heights (Estimated Mean) to estimate the average of heights in the state(True Mean)"
},
{
"code": null,
"e": 2043,
"s": 1854,
"text": "This is all well and good, but you being the true data scientist, are not satisfied. The estimated mean is just a single number, and you want to have a range where the true mean could lie."
},
{
"code": null,
"e": 2145,
"s": 2043,
"text": "Why do we want a range? Because in real life, we are concerned about the confidence of our estimates."
},
{
"code": null,
"e": 2388,
"s": 2145,
"text": "Typically even if I ask you to guess the height of people in the particular US state, you are more inclined to say something like: βI believe it is between 6 foot to 6 Foot 2 Inchβ rather than a point estimate like βIts 6 foot 2.2345 inchesβ."
},
{
"code": null,
"e": 2507,
"s": 2388,
"text": "We humans also like to attach a level of confidence when we give estimates. Have you ever said β βI am 90% confidentβ."
},
{
"code": null,
"e": 2730,
"s": 2507,
"text": "In this particular example, I can be more confident about the statement- βI believe it is between 5 foot to 7 Footβ than βI believe it is between 6 foot to 6 Foot 2 Inchβ as the first range is a superset of the second one."
},
{
"code": null,
"e": 2791,
"s": 2730,
"text": "So how do we get this range and quantify a confidence value?"
},
{
"code": null,
"e": 2902,
"s": 2791,
"text": "To understand how we will calculate the confidence intervals, we need to understand the Central Limit Theorem."
},
{
"code": null,
"e": 3338,
"s": 2902,
"text": "Central Limit Theorem: The Central Limit Theorem(CLT) simply states that if you have a population with mean ΞΌ and standard deviation Ο, and take random samples from the population, then the distribution of the sample means will be approximately normally distributed with mean as the population mean and estimated standard deviation s/βn where s is the standard deviation of the sample and n is the number of observations in the sample."
},
{
"code": null,
"e": 3454,
"s": 3338,
"text": "So knowing all this, you become curious. We already have a sample of 1000 people in the US state. Can we apply CLT?"
},
{
"code": null,
"e": 3746,
"s": 3454,
"text": "We know that the mean of the sampling distribution is equal to the population mean(which we donβt know and want to estimate)and the sample deviation of the sampling distribution is given by Ο/βn( i.e., the standard deviation of the sample divided by the number of observations in the sample)"
},
{
"code": null,
"e": 3832,
"s": 3746,
"text": "Now, you want to find intervals on the X-axis that contains the true population mean."
},
{
"code": null,
"e": 3888,
"s": 3832,
"text": "So what do we do? We cast a net from the value we know."
},
{
"code": null,
"e": 4048,
"s": 3888,
"text": "To get such ranges/intervals, we go 1.96 standard deviations away from Xbar, the sample mean in both directions. And this range is the 95% confidence interval."
},
{
"code": null,
"e": 4199,
"s": 4048,
"text": "Now, when I say that I estimate the true mean to be Xbar (The sample Mean) with a confidence interval of [Xbar-1.96SD, Xbar+1.96SD], I am saying that:"
},
{
"code": null,
"e": 4471,
"s": 4199,
"text": "That this is an interval constructed using a certain procedure. Were this procedure to be repeated on numerous samples, the fraction of calculated confidence intervals (which would differ for each sample) that encompass the true population parameter would tend toward 95%"
},
{
"code": null,
"e": 4591,
"s": 4471,
"text": "When you take 99% CI, you essentially increase the proportion and thus cast a wider net with three standard deviations."
},
{
"code": null,
"e": 4663,
"s": 4591,
"text": "Here Xbar is the sample mean(mean of the 1000 heights sample you took)."
},
{
"code": null,
"e": 4785,
"s": 4663,
"text": "Z is the no of standard deviations away from the sample mean(1.96 for 95%, 2.576 for 99%) β level of confidence you want."
},
{
"code": null,
"e": 4828,
"s": 4785,
"text": "s is the standard deviation in the sample."
},
{
"code": null,
"e": 4857,
"s": 4828,
"text": "n is the size of the sample."
},
{
"code": null,
"e": 5045,
"s": 4857,
"text": "Each line in the figure above is one such experiment where the dot signifies the sample mean, and the line signifies the range. The dotted line in this figure is the true population mean."
},
{
"code": null,
"e": 5182,
"s": 5045,
"text": "See how some of these intervals donβt contain the true population mean, and almost all of them(95%) do include the true population mean."
},
{
"code": null,
"e": 5316,
"s": 5182,
"text": "As we said, Z is the no of standard deviations away from the sample mean(1.96 for 95%, 2.576 for 99%) β level of confidence you want."
},
{
"code": null,
"e": 5507,
"s": 5316,
"text": "You can go for any arbitrary level of confidence. Say, for example, you want 90% confidence. You can get that by using the idea that the shaded area inside the normal curve needs to be 0.90."
},
{
"code": null,
"e": 5669,
"s": 5507,
"text": "import scipy.stats as stp = 0.9 + (1-0.9)/2Z = st.norm.ppf(p, loc=0, scale=1)print(Z)----------------------------------------------------------1.6448536269514722"
},
{
"code": null,
"e": 6017,
"s": 5669,
"text": "If you want to learn more about hypothesis testing, confidence intervals, and statistical inference methods for numerical and categorical data, Mine CΜ§etinkaya-Rundel teaches Inferential Statistics course on coursera, and it cannot get simpler than this one. She is a great instructor and explains the fundamentals of Statistical inference nicely."
},
{
"code": null,
"e": 6280,
"s": 6017,
"text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz"
}
] |
How to get the width of scroll bar using JavaScript ? - GeeksforGeeks
|
05 Sep, 2019
Given an HTML document and the task is to get the width of the scrollbar using JavaScript. There are two different approach to solve this problem which are discussed below:
Approach 1:
Create an element (div) containing scrollbar.
OffsetWidth defines the width of an element + scrollbar width.
ClientWidth defines the width of an element.
So scrollbar can be defined as width = offsetWidth β clientWidth.
Example 1: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to get the width of scroll bar using JavaScript ? </title> <style> body { text-align:center; } h1 { color:green; } #div { width:200px; height:150px; overflow:auto; margin:auto; text-align:justify; border:1px solid black; } #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p id = "GFG_UP"></p> <div id="div"> JavaScript has stormed the web technology and nowadays small software ventures to fortune 500, all are using node js for web apps. Recently wordpress.com has rewritten its dashboard in javascript, paypal also chose to rewrite some of its components in java script. Be it google/twitter/facebook, javascript is important for everyone. It is used in applications like single page applications, Geolocation APIs, net advertisements etc. </div> <br> <button onclick = "GFG_FUN()"> click here </button> <p id = "GFG_DOWN"></p> <script> var element = document.getElementById('div'); var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to get " + "the width of the scrollbar."; function GFG_FUN() { el_down.innerHTML = element.offsetWidth - element.clientWidth + "px"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Create an outer div element.
Create a div inside outer div, call it inner div.
Subtract the width of inner div from the outer div to get the scrollbar width.
Example 2: This example implements the above approach.
<!DOCTYPE HTML> <html> <head> <title> How to get the width of scroll bar using JavaScript ? </title> <style> body { text-align:center; } h1 { color:green; } .outer { width:200px; height:150px; overflow-y:auto; margin:auto; text-align:justify; border:1px solid black; } #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p id = "GFG_UP"></p> <div class="outer"> <div class="inner"> JavaScript has stormed the web technology and nowadays small software ventures to fortune 500, all are using node js for web apps. Recently wordpress.com has rewritten its dashboard in javascript, paypal also chose to rewrite some of its components in java script. Be it google/twitter/facebook, javascript is important for everyone. It is used in applications like single page applications, Geolocation APIs, net advertisements etc. </div> </div> <br> <button onclick = "GFG_FUN()"> click here </button> <p id = "GFG_DOWN"></p> <script> var element = document.getElementById('div'); var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to get " + "the width of the scrollbar."; function GFG_FUN() { var child = document.querySelector(".inner"); var scroll = child.parentNode.offsetWidth - child.offsetWidth; el_down.innerHTML = scroll + "px"; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25082,
"s": 24909,
"text": "Given an HTML document and the task is to get the width of the scrollbar using JavaScript. There are two different approach to solve this problem which are discussed below:"
},
{
"code": null,
"e": 25094,
"s": 25082,
"text": "Approach 1:"
},
{
"code": null,
"e": 25140,
"s": 25094,
"text": "Create an element (div) containing scrollbar."
},
{
"code": null,
"e": 25203,
"s": 25140,
"text": "OffsetWidth defines the width of an element + scrollbar width."
},
{
"code": null,
"e": 25248,
"s": 25203,
"text": "ClientWidth defines the width of an element."
},
{
"code": null,
"e": 25314,
"s": 25248,
"text": "So scrollbar can be defined as width = offsetWidth β clientWidth."
},
{
"code": null,
"e": 25369,
"s": 25314,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the width of scroll bar using JavaScript ? </title> <style> body { text-align:center; } h1 { color:green; } #div { width:200px; height:150px; overflow:auto; margin:auto; text-align:justify; border:1px solid black; } #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p id = \"GFG_UP\"></p> <div id=\"div\"> JavaScript has stormed the web technology and nowadays small software ventures to fortune 500, all are using node js for web apps. Recently wordpress.com has rewritten its dashboard in javascript, paypal also chose to rewrite some of its components in java script. Be it google/twitter/facebook, javascript is important for everyone. It is used in applications like single page applications, Geolocation APIs, net advertisements etc. </div> <br> <button onclick = \"GFG_FUN()\"> click here </button> <p id = \"GFG_DOWN\"></p> <script> var element = document.getElementById('div'); var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to get \" + \"the width of the scrollbar.\"; function GFG_FUN() { el_down.innerHTML = element.offsetWidth - element.clientWidth + \"px\"; } </script> </body> </html>",
"e": 27229,
"s": 25369,
"text": null
},
{
"code": null,
"e": 27237,
"s": 27229,
"text": "Output:"
},
{
"code": null,
"e": 27268,
"s": 27237,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27298,
"s": 27268,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27310,
"s": 27298,
"text": "Approach 2:"
},
{
"code": null,
"e": 27339,
"s": 27310,
"text": "Create an outer div element."
},
{
"code": null,
"e": 27389,
"s": 27339,
"text": "Create a div inside outer div, call it inner div."
},
{
"code": null,
"e": 27468,
"s": 27389,
"text": "Subtract the width of inner div from the outer div to get the scrollbar width."
},
{
"code": null,
"e": 27523,
"s": 27468,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the width of scroll bar using JavaScript ? </title> <style> body { text-align:center; } h1 { color:green; } .outer { width:200px; height:150px; overflow-y:auto; margin:auto; text-align:justify; border:1px solid black; } #GFG_UP { font-size: 17px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p id = \"GFG_UP\"></p> <div class=\"outer\"> <div class=\"inner\"> JavaScript has stormed the web technology and nowadays small software ventures to fortune 500, all are using node js for web apps. Recently wordpress.com has rewritten its dashboard in javascript, paypal also chose to rewrite some of its components in java script. Be it google/twitter/facebook, javascript is important for everyone. It is used in applications like single page applications, Geolocation APIs, net advertisements etc. </div> </div> <br> <button onclick = \"GFG_FUN()\"> click here </button> <p id = \"GFG_DOWN\"></p> <script> var element = document.getElementById('div'); var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to get \" + \"the width of the scrollbar.\"; function GFG_FUN() { var child = document.querySelector(\".inner\"); var scroll = child.parentNode.offsetWidth - child.offsetWidth; el_down.innerHTML = scroll + \"px\"; } </script> </body> </html>",
"e": 29539,
"s": 27523,
"text": null
},
{
"code": null,
"e": 29547,
"s": 29539,
"text": "Output:"
},
{
"code": null,
"e": 29578,
"s": 29547,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29608,
"s": 29578,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29619,
"s": 29608,
"text": "JavaScript"
},
{
"code": null,
"e": 29636,
"s": 29619,
"text": "Web Technologies"
},
{
"code": null,
"e": 29663,
"s": 29636,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29761,
"s": 29663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29770,
"s": 29761,
"text": "Comments"
},
{
"code": null,
"e": 29783,
"s": 29770,
"text": "Old Comments"
},
{
"code": null,
"e": 29844,
"s": 29783,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29885,
"s": 29844,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29925,
"s": 29885,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29979,
"s": 29925,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30041,
"s": 29979,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 30097,
"s": 30041,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30130,
"s": 30097,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30192,
"s": 30130,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30235,
"s": 30192,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C/C++ For loop with Examples - GeeksforGeeks
|
22 Nov, 2019
Loops in C/C++ come into use when we need to repeatedly execute a block of statements.
For loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
The various parts of the For loop are:
Initialization Expression: In this expression we have to initialize the loop counter to some value.Example:int i=1;Condition: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop.Example:i <= 10Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;
Initialization Expression: In this expression we have to initialize the loop counter to some value.Example:int i=1;
int i=1;
Condition: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop.Example:i <= 10
i <= 10
Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;
i++;
How does a For loop executes?
Control falls into the for loop. Initialization is doneThe flow jumps to ConditionCondition is tested.If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.The flow goes to the UpdationUpdation takes place and the flow goes to Step 3 againThe for loop has ended and the flow has gone outside.
Control falls into the for loop. Initialization is done
The flow jumps to Condition
Condition is tested.If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop
If Condition yields true, the flow goes into the Body
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
The flow goes to the Updation
Updation takes place and the flow goes to Step 3 again
The for loop has ended and the flow has gone outside.
Flow chart for loop (For Control Flow):
Example 1: This program will try to print βHello Worldβ 5 times. The program will execute in the following manner:
C
C++
// C program to illustrate for loop #include <stdio.h> int main(){ int i = 0; // Writing a for loop // to print Hello World 5 times for (i = 1; i <= 5; i++) { printf("Hello World\n"); } return 0;}
// C++ program to illustrate for loop #include <iostream>using namespace std; int main(){ // Writing a for loop // to print Hello World 5 times for (int i = 1; i <= 5; i++) { cout << "Hello World\n"; } return 0;}
Hello World
Hello World
Hello World
Hello World
Hello World
Dry-Running Example 1:
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 <= 5 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 <= 5 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 <= 5 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 <= 5 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 <= 5 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 <= 5 yields false.
9. Flow goes outside the loop to return 0
Example 2:
C
C++
// C program to illustrate for loop #include <stdio.h> int main(){ int i = 0; // Writing a for loop // to print odd numbers upto N for (i = 1; i <= 10; i += 2) { printf("%d\n", i); } return 0;}
// C++ program to illustrate for loop #include <iostream>using namespace std; int main(){ int i = 0; // Writing a for loop // to print odd numbers upto N for (i = 1; i <= 10; i += 2) { cout << i << "\n"; } return 0;}
1
3
5
7
9
Related Articles:
Loops in C and C++C/C++ while loop with ExamplesC/C++ do while loop with ExamplesDifference between while and do-while loop in C, C++, JavaDifference between for and while loop in C, C++, Java
Loops in C and C++
C/C++ while loop with Examples
C/C++ do while loop with Examples
Difference between while and do-while loop in C, C++, Java
Difference between for and while loop in C, C++, Java
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 24319,
"s": 24232,
"text": "Loops in C/C++ come into use when we need to repeatedly execute a block of statements."
},
{
"code": null,
"e": 24510,
"s": 24319,
"text": "For loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line."
},
{
"code": null,
"e": 24518,
"s": 24510,
"text": "Syntax:"
},
{
"code": null,
"e": 24640,
"s": 24518,
"text": "for (initialization expr; test expr; update expr)\n{ \n // body of the loop\n // statements we want to execute\n}\n"
},
{
"code": null,
"e": 24679,
"s": 24640,
"text": "The various parts of the For loop are:"
},
{
"code": null,
"e": 25151,
"s": 24679,
"text": "Initialization Expression: In this expression we have to initialize the loop counter to some value.Example:int i=1;Condition: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop.Example:i <= 10Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;"
},
{
"code": null,
"e": 25267,
"s": 25151,
"text": "Initialization Expression: In this expression we have to initialize the loop counter to some value.Example:int i=1;"
},
{
"code": null,
"e": 25276,
"s": 25267,
"text": "int i=1;"
},
{
"code": null,
"e": 25501,
"s": 25276,
"text": "Condition: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression. Otherwise, we will exit from the for loop.Example:i <= 10"
},
{
"code": null,
"e": 25509,
"s": 25501,
"text": "i <= 10"
},
{
"code": null,
"e": 25642,
"s": 25509,
"text": "Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value.Example:i++;"
},
{
"code": null,
"e": 25647,
"s": 25642,
"text": "i++;"
},
{
"code": null,
"e": 25677,
"s": 25647,
"text": "How does a For loop executes?"
},
{
"code": null,
"e": 26082,
"s": 25677,
"text": "Control falls into the for loop. Initialization is doneThe flow jumps to ConditionCondition is tested.If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loopThe statements inside the body of the loop get executed.The flow goes to the UpdationUpdation takes place and the flow goes to Step 3 againThe for loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 26138,
"s": 26082,
"text": "Control falls into the for loop. Initialization is done"
},
{
"code": null,
"e": 26166,
"s": 26138,
"text": "The flow jumps to Condition"
},
{
"code": null,
"e": 26297,
"s": 26166,
"text": "Condition is tested.If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 26408,
"s": 26297,
"text": "If Condition yields true, the flow goes into the BodyIf Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 26462,
"s": 26408,
"text": "If Condition yields true, the flow goes into the Body"
},
{
"code": null,
"e": 26520,
"s": 26462,
"text": "If Condition yields false, the flow goes outside the loop"
},
{
"code": null,
"e": 26577,
"s": 26520,
"text": "The statements inside the body of the loop get executed."
},
{
"code": null,
"e": 26607,
"s": 26577,
"text": "The flow goes to the Updation"
},
{
"code": null,
"e": 26662,
"s": 26607,
"text": "Updation takes place and the flow goes to Step 3 again"
},
{
"code": null,
"e": 26716,
"s": 26662,
"text": "The for loop has ended and the flow has gone outside."
},
{
"code": null,
"e": 26756,
"s": 26716,
"text": "Flow chart for loop (For Control Flow):"
},
{
"code": null,
"e": 26871,
"s": 26756,
"text": "Example 1: This program will try to print βHello Worldβ 5 times. The program will execute in the following manner:"
},
{
"code": null,
"e": 26873,
"s": 26871,
"text": "C"
},
{
"code": null,
"e": 26877,
"s": 26873,
"text": "C++"
},
{
"code": "// C program to illustrate for loop #include <stdio.h> int main(){ int i = 0; // Writing a for loop // to print Hello World 5 times for (i = 1; i <= 5; i++) { printf(\"Hello World\\n\"); } return 0;}",
"e": 27105,
"s": 26877,
"text": null
},
{
"code": "// C++ program to illustrate for loop #include <iostream>using namespace std; int main(){ // Writing a for loop // to print Hello World 5 times for (int i = 1; i <= 5; i++) { cout << \"Hello World\\n\"; } return 0;}",
"e": 27346,
"s": 27105,
"text": null
},
{
"code": null,
"e": 27407,
"s": 27346,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World\n"
},
{
"code": null,
"e": 27430,
"s": 27407,
"text": "Dry-Running Example 1:"
},
{
"code": null,
"e": 28194,
"s": 27430,
"text": "1. Program starts.\n2. i is initialized with value 1.\n3. Condition is checked. 1 <= 5 yields true.\n 3.a) \"Hello World\" gets printed 1st time.\n 3.b) Updation is done. Now i = 2.\n4. Condition is checked. 2 <= 5 yields true.\n 4.a) \"Hello World\" gets printed 2nd time.\n 4.b) Updation is done. Now i = 3.\n5. Condition is checked. 3 <= 5 yields true.\n 5.a) \"Hello World\" gets printed 3rd time\n 5.b) Updation is done. Now i = 4.\n6. Condition is checked. 4 <= 5 yields true.\n 6.a) \"Hello World\" gets printed 4th time\n 6.b) Updation is done. Now i = 5.\n7. Condition is checked. 5 <= 5 yields true.\n 7.a) \"Hello World\" gets printed 5th time\n 7.b) Updation is done. Now i = 6.\n8. Condition is checked. 6 <= 5 yields false.\n9. Flow goes outside the loop to return 0\n"
},
{
"code": null,
"e": 28205,
"s": 28194,
"text": "Example 2:"
},
{
"code": null,
"e": 28207,
"s": 28205,
"text": "C"
},
{
"code": null,
"e": 28211,
"s": 28207,
"text": "C++"
},
{
"code": "// C program to illustrate for loop #include <stdio.h> int main(){ int i = 0; // Writing a for loop // to print odd numbers upto N for (i = 1; i <= 10; i += 2) { printf(\"%d\\n\", i); } return 0;}",
"e": 28436,
"s": 28211,
"text": null
},
{
"code": "// C++ program to illustrate for loop #include <iostream>using namespace std; int main(){ int i = 0; // Writing a for loop // to print odd numbers upto N for (i = 1; i <= 10; i += 2) { cout << i << \"\\n\"; } return 0;}",
"e": 28684,
"s": 28436,
"text": null
},
{
"code": null,
"e": 28695,
"s": 28684,
"text": "1\n3\n5\n7\n9\n"
},
{
"code": null,
"e": 28713,
"s": 28695,
"text": "Related Articles:"
},
{
"code": null,
"e": 28906,
"s": 28713,
"text": "Loops in C and C++C/C++ while loop with ExamplesC/C++ do while loop with ExamplesDifference between while and do-while loop in C, C++, JavaDifference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 28925,
"s": 28906,
"text": "Loops in C and C++"
},
{
"code": null,
"e": 28956,
"s": 28925,
"text": "C/C++ while loop with Examples"
},
{
"code": null,
"e": 28990,
"s": 28956,
"text": "C/C++ do while loop with Examples"
},
{
"code": null,
"e": 29049,
"s": 28990,
"text": "Difference between while and do-while loop in C, C++, Java"
},
{
"code": null,
"e": 29103,
"s": 29049,
"text": "Difference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 29114,
"s": 29103,
"text": "C Language"
},
{
"code": null,
"e": 29118,
"s": 29114,
"text": "C++"
},
{
"code": null,
"e": 29137,
"s": 29118,
"text": "School Programming"
},
{
"code": null,
"e": 29141,
"s": 29137,
"text": "CPP"
},
{
"code": null,
"e": 29239,
"s": 29141,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29277,
"s": 29239,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29297,
"s": 29277,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29323,
"s": 29297,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29345,
"s": 29323,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29386,
"s": 29345,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29404,
"s": 29386,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29450,
"s": 29404,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29469,
"s": 29450,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29512,
"s": 29469,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Five Cool Python Looping Tips. 5 Tips to help your iterative looping... | by Emmett Boudreau | Towards Data Science
|
For loops are likely to be one of the first concepts that a new Python programmer will pick up. This is for good reason because for loops can do a lot of things with data without getting crafty. However, often it can be easy to get your mind stuck in the world of simple iteration and not take advantage of some of the more efficient and concise methods of iteration and tricks to apply to for loops. Using these tricks can not only make your for loops faster, but can also make your code more concise and open up a new door for potential looping opportunities in Python.
One tool I have found really valuable in my experience is the ability to loop through two arrays at once. This is something noticeably more difficult in other languages, and something I really appreciate the ease of in Python. In order to loop through two arrays at once, we simply use the zip() method.
for first,second in zip(array1,array2): print(first) print(second)
A good example to demonstrate this is by counting with a list of even and a list of odd integers:
odds = [1,3,5,7,9]evens = [2,4,6,8,10]for oddnum, evennum in zip(odds,evens): print(oddnum) print(evennum)
And our output would be:
12345678910
Though it might seem rather basic, there are a lot of interesting things you can do with a classic C style for loop.
for i in range(10): print(i) if i == 3: i.update(7)
The C lovers among us might be thinking that this isnβt necessarily a C-style for loop, but this is the closest you can get without writing your own iteration method. Fortunately, I enjoy wasting my time, so I decided to write a new iterator to get as close to a classic C loop as possible:
class forrange: def __init__(self, startOrStop, stop=None, step=1): if step == 0: raise ValueError('forrange step argument must not be zero') if not isinstance(startOrStop, int): raise TypeError('forrange startOrStop argument must be an int') if stop is not None and not isinstance(stop, int): raise TypeError('forrange stop argument must be an int') if stop is None: self.start = 0 self.stop = startOrStop self.step = step else: self.start = startOrStop self.stop = stop self.step = step def __iter__(self): return self.foriterator(self.start, self.stop, self.step) class foriterator: def __init__(self, start, stop, step): self.currentValue = None self.nextValue = start self.stop = stop self.step = step def __iter__(self): return self def next(self): if self.step > 0 and self.nextValue >= self.stop: raise StopIteration if self.step < 0 and self.nextValue <= self.stop: raise StopIteration self.currentValue = forrange.forvalue(self.nextValue, self) self.nextValue += self.step return self.currentValue class forvalue(int): def __new__(cls, value, iterator): value = super(forrange.forvalue, cls).__new__(cls, value) value.iterator = iterator return value def update(self, value): if not isinstance(self, int): raise TypeError('forvalue.update value must be an int') if self == self.iterator.currentValue: self.iterator.nextValue = value + self.iterator.step
The enumerate method in Python allows Python to number list indices as they are coming out of the array. To demonstrate this, Iβll make a three-element list:
l = [5,10,15]
Now we can access our array indices like this:
l[1]10l[0]5l[2]15
When enumerating through these lists, we will get the index position of the dim, along with the dim, smashed together into a new variable. Notice the type of the new variable.
Python will automatically put these indices into a tuple, which I think is strange. I would certainly prefer to receive the results in a one-element Python dictionary. Fortunately, we could always turn our enumerates into a Python dictionary with Pythonβs
β easy as Pyβ
type assertion!
data = dict(enumerate(l))
Which would give us:
>>> data{0: 5, 1: 10, 2: 15}
The sort method is an essential method for anyone dealing with copious amount of data, as a Data Scientist often should. Sorting works how expected, with strings being sorted in alphabetical order from the letter A to the letter B, and sorting integers and doubles ascending from -β. An important note to make about this function is that it will not work with lists containing strings and integers or floats.
l = [15,6,1,8]for i in sorted(l): print(i)16815
We can also do the inverse by setting the reverse parameter to False:
for i in sorted(l,reverse = True): print(i)15861
And for the last parameter available to us, we can use a key. A key is a function that is applied to each dim inside of a given loop. For this, I like to use lambda, which will create an anonymous, but still callable, function.
l.sort(key=lambda s: s[::-1])
A function that will definitely help the performance side of things when working with heaps of data is the filter function. The filter function does exactly what youβd expect, and filters out data prior to iterating over it. This can be useful when you only want to have an effect on data in a certain range without ever having to apply a condition to it.
people = [{"name": "John", "id": 1}, {"name": "Mike", "id": 4}, {"name": "Sandra", "id": 2}, {"name": "Jennifer", "id": 3}]for person in filter(lambda i: i["id"] % 2 == 0, people):... print(person)... {'name': 'Mike', 'id': 4}{'name': 'Sandra', 'id': 2}
Ideally, applying these methods to your Python code will make it not only more concise, but also most likely faster. Taking advantage of these methods will give you iteration superpowers and make it far easier to go through massive amounts of data with iteration, which is sometimes not avoidable.
|
[
{
"code": null,
"e": 743,
"s": 171,
"text": "For loops are likely to be one of the first concepts that a new Python programmer will pick up. This is for good reason because for loops can do a lot of things with data without getting crafty. However, often it can be easy to get your mind stuck in the world of simple iteration and not take advantage of some of the more efficient and concise methods of iteration and tricks to apply to for loops. Using these tricks can not only make your for loops faster, but can also make your code more concise and open up a new door for potential looping opportunities in Python."
},
{
"code": null,
"e": 1047,
"s": 743,
"text": "One tool I have found really valuable in my experience is the ability to loop through two arrays at once. This is something noticeably more difficult in other languages, and something I really appreciate the ease of in Python. In order to loop through two arrays at once, we simply use the zip() method."
},
{
"code": null,
"e": 1120,
"s": 1047,
"text": "for first,second in zip(array1,array2): print(first) print(second)"
},
{
"code": null,
"e": 1218,
"s": 1120,
"text": "A good example to demonstrate this is by counting with a list of even and a list of odd integers:"
},
{
"code": null,
"e": 1331,
"s": 1218,
"text": "odds = [1,3,5,7,9]evens = [2,4,6,8,10]for oddnum, evennum in zip(odds,evens): print(oddnum) print(evennum)"
},
{
"code": null,
"e": 1356,
"s": 1331,
"text": "And our output would be:"
},
{
"code": null,
"e": 1368,
"s": 1356,
"text": "12345678910"
},
{
"code": null,
"e": 1485,
"s": 1368,
"text": "Though it might seem rather basic, there are a lot of interesting things you can do with a classic C style for loop."
},
{
"code": null,
"e": 1550,
"s": 1485,
"text": "for i in range(10): print(i) if i == 3: i.update(7)"
},
{
"code": null,
"e": 1841,
"s": 1550,
"text": "The C lovers among us might be thinking that this isnβt necessarily a C-style for loop, but this is the closest you can get without writing your own iteration method. Fortunately, I enjoy wasting my time, so I decided to write a new iterator to get as close to a classic C loop as possible:"
},
{
"code": null,
"e": 3607,
"s": 1841,
"text": "class forrange: def __init__(self, startOrStop, stop=None, step=1): if step == 0: raise ValueError('forrange step argument must not be zero') if not isinstance(startOrStop, int): raise TypeError('forrange startOrStop argument must be an int') if stop is not None and not isinstance(stop, int): raise TypeError('forrange stop argument must be an int') if stop is None: self.start = 0 self.stop = startOrStop self.step = step else: self.start = startOrStop self.stop = stop self.step = step def __iter__(self): return self.foriterator(self.start, self.stop, self.step) class foriterator: def __init__(self, start, stop, step): self.currentValue = None self.nextValue = start self.stop = stop self.step = step def __iter__(self): return self def next(self): if self.step > 0 and self.nextValue >= self.stop: raise StopIteration if self.step < 0 and self.nextValue <= self.stop: raise StopIteration self.currentValue = forrange.forvalue(self.nextValue, self) self.nextValue += self.step return self.currentValue class forvalue(int): def __new__(cls, value, iterator): value = super(forrange.forvalue, cls).__new__(cls, value) value.iterator = iterator return value def update(self, value): if not isinstance(self, int): raise TypeError('forvalue.update value must be an int') if self == self.iterator.currentValue: self.iterator.nextValue = value + self.iterator.step"
},
{
"code": null,
"e": 3765,
"s": 3607,
"text": "The enumerate method in Python allows Python to number list indices as they are coming out of the array. To demonstrate this, Iβll make a three-element list:"
},
{
"code": null,
"e": 3779,
"s": 3765,
"text": "l = [5,10,15]"
},
{
"code": null,
"e": 3826,
"s": 3779,
"text": "Now we can access our array indices like this:"
},
{
"code": null,
"e": 3844,
"s": 3826,
"text": "l[1]10l[0]5l[2]15"
},
{
"code": null,
"e": 4020,
"s": 3844,
"text": "When enumerating through these lists, we will get the index position of the dim, along with the dim, smashed together into a new variable. Notice the type of the new variable."
},
{
"code": null,
"e": 4276,
"s": 4020,
"text": "Python will automatically put these indices into a tuple, which I think is strange. I would certainly prefer to receive the results in a one-element Python dictionary. Fortunately, we could always turn our enumerates into a Python dictionary with Pythonβs"
},
{
"code": null,
"e": 4290,
"s": 4276,
"text": "β easy as Pyβ"
},
{
"code": null,
"e": 4306,
"s": 4290,
"text": "type assertion!"
},
{
"code": null,
"e": 4332,
"s": 4306,
"text": "data = dict(enumerate(l))"
},
{
"code": null,
"e": 4353,
"s": 4332,
"text": "Which would give us:"
},
{
"code": null,
"e": 4382,
"s": 4353,
"text": ">>> data{0: 5, 1: 10, 2: 15}"
},
{
"code": null,
"e": 4791,
"s": 4382,
"text": "The sort method is an essential method for anyone dealing with copious amount of data, as a Data Scientist often should. Sorting works how expected, with strings being sorted in alphabetical order from the letter A to the letter B, and sorting integers and doubles ascending from -β. An important note to make about this function is that it will not work with lists containing strings and integers or floats."
},
{
"code": null,
"e": 4842,
"s": 4791,
"text": "l = [15,6,1,8]for i in sorted(l): print(i)16815"
},
{
"code": null,
"e": 4912,
"s": 4842,
"text": "We can also do the inverse by setting the reverse parameter to False:"
},
{
"code": null,
"e": 4964,
"s": 4912,
"text": "for i in sorted(l,reverse = True): print(i)15861"
},
{
"code": null,
"e": 5192,
"s": 4964,
"text": "And for the last parameter available to us, we can use a key. A key is a function that is applied to each dim inside of a given loop. For this, I like to use lambda, which will create an anonymous, but still callable, function."
},
{
"code": null,
"e": 5222,
"s": 5192,
"text": "l.sort(key=lambda s: s[::-1])"
},
{
"code": null,
"e": 5578,
"s": 5222,
"text": "A function that will definitely help the performance side of things when working with heaps of data is the filter function. The filter function does exactly what youβd expect, and filters out data prior to iterating over it. This can be useful when you only want to have an effect on data in a certain range without ever having to apply a condition to it."
},
{
"code": null,
"e": 5836,
"s": 5578,
"text": "people = [{\"name\": \"John\", \"id\": 1}, {\"name\": \"Mike\", \"id\": 4}, {\"name\": \"Sandra\", \"id\": 2}, {\"name\": \"Jennifer\", \"id\": 3}]for person in filter(lambda i: i[\"id\"] % 2 == 0, people):... print(person)... {'name': 'Mike', 'id': 4}{'name': 'Sandra', 'id': 2}"
}
] |
Python | Convert column to separate elements in list of lists - GeeksforGeeks
|
11 Jun, 2021
There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Letβs discuss certain ways in which this action can be performed.Method #1 : Using list slicing and list comprehension The functionality of list slicing and comprehension can be clubbed to perform the particular task of extracting a column from a list and then it can be added as new element using list comprehension.
Python3
# Python3 code to demonstrate # column to separate elements in list of lists# using list slicing and list comprehension # initializing list of listtest_list = [[1, 3, 4], [6, 2, 8], [9, 10, 5]] # printing original listprint ("The original list is : " + str(test_list)) # using list slicing and list comprehension# column to separate elements in list of listsres = [i for nest_list in [[j[1 : ], [j[0]]] for j in test_list] for i in nest_list] # printing resultprint ("The list after column shift is : " + str(res))
The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]
Method #2 : Using itertools.chain() + list comprehension + list slicing The above method can be improved by inducing the concept of element chaining and reduce the overhead of the list comprehension and reducing the time taken to execute this particular task.
Python3
# Python3 code to demonstrate # column to separate elements in list of lists# using itertools.chain()+ list comprehension + list slicingfrom itertools import chain # initializing list of listtest_list = [[1, 3, 4], [6, 2, 8], [9, 10, 5]] # printing original listprint ("The original list is : " + str(test_list)) # using itertools.chain() + list comprehension + list slicing# column to separate elements in list of listsres = list(chain(*[list((sub[1: ], [sub[0]])) for sub in test_list])) # printing resultprint ("The list after column shift is : " + str(res))
The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]
arorakashish0911
Python list-programs
Python
Python Programs
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24540,
"s": 24512,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 25062,
"s": 24540,
"text": "There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Letβs discuss certain ways in which this action can be performed.Method #1 : Using list slicing and list comprehension The functionality of list slicing and comprehension can be clubbed to perform the particular task of extracting a column from a list and then it can be added as new element using list comprehension. "
},
{
"code": null,
"e": 25070,
"s": 25062,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate # column to separate elements in list of lists# using list slicing and list comprehension # initializing list of listtest_list = [[1, 3, 4], [6, 2, 8], [9, 10, 5]] # printing original listprint (\"The original list is : \" + str(test_list)) # using list slicing and list comprehension# column to separate elements in list of listsres = [i for nest_list in [[j[1 : ], [j[0]]] for j in test_list] for i in nest_list] # printing resultprint (\"The list after column shift is : \" + str(res))",
"e": 25617,
"s": 25070,
"text": null
},
{
"code": null,
"e": 25750,
"s": 25617,
"text": "The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]\nThe list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]\n"
},
{
"code": null,
"e": 26012,
"s": 25750,
"text": " Method #2 : Using itertools.chain() + list comprehension + list slicing The above method can be improved by inducing the concept of element chaining and reduce the overhead of the list comprehension and reducing the time taken to execute this particular task. "
},
{
"code": null,
"e": 26020,
"s": 26012,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate # column to separate elements in list of lists# using itertools.chain()+ list comprehension + list slicingfrom itertools import chain # initializing list of listtest_list = [[1, 3, 4], [6, 2, 8], [9, 10, 5]] # printing original listprint (\"The original list is : \" + str(test_list)) # using itertools.chain() + list comprehension + list slicing# column to separate elements in list of listsres = list(chain(*[list((sub[1: ], [sub[0]])) for sub in test_list])) # printing resultprint (\"The list after column shift is : \" + str(res))",
"e": 26627,
"s": 26020,
"text": null
},
{
"code": null,
"e": 26760,
"s": 26627,
"text": "The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]\nThe list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]\n"
},
{
"code": null,
"e": 26777,
"s": 26760,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26798,
"s": 26777,
"text": "Python list-programs"
},
{
"code": null,
"e": 26805,
"s": 26798,
"text": "Python"
},
{
"code": null,
"e": 26821,
"s": 26805,
"text": "Python Programs"
},
{
"code": null,
"e": 26919,
"s": 26821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26937,
"s": 26919,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26972,
"s": 26937,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27004,
"s": 26972,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27046,
"s": 27004,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27072,
"s": 27046,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27094,
"s": 27072,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27137,
"s": 27094,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27176,
"s": 27137,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27222,
"s": 27176,
"text": "Python | Split string into list of characters"
}
] |
Adding Colors to Charts in R Programming - GeeksforGeeks
|
09 Dec, 2021
R Programming language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R.
There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram, pie chart, scatter graph, etc. We can visually enhance our plots and make them more attractive through colors. The col graphical parameter is brought into use for this purpose. The desired colorβs name can be expressed in the string.
Syntax: barplot( A, col=color_name)
Example:
R
# Creating a listtemp<-c(5, 10, 15, 20, 25) # Barplot with default colorbarplot(temp, main ="By default") # Barplot with green colorbarplot(temp, col ="green", main ="With coloring")
Output:
There are a variety of 657 colors present in the R language for better data presentation. Through colors() function one can learn about all the vibrant colors present in R. The names of colors displayed are arranged alphabetically (except the color βwhiteβ which is the first color displayed).
For using color in code, either its name is used or its order number is used.
Example:
R
# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = colors()[655], main ="With coloring")
Output:
Though remembering color names is easier, at times colors are defined by the unique hexadecimal numbers which have been already predefined for each color in R. The six-digit length of the Hexadecimal number is in the format #RRGGBB.
The letters in this format signify:
RR β Red
GG β Green
BB β Blue
And the color codes of Red, Green, and Blue ranges from 00 to FF. Then the color codes of Red, Green, and Blue will form a six-digit length of the Hexadecimal number which represents a color formed by mixing all the defined shades.
Hence three basic pure shades can be written as:
#FF0000 RED
#00FF00 GREEN
#0000FF Blue
Shade, when no color is present, is white(000000). Shade, when all the colors are present, is black(FFFFFF).
The function RGB specifies the shade of the color red, green, and blue between 0 and 1. Further the specified shades of these three basic components will be mixed to form a new shade. The shade of the color red, green, and blue can also be specified between 0 and 255. But there will be an added argument max=255 while using this range.
The function rgb() will return the corresponding hexadecimal code of the specified shade.
R
rgb (0.9, 0.7, 0.8)rgb(5, 0, 70, max = 255)
Output:
[1] "#E6B3CC"
[1] "#050046"
R
# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = rgb(5, 0, 70, max = 255), main ="With coloring")
Output:
Python3
# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = rgb (0.9, 0.7, 0.8), main ="With coloring")
Output:
What if we require to represent every bar of the barplot with various colors? In that case, a vector of colors is created and this is also known as color cycling in R.
R
temp<-c(5, 10, 15, 20, 25)barplot(temp, col = c("# F50629", "# 00FFAA", "# AAFF33", "# 336622", "# 5F2910"), main ="With 5 colors")
Output:
If the provided vectorβs length is less than the number of bars present in the barplot then the color vector is reused.
R
temp<-c(5, 10, 15, 20, 25)barplot(temp, col = c("# F50629", "# 00FFAA", "# AAFF33"), main ="With 3 colors")
Output:
The five inbuilt color palettes are provided in the R language for generating color vector easily and faster. They are:
rainbow()
terrain.colors()
heat.colors()
cm.colors()
topo.colors()
All the stated functions take the color vectorβs desired length as the parameter value. The function returns the hexadecimal code of the colors available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and 00 is transparent)
R
rainbow(5)heat.colors(5)terrain.colors(5)topo.colors(5)
Output:
[1] "#FF0000" "#CCFF00" "#00FF66" "#0066FF" "#CC00FF"
[1] "#FF0000" "#FF5500" "#FFAA00" "#FFFF00" "#FFFF80"
[1] "#00A600" "#E6E600" "#EAB64E" "#EEB99F" "#F2F2F2"
[1] "#4C00FF" "#004CFF" "#00E5FF" "#00FF4D" "#FFFF00"
R
temp<-c(5, 10, 15, 20, 25)barplot(temp, col = rainbow(5), main ="rainbow")
Output:
kumar_satyam
R-Charts
R-Graphs
R-plots
R-Statistics
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 26690,
"s": 26487,
"text": "R Programming language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R. "
},
{
"code": null,
"e": 27055,
"s": 26690,
"text": "There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram, pie chart, scatter graph, etc. We can visually enhance our plots and make them more attractive through colors. The col graphical parameter is brought into use for this purpose. The desired colorβs name can be expressed in the string. "
},
{
"code": null,
"e": 27091,
"s": 27055,
"text": "Syntax: barplot( A, col=color_name)"
},
{
"code": null,
"e": 27101,
"s": 27091,
"text": "Example: "
},
{
"code": null,
"e": 27103,
"s": 27101,
"text": "R"
},
{
"code": "# Creating a listtemp<-c(5, 10, 15, 20, 25) # Barplot with default colorbarplot(temp, main =\"By default\") # Barplot with green colorbarplot(temp, col =\"green\", main =\"With coloring\")",
"e": 27297,
"s": 27103,
"text": null
},
{
"code": null,
"e": 27306,
"s": 27297,
"text": "Output: "
},
{
"code": null,
"e": 27601,
"s": 27306,
"text": "There are a variety of 657 colors present in the R language for better data presentation. Through colors() function one can learn about all the vibrant colors present in R. The names of colors displayed are arranged alphabetically (except the color βwhiteβ which is the first color displayed). "
},
{
"code": null,
"e": 27679,
"s": 27601,
"text": "For using color in code, either its name is used or its order number is used."
},
{
"code": null,
"e": 27689,
"s": 27679,
"text": "Example: "
},
{
"code": null,
"e": 27691,
"s": 27689,
"text": "R"
},
{
"code": "# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = colors()[655], main =\"With coloring\")",
"e": 27818,
"s": 27691,
"text": null
},
{
"code": null,
"e": 27827,
"s": 27818,
"text": "Output: "
},
{
"code": null,
"e": 28061,
"s": 27827,
"text": "Though remembering color names is easier, at times colors are defined by the unique hexadecimal numbers which have been already predefined for each color in R. The six-digit length of the Hexadecimal number is in the format #RRGGBB. "
},
{
"code": null,
"e": 28098,
"s": 28061,
"text": "The letters in this format signify: "
},
{
"code": null,
"e": 28107,
"s": 28098,
"text": "RR β Red"
},
{
"code": null,
"e": 28118,
"s": 28107,
"text": "GG β Green"
},
{
"code": null,
"e": 28128,
"s": 28118,
"text": "BB β Blue"
},
{
"code": null,
"e": 28361,
"s": 28128,
"text": "And the color codes of Red, Green, and Blue ranges from 00 to FF. Then the color codes of Red, Green, and Blue will form a six-digit length of the Hexadecimal number which represents a color formed by mixing all the defined shades. "
},
{
"code": null,
"e": 28411,
"s": 28361,
"text": "Hence three basic pure shades can be written as: "
},
{
"code": null,
"e": 28423,
"s": 28411,
"text": "#FF0000 RED"
},
{
"code": null,
"e": 28437,
"s": 28423,
"text": "#00FF00 GREEN"
},
{
"code": null,
"e": 28450,
"s": 28437,
"text": "#0000FF Blue"
},
{
"code": null,
"e": 28559,
"s": 28450,
"text": "Shade, when no color is present, is white(000000). Shade, when all the colors are present, is black(FFFFFF)."
},
{
"code": null,
"e": 28896,
"s": 28559,
"text": "The function RGB specifies the shade of the color red, green, and blue between 0 and 1. Further the specified shades of these three basic components will be mixed to form a new shade. The shade of the color red, green, and blue can also be specified between 0 and 255. But there will be an added argument max=255 while using this range."
},
{
"code": null,
"e": 28986,
"s": 28896,
"text": "The function rgb() will return the corresponding hexadecimal code of the specified shade."
},
{
"code": null,
"e": 28988,
"s": 28986,
"text": "R"
},
{
"code": "rgb (0.9, 0.7, 0.8)rgb(5, 0, 70, max = 255)",
"e": 29032,
"s": 28988,
"text": null
},
{
"code": null,
"e": 29041,
"s": 29032,
"text": "Output: "
},
{
"code": null,
"e": 29069,
"s": 29041,
"text": "[1] \"#E6B3CC\"\n[1] \"#050046\""
},
{
"code": null,
"e": 29071,
"s": 29069,
"text": "R"
},
{
"code": "# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = rgb(5, 0, 70, max = 255), main =\"With coloring\")",
"e": 29209,
"s": 29071,
"text": null
},
{
"code": null,
"e": 29218,
"s": 29209,
"text": "Output: "
},
{
"code": null,
"e": 29226,
"s": 29218,
"text": "Python3"
},
{
"code": "# Creating a listtemp<-c(5, 10, 15, 20, 25) # Creating barplotbarplot(temp, col = rgb (0.9, 0.7, 0.8), main =\"With coloring\")",
"e": 29359,
"s": 29226,
"text": null
},
{
"code": null,
"e": 29368,
"s": 29359,
"text": "Output: "
},
{
"code": null,
"e": 29536,
"s": 29368,
"text": "What if we require to represent every bar of the barplot with various colors? In that case, a vector of colors is created and this is also known as color cycling in R."
},
{
"code": null,
"e": 29538,
"s": 29536,
"text": "R"
},
{
"code": "temp<-c(5, 10, 15, 20, 25)barplot(temp, col = c(\"# F50629\", \"# 00FFAA\", \"# AAFF33\", \"# 336622\", \"# 5F2910\"), main =\"With 5 colors\")",
"e": 29715,
"s": 29538,
"text": null
},
{
"code": null,
"e": 29723,
"s": 29715,
"text": "Output:"
},
{
"code": null,
"e": 29843,
"s": 29723,
"text": "If the provided vectorβs length is less than the number of bars present in the barplot then the color vector is reused."
},
{
"code": null,
"e": 29845,
"s": 29843,
"text": "R"
},
{
"code": "temp<-c(5, 10, 15, 20, 25)barplot(temp, col = c(\"# F50629\", \"# 00FFAA\", \"# AAFF33\"), main =\"With 3 colors\")",
"e": 29979,
"s": 29845,
"text": null
},
{
"code": null,
"e": 29987,
"s": 29979,
"text": "Output:"
},
{
"code": null,
"e": 30108,
"s": 29987,
"text": "The five inbuilt color palettes are provided in the R language for generating color vector easily and faster. They are: "
},
{
"code": null,
"e": 30118,
"s": 30108,
"text": "rainbow()"
},
{
"code": null,
"e": 30135,
"s": 30118,
"text": "terrain.colors()"
},
{
"code": null,
"e": 30149,
"s": 30135,
"text": "heat.colors()"
},
{
"code": null,
"e": 30161,
"s": 30149,
"text": "cm.colors()"
},
{
"code": null,
"e": 30175,
"s": 30161,
"text": "topo.colors()"
},
{
"code": null,
"e": 30486,
"s": 30175,
"text": "All the stated functions take the color vectorβs desired length as the parameter value. The function returns the hexadecimal code of the colors available. This hexadecimal code is of eight digits. This is because the last two digits specify the level of transparency (where FF is opaque and 00 is transparent) "
},
{
"code": null,
"e": 30488,
"s": 30486,
"text": "R"
},
{
"code": "rainbow(5)heat.colors(5)terrain.colors(5)topo.colors(5)",
"e": 30544,
"s": 30488,
"text": null
},
{
"code": null,
"e": 30553,
"s": 30544,
"text": "Output: "
},
{
"code": null,
"e": 30772,
"s": 30553,
"text": "[1] \"#FF0000\" \"#CCFF00\" \"#00FF66\" \"#0066FF\" \"#CC00FF\"\n\n[1] \"#FF0000\" \"#FF5500\" \"#FFAA00\" \"#FFFF00\" \"#FFFF80\"\n\n[1] \"#00A600\" \"#E6E600\" \"#EAB64E\" \"#EEB99F\" \"#F2F2F2\"\n\n[1] \"#4C00FF\" \"#004CFF\" \"#00E5FF\" \"#00FF4D\" \"#FFFF00\""
},
{
"code": null,
"e": 30774,
"s": 30772,
"text": "R"
},
{
"code": "temp<-c(5, 10, 15, 20, 25)barplot(temp, col = rainbow(5), main =\"rainbow\")",
"e": 30856,
"s": 30774,
"text": null
},
{
"code": null,
"e": 30864,
"s": 30856,
"text": "Output:"
},
{
"code": null,
"e": 30877,
"s": 30864,
"text": "kumar_satyam"
},
{
"code": null,
"e": 30886,
"s": 30877,
"text": "R-Charts"
},
{
"code": null,
"e": 30895,
"s": 30886,
"text": "R-Graphs"
},
{
"code": null,
"e": 30903,
"s": 30895,
"text": "R-plots"
},
{
"code": null,
"e": 30916,
"s": 30903,
"text": "R-Statistics"
},
{
"code": null,
"e": 30927,
"s": 30916,
"text": "R Language"
},
{
"code": null,
"e": 31025,
"s": 30927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31077,
"s": 31025,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31112,
"s": 31077,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31150,
"s": 31112,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31208,
"s": 31150,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31251,
"s": 31208,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31300,
"s": 31251,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 31317,
"s": 31300,
"text": "R - if statement"
},
{
"code": null,
"e": 31367,
"s": 31317,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31419,
"s": 31367,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Python | Scipy stats.hypsecant.ppf() method - GeeksforGeeks
|
10 Feb, 2020
With the help of stats.hypsecant.ppf() method, we can get the value of percentage point function which is inverse( cdf ) by using stats.hypsecant.ppf() method.
Syntax : stats.hypsecant.ppf(x, beta)Return : Return the value of percentage point function.
Example #1 :In this example we can see that by using stats.hypsecant.ppf() method, we are able to get the value of percentage point function by using this method.
# import hypsecantfrom scipy.stats import hypsecantbeta = 1 # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.3, beta) print(gfg)
Output :
0.3257245223731834
Example #2 :
# import hypsecantfrom scipy.stats import hypsecantbeta = 4 # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.9, beta) print(gfg)
Output :
5.842730034701113
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 25807,
"s": 25647,
"text": "With the help of stats.hypsecant.ppf() method, we can get the value of percentage point function which is inverse( cdf ) by using stats.hypsecant.ppf() method."
},
{
"code": null,
"e": 25900,
"s": 25807,
"text": "Syntax : stats.hypsecant.ppf(x, beta)Return : Return the value of percentage point function."
},
{
"code": null,
"e": 26063,
"s": 25900,
"text": "Example #1 :In this example we can see that by using stats.hypsecant.ppf() method, we are able to get the value of percentage point function by using this method."
},
{
"code": "# import hypsecantfrom scipy.stats import hypsecantbeta = 1 # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.3, beta) print(gfg)",
"e": 26203,
"s": 26063,
"text": null
},
{
"code": null,
"e": 26212,
"s": 26203,
"text": "Output :"
},
{
"code": null,
"e": 26231,
"s": 26212,
"text": "0.3257245223731834"
},
{
"code": null,
"e": 26244,
"s": 26231,
"text": "Example #2 :"
},
{
"code": "# import hypsecantfrom scipy.stats import hypsecantbeta = 4 # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.9, beta) print(gfg)",
"e": 26384,
"s": 26244,
"text": null
},
{
"code": null,
"e": 26393,
"s": 26384,
"text": "Output :"
},
{
"code": null,
"e": 26411,
"s": 26393,
"text": "5.842730034701113"
},
{
"code": null,
"e": 26440,
"s": 26411,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26453,
"s": 26440,
"text": "Python-scipy"
},
{
"code": null,
"e": 26460,
"s": 26453,
"text": "Python"
},
{
"code": null,
"e": 26558,
"s": 26460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26590,
"s": 26558,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26632,
"s": 26590,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26674,
"s": 26632,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26730,
"s": 26674,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26757,
"s": 26730,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26788,
"s": 26757,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26824,
"s": 26788,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26853,
"s": 26824,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26875,
"s": 26853,
"text": "Defaultdict in Python"
}
] |
Decimal Functions in Python
|
In Python, there is a module called Decimal, which is used to do some decimal floating point related tasks. This module provides correctly-rounded floating point arithmetic.
To use it at first we need to import it the Decimal standard library module.
import decimal
In this section we will see some important functions of the Decimal module.
The sqrt() method is used to calculate the square root of a given decimal type object. And the exp() method returns the e^x value for the given x as Decimal number.
#Perform sqrt() and exp() methods
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
#Find Square Root of the decimal number
print('Square Root is: ' + str(my_dec.sqrt()))
#Find e^x for the decimal number
print('e^x is: ' + str(my_dec.exp()))
25.3599999999999994315658113919198513031005859375
Square Root is: 5.035871324805668565859161094
e^x is: 103206740212.7314661465187086
There are some logarithmic functions in the Decimal module. Here we are discussing about two of them. The first one is the ln() method. This method is used to find the natural logarithm of the decimal number.
Another method is log10() method. This method is used to find the logarithmic value where base is 10.
#Perform ln() and log10() methods
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
#Find logarithmic value with base e
print('ln(x) is: ' + str(my_dec.ln()))
#Find logarithmic value with base 10
print('log(x) is: ' + str(my_dec.log10()))
25.3599999999999994315658113919198513031005859375
ln(x) is: 3.233173129569025152000878282
log(x) is: 1.404149249209695070459909761
The as_tuple method is used to represent the decimal as a tuple with three elements. The elements are sign, digits and the exponent value. In the sign field when the number is 0, it means the decimal is positive, when it is 1, it represents the negative number.
The fma() method is known as the fused multiplication and add. If we use fma(x, y) It will compute the (number * x) + y. In this case the (number*x) part is not rounded off.
#Perform as_tuple() and fma() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show decimal as tuple
print('\nmy_dec1 as tuple: ' + str(my_dec1.as_tuple()))
print('\nmy_dec2 as tuple: ' + str(my_dec2.as_tuple()))
#Perform Fused Multiply and Add
print('\n(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
my_dec1 as tuple: DecimalTuple(sign=0, digits=(5, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 2, 2, 3, 6, 4,
3, 1, 6, 0, 5, 9, 9, 7, 4, 9, 5, 3, 5, 3, 2, 2, 1, 8, 9, 3, 3, 1, 0, 5, 4, 6, 8, 7, 5), exponent=-50)
my_dec2 as tuple: DecimalTuple(sign=1, digits=(9, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 6, 3, 2, 5,
6, 4, 1, 4, 5, 6, 0, 6, 0, 1, 1, 1, 5, 2, 2, 6, 7, 4, 5, 6, 0, 5, 4, 6, 8, 7, 5), exponent=-48)
(x*5)+8 is: 34.49999999999999911182158030
This compare method is for comparing two decimal numbers. When the numbers are same, it will return 0, otherwise, when the first number is greater, it will give +1, and when first argument is smaller, it will return -1.
#Perform compare() method
import decimal
#Compare when both are equal
print('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(-5.3))))
#Compare when first one is smaller
print('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(9.26))))
#Compare when first one is greater
print('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(-13.25))))
Compare value: 0
Compare value: -1
Compare value: 1
There are some different methods for copying decimal numbers into another decimal object. The first method is copy_abs(). It is used to get the absolute value from the decimal number. The second method is copy_negate(), It is used to copy the decimal number after negating the actual number. The third function is copy_sign(). this method prints the first argument, by taking the sign from the second argument.
#Perform copy_abs(), copy_negate() and copy_sign()
import decimal
my_dec = decimal.Decimal(-25.36)
print(my_dec)
#copy the absolute value
temp_dec = my_dec.copy_abs()
print('Absolute is: ' + str(temp_dec))
#copy the negative value
my_dec = decimal.Decimal(7.26)
temp_dec = my_dec.copy_negate()
print('Negate of 7.26 is: ' + str(temp_dec))
#copy the sign value from second argument to first one
my_dec = decimal.Decimal(-25.36)
temp_dec = my_dec.copy_sign(decimal.Decimal(12.5))
print('Copy sign from second argument: ' + str(temp_dec))
-25.3599999999999994315658113919198513031005859375
Absolute is: 25.3599999999999994315658113919198513031005859375
Negate of 7.26 is: -7.2599999999999997868371792719699442386627197265625
Copy sign from second argument: 25.3599999999999994315658113919198513031005859375
The max and min are two simple methods. These are used to find the maximum or minimum between two numbers respectively.
#Perform max() and min() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show Minimum and Maximum
print('Minumum: ' + str(my_dec1.min(my_dec2)))
print('Maximum: ' + str(my_dec2.max(my_dec1)))
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Minumum: -9.230000000000000426325641456
Maximum: 5.299999999999999822364316060
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "In Python, there is a module called Decimal, which is used to do some decimal floating point related tasks. This module provides correctly-rounded floating point arithmetic."
},
{
"code": null,
"e": 1313,
"s": 1236,
"text": "To use it at first we need to import it the Decimal standard library module."
},
{
"code": null,
"e": 1329,
"s": 1313,
"text": "import decimal\n"
},
{
"code": null,
"e": 1405,
"s": 1329,
"text": "In this section we will see some important functions of the Decimal module."
},
{
"code": null,
"e": 1570,
"s": 1405,
"text": "The sqrt() method is used to calculate the square root of a given decimal type object. And the exp() method returns the e^x value for the given x as Decimal number."
},
{
"code": null,
"e": 1823,
"s": 1570,
"text": "#Perform sqrt() and exp() methods\nimport decimal\nmy_dec = decimal.Decimal(25.36)\nprint(my_dec)\n#Find Square Root of the decimal number\nprint('Square Root is: ' + str(my_dec.sqrt()))\n#Find e^x for the decimal number\nprint('e^x is: ' + str(my_dec.exp()))"
},
{
"code": null,
"e": 1958,
"s": 1823,
"text": "25.3599999999999994315658113919198513031005859375\nSquare Root is: 5.035871324805668565859161094\ne^x is: 103206740212.7314661465187086\n"
},
{
"code": null,
"e": 2167,
"s": 1958,
"text": "There are some logarithmic functions in the Decimal module. Here we are discussing about two of them. The first one is the ln() method. This method is used to find the natural logarithm of the decimal number."
},
{
"code": null,
"e": 2269,
"s": 2167,
"text": "Another method is log10() method. This method is used to find the logarithmic value where base is 10."
},
{
"code": null,
"e": 2519,
"s": 2269,
"text": "#Perform ln() and log10() methods\nimport decimal\nmy_dec = decimal.Decimal(25.36)\nprint(my_dec)\n#Find logarithmic value with base e\nprint('ln(x) is: ' + str(my_dec.ln()))\n#Find logarithmic value with base 10\nprint('log(x) is: ' + str(my_dec.log10()))"
},
{
"code": null,
"e": 2651,
"s": 2519,
"text": "25.3599999999999994315658113919198513031005859375\nln(x) is: 3.233173129569025152000878282\nlog(x) is: 1.404149249209695070459909761\n"
},
{
"code": null,
"e": 2913,
"s": 2651,
"text": "The as_tuple method is used to represent the decimal as a tuple with three elements. The elements are sign, digits and the exponent value. In the sign field when the number is 0, it means the decimal is positive, when it is 1, it represents the negative number."
},
{
"code": null,
"e": 3087,
"s": 2913,
"text": "The fma() method is known as the fused multiplication and add. If we use fma(x, y) It will compute the (number * x) + y. In this case the (number*x) part is not rounded off."
},
{
"code": null,
"e": 3450,
"s": 3087,
"text": "#Perform as_tuple() and fma() methods\nimport decimal\nmy_dec1 = decimal.Decimal(5.3)\nprint(my_dec1)\nmy_dec2 = decimal.Decimal(-9.23)\nprint(my_dec2)\n#Show decimal as tuple\nprint('\\nmy_dec1 as tuple: ' + str(my_dec1.as_tuple()))\nprint('\\nmy_dec2 as tuple: ' + str(my_dec2.as_tuple()))\n#Perform Fused Multiply and Add\nprint('\\n(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))"
},
{
"code": null,
"e": 4027,
"s": 3450,
"text": "5.29999999999999982236431605997495353221893310546875\n-9.230000000000000426325641456060111522674560546875\n\nmy_dec1 as tuple: DecimalTuple(sign=0, digits=(5, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 2, 2, 3, 6, 4, \n3, 1, 6, 0, 5, 9, 9, 7, 4, 9, 5, 3, 5, 3, 2, 2, 1, 8, 9, 3, 3, 1, 0, 5, 4, 6, 8, 7, 5), exponent=-50)\n\nmy_dec2 as tuple: DecimalTuple(sign=1, digits=(9, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 6, 3, 2, 5,\n 6, 4, 1, 4, 5, 6, 0, 6, 0, 1, 1, 1, 5, 2, 2, 6, 7, 4, 5, 6, 0, 5, 4, 6, 8, 7, 5), exponent=-48)\n\n(x*5)+8 is: 34.49999999999999911182158030\n"
},
{
"code": null,
"e": 4247,
"s": 4027,
"text": "This compare method is for comparing two decimal numbers. When the numbers are same, it will return 0, otherwise, when the first number is greater, it will give +1, and when first argument is smaller, it will return -1."
},
{
"code": null,
"e": 4644,
"s": 4247,
"text": "#Perform compare() method\nimport decimal\n#Compare when both are equal\nprint('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(-5.3))))\n#Compare when first one is smaller\nprint('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(9.26))))\n#Compare when first one is greater\nprint('Compare value: ' + str(decimal.Decimal(-5.3).compare(decimal.Decimal(-13.25))))"
},
{
"code": null,
"e": 4697,
"s": 4644,
"text": "Compare value: 0\nCompare value: -1\nCompare value: 1\n"
},
{
"code": null,
"e": 5108,
"s": 4697,
"text": "There are some different methods for copying decimal numbers into another decimal object. The first method is copy_abs(). It is used to get the absolute value from the decimal number. The second method is copy_negate(), It is used to copy the decimal number after negating the actual number. The third function is copy_sign(). this method prints the first argument, by taking the sign from the second argument."
},
{
"code": null,
"e": 5644,
"s": 5108,
"text": "#Perform copy_abs(), copy_negate() and copy_sign()\nimport decimal\nmy_dec = decimal.Decimal(-25.36)\nprint(my_dec)\n#copy the absolute value\ntemp_dec = my_dec.copy_abs()\nprint('Absolute is: ' + str(temp_dec))\n#copy the negative value\nmy_dec = decimal.Decimal(7.26)\ntemp_dec = my_dec.copy_negate()\nprint('Negate of 7.26 is: ' + str(temp_dec))\n#copy the sign value from second argument to first one\nmy_dec = decimal.Decimal(-25.36)\ntemp_dec = my_dec.copy_sign(decimal.Decimal(12.5))\nprint('Copy sign from second argument: ' + str(temp_dec))"
},
{
"code": null,
"e": 5913,
"s": 5644,
"text": "-25.3599999999999994315658113919198513031005859375\nAbsolute is: 25.3599999999999994315658113919198513031005859375\nNegate of 7.26 is: -7.2599999999999997868371792719699442386627197265625\nCopy sign from second argument: 25.3599999999999994315658113919198513031005859375\n"
},
{
"code": null,
"e": 6033,
"s": 5913,
"text": "The max and min are two simple methods. These are used to find the maximum or minimum between two numbers respectively."
},
{
"code": null,
"e": 6295,
"s": 6033,
"text": "#Perform max() and min() methods\nimport decimal\nmy_dec1 = decimal.Decimal(5.3)\nprint(my_dec1)\nmy_dec2 = decimal.Decimal(-9.23)\nprint(my_dec2)\n#Show Minimum and Maximum\nprint('Minumum: ' + str(my_dec1.min(my_dec2)))\nprint('Maximum: ' + str(my_dec2.max(my_dec1)))"
},
{
"code": null,
"e": 6480,
"s": 6295,
"text": "5.29999999999999982236431605997495353221893310546875\n-9.230000000000000426325641456060111522674560546875\nMinumum: -9.230000000000000426325641456\nMaximum: 5.299999999999999822364316060\n"
}
] |
HBase - Delete Data
|
Using the delete command, you can delete a specific cell in a table. The syntax of delete command is as follows:
delete β<table name>β, β<row>β, β<column name >β, β<time stamp>β
Here is an example to delete a specific cell. Here we are deleting the salary.
hbase(main):006:0> delete 'emp', '1', 'personal data:city',
1417521848375
0 row(s) in 0.0060 seconds
Using the βdeleteallβ command, you can delete all the cells in a row. Given below is the syntax of deleteall command.
deleteall β<table name>β, β<row>β,
Here is an example of βdeleteallβ command, where we are deleting all the cells of row1 of emp table.
hbase(main):007:0> deleteall 'emp','1'
0 row(s) in 0.0240 seconds
Verify the table using the scan command. A snapshot of the table after deleting the table is given below.
hbase(main):022:0> scan 'emp'
ROW COLUMN + CELL
2 column = personal data:city, timestamp = 1417524574905, value = chennai
2 column = personal data:name, timestamp = 1417524556125, value = ravi
2 column = professional data:designation, timestamp = 1417524204, value = sr:engg
2 column = professional data:salary, timestamp = 1417524604221, value = 30000
3 column = personal data:city, timestamp = 1417524681780, value = delhi
3 column = personal data:name, timestamp = 1417524672067, value = rajesh
3 column = professional data:designation, timestamp = 1417523187, value = jr:engg
3 column = professional data:salary, timestamp = 1417524702514, value = 25000
You can delete data from an HBase table using the delete() method of the HTable class. Follow the steps given below to delete data from a table.
Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the the HbaseConfiguration class as shown below.
Configuration conf = HbaseConfiguration.create();
You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below.
HTable hTable = new HTable(conf, tableName);
Instantiate the Delete class by passing the rowid of the row that is to be deleted, in byte array format. You can also pass timestamp and Rowlock to this constructor.
Delete delete = new Delete(toBytes("row1"));
You can delete the data using the delete methods of the Delete class. This class has various delete methods. Choose the columns or column families to be deleted using those methods. Take a look at the following examples that show the usage of Delete class methods.
delete.deleteColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"));
delete.deleteFamily(Bytes.toBytes("professional"));
Delete the selected data by passing the delete instance to the delete() method of the HTable class as shown below.
table.delete(delete);
After deleting the data, close the HTable Instance.
table.close();
Given below is the complete program to delete data from the HBase table.
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.util.Bytes;
public class DeleteData {
public static void main(String[] args) throws IOException {
// Instantiating Configuration class
Configuration conf = HBaseConfiguration.create();
// Instantiating HTable class
HTable table = new HTable(conf, "employee");
// Instantiating Delete class
Delete delete = new Delete(Bytes.toBytes("row1"));
delete.deleteColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"));
delete.deleteFamily(Bytes.toBytes("professional"));
// deleting the data
table.delete(delete);
// closing the HTable object
table.close();
System.out.println("data deleted.....");
}
}
Compile and execute the above program as shown below.
$javac Deletedata.java
$java DeleteData
The following should be the output:
data deleted
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2150,
"s": 2037,
"text": "Using the delete command, you can delete a specific cell in a table. The syntax of delete command is as follows:"
},
{
"code": null,
"e": 2216,
"s": 2150,
"text": "delete β<table name>β, β<row>β, β<column name >β, β<time stamp>β\n"
},
{
"code": null,
"e": 2295,
"s": 2216,
"text": "Here is an example to delete a specific cell. Here we are deleting the salary."
},
{
"code": null,
"e": 2397,
"s": 2295,
"text": "hbase(main):006:0> delete 'emp', '1', 'personal data:city',\n1417521848375\n0 row(s) in 0.0060 seconds\n"
},
{
"code": null,
"e": 2515,
"s": 2397,
"text": "Using the βdeleteallβ command, you can delete all the cells in a row. Given below is the syntax of deleteall command."
},
{
"code": null,
"e": 2551,
"s": 2515,
"text": "deleteall β<table name>β, β<row>β,\n"
},
{
"code": null,
"e": 2652,
"s": 2551,
"text": "Here is an example of βdeleteallβ command, where we are deleting all the cells of row1 of emp table."
},
{
"code": null,
"e": 2719,
"s": 2652,
"text": "hbase(main):007:0> deleteall 'emp','1'\n0 row(s) in 0.0240 seconds\n"
},
{
"code": null,
"e": 2825,
"s": 2719,
"text": "Verify the table using the scan command. A snapshot of the table after deleting the table is given below."
},
{
"code": null,
"e": 3512,
"s": 2825,
"text": "hbase(main):022:0> scan 'emp'\n\nROW COLUMN + CELL\n\n2 column = personal data:city, timestamp = 1417524574905, value = chennai \n\n2 column = personal data:name, timestamp = 1417524556125, value = ravi\n\n2 column = professional data:designation, timestamp = 1417524204, value = sr:engg\n\n2 column = professional data:salary, timestamp = 1417524604221, value = 30000\n\n3 column = personal data:city, timestamp = 1417524681780, value = delhi\n\n3 column = personal data:name, timestamp = 1417524672067, value = rajesh\n \n3 column = professional data:designation, timestamp = 1417523187, value = jr:engg\n\n3 column = professional data:salary, timestamp = 1417524702514, value = 25000\n"
},
{
"code": null,
"e": 3657,
"s": 3512,
"text": "You can delete data from an HBase table using the delete() method of the HTable class. Follow the steps given below to delete data from a table."
},
{
"code": null,
"e": 3839,
"s": 3657,
"text": "Configuration class adds HBase configuration files to its object. You can create a configuration object using the create() method of the the HbaseConfiguration class as shown below."
},
{
"code": null,
"e": 3890,
"s": 3839,
"text": "Configuration conf = HbaseConfiguration.create();\n"
},
{
"code": null,
"e": 4175,
"s": 3890,
"text": "You have a class called HTable, an implementation of Table in HBase. This class is used to communicate with a single HBase table. While instantiating this class, it accepts the configuration object and the table name as parameters. You can instantiate the HTable class as shown below."
},
{
"code": null,
"e": 4222,
"s": 4175,
"text": "HTable hTable = new HTable(conf, tableName); \n"
},
{
"code": null,
"e": 4389,
"s": 4222,
"text": "Instantiate the Delete class by passing the rowid of the row that is to be deleted, in byte array format. You can also pass timestamp and Rowlock to this constructor."
},
{
"code": null,
"e": 4435,
"s": 4389,
"text": "Delete delete = new Delete(toBytes(\"row1\"));\n"
},
{
"code": null,
"e": 4700,
"s": 4435,
"text": "You can delete the data using the delete methods of the Delete class. This class has various delete methods. Choose the columns or column families to be deleted using those methods. Take a look at the following examples that show the usage of Delete class methods."
},
{
"code": null,
"e": 4824,
"s": 4700,
"text": "delete.deleteColumn(Bytes.toBytes(\"personal\"), Bytes.toBytes(\"name\"));\ndelete.deleteFamily(Bytes.toBytes(\"professional\"));\n"
},
{
"code": null,
"e": 4939,
"s": 4824,
"text": "Delete the selected data by passing the delete instance to the delete() method of the HTable class as shown below."
},
{
"code": null,
"e": 4963,
"s": 4939,
"text": "table.delete(delete); \n"
},
{
"code": null,
"e": 5015,
"s": 4963,
"text": "After deleting the data, close the HTable Instance."
},
{
"code": null,
"e": 5031,
"s": 5015,
"text": "table.close();\n"
},
{
"code": null,
"e": 5104,
"s": 5031,
"text": "Given below is the complete program to delete data from the HBase table."
},
{
"code": null,
"e": 6040,
"s": 5104,
"text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.HTable;\nimport org.apache.hadoop.hbase.util.Bytes;\n\npublic class DeleteData {\n\n public static void main(String[] args) throws IOException {\n\n // Instantiating Configuration class\n Configuration conf = HBaseConfiguration.create();\n\n // Instantiating HTable class\n HTable table = new HTable(conf, \"employee\");\n\n // Instantiating Delete class\n Delete delete = new Delete(Bytes.toBytes(\"row1\"));\n delete.deleteColumn(Bytes.toBytes(\"personal\"), Bytes.toBytes(\"name\"));\n delete.deleteFamily(Bytes.toBytes(\"professional\"));\n\n // deleting the data\n table.delete(delete);\n\n // closing the HTable object\n table.close();\n System.out.println(\"data deleted.....\");\n }\n}"
},
{
"code": null,
"e": 6094,
"s": 6040,
"text": "Compile and execute the above program as shown below."
},
{
"code": null,
"e": 6135,
"s": 6094,
"text": "$javac Deletedata.java\n$java DeleteData\n"
},
{
"code": null,
"e": 6171,
"s": 6135,
"text": "The following should be the output:"
},
{
"code": null,
"e": 6185,
"s": 6171,
"text": "data deleted\n"
},
{
"code": null,
"e": 6192,
"s": 6185,
"text": " Print"
},
{
"code": null,
"e": 6203,
"s": 6192,
"text": " Add Notes"
}
] |
Getting Started with Breakpoints Analysis in Python | by Angelica Lo Duca | Towards Data Science
|
When dealing with time series, it is very important to identify breakpoints. In fact, the presence of breakpoints in data may lead to errors and model instability while performing predictions.
A breakpoint is a structural change in data, such as an anomaly or an expected event.
Many techniques exist to identify breakpoints. In general, these techniques can be classified into two categories:
detection β detect one or many breakpoints
test β given a point, check whether it is a breakpoint or not. This category of techniques includes the famous Chow Test.
In this short tutorial, I focus on the first category of breakpoints and I compare two Python libraries for breakpoints analysis: ruptures and jenkspy.
The code is available as a Jupyter notebook and can be downloaded from my Github repository.
Firstly I load the dataset as a pandas dataframe. As dataset I exploit the Giallozafferano audience trend from 2015 to 2020. Giallozafferano is a very famous Italian food blog. Data have been extracted from Audiweb, an Italian Web site which analyses the use of Internet in Italy, and, then elaborated through a software implemented by one of my students, called LEX. LEX is a very useful software which converts multiple files in Microsoft Excel, divided by dates, to a single CSV file. If you want to know more about this software, please drop me a message :)
import pandas as pddf = pd.read_csv('GialloZafferano.csv')df.head()
Now I convert the dataframe into a time series. This can be done in three steps:
convert the data field to a datetime
set the date column as index of the time series
assign the column of values to a new variable, called ts.
df['date'] = pd.to_datetime(df['date'])df.set_index(df['date'], inplace = True)ts = df['audience']
I plot the time series. I exploit the matplotlib library.
Looking at the graph, I note that the are about three main breaks. Thus, I decide to search for 3 breaks.
n_breaks = 3
I prepare data to be given as input of the tested libraries. I convert the time series to array.
import numpy as npy = np.array(ts.tolist())
The first breakpoints detection library is Ruptures, which can be installed through the command pip install rupture.
Ruptures provides six different models to detect breakpoints: Dynp, KernelCPD, Pelt, Binseg, BottomUp, Window. Each model must be built, trained (through the fit() function) and then used for prediction. The predict() function receives as input the number of breakpoints (minus 1) to be identified. In this example I exploit the Dynp model, which corresponds to Dynamic Programming.
import ruptures as rptmodel = rpt.Dynp(model="l1")model.fit(y)breaks = model.predict(n_bkps=n_breaks-1)
Since ruptures returns the index at which the structural change happens, I retrieve the date from the original time series ts.
breaks_rpt = []for i in breaks: breaks_rpt.append(ts.index[i-1])breaks_rpt = pd.to_datetime(breaks_rpt)breaks_rpt
which produces the following output:
DatetimeIndex(['2016-03-01', '2018-04-01', '2020-11-01'], dtype='datetime64[ns]', freq=None)
Now I plot results.
plt.plot(ts, label='data')plt.title('Audience')print_legend = Truefor i in breaks_rpt: if print_legend: plt.axvline(i, color='red',linestyle='dashed', label='breaks') print_legend = False else: plt.axvline(i, color='red',linestyle='dashed')plt.grid()plt.legend()plt.show()
The second breakpoints detection library is Jenkspy, which can be installed through the following command: pip install jenkspy. This library computes the natural breaks into an array according to the Fisher-Jenks algorithm.
I import the library (import jenkspy) and then I call the jenks_breaks() function, which receives the arrary of values and the number of breaks to be detected as input. As output, the function returns the values corresponding to the identified breaks. Remind that Ruptures, instead, returns the breaks indexes.
import jenkspybreaks = jenkspy.jenks_breaks(y, nb_class=n_breaks-1)
I calculate the breaks indexes, by looping through the breaks array.
breaks_jkp = []for v in breaks: idx = ts.index[ts == v] breaks_jkp.append(idx)breaks_jkp
which produces the following output:
[DatetimeIndex(['2017-07-01'], dtype='datetime64[ns]', name='date', freq=None), DatetimeIndex(['2018-04-01'], dtype='datetime64[ns]', name='date', freq=None), DatetimeIndex(['2020-04-01'], dtype='datetime64[ns]', name='date', freq=None)]
And I plot results.
plt.plot(ts, label='data')plt.title('Audience')print_legend = Truefor i in breaks_jkp: if print_legend: plt.axvline(i, color='red',linestyle='dashed', label='breaks') print_legend = False else: plt.axvline(i, color='red',linestyle='dashed')plt.grid()plt.legend()plt.show()
Finally, I compare the results produced by the two libraries. I perform a visual comparison.
I calculate the ideal case, where both the algorithms produce the same result.
x_ideal = ts.indexy_ideal = x_ideal
I compare the two algorithms through a scatter plot. The ideal case is plotted in red. I note that there is only a common break (the one crossing the ideal case). The first breakpoint is quite different, while the third one is quite similar.
plt.figure(figsize=(5, 5), dpi=80)plt.scatter(breaks_rpt,breaks_jkp)plt.xlabel('Ruptures')plt.ylabel('Jenkspy')plt.title('Jenskpy VS Ruptures')plt.xlim(ts.index[0], ts.index[len(ts)-1])plt.ylim(ts.index[0], ts.index[len(ts)-1])plt.plot(x_ideal,y_ideal, color='r', linestyle='dashed')plt.grid()plt.show()
In this tutorial, I have illustrated how to detect breakpoints in Python with two libraries: ruptures and jenkspy. The two libraries produce different outputs. Comparing the outputs with the visual breakpoints, in this specific example the Jenkspy algorithm seems to outperform the Dynamic Programming.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github.
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "When dealing with time series, it is very important to identify breakpoints. In fact, the presence of breakpoints in data may lead to errors and model instability while performing predictions."
},
{
"code": null,
"e": 451,
"s": 365,
"text": "A breakpoint is a structural change in data, such as an anomaly or an expected event."
},
{
"code": null,
"e": 566,
"s": 451,
"text": "Many techniques exist to identify breakpoints. In general, these techniques can be classified into two categories:"
},
{
"code": null,
"e": 609,
"s": 566,
"text": "detection β detect one or many breakpoints"
},
{
"code": null,
"e": 731,
"s": 609,
"text": "test β given a point, check whether it is a breakpoint or not. This category of techniques includes the famous Chow Test."
},
{
"code": null,
"e": 883,
"s": 731,
"text": "In this short tutorial, I focus on the first category of breakpoints and I compare two Python libraries for breakpoints analysis: ruptures and jenkspy."
},
{
"code": null,
"e": 976,
"s": 883,
"text": "The code is available as a Jupyter notebook and can be downloaded from my Github repository."
},
{
"code": null,
"e": 1538,
"s": 976,
"text": "Firstly I load the dataset as a pandas dataframe. As dataset I exploit the Giallozafferano audience trend from 2015 to 2020. Giallozafferano is a very famous Italian food blog. Data have been extracted from Audiweb, an Italian Web site which analyses the use of Internet in Italy, and, then elaborated through a software implemented by one of my students, called LEX. LEX is a very useful software which converts multiple files in Microsoft Excel, divided by dates, to a single CSV file. If you want to know more about this software, please drop me a message :)"
},
{
"code": null,
"e": 1606,
"s": 1538,
"text": "import pandas as pddf = pd.read_csv('GialloZafferano.csv')df.head()"
},
{
"code": null,
"e": 1687,
"s": 1606,
"text": "Now I convert the dataframe into a time series. This can be done in three steps:"
},
{
"code": null,
"e": 1724,
"s": 1687,
"text": "convert the data field to a datetime"
},
{
"code": null,
"e": 1772,
"s": 1724,
"text": "set the date column as index of the time series"
},
{
"code": null,
"e": 1830,
"s": 1772,
"text": "assign the column of values to a new variable, called ts."
},
{
"code": null,
"e": 1929,
"s": 1830,
"text": "df['date'] = pd.to_datetime(df['date'])df.set_index(df['date'], inplace = True)ts = df['audience']"
},
{
"code": null,
"e": 1987,
"s": 1929,
"text": "I plot the time series. I exploit the matplotlib library."
},
{
"code": null,
"e": 2093,
"s": 1987,
"text": "Looking at the graph, I note that the are about three main breaks. Thus, I decide to search for 3 breaks."
},
{
"code": null,
"e": 2106,
"s": 2093,
"text": "n_breaks = 3"
},
{
"code": null,
"e": 2203,
"s": 2106,
"text": "I prepare data to be given as input of the tested libraries. I convert the time series to array."
},
{
"code": null,
"e": 2247,
"s": 2203,
"text": "import numpy as npy = np.array(ts.tolist())"
},
{
"code": null,
"e": 2364,
"s": 2247,
"text": "The first breakpoints detection library is Ruptures, which can be installed through the command pip install rupture."
},
{
"code": null,
"e": 2747,
"s": 2364,
"text": "Ruptures provides six different models to detect breakpoints: Dynp, KernelCPD, Pelt, Binseg, BottomUp, Window. Each model must be built, trained (through the fit() function) and then used for prediction. The predict() function receives as input the number of breakpoints (minus 1) to be identified. In this example I exploit the Dynp model, which corresponds to Dynamic Programming."
},
{
"code": null,
"e": 2851,
"s": 2747,
"text": "import ruptures as rptmodel = rpt.Dynp(model=\"l1\")model.fit(y)breaks = model.predict(n_bkps=n_breaks-1)"
},
{
"code": null,
"e": 2978,
"s": 2851,
"text": "Since ruptures returns the index at which the structural change happens, I retrieve the date from the original time series ts."
},
{
"code": null,
"e": 3095,
"s": 2978,
"text": "breaks_rpt = []for i in breaks: breaks_rpt.append(ts.index[i-1])breaks_rpt = pd.to_datetime(breaks_rpt)breaks_rpt"
},
{
"code": null,
"e": 3132,
"s": 3095,
"text": "which produces the following output:"
},
{
"code": null,
"e": 3225,
"s": 3132,
"text": "DatetimeIndex(['2016-03-01', '2018-04-01', '2020-11-01'], dtype='datetime64[ns]', freq=None)"
},
{
"code": null,
"e": 3245,
"s": 3225,
"text": "Now I plot results."
},
{
"code": null,
"e": 3545,
"s": 3245,
"text": "plt.plot(ts, label='data')plt.title('Audience')print_legend = Truefor i in breaks_rpt: if print_legend: plt.axvline(i, color='red',linestyle='dashed', label='breaks') print_legend = False else: plt.axvline(i, color='red',linestyle='dashed')plt.grid()plt.legend()plt.show()"
},
{
"code": null,
"e": 3769,
"s": 3545,
"text": "The second breakpoints detection library is Jenkspy, which can be installed through the following command: pip install jenkspy. This library computes the natural breaks into an array according to the Fisher-Jenks algorithm."
},
{
"code": null,
"e": 4080,
"s": 3769,
"text": "I import the library (import jenkspy) and then I call the jenks_breaks() function, which receives the arrary of values and the number of breaks to be detected as input. As output, the function returns the values corresponding to the identified breaks. Remind that Ruptures, instead, returns the breaks indexes."
},
{
"code": null,
"e": 4148,
"s": 4080,
"text": "import jenkspybreaks = jenkspy.jenks_breaks(y, nb_class=n_breaks-1)"
},
{
"code": null,
"e": 4217,
"s": 4148,
"text": "I calculate the breaks indexes, by looping through the breaks array."
},
{
"code": null,
"e": 4312,
"s": 4217,
"text": "breaks_jkp = []for v in breaks: idx = ts.index[ts == v] breaks_jkp.append(idx)breaks_jkp"
},
{
"code": null,
"e": 4349,
"s": 4312,
"text": "which produces the following output:"
},
{
"code": null,
"e": 4587,
"s": 4349,
"text": "[DatetimeIndex(['2017-07-01'], dtype='datetime64[ns]', name='date', freq=None), DatetimeIndex(['2018-04-01'], dtype='datetime64[ns]', name='date', freq=None), DatetimeIndex(['2020-04-01'], dtype='datetime64[ns]', name='date', freq=None)]"
},
{
"code": null,
"e": 4607,
"s": 4587,
"text": "And I plot results."
},
{
"code": null,
"e": 4907,
"s": 4607,
"text": "plt.plot(ts, label='data')plt.title('Audience')print_legend = Truefor i in breaks_jkp: if print_legend: plt.axvline(i, color='red',linestyle='dashed', label='breaks') print_legend = False else: plt.axvline(i, color='red',linestyle='dashed')plt.grid()plt.legend()plt.show()"
},
{
"code": null,
"e": 5000,
"s": 4907,
"text": "Finally, I compare the results produced by the two libraries. I perform a visual comparison."
},
{
"code": null,
"e": 5079,
"s": 5000,
"text": "I calculate the ideal case, where both the algorithms produce the same result."
},
{
"code": null,
"e": 5115,
"s": 5079,
"text": "x_ideal = ts.indexy_ideal = x_ideal"
},
{
"code": null,
"e": 5357,
"s": 5115,
"text": "I compare the two algorithms through a scatter plot. The ideal case is plotted in red. I note that there is only a common break (the one crossing the ideal case). The first breakpoint is quite different, while the third one is quite similar."
},
{
"code": null,
"e": 5661,
"s": 5357,
"text": "plt.figure(figsize=(5, 5), dpi=80)plt.scatter(breaks_rpt,breaks_jkp)plt.xlabel('Ruptures')plt.ylabel('Jenkspy')plt.title('Jenskpy VS Ruptures')plt.xlim(ts.index[0], ts.index[len(ts)-1])plt.ylim(ts.index[0], ts.index[len(ts)-1])plt.plot(x_ideal,y_ideal, color='r', linestyle='dashed')plt.grid()plt.show()"
},
{
"code": null,
"e": 5964,
"s": 5661,
"text": "In this tutorial, I have illustrated how to detect breakpoints in Python with two libraries: ruptures and jenkspy. The two libraries produce different outputs. Comparing the outputs with the visual breakpoints, in this specific example the Jenkspy algorithm seems to outperform the Dynamic Programming."
}
] |
Change Background color of a web page using onmouseover property
|
The onmouseover property allows you set a script when the mouse pointer is moved onto an element. To change the background color, use the HTML DOM backgroundColor property.
Let us see an example to implement the onmouseover property and change the background color β
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Heading Two</h2>
<a onmouseover="document.body.style.backgroundColor ='orange'">Hover over me to change the background color.</a><br>
</body>
</html>
Now hover over the text to change the background color of the web page β
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "The onmouseover property allows you set a script when the mouse pointer is moved onto an element. To change the background color, use the HTML DOM backgroundColor property."
},
{
"code": null,
"e": 1329,
"s": 1235,
"text": "Let us see an example to implement the onmouseover property and change the background color β"
},
{
"code": null,
"e": 1340,
"s": 1329,
"text": " Live Demo"
},
{
"code": null,
"e": 1527,
"s": 1340,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Heading Two</h2>\n <a onmouseover=\"document.body.style.backgroundColor ='orange'\">Hover over me to change the background color.</a><br>\n</body>\n</html>"
},
{
"code": null,
"e": 1600,
"s": 1527,
"text": "Now hover over the text to change the background color of the web page β"
}
] |
Example program on Dynamic memory allocation function in C language
|
How to display and calculate the sum of n numbers by using dynamic memory allocation function in C language?
Following is the C program to display the elements and calculate the sum of n numbers by the user by using dynamic memory allocation functions. Here, we also try to reduce the wastage of memory.
Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointers,sum//
int numofe,i,sum=0;
int *p;
//Reading number of elements from user//
printf("Enter the number of elements : ");
scanf("%d",&numofe);
//Calling malloc() function//
p=(int *)malloc(numofe*sizeof(int));
/*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/
if (p==NULL){
printf("Memory not available");
exit(0);
}
//Printing elements//
printf("Enter the elements : \n");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
}
When the above program is executed, it produces the following result β
Enter the number of elements: 4
Enter the elements:
23
45
67
89
The sum of elements is 224
Displaying the cleared out memory location:
7410816
0
7405904
0
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "How to display and calculate the sum of n numbers by using dynamic memory allocation function in C language?"
},
{
"code": null,
"e": 1366,
"s": 1171,
"text": "Following is the C program to display the elements and calculate the sum of n numbers by the user by using dynamic memory allocation functions. Here, we also try to reduce the wastage of memory."
},
{
"code": null,
"e": 1377,
"s": 1366,
"text": " Live Demo"
},
{
"code": null,
"e": 2291,
"s": 1377,
"text": "#include<stdio.h>\n#include<stdlib.h>\nvoid main(){\n //Declaring variables and pointers,sum//\n int numofe,i,sum=0;\n int *p;\n //Reading number of elements from user//\n printf(\"Enter the number of elements : \");\n scanf(\"%d\",&numofe);\n //Calling malloc() function//\n p=(int *)malloc(numofe*sizeof(int));\n /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/\n if (p==NULL){\n printf(\"Memory not available\");\n exit(0);\n }\n //Printing elements//\n printf(\"Enter the elements : \\n\");\n for(i=0;i<numofe;i++){\n scanf(\"%d\",p+i);\n sum=sum+*(p+i);\n }\n printf(\"\\nThe sum of elements is %d\",sum);\n free(p);//Erase first 2 memory locations//\n printf(\"\\nDisplaying the cleared out memory location : \\n\");\n for(i=0;i<numofe;i++){\n printf(\"%d\\n\",p[i]);//Garbage values will be displayed//\n }\n}"
},
{
"code": null,
"e": 2362,
"s": 2291,
"text": "When the above program is executed, it produces the following result β"
},
{
"code": null,
"e": 2517,
"s": 2362,
"text": "Enter the number of elements: 4\nEnter the elements:\n23\n45\n67\n89\nThe sum of elements is 224\nDisplaying the cleared out memory location:\n7410816\n0\n7405904\n0"
}
] |
\leftrightharpoons - Tex Command
|
\leftrightharpoons - Used to draw leftrightharpoons symbol.
{ \leftrightharpoons }
\leftrightharpoons command is used to draw leftrightharpoons symbol.
\leftrightharpoons
β
\leftrightharpoons
β
\leftrightharpoons
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8046,
"s": 7986,
"text": "\\leftrightharpoons - Used to draw leftrightharpoons symbol."
},
{
"code": null,
"e": 8069,
"s": 8046,
"text": "{ \\leftrightharpoons }"
},
{
"code": null,
"e": 8138,
"s": 8069,
"text": "\\leftrightharpoons command is used to draw leftrightharpoons symbol."
},
{
"code": null,
"e": 8164,
"s": 8138,
"text": "\n\\leftrightharpoons\n\nβ\n\n\n"
},
{
"code": null,
"e": 8188,
"s": 8164,
"text": "\\leftrightharpoons\n\nβ\n\n"
},
{
"code": null,
"e": 8207,
"s": 8188,
"text": "\\leftrightharpoons"
},
{
"code": null,
"e": 8239,
"s": 8207,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8252,
"s": 8239,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8285,
"s": 8252,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8298,
"s": 8285,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8330,
"s": 8298,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8366,
"s": 8330,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8401,
"s": 8366,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8418,
"s": 8401,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8451,
"s": 8418,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8465,
"s": 8451,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8497,
"s": 8465,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8512,
"s": 8497,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8519,
"s": 8512,
"text": " Print"
},
{
"code": null,
"e": 8530,
"s": 8519,
"text": " Add Notes"
}
] |
Cleaning and Exploring Data with the βjanitorβ Package | by Emily A. Halford | Towards Data Science
|
The janitor package is available on CRAN and was created by Sam Firke, Bill Denney, Chris Haid, Ryan Knight, Malte Grosser, and Jonathan Zadra. While arguably best known for its extraordinarily useful clean_names() function (which I will be covering later on in this article), the janitor package has a wide range of functions that facilitate data cleaning and exploration. The package is designed to be compatible with the tidyverse, and can therefore be seamlessly integrated into most data prep workflows. Useful overviews of janitor package functions that I have consulted can be found here and here. Additionally, all data and code referenced below can be accessed in this GitHub repo.
The data that we will be using in this tutorial comes from the Geographic Names Information System (GNIS), a database created by the U.S. Board on Geographic Names. This dataset was featured in Jeremy Singer-Vineβs Data is Plural newsletter, and is essentially a searchable catalogue of domestic place names.
In order to download the data, we will first need to navigate to the Query Form:
I chose to utilize data representing place names in Berkshire County, Massachusetts, a region that includes my hometown. In order to create this search, select βMassachusettsβ from the state drop-down menu and βBerkshireβ from the county drop-down menu. Then, click the βSend Queryβ button:
The query results will appear as shown below. Beneath the results table, click βSave as pipe β|β delimited fileβ to save the data locally:
The data should begin to download automatically, and will appear in a .csv file with features delimited by β|β:
Save this csv file into a βdataβ folder in a new R project. Letβs bring the data into R, separate these columns out, and perform a bit of modification to facilitate our janitor package exploration. First, load the tidyverse and janitor packages in a new R Markdown file. Use the read.csv() function to load in the data as βplace_namesβ:
library(tidyverse)library(janitor)place_names = read.csv("./data/GNIS Query Result.csv")
The data should look pretty much the same as it did in Excel, with one massive column containing all of our data:
Letβs work with this a bit. First, we assign the name βcolumnsβ to this single column to avoid having to include something as messy and long as the default column name in our code. Next, we use the separate() function to separate this one column into all of its component parts. We then filter the data down to Berkshire County, as upon further inspection of the data it becomes clear that a few entries from outside this county were included in our Berkshire County query. We then dirty the data a bit in a mutate() step so as to tidy it later. str_replace() is used to replace the ID β598673β with β598712,β an ID number that already exists in the dataset, in order to create a duplicate ID. Finally, an extra column called βextra_columnβ is created with NAs in every row:
colnames(place_names) = "columns"place_names = place_names %>% separate(columns, c("Feature Name", "ID", "Class", "County", "State", "Latitude", "Longitude", "Ele(ft)", "Map", "BGN Date", "Entry Date"), sep = "[|]") %>% filter(County == "Berkshire") %>% mutate( ID = str_replace(ID, "598673", "598712"), extra_column = NA )
Before moving on, letβs quickly create a second data set called βnon_ma_namesβ containing those entries that were not actually from Berkshire County. Yet again we read in the βGNIS Query Result.csvβ file and separate out the column names. We then apply the clean_names() function from the janitor package, which we will cover in depth in the following section. Finally, we use as.numeric() and as.factor() in a mutate step to transform our ele_ft variable to an numeric variable and our map variable to a factor:
non_ma_names = read.csv("./data/GNIS Query Result.csv")colnames(non_ma_names) = "columns"non_ma_names = non_ma_names %>% separate(columns, c("Feature Name", "ID", "Class", "County", "State", "Latitude", "Longitude", "Ele(ft)", "Map", "BGN Date", "Entry Date"), sep = "[|]") %>% filter(County != "Berkshire") %>% clean_names() %>% mutate( ele_ft = as.numeric(ele_ft), map = as.factor(map) )
Now letβs see what janitor can do!
Youβve probably received plenty of data files, likely in .xlsx form, that have several rows at the top of the spreadsheet before the actual data begins. These rows may be blank, or filled with information and corporate logos. When you load such data into R, content from these leading rows may automatically become your column headers and first rows. The row_to_names() function in the janitor package allows you to indicate which row in your data frame contains the actual column names and to delete everything else that precedes that row. Conveniently for us, the GNIS data already had column names in the correct place. Letβs try this out anyway, though, pretending that the column names were actually in the third row.
We use the row_to_names() function to create a new data frame called βtest_namesβ. The row_to_names() function takes the following arguments: the data source, the row number that column names should come from, whether that row should be deleted from the data, and whether the rows above should be deleted from the data:
test_names = row_to_names(place_names, 3, remove_row = TRUE, remove_rows_above = TRUE)
We can see that the information from row 3 now makes up our column names. That row and those above it were removed from the data frame, and we can see that the data now begins on row 4:
While this function isnβt necessary to clean the GNIS data, it certainly comes in handy with other data sets!
This function is one that I use almost every time I load a new dataset into R. If youβre not already using this function, I highly recommend incorporating it into your workflow. Itβs the most popular function from this package for a reason β itβs extremely useful!
The tidyverse style guide recommends snake case (words separated by underscores like_this) for object and column names. Letβs look back at our column names for a minute. There are all sorts of capital letters and spaces (e.g. βFeature Name,β βBGN Dateβ) as well as symbols (βEle(ft)β). The clean_names() function will convert all of these to snake case for us.
Using clean_names() is as easy as follows:
place_names = clean_names(place_names)ORplace_names = place_names %>% clean_names()
As you can see below, this one function handled every kind of messy column name that was present in our data set. Everything now looks neat and tidy:
The remove_empty() function, as its name suggests, deletes columns that are empty. We created an empty column in our βplace_namesβ data frame while prepping our data, so we know that at least one column should be impacted by this function. Letβs try it out:
place_names = place_names %>% remove_empty()
As you can see, the empty_column has been dropped from our data frame, leaving only columns that contain data:
The bgn_date column looks empty, but the fact that it was not dropped by remove_empty() tells us that there must be data in at least one row. If we scroll down, we see that this is in fact the case:
The remove_constant() function deletes columns with the same value in all rows. Our dataset currently has two of these β since we filtered the data down to Berkshire County, and all of Berkshire County is within Massachusetts, county = βBerkshireβ and state = βMAβ for all rows. These rows arenβt particularly useful to keep in the dataset since they provide no row-specific information. We could simply use select() to drop these columns, but the benefit of remove_constant() is that this function double-checks the assumption weβre making that all entries are the same. In fact, using remove_constant() was how I first discovered that 38 out of 1968 entries in the raw data werenβt actually from Berkshire Country!
Like remove_empty(), all the information that the remove_constant() function needs is the dataset it should act on:
place_names = place_names %>% remove_constant()
As you can see below, the county and state columns have been dropped:
Ever try using rbind() to stack two data frames together and run into an unexpected error? The compare_df_cols() function directly compares the columns in the two data frames and is incredibly useful for troubleshooting this problem. Letβs try it out by comparing our βplace_namesβ data frame to the data frame that we created containing entries outside of Berkshire County, βnon_ma_namesβ:
compare_df_cols(place_names, non_ma_names)
The output is a convenient table comparing the two data frames. We see βNAβ for county and state in place_names and βcharacterβ for these variables in non_ma_names. This is because we deleted these columns with remove_constant() from place_names, but never did anything to the default character variables in non_ma_names. We also see ele_ft as numeric and map as a factor variable in non_ma_names, which we specifically designated during data prep. If we were trying to merge these data frames back together, it would be useful to know which columns are missing as well as which columns have inconsistent types across data frames. In data frames with many columns, compare_df_cols() can significantly reduce the time spent making these comparisons.
Iβve frequently worked on projects with unique patient IDs that you do not expect to see duplicated in your dataset. There are plenty of other instances when you might want to make sure that some ID variable has entirely unique values, including our GNIS data. As youβll recall, we created a duplicate ID when prepping our data. Letβs see how get_dupes() detects this. The function just needs the name of our data frame and the name of the column acting as an identifier:
get_dupes(place_names, id)
As shown below, the data frame is filtered down to those rows with duplicate values in the ID column, making it easy to investigate any problems:
The tabyl() function is a tidyverse-compatible replacement for the table() function. It is also compatible with the knitr package, and is quite useful for data exploration.
Letβs try it out first with a single variable. Say weβre interested in how many schools are in each of the towns in Berkshire County. We first filter our class variable to βSchool,β then use the tabyl() function with our map (location) variable. Finally, we pipe that into knitr::kable() to format the output in a nice table:
place_names %>% filter(class %in% "School") %>% tabyl(map) %>% knitr::kable()
Running this very basic code chunk produces the following output table:
When we knit our Rmd file, the kable() function will have formatted the table nicely, as shown below. We conveniently get a count of schools in each town, as well as the percentage of all schools that are in that town. Itβs easy to make observations about these data, such as that 29.5% of all schools are in Pittsfield East, which has 41 schools. Or that 3 towns are so small that they only have 1 school:
Now letβs try the cross-tabulation of two variables. Letβs see how many landmarks of each type are present in each town:
place_names %>% tabyl(map, class) %>% knitr::kable()
A portion of our table (once knitted) is shown below. For each town, we can clearly see how many of each landmark type are in the database:
While simple counts like this can be quite useful, maybe we care more about column percentages. In other words, what percentage of entries for each landmark type are in each town? This is easy to investigate with tabyl() via the βadorn_percentages()β function:
place_names %>% tabyl(map, class) %>% adorn_percentages("col") %>% knitr::kable()
Now we see these column percentages instead of counts, but the table is rather difficult to read:
We can clean this up a bit with the adorn_pct_formatting() function, which allows the user to specify the number of decimal places to include in the output. Precision isnβt particularly important for this exploratory table, so letβs use 0 decimal places to make this table easier to read:
place_names %>% tabyl(map, class) %>% adorn_percentages("col") %>% adorn_pct_formatting(digits = 0) %>% knitr::kable()
Much better! Now it is much easier to read the table and understand our column percentages:
It is just as easy to use adorn_percentages() to instead look at row percentages (in our case, the percentage of entries from each town belonging to each landmark type):
place_names %>% tabyl(map, class) %>% adorn_percentages("row") %>% adorn_pct_formatting(digits = 0) %>% knitr::kable()
In this article I have described the functions from the janitor package that I find useful in my day-to-day work. However, this is not an exhaustive list of janitor functions and I recommend consulting the documentation for further information on this package.
That being said, there are a few other functions that are worth at least noting here:
excel_numeric_to_date(): This function is designed to handle many of Excelβs date formats and to convert these numeric variables to date variables. It seems like a big time saver for those who frequently work with data in Excel. As an infrequent Excel user, I instead rely heavily on the lubridate package for working with date variables.round_to_fraction(): This function allows you to round decimal numbers to a precise fractional denominator. Want all of your values rounded to the nearest quarter, or are you using decimals to represent minutes in an hour? Itβs likely that the round_to_fraction() function can help you.top_levels(): This function generates a frequency table which collapses a categorical variable into high, middle, and low levels. Common use cases include simplifying Likert-type scales.
excel_numeric_to_date(): This function is designed to handle many of Excelβs date formats and to convert these numeric variables to date variables. It seems like a big time saver for those who frequently work with data in Excel. As an infrequent Excel user, I instead rely heavily on the lubridate package for working with date variables.
round_to_fraction(): This function allows you to round decimal numbers to a precise fractional denominator. Want all of your values rounded to the nearest quarter, or are you using decimals to represent minutes in an hour? Itβs likely that the round_to_fraction() function can help you.
top_levels(): This function generates a frequency table which collapses a categorical variable into high, middle, and low levels. Common use cases include simplifying Likert-type scales.
Itβs common knowledge at this point that most data analysts and data scientists devote a majority of their time to data cleaning and exploration, and I therefore always find it exciting to discover new packages and functions that make these processes a little more efficient.
Whether or not you have previously used the janitor package, I hope that this article has introduced you to some functions that will prove to be useful additions to your data science toolkit.
|
[
{
"code": null,
"e": 862,
"s": 171,
"text": "The janitor package is available on CRAN and was created by Sam Firke, Bill Denney, Chris Haid, Ryan Knight, Malte Grosser, and Jonathan Zadra. While arguably best known for its extraordinarily useful clean_names() function (which I will be covering later on in this article), the janitor package has a wide range of functions that facilitate data cleaning and exploration. The package is designed to be compatible with the tidyverse, and can therefore be seamlessly integrated into most data prep workflows. Useful overviews of janitor package functions that I have consulted can be found here and here. Additionally, all data and code referenced below can be accessed in this GitHub repo."
},
{
"code": null,
"e": 1171,
"s": 862,
"text": "The data that we will be using in this tutorial comes from the Geographic Names Information System (GNIS), a database created by the U.S. Board on Geographic Names. This dataset was featured in Jeremy Singer-Vineβs Data is Plural newsletter, and is essentially a searchable catalogue of domestic place names."
},
{
"code": null,
"e": 1252,
"s": 1171,
"text": "In order to download the data, we will first need to navigate to the Query Form:"
},
{
"code": null,
"e": 1543,
"s": 1252,
"text": "I chose to utilize data representing place names in Berkshire County, Massachusetts, a region that includes my hometown. In order to create this search, select βMassachusettsβ from the state drop-down menu and βBerkshireβ from the county drop-down menu. Then, click the βSend Queryβ button:"
},
{
"code": null,
"e": 1682,
"s": 1543,
"text": "The query results will appear as shown below. Beneath the results table, click βSave as pipe β|β delimited fileβ to save the data locally:"
},
{
"code": null,
"e": 1794,
"s": 1682,
"text": "The data should begin to download automatically, and will appear in a .csv file with features delimited by β|β:"
},
{
"code": null,
"e": 2131,
"s": 1794,
"text": "Save this csv file into a βdataβ folder in a new R project. Letβs bring the data into R, separate these columns out, and perform a bit of modification to facilitate our janitor package exploration. First, load the tidyverse and janitor packages in a new R Markdown file. Use the read.csv() function to load in the data as βplace_namesβ:"
},
{
"code": null,
"e": 2220,
"s": 2131,
"text": "library(tidyverse)library(janitor)place_names = read.csv(\"./data/GNIS Query Result.csv\")"
},
{
"code": null,
"e": 2334,
"s": 2220,
"text": "The data should look pretty much the same as it did in Excel, with one massive column containing all of our data:"
},
{
"code": null,
"e": 3109,
"s": 2334,
"text": "Letβs work with this a bit. First, we assign the name βcolumnsβ to this single column to avoid having to include something as messy and long as the default column name in our code. Next, we use the separate() function to separate this one column into all of its component parts. We then filter the data down to Berkshire County, as upon further inspection of the data it becomes clear that a few entries from outside this county were included in our Berkshire County query. We then dirty the data a bit in a mutate() step so as to tidy it later. str_replace() is used to replace the ID β598673β with β598712,β an ID number that already exists in the dataset, in order to create a duplicate ID. Finally, an extra column called βextra_columnβ is created with NAs in every row:"
},
{
"code": null,
"e": 3447,
"s": 3109,
"text": "colnames(place_names) = \"columns\"place_names = place_names %>% separate(columns, c(\"Feature Name\", \"ID\", \"Class\", \"County\", \"State\", \"Latitude\", \"Longitude\", \"Ele(ft)\", \"Map\", \"BGN Date\", \"Entry Date\"), sep = \"[|]\") %>% filter(County == \"Berkshire\") %>% mutate( ID = str_replace(ID, \"598673\", \"598712\"), extra_column = NA )"
},
{
"code": null,
"e": 3960,
"s": 3447,
"text": "Before moving on, letβs quickly create a second data set called βnon_ma_namesβ containing those entries that were not actually from Berkshire County. Yet again we read in the βGNIS Query Result.csvβ file and separate out the column names. We then apply the clean_names() function from the janitor package, which we will cover in depth in the following section. Finally, we use as.numeric() and as.factor() in a mutate step to transform our ele_ft variable to an numeric variable and our map variable to a factor:"
},
{
"code": null,
"e": 4367,
"s": 3960,
"text": "non_ma_names = read.csv(\"./data/GNIS Query Result.csv\")colnames(non_ma_names) = \"columns\"non_ma_names = non_ma_names %>% separate(columns, c(\"Feature Name\", \"ID\", \"Class\", \"County\", \"State\", \"Latitude\", \"Longitude\", \"Ele(ft)\", \"Map\", \"BGN Date\", \"Entry Date\"), sep = \"[|]\") %>% filter(County != \"Berkshire\") %>% clean_names() %>% mutate( ele_ft = as.numeric(ele_ft), map = as.factor(map) )"
},
{
"code": null,
"e": 4402,
"s": 4367,
"text": "Now letβs see what janitor can do!"
},
{
"code": null,
"e": 5125,
"s": 4402,
"text": "Youβve probably received plenty of data files, likely in .xlsx form, that have several rows at the top of the spreadsheet before the actual data begins. These rows may be blank, or filled with information and corporate logos. When you load such data into R, content from these leading rows may automatically become your column headers and first rows. The row_to_names() function in the janitor package allows you to indicate which row in your data frame contains the actual column names and to delete everything else that precedes that row. Conveniently for us, the GNIS data already had column names in the correct place. Letβs try this out anyway, though, pretending that the column names were actually in the third row."
},
{
"code": null,
"e": 5445,
"s": 5125,
"text": "We use the row_to_names() function to create a new data frame called βtest_namesβ. The row_to_names() function takes the following arguments: the data source, the row number that column names should come from, whether that row should be deleted from the data, and whether the rows above should be deleted from the data:"
},
{
"code": null,
"e": 5532,
"s": 5445,
"text": "test_names = row_to_names(place_names, 3, remove_row = TRUE, remove_rows_above = TRUE)"
},
{
"code": null,
"e": 5718,
"s": 5532,
"text": "We can see that the information from row 3 now makes up our column names. That row and those above it were removed from the data frame, and we can see that the data now begins on row 4:"
},
{
"code": null,
"e": 5828,
"s": 5718,
"text": "While this function isnβt necessary to clean the GNIS data, it certainly comes in handy with other data sets!"
},
{
"code": null,
"e": 6093,
"s": 5828,
"text": "This function is one that I use almost every time I load a new dataset into R. If youβre not already using this function, I highly recommend incorporating it into your workflow. Itβs the most popular function from this package for a reason β itβs extremely useful!"
},
{
"code": null,
"e": 6454,
"s": 6093,
"text": "The tidyverse style guide recommends snake case (words separated by underscores like_this) for object and column names. Letβs look back at our column names for a minute. There are all sorts of capital letters and spaces (e.g. βFeature Name,β βBGN Dateβ) as well as symbols (βEle(ft)β). The clean_names() function will convert all of these to snake case for us."
},
{
"code": null,
"e": 6497,
"s": 6454,
"text": "Using clean_names() is as easy as follows:"
},
{
"code": null,
"e": 6585,
"s": 6497,
"text": "place_names = clean_names(place_names)ORplace_names = place_names %>% clean_names()"
},
{
"code": null,
"e": 6735,
"s": 6585,
"text": "As you can see below, this one function handled every kind of messy column name that was present in our data set. Everything now looks neat and tidy:"
},
{
"code": null,
"e": 6993,
"s": 6735,
"text": "The remove_empty() function, as its name suggests, deletes columns that are empty. We created an empty column in our βplace_namesβ data frame while prepping our data, so we know that at least one column should be impacted by this function. Letβs try it out:"
},
{
"code": null,
"e": 7042,
"s": 6993,
"text": "place_names = place_names %>% remove_empty()"
},
{
"code": null,
"e": 7153,
"s": 7042,
"text": "As you can see, the empty_column has been dropped from our data frame, leaving only columns that contain data:"
},
{
"code": null,
"e": 7352,
"s": 7153,
"text": "The bgn_date column looks empty, but the fact that it was not dropped by remove_empty() tells us that there must be data in at least one row. If we scroll down, we see that this is in fact the case:"
},
{
"code": null,
"e": 8069,
"s": 7352,
"text": "The remove_constant() function deletes columns with the same value in all rows. Our dataset currently has two of these β since we filtered the data down to Berkshire County, and all of Berkshire County is within Massachusetts, county = βBerkshireβ and state = βMAβ for all rows. These rows arenβt particularly useful to keep in the dataset since they provide no row-specific information. We could simply use select() to drop these columns, but the benefit of remove_constant() is that this function double-checks the assumption weβre making that all entries are the same. In fact, using remove_constant() was how I first discovered that 38 out of 1968 entries in the raw data werenβt actually from Berkshire Country!"
},
{
"code": null,
"e": 8185,
"s": 8069,
"text": "Like remove_empty(), all the information that the remove_constant() function needs is the dataset it should act on:"
},
{
"code": null,
"e": 8237,
"s": 8185,
"text": "place_names = place_names %>% remove_constant()"
},
{
"code": null,
"e": 8307,
"s": 8237,
"text": "As you can see below, the county and state columns have been dropped:"
},
{
"code": null,
"e": 8698,
"s": 8307,
"text": "Ever try using rbind() to stack two data frames together and run into an unexpected error? The compare_df_cols() function directly compares the columns in the two data frames and is incredibly useful for troubleshooting this problem. Letβs try it out by comparing our βplace_namesβ data frame to the data frame that we created containing entries outside of Berkshire County, βnon_ma_namesβ:"
},
{
"code": null,
"e": 8741,
"s": 8698,
"text": "compare_df_cols(place_names, non_ma_names)"
},
{
"code": null,
"e": 9490,
"s": 8741,
"text": "The output is a convenient table comparing the two data frames. We see βNAβ for county and state in place_names and βcharacterβ for these variables in non_ma_names. This is because we deleted these columns with remove_constant() from place_names, but never did anything to the default character variables in non_ma_names. We also see ele_ft as numeric and map as a factor variable in non_ma_names, which we specifically designated during data prep. If we were trying to merge these data frames back together, it would be useful to know which columns are missing as well as which columns have inconsistent types across data frames. In data frames with many columns, compare_df_cols() can significantly reduce the time spent making these comparisons."
},
{
"code": null,
"e": 9962,
"s": 9490,
"text": "Iβve frequently worked on projects with unique patient IDs that you do not expect to see duplicated in your dataset. There are plenty of other instances when you might want to make sure that some ID variable has entirely unique values, including our GNIS data. As youβll recall, we created a duplicate ID when prepping our data. Letβs see how get_dupes() detects this. The function just needs the name of our data frame and the name of the column acting as an identifier:"
},
{
"code": null,
"e": 9989,
"s": 9962,
"text": "get_dupes(place_names, id)"
},
{
"code": null,
"e": 10135,
"s": 9989,
"text": "As shown below, the data frame is filtered down to those rows with duplicate values in the ID column, making it easy to investigate any problems:"
},
{
"code": null,
"e": 10308,
"s": 10135,
"text": "The tabyl() function is a tidyverse-compatible replacement for the table() function. It is also compatible with the knitr package, and is quite useful for data exploration."
},
{
"code": null,
"e": 10634,
"s": 10308,
"text": "Letβs try it out first with a single variable. Say weβre interested in how many schools are in each of the towns in Berkshire County. We first filter our class variable to βSchool,β then use the tabyl() function with our map (location) variable. Finally, we pipe that into knitr::kable() to format the output in a nice table:"
},
{
"code": null,
"e": 10718,
"s": 10634,
"text": "place_names %>% filter(class %in% \"School\") %>% tabyl(map) %>% knitr::kable()"
},
{
"code": null,
"e": 10790,
"s": 10718,
"text": "Running this very basic code chunk produces the following output table:"
},
{
"code": null,
"e": 11197,
"s": 10790,
"text": "When we knit our Rmd file, the kable() function will have formatted the table nicely, as shown below. We conveniently get a count of schools in each town, as well as the percentage of all schools that are in that town. Itβs easy to make observations about these data, such as that 29.5% of all schools are in Pittsfield East, which has 41 schools. Or that 3 towns are so small that they only have 1 school:"
},
{
"code": null,
"e": 11318,
"s": 11197,
"text": "Now letβs try the cross-tabulation of two variables. Letβs see how many landmarks of each type are present in each town:"
},
{
"code": null,
"e": 11375,
"s": 11318,
"text": "place_names %>% tabyl(map, class) %>% knitr::kable()"
},
{
"code": null,
"e": 11515,
"s": 11375,
"text": "A portion of our table (once knitted) is shown below. For each town, we can clearly see how many of each landmark type are in the database:"
},
{
"code": null,
"e": 11776,
"s": 11515,
"text": "While simple counts like this can be quite useful, maybe we care more about column percentages. In other words, what percentage of entries for each landmark type are in each town? This is easy to investigate with tabyl() via the βadorn_percentages()β function:"
},
{
"code": null,
"e": 11864,
"s": 11776,
"text": "place_names %>% tabyl(map, class) %>% adorn_percentages(\"col\") %>% knitr::kable()"
},
{
"code": null,
"e": 11962,
"s": 11864,
"text": "Now we see these column percentages instead of counts, but the table is rather difficult to read:"
},
{
"code": null,
"e": 12251,
"s": 11962,
"text": "We can clean this up a bit with the adorn_pct_formatting() function, which allows the user to specify the number of decimal places to include in the output. Precision isnβt particularly important for this exploratory table, so letβs use 0 decimal places to make this table easier to read:"
},
{
"code": null,
"e": 12378,
"s": 12251,
"text": "place_names %>% tabyl(map, class) %>% adorn_percentages(\"col\") %>% adorn_pct_formatting(digits = 0) %>% knitr::kable()"
},
{
"code": null,
"e": 12470,
"s": 12378,
"text": "Much better! Now it is much easier to read the table and understand our column percentages:"
},
{
"code": null,
"e": 12640,
"s": 12470,
"text": "It is just as easy to use adorn_percentages() to instead look at row percentages (in our case, the percentage of entries from each town belonging to each landmark type):"
},
{
"code": null,
"e": 12767,
"s": 12640,
"text": "place_names %>% tabyl(map, class) %>% adorn_percentages(\"row\") %>% adorn_pct_formatting(digits = 0) %>% knitr::kable()"
},
{
"code": null,
"e": 13028,
"s": 12767,
"text": "In this article I have described the functions from the janitor package that I find useful in my day-to-day work. However, this is not an exhaustive list of janitor functions and I recommend consulting the documentation for further information on this package."
},
{
"code": null,
"e": 13114,
"s": 13028,
"text": "That being said, there are a few other functions that are worth at least noting here:"
},
{
"code": null,
"e": 13925,
"s": 13114,
"text": "excel_numeric_to_date(): This function is designed to handle many of Excelβs date formats and to convert these numeric variables to date variables. It seems like a big time saver for those who frequently work with data in Excel. As an infrequent Excel user, I instead rely heavily on the lubridate package for working with date variables.round_to_fraction(): This function allows you to round decimal numbers to a precise fractional denominator. Want all of your values rounded to the nearest quarter, or are you using decimals to represent minutes in an hour? Itβs likely that the round_to_fraction() function can help you.top_levels(): This function generates a frequency table which collapses a categorical variable into high, middle, and low levels. Common use cases include simplifying Likert-type scales."
},
{
"code": null,
"e": 14264,
"s": 13925,
"text": "excel_numeric_to_date(): This function is designed to handle many of Excelβs date formats and to convert these numeric variables to date variables. It seems like a big time saver for those who frequently work with data in Excel. As an infrequent Excel user, I instead rely heavily on the lubridate package for working with date variables."
},
{
"code": null,
"e": 14551,
"s": 14264,
"text": "round_to_fraction(): This function allows you to round decimal numbers to a precise fractional denominator. Want all of your values rounded to the nearest quarter, or are you using decimals to represent minutes in an hour? Itβs likely that the round_to_fraction() function can help you."
},
{
"code": null,
"e": 14738,
"s": 14551,
"text": "top_levels(): This function generates a frequency table which collapses a categorical variable into high, middle, and low levels. Common use cases include simplifying Likert-type scales."
},
{
"code": null,
"e": 15014,
"s": 14738,
"text": "Itβs common knowledge at this point that most data analysts and data scientists devote a majority of their time to data cleaning and exploration, and I therefore always find it exciting to discover new packages and functions that make these processes a little more efficient."
}
] |
Count Primes in Python
|
Suppose we have a limit n. We have to count the number of primes present in the range 2 to n. So if n = 10, the result will be 4. As there are four primes before 10, they are 2, 3, 5, 7.
To solve this, we will follow this approach β
count = 0
take one array prime = of size n + 1, and fill it with False
for i = 0 to n, doif prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1
if prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1
increase count by 1
set j = 2
while j * i <n, thenprime[i * j] = Truej = j + 1
prime[i * j] = True
j = j + 1
return count
Let us see the following implementation to get a better understanding β
Live Demo
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
primes = [False for i in range(n+1)]
for i in range(2,n):
if primes[i] == False:
count+=1
j = 2
while j*i<n:
primes[j*i] = True
j+=1
return count
ob1 = Solution()
print(ob1.countPrimes(50))
print(ob1.countPrimes(10))
n = 50
n = 10
15
4
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "Suppose we have a limit n. We have to count the number of primes present in the range 2 to n. So if n = 10, the result will be 4. As there are four primes before 10, they are 2, 3, 5, 7."
},
{
"code": null,
"e": 1295,
"s": 1249,
"text": "To solve this, we will follow this approach β"
},
{
"code": null,
"e": 1305,
"s": 1295,
"text": "count = 0"
},
{
"code": null,
"e": 1366,
"s": 1305,
"text": "take one array prime = of size n + 1, and fill it with False"
},
{
"code": null,
"e": 1486,
"s": 1366,
"text": "for i = 0 to n, doif prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1"
},
{
"code": null,
"e": 1588,
"s": 1486,
"text": "if prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1"
},
{
"code": null,
"e": 1608,
"s": 1588,
"text": "increase count by 1"
},
{
"code": null,
"e": 1618,
"s": 1608,
"text": "set j = 2"
},
{
"code": null,
"e": 1667,
"s": 1618,
"text": "while j * i <n, thenprime[i * j] = Truej = j + 1"
},
{
"code": null,
"e": 1687,
"s": 1667,
"text": "prime[i * j] = True"
},
{
"code": null,
"e": 1697,
"s": 1687,
"text": "j = j + 1"
},
{
"code": null,
"e": 1710,
"s": 1697,
"text": "return count"
},
{
"code": null,
"e": 1782,
"s": 1710,
"text": "Let us see the following implementation to get a better understanding β"
},
{
"code": null,
"e": 1793,
"s": 1782,
"text": " Live Demo"
},
{
"code": null,
"e": 2229,
"s": 1793,
"text": "class Solution(object):\n def countPrimes(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n count = 0\n primes = [False for i in range(n+1)]\n for i in range(2,n):\n if primes[i] == False:\n count+=1\n j = 2\n while j*i<n:\n primes[j*i] = True\n j+=1\n return count\nob1 = Solution()\nprint(ob1.countPrimes(50))\nprint(ob1.countPrimes(10))"
},
{
"code": null,
"e": 2243,
"s": 2229,
"text": "n = 50\nn = 10"
},
{
"code": null,
"e": 2248,
"s": 2243,
"text": "15\n4"
}
] |
How to use UICollectionView in Swift?
|
To use collection view in swift, first, we need to create a collection View. We can either drag and drop it to the storyboard, or we can make it programmatically. After that, we need to confirm our class to UICollectionViewDataSource and UICollectionViewDelegate. Also if we need custom cell size and layouts, we need to confirm it to UICollectionViewDelegateFlowLayout.
Letβs see the step required to create a collection View programmatically.
func initCollection() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 50, height: 50)
let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
collection.dataSource = self
collection.delegate = self
collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.view.addSubview(collection)
}
We need to call the above function in our ViewDidLoad() method. Whether we create a collection programmatically, or with a storyboard, we need to allocate data source, and delegate to give data to table, and observe its actions respectively.
Now, we need to tell the collection, how many sections it should have β
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
After that, we need to tell how many items it will have, and what data should be present in the cells.
func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
return cell
}
Optionally we can give it different size according to requirement.
func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: 200, height: 50)
return size
}
When we run the above code on a device, this is the result thatβs produced.
|
[
{
"code": null,
"e": 1433,
"s": 1062,
"text": "To use collection view in swift, first, we need to create a collection View. We can either drag and drop it to the storyboard, or we can make it programmatically. After that, we need to confirm our class to UICollectionViewDataSource and UICollectionViewDelegate. Also if we need custom cell size and layouts, we need to confirm it to UICollectionViewDelegateFlowLayout."
},
{
"code": null,
"e": 1507,
"s": 1433,
"text": "Letβs see the step required to create a collection View programmatically."
},
{
"code": null,
"e": 2024,
"s": 1507,
"text": "func initCollection() {\n let layout = UICollectionViewFlowLayout()\n layout.itemSize = CGSize(width: 50, height: 50)\n let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)\n collection.dataSource = self\n collection.delegate = self\n collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)\n collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: \"cell\")\n self.view.addSubview(collection)\n}"
},
{
"code": null,
"e": 2266,
"s": 2024,
"text": "We need to call the above function in our ViewDidLoad() method. Whether we create a collection programmatically, or with a storyboard, we need to allocate data source, and delegate to give data to table, and observe its actions respectively."
},
{
"code": null,
"e": 2338,
"s": 2266,
"text": "Now, we need to tell the collection, how many sections it should have β"
},
{
"code": null,
"e": 2420,
"s": 2338,
"text": "func numberOfSections(in collectionView: UICollectionView) -> Int {\n return 1\n}"
},
{
"code": null,
"e": 2523,
"s": 2420,
"text": "After that, we need to tell how many items it will have, and what data should be present in the cells."
},
{
"code": null,
"e": 2972,
"s": 2523,
"text": "func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {\n return 7\n}\nfunc collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {\n let cell = collection.dequeueReusableCell(withReuseIdentifier: \"cell\", for: indexPath)\n cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)\n return cell\n}"
},
{
"code": null,
"e": 3039,
"s": 2972,
"text": "Optionally we can give it different size according to requirement."
},
{
"code": null,
"e": 3254,
"s": 3039,
"text": "func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {\n let size = CGSize(width: 200, height: 50)\n return size\n}"
},
{
"code": null,
"e": 3330,
"s": 3254,
"text": "When we run the above code on a device, this is the result thatβs produced."
}
] |
A comprehensive and practical guide to Image Processing and Computer Vision using Python: Part 1 (Introduction) | by Pranav Natekar | Towards Data Science
|
Todayβs world is the data-driven world and images form a significant part of it.
Over 2.5 quintillion bytes of data are created every single day, and itβs only going to grow from there. By 2020, itβs estimated that 1.7MB of data will be created every second for every person on earth.
β https://www.domo.com/solution/data-never-sleeps-6
Approximately 55β60% of this data is image/video data. However, the data generated is raw data. This data must be pre-processed. According to the needs, these images must be analyzed, processed and then manipulated before that can be put to use. So here comes, Image processing and Computer vision in the picture.
After weβre done with this guide, you will be able to:-
Basic Image handling.
I/O images and videos after processing them.
Perform techniques under the titles of Affine, Morphological, Segmentation, Hough transforms, etc.
Some Face Detection and Object Detection(Yayyyy!! \ (β’β‘β’) / )
And much more...
This article is my humble effort to get people interested in these areas by a practical or hands-on approach. All we need is Python and OpenCV installed(discussed further) on your on-premise desktop/laptop or the VM instance you are running on some cloud!!
If you are a Linux or a Mac user, donβt worry you already have Python on your machine(Hushhhhh(~ ΜβΎ Μ)~). But if you are a Windows user, download Python from here. And donβt forget to add Python to your $PATH while it asks during the setup.
This article is directed towards the folks having a good grasp over Python but might be still starting with Image Processing and OpenCV.
OpenCV(Open Source Computer Vision) is a widely used library for Computer vision and Machine Learning tasks. The original implementation of OpenCV is in C++. Python is slower as compared to C/C++, but on the other hand, it can be easily extended with these languages. This feature allowed us to create computationally intensive codes in C++ but wrappers in Python so that they could be used as Python modules. OpenCV-Python is the Python implementation of OpenCV. The library is cross-platformed and can be used under the open-source BSD license. OpenCV has support across multiple programming languages, operating systems and also hardware. There are bindings in Python, Java, and MATLAB/Octave. Since version 3.4, OpenCV.js is the JavaScript binding of the OpenCV lib.
Also, OpenCV needs some prerequisites like NumPy and Matplotlib, install them by using :
python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
For Linux users, this is sure to work:
sudo pip3 install opencv-python
More instructions here.
Sorry, I donβt own a Mac(β£Μ©Μ©Μ_β£Μ©Μ©Μ) and hate using Python on Windows()γ)).
If you get the no errors while importing, then you are ready to go. Ready? Letβs dive off the deep end!
Image processing (generally termed as Digital Image Processing) and Computer Vision are the fields in Computer Science with a plethora of algorithms that deal with images or videos for gaining some kind of information. While image processing deals with image-to-image transformations i.e, the input and output of the processing are both images, computer vision is an interdisciplinary field dealing with how a computer can be made to understand or gain high-level insights or information from a digital image or a video. The map shown below gives a visual understanding of what is said above!
An image processing algorithm takes in an image or a video as an input, processes it and the result of the processing is still, an image or a video. But, a computer vision algorithm takes in an image or a video, processes it and constructs explicit and meaningful descriptions from it.
An image can be defined as a two-dimensional function, f(x, y), where x and y are spatial(plane) coordinates and the amplitude of f at any pair of coordinates (x, y) is called the intensity or gray-level of the image at that point. When (x, y), and the amplitude of f are all finite, discrete values, we call the image as the digital image.
β Rafael C. Gonzalez & Richard E. Woods
A basic definition of a video is nothing but images stacked along the temporal axis. A video can be characterized by the aspect ratio, frame rate, interlaced vs progressive, color model, compression method, etc.
Considering the slice of the video M, X[n] is the first frame and X[n+M-1] is the last frame, and Y[n] is the vector stacking all of these to form a slice(part) of the whole video.
OpenCV supports a lot of image and video formats for I/O. First, letβs understand a few paradigms when it comes to video analysis. With the way just about todayβs cameras record, recordings(videos) boil down to frames that are displayed 30β60 FPS(Frames Per Second), where frames being images. Thus, image processing and video analysis use identical methods for the most part
For cv2.imread(), following formats are supported:
Windows bitmaps β *.bmp, *.dib
JPEG files β *.jpeg, *.jpg, *.jpe
JPEG 2000 files β *.jp2
Portable Network Graphics β *.png
Portable image format β *.pbm, *.pgm, *.ppm
Sun rasters β *.sr, *.ras
TIFF files β *.tiff, *.tif
For cv2.VideoCapture(), AVI files β *.avi format has full support because it seems that AVI is the only format with decent cross-platform support. See here for more info.
Below are some examples of Image and Video I/O in OpenCV:
As you can see above, the type of image is Numpyβs βndarrayβ(n-dimensional array), letβs have a look at some of the image manipulations(array manipulations)and some without using OpenCVβs core modules.
import cv2img = cv2.imread('test1.jpeg')print("The properties of the image are:")print("Shape:" + str(img.shape))print("Total no. of pixels:" + str(img.size))print("Data type of image:" + str(img.dtype))
Access an individual pixel for its gray-level/intensity:
import cv2import numpy as npm = cv2.imread("test1.jpeg")height,width,depth = np.shape(m)y = 1 # y coordinate(across height)x = 1 # x coordinate(across width)print("Value at (1, 1, 0) = " + str(m[y][x][0])) # This will print the pixel value at given coordinates at depth zero(blue)print("Value at (1, 1, 1) = " + str(m[y][x][1])) # This will print the pixel value at given coordinates at depth one(green)print("Value at (1, 1, 2) = " + str(m[y][x][2])) # This will print the pixel value at given coordinates at depth two(red)
To simply iterate over all pixels in the image we can use:
import cv2import numpy as npm = cv2.imread("test1.jpeg")height, width, depth= np.shape(m)# iterate over the entire image.for y in range(0, height): for x in range(0, width): print(m[y][x])
Behold, this will print a lot of numbers in your terminal!!
To modify the pixel value:
import cv2import numpy as npm = cv2.imread("test1.jpeg")height, width ,depth = np.shape(m)for py in range(0, height): for px in range(0, width): m[py][px][0] = 0cv2.imshow('matrix', m)cv2.imwrite('output2.png', m)cv2.waitKey(0)cv2.destroyAllWindows()
Generally, an RGB image has a 24-bit βcolor-depthβ data i.e, three 8-bit channels of RGB data. These channels are nothing but the colors blue, green and red with intensity level ranging from 0 to 255. Itβs possible to split the image in OpenCV using cv2.split() but this method is computationally costly and therefore we opt to go with Numpy indexing as itβs much more efficient and should be used if possible.
Splitting using the cv2.split() method is as easy as:
b,g,r = cv2.split(img)
In OpenCV, the order of channels is BGR and not RGB.
Splitting using indexing:
import cv2import numpy as npm = cv2.imread("test1.jpeg")blue = m[:, :, 0]green = m[:, :, 1]red = m[:, :, 2]
To understand indexing and splicing more, refer to this.
In the next part of this article, weβll cover the image processing techniques with the respective codes associated with it in OpenCV.
All the code used in this tutorial can be found in the repository below.
|
[
{
"code": null,
"e": 253,
"s": 172,
"text": "Todayβs world is the data-driven world and images form a significant part of it."
},
{
"code": null,
"e": 457,
"s": 253,
"text": "Over 2.5 quintillion bytes of data are created every single day, and itβs only going to grow from there. By 2020, itβs estimated that 1.7MB of data will be created every second for every person on earth."
},
{
"code": null,
"e": 509,
"s": 457,
"text": "β https://www.domo.com/solution/data-never-sleeps-6"
},
{
"code": null,
"e": 823,
"s": 509,
"text": "Approximately 55β60% of this data is image/video data. However, the data generated is raw data. This data must be pre-processed. According to the needs, these images must be analyzed, processed and then manipulated before that can be put to use. So here comes, Image processing and Computer vision in the picture."
},
{
"code": null,
"e": 879,
"s": 823,
"text": "After weβre done with this guide, you will be able to:-"
},
{
"code": null,
"e": 901,
"s": 879,
"text": "Basic Image handling."
},
{
"code": null,
"e": 946,
"s": 901,
"text": "I/O images and videos after processing them."
},
{
"code": null,
"e": 1045,
"s": 946,
"text": "Perform techniques under the titles of Affine, Morphological, Segmentation, Hough transforms, etc."
},
{
"code": null,
"e": 1107,
"s": 1045,
"text": "Some Face Detection and Object Detection(Yayyyy!! \\ (β’β‘β’) / )"
},
{
"code": null,
"e": 1124,
"s": 1107,
"text": "And much more..."
},
{
"code": null,
"e": 1381,
"s": 1124,
"text": "This article is my humble effort to get people interested in these areas by a practical or hands-on approach. All we need is Python and OpenCV installed(discussed further) on your on-premise desktop/laptop or the VM instance you are running on some cloud!!"
},
{
"code": null,
"e": 1622,
"s": 1381,
"text": "If you are a Linux or a Mac user, donβt worry you already have Python on your machine(Hushhhhh(~ ΜβΎ Μ)~). But if you are a Windows user, download Python from here. And donβt forget to add Python to your $PATH while it asks during the setup."
},
{
"code": null,
"e": 1759,
"s": 1622,
"text": "This article is directed towards the folks having a good grasp over Python but might be still starting with Image Processing and OpenCV."
},
{
"code": null,
"e": 2530,
"s": 1759,
"text": "OpenCV(Open Source Computer Vision) is a widely used library for Computer vision and Machine Learning tasks. The original implementation of OpenCV is in C++. Python is slower as compared to C/C++, but on the other hand, it can be easily extended with these languages. This feature allowed us to create computationally intensive codes in C++ but wrappers in Python so that they could be used as Python modules. OpenCV-Python is the Python implementation of OpenCV. The library is cross-platformed and can be used under the open-source BSD license. OpenCV has support across multiple programming languages, operating systems and also hardware. There are bindings in Python, Java, and MATLAB/Octave. Since version 3.4, OpenCV.js is the JavaScript binding of the OpenCV lib."
},
{
"code": null,
"e": 2619,
"s": 2530,
"text": "Also, OpenCV needs some prerequisites like NumPy and Matplotlib, install them by using :"
},
{
"code": null,
"e": 2705,
"s": 2619,
"text": "python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose"
},
{
"code": null,
"e": 2744,
"s": 2705,
"text": "For Linux users, this is sure to work:"
},
{
"code": null,
"e": 2776,
"s": 2744,
"text": "sudo pip3 install opencv-python"
},
{
"code": null,
"e": 2800,
"s": 2776,
"text": "More instructions here."
},
{
"code": null,
"e": 2875,
"s": 2800,
"text": "Sorry, I donβt own a Mac(β£Μ©Μ©Μ_β£Μ©Μ©Μ) and hate using Python on Windows()γ))."
},
{
"code": null,
"e": 2979,
"s": 2875,
"text": "If you get the no errors while importing, then you are ready to go. Ready? Letβs dive off the deep end!"
},
{
"code": null,
"e": 3572,
"s": 2979,
"text": "Image processing (generally termed as Digital Image Processing) and Computer Vision are the fields in Computer Science with a plethora of algorithms that deal with images or videos for gaining some kind of information. While image processing deals with image-to-image transformations i.e, the input and output of the processing are both images, computer vision is an interdisciplinary field dealing with how a computer can be made to understand or gain high-level insights or information from a digital image or a video. The map shown below gives a visual understanding of what is said above!"
},
{
"code": null,
"e": 3858,
"s": 3572,
"text": "An image processing algorithm takes in an image or a video as an input, processes it and the result of the processing is still, an image or a video. But, a computer vision algorithm takes in an image or a video, processes it and constructs explicit and meaningful descriptions from it."
},
{
"code": null,
"e": 4199,
"s": 3858,
"text": "An image can be defined as a two-dimensional function, f(x, y), where x and y are spatial(plane) coordinates and the amplitude of f at any pair of coordinates (x, y) is called the intensity or gray-level of the image at that point. When (x, y), and the amplitude of f are all finite, discrete values, we call the image as the digital image."
},
{
"code": null,
"e": 4239,
"s": 4199,
"text": "β Rafael C. Gonzalez & Richard E. Woods"
},
{
"code": null,
"e": 4451,
"s": 4239,
"text": "A basic definition of a video is nothing but images stacked along the temporal axis. A video can be characterized by the aspect ratio, frame rate, interlaced vs progressive, color model, compression method, etc."
},
{
"code": null,
"e": 4632,
"s": 4451,
"text": "Considering the slice of the video M, X[n] is the first frame and X[n+M-1] is the last frame, and Y[n] is the vector stacking all of these to form a slice(part) of the whole video."
},
{
"code": null,
"e": 5008,
"s": 4632,
"text": "OpenCV supports a lot of image and video formats for I/O. First, letβs understand a few paradigms when it comes to video analysis. With the way just about todayβs cameras record, recordings(videos) boil down to frames that are displayed 30β60 FPS(Frames Per Second), where frames being images. Thus, image processing and video analysis use identical methods for the most part"
},
{
"code": null,
"e": 5059,
"s": 5008,
"text": "For cv2.imread(), following formats are supported:"
},
{
"code": null,
"e": 5090,
"s": 5059,
"text": "Windows bitmaps β *.bmp, *.dib"
},
{
"code": null,
"e": 5124,
"s": 5090,
"text": "JPEG files β *.jpeg, *.jpg, *.jpe"
},
{
"code": null,
"e": 5148,
"s": 5124,
"text": "JPEG 2000 files β *.jp2"
},
{
"code": null,
"e": 5182,
"s": 5148,
"text": "Portable Network Graphics β *.png"
},
{
"code": null,
"e": 5226,
"s": 5182,
"text": "Portable image format β *.pbm, *.pgm, *.ppm"
},
{
"code": null,
"e": 5252,
"s": 5226,
"text": "Sun rasters β *.sr, *.ras"
},
{
"code": null,
"e": 5279,
"s": 5252,
"text": "TIFF files β *.tiff, *.tif"
},
{
"code": null,
"e": 5450,
"s": 5279,
"text": "For cv2.VideoCapture(), AVI files β *.avi format has full support because it seems that AVI is the only format with decent cross-platform support. See here for more info."
},
{
"code": null,
"e": 5508,
"s": 5450,
"text": "Below are some examples of Image and Video I/O in OpenCV:"
},
{
"code": null,
"e": 5710,
"s": 5508,
"text": "As you can see above, the type of image is Numpyβs βndarrayβ(n-dimensional array), letβs have a look at some of the image manipulations(array manipulations)and some without using OpenCVβs core modules."
},
{
"code": null,
"e": 5914,
"s": 5710,
"text": "import cv2img = cv2.imread('test1.jpeg')print(\"The properties of the image are:\")print(\"Shape:\" + str(img.shape))print(\"Total no. of pixels:\" + str(img.size))print(\"Data type of image:\" + str(img.dtype))"
},
{
"code": null,
"e": 5971,
"s": 5914,
"text": "Access an individual pixel for its gray-level/intensity:"
},
{
"code": null,
"e": 6497,
"s": 5971,
"text": "import cv2import numpy as npm = cv2.imread(\"test1.jpeg\")height,width,depth = np.shape(m)y = 1 # y coordinate(across height)x = 1 # x coordinate(across width)print(\"Value at (1, 1, 0) = \" + str(m[y][x][0])) # This will print the pixel value at given coordinates at depth zero(blue)print(\"Value at (1, 1, 1) = \" + str(m[y][x][1])) # This will print the pixel value at given coordinates at depth one(green)print(\"Value at (1, 1, 2) = \" + str(m[y][x][2])) # This will print the pixel value at given coordinates at depth two(red)"
},
{
"code": null,
"e": 6556,
"s": 6497,
"text": "To simply iterate over all pixels in the image we can use:"
},
{
"code": null,
"e": 6756,
"s": 6556,
"text": "import cv2import numpy as npm = cv2.imread(\"test1.jpeg\")height, width, depth= np.shape(m)# iterate over the entire image.for y in range(0, height): for x in range(0, width): print(m[y][x])"
},
{
"code": null,
"e": 6816,
"s": 6756,
"text": "Behold, this will print a lot of numbers in your terminal!!"
},
{
"code": null,
"e": 6843,
"s": 6816,
"text": "To modify the pixel value:"
},
{
"code": null,
"e": 7105,
"s": 6843,
"text": "import cv2import numpy as npm = cv2.imread(\"test1.jpeg\")height, width ,depth = np.shape(m)for py in range(0, height): for px in range(0, width): m[py][px][0] = 0cv2.imshow('matrix', m)cv2.imwrite('output2.png', m)cv2.waitKey(0)cv2.destroyAllWindows()"
},
{
"code": null,
"e": 7516,
"s": 7105,
"text": "Generally, an RGB image has a 24-bit βcolor-depthβ data i.e, three 8-bit channels of RGB data. These channels are nothing but the colors blue, green and red with intensity level ranging from 0 to 255. Itβs possible to split the image in OpenCV using cv2.split() but this method is computationally costly and therefore we opt to go with Numpy indexing as itβs much more efficient and should be used if possible."
},
{
"code": null,
"e": 7570,
"s": 7516,
"text": "Splitting using the cv2.split() method is as easy as:"
},
{
"code": null,
"e": 7593,
"s": 7570,
"text": "b,g,r = cv2.split(img)"
},
{
"code": null,
"e": 7646,
"s": 7593,
"text": "In OpenCV, the order of channels is BGR and not RGB."
},
{
"code": null,
"e": 7672,
"s": 7646,
"text": "Splitting using indexing:"
},
{
"code": null,
"e": 7781,
"s": 7672,
"text": "import cv2import numpy as npm = cv2.imread(\"test1.jpeg\")blue = m[:, :, 0]green = m[:, :, 1]red = m[:, :, 2]"
},
{
"code": null,
"e": 7838,
"s": 7781,
"text": "To understand indexing and splicing more, refer to this."
},
{
"code": null,
"e": 7972,
"s": 7838,
"text": "In the next part of this article, weβll cover the image processing techniques with the respective codes associated with it in OpenCV."
}
] |
Amplitude Modulation based on Depth of Modulation(Modulation Factor) using GNU Octave - GeeksforGeeks
|
17 Feb, 2021
Modulation in communication systems is a widely used process in which characteristics like amplitude, frequency, or phase angle of a high-frequency carrier wave is varied according to the instantaneous value of the low-frequency message signal.
Amplitude modulation is a modulation technique utilized in electronic communication, most ordinarily for transmitting data by means of a carrier wave. In amplitude modulation, the amplitude that is the signal quality of the carrier wave differs with respect to that of the message signal being transmitted.
There are mainly three types of modulation techniques: Amplitude Modulation, Frequency Modulation, and Phase Modulation.
In this article, we are going to discuss how to generate the Amplitude Modulated waveforms using GNU Octave.
GNU Octave is an open-source software that supports high-level programming language. It is similar to MATLAB in terms of writing the program/code for performing various mathematical operations or plots. You can learn how to perform basic operations on Octave from here.
Amplitude modulation of a sine wave can be generated using Octave with the following programs:
Assigning all the required parameters:
MATLAB
% time sampling where Step Size = 0.001t = 0:0.001:1 % frequency of input or modulating signalfm = 10 % frequency of output or modulated signalfc = 100
Program to visualize the Modulating Signal:
MATLAB
% Input or Modulating Signalinput_signal = sin(2 * pi * fm * t)plot(input_signal,'k') % 'k' gives black colour plot xlabel('Time')ylabel('Amplitude')title('Input or Modulating Signal')
Output:
Program to visualize the Carrier Signal:
MATLAB
% Carrier Signalcarrier_signal = sin(2 * pi * fc *t)plot(carrier_signal,'r') % 'r' gives red colour plot xlabel('Time')ylabel('Amplitude')title('Carrier Signal')
Output:
There are three different cases of Amplitude Modulation depending upon the value of modulation factor also known as depth of modulation (m). The modulation factor can be defined as the ratio of the difference between the maximum and minimum amplitudes of the modulated signal to the sum of these amplitudes.
Under Modulation (m < 1)
MATLAB
% Output or Amplitude Modulated Signal (Under Modulated)m = 0.5 % modulation factor (m < 1)under_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(under_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Under Modulated Output Signal (m < 1)')
Output:
Critical or Full Modulation (m = 1)
MATLAB
% Output or Amplitude Modulated Signal (Fully or Critically Modulated)m = 1.0 % modulation factor (m = 1)fully_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(fully_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Critically Modulated Output Signal (m = 1)')
Output:
Over Modulation (m > 1)
MATLAB
% Output or Amplitude Modulated Signal (Over Modulated)m = 1.5 % modulation factor (m > 1)over_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(over_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Over Modulated Output Signal (m > 1)')
Output:
If you want to implement Amplitude Modulation using MATLAB, then please take guidance from here.
Octave-GNU
Technical Scripter 2020
Advanced Computer Subject
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
ML | Stochastic Gradient Descent (SGD)
Fuzzy Logic | Introduction
Q-Learning in Python
Getting Started with System Design
ML | Data Preprocessing in Python
Classifying data using Support Vector Machines(SVMs) in Python
Monolithic vs Microservices architecture
OpenCV - Overview
|
[
{
"code": null,
"e": 24174,
"s": 24146,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 24419,
"s": 24174,
"text": "Modulation in communication systems is a widely used process in which characteristics like amplitude, frequency, or phase angle of a high-frequency carrier wave is varied according to the instantaneous value of the low-frequency message signal."
},
{
"code": null,
"e": 24726,
"s": 24419,
"text": "Amplitude modulation is a modulation technique utilized in electronic communication, most ordinarily for transmitting data by means of a carrier wave. In amplitude modulation, the amplitude that is the signal quality of the carrier wave differs with respect to that of the message signal being transmitted."
},
{
"code": null,
"e": 24848,
"s": 24726,
"text": "There are mainly three types of modulation techniques: Amplitude Modulation, Frequency Modulation, and Phase Modulation. "
},
{
"code": null,
"e": 24957,
"s": 24848,
"text": "In this article, we are going to discuss how to generate the Amplitude Modulated waveforms using GNU Octave."
},
{
"code": null,
"e": 25227,
"s": 24957,
"text": "GNU Octave is an open-source software that supports high-level programming language. It is similar to MATLAB in terms of writing the program/code for performing various mathematical operations or plots. You can learn how to perform basic operations on Octave from here."
},
{
"code": null,
"e": 25323,
"s": 25227,
"text": "Amplitude modulation of a sine wave can be generated using Octave with the following programs: "
},
{
"code": null,
"e": 25362,
"s": 25323,
"text": "Assigning all the required parameters:"
},
{
"code": null,
"e": 25369,
"s": 25362,
"text": "MATLAB"
},
{
"code": "% time sampling where Step Size = 0.001t = 0:0.001:1 % frequency of input or modulating signalfm = 10 % frequency of output or modulated signalfc = 100",
"e": 25523,
"s": 25369,
"text": null
},
{
"code": null,
"e": 25567,
"s": 25523,
"text": "Program to visualize the Modulating Signal:"
},
{
"code": null,
"e": 25574,
"s": 25567,
"text": "MATLAB"
},
{
"code": "% Input or Modulating Signalinput_signal = sin(2 * pi * fm * t)plot(input_signal,'k') % 'k' gives black colour plot xlabel('Time')ylabel('Amplitude')title('Input or Modulating Signal')",
"e": 25760,
"s": 25574,
"text": null
},
{
"code": null,
"e": 25768,
"s": 25760,
"text": "Output:"
},
{
"code": null,
"e": 25809,
"s": 25768,
"text": "Program to visualize the Carrier Signal:"
},
{
"code": null,
"e": 25816,
"s": 25809,
"text": "MATLAB"
},
{
"code": "% Carrier Signalcarrier_signal = sin(2 * pi * fc *t)plot(carrier_signal,'r') % 'r' gives red colour plot xlabel('Time')ylabel('Amplitude')title('Carrier Signal')",
"e": 25979,
"s": 25816,
"text": null
},
{
"code": null,
"e": 25987,
"s": 25979,
"text": "Output:"
},
{
"code": null,
"e": 26295,
"s": 25987,
"text": "There are three different cases of Amplitude Modulation depending upon the value of modulation factor also known as depth of modulation (m). The modulation factor can be defined as the ratio of the difference between the maximum and minimum amplitudes of the modulated signal to the sum of these amplitudes."
},
{
"code": null,
"e": 26320,
"s": 26295,
"text": "Under Modulation (m < 1)"
},
{
"code": null,
"e": 26327,
"s": 26320,
"text": "MATLAB"
},
{
"code": "% Output or Amplitude Modulated Signal (Under Modulated)m = 0.5 % modulation factor (m < 1)under_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(under_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Under Modulated Output Signal (m < 1)')",
"e": 26639,
"s": 26327,
"text": null
},
{
"code": null,
"e": 26647,
"s": 26639,
"text": "Output:"
},
{
"code": null,
"e": 26683,
"s": 26647,
"text": "Critical or Full Modulation (m = 1)"
},
{
"code": null,
"e": 26690,
"s": 26683,
"text": "MATLAB"
},
{
"code": "% Output or Amplitude Modulated Signal (Fully or Critically Modulated)m = 1.0 % modulation factor (m = 1)fully_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(fully_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Critically Modulated Output Signal (m = 1)')",
"e": 27021,
"s": 26690,
"text": null
},
{
"code": null,
"e": 27029,
"s": 27021,
"text": "Output:"
},
{
"code": null,
"e": 27053,
"s": 27029,
"text": "Over Modulation (m > 1)"
},
{
"code": null,
"e": 27060,
"s": 27053,
"text": "MATLAB"
},
{
"code": "% Output or Amplitude Modulated Signal (Over Modulated)m = 1.5 % modulation factor (m > 1)over_modulated_signal = (1 + m * sin(2 * pi * fm *t)) .* sin(2 * pi * fc * t)plot(over_modulated_signal,'b') % 'b' gives blue colour plot xlabel('Time')ylabel('Amplitude')title('Over Modulated Output Signal (m > 1)')",
"e": 27368,
"s": 27060,
"text": null
},
{
"code": null,
"e": 27376,
"s": 27368,
"text": "Output:"
},
{
"code": null,
"e": 27473,
"s": 27376,
"text": "If you want to implement Amplitude Modulation using MATLAB, then please take guidance from here."
},
{
"code": null,
"e": 27484,
"s": 27473,
"text": "Octave-GNU"
},
{
"code": null,
"e": 27508,
"s": 27484,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27534,
"s": 27508,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27553,
"s": 27534,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27651,
"s": 27553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27660,
"s": 27651,
"text": "Comments"
},
{
"code": null,
"e": 27673,
"s": 27660,
"text": "Old Comments"
},
{
"code": null,
"e": 27717,
"s": 27673,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27758,
"s": 27717,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27797,
"s": 27758,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 27824,
"s": 27797,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27845,
"s": 27824,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 27880,
"s": 27845,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 27914,
"s": 27880,
"text": "ML | Data Preprocessing in Python"
},
{
"code": null,
"e": 27977,
"s": 27914,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 28018,
"s": 27977,
"text": "Monolithic vs Microservices architecture"
}
] |
How to Alter a Column from Null to Not Null in SQL Server? - GeeksforGeeks
|
23 Sep, 2021
With this article, we will learn how to alter a column from accepting Null values to Not Null in SQL Server. The prerequisites of this article are you should be having a MSSQL server on your computer.
A query is a statement or a group of statements written to perform a specific task, like retrieve data, save data into a database.
So, we will create a database first:
CREATE DATABASE GFG
USE GFG
CREATE TABLE gfgTutorial(
id integer,
Name varchar(20)
)
sp_help 'dbo.gfgTutorial'
ALTER TABLE gfgTutorial ALTER COLUMN id VARCHAR (50) NOT NULL;
So now our table id column is changed to not null
Changed null id to not null
So we have successfully changed the id column to not null in the gfgTutorial table.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24567,
"s": 24366,
"text": "With this article, we will learn how to alter a column from accepting Null values to Not Null in SQL Server. The prerequisites of this article are you should be having a MSSQL server on your computer."
},
{
"code": null,
"e": 24698,
"s": 24567,
"text": "A query is a statement or a group of statements written to perform a specific task, like retrieve data, save data into a database."
},
{
"code": null,
"e": 24735,
"s": 24698,
"text": "So, we will create a database first:"
},
{
"code": null,
"e": 24755,
"s": 24735,
"text": "CREATE DATABASE GFG"
},
{
"code": null,
"e": 24763,
"s": 24755,
"text": "USE GFG"
},
{
"code": null,
"e": 24820,
"s": 24763,
"text": "CREATE TABLE gfgTutorial(\nid integer,\nName varchar(20)\n)"
},
{
"code": null,
"e": 24846,
"s": 24820,
"text": "sp_help 'dbo.gfgTutorial'"
},
{
"code": null,
"e": 24909,
"s": 24846,
"text": "ALTER TABLE gfgTutorial ALTER COLUMN id VARCHAR (50) NOT NULL;"
},
{
"code": null,
"e": 24959,
"s": 24909,
"text": "So now our table id column is changed to not null"
},
{
"code": null,
"e": 24987,
"s": 24959,
"text": "Changed null id to not null"
},
{
"code": null,
"e": 25071,
"s": 24987,
"text": "So we have successfully changed the id column to not null in the gfgTutorial table."
},
{
"code": null,
"e": 25078,
"s": 25071,
"text": "Picked"
},
{
"code": null,
"e": 25089,
"s": 25078,
"text": "SQL-Server"
},
{
"code": null,
"e": 25093,
"s": 25089,
"text": "SQL"
},
{
"code": null,
"e": 25097,
"s": 25093,
"text": "SQL"
},
{
"code": null,
"e": 25195,
"s": 25097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25261,
"s": 25195,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25318,
"s": 25261,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 25350,
"s": 25318,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25386,
"s": 25350,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 25401,
"s": 25386,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 25479,
"s": 25401,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25496,
"s": 25479,
"text": "SQL using Python"
},
{
"code": null,
"e": 25558,
"s": 25496,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 25624,
"s": 25558,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
DateTime.AddHours() Method in C#
|
The DateTime.AddHours() method in C# is used to add the specified number of hours to the value of this instance. This method returns a new DateTime.
Following is the syntax β
public DateTime AddHours (double hrs);
Above, hrs are the number of hours to be added. The value can be negative to subtract the hours.
Let us now see an example to implement the DateTime.AddHours() method
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 11, 2, 9, 0, 10);
DateTime d2 = d1.AddHours(2);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
System.Console.WriteLine("\nNew DateTime (After adding hours) = {0:dd} {0:y}, {0:t} ", d2);
}
}
This will produce the following output β
Initial DateTime = 02 November 2019, 9:00 AM
New DateTime (After adding hours) = 02 November 2019, 11:00 AM
Let us now see another example to implement the DateTime.AddHours() method β
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 10, 5, 9, 0, 10);
DateTime d2 = d1.AddHours(-5);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
System.Console.WriteLine("\nNew DateTime (After subtracting hours) = {0:dd} {0:y}, {0:t} ", d2);
}
}
This will produce the following output β
Initial DateTime = 05 October 2019, 9:00 AM
New DateTime (After subtracting hours) = 05 October 2019, 4:00 AM
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "The DateTime.AddHours() method in C# is used to add the specified number of hours to the value of this instance. This method returns a new DateTime."
},
{
"code": null,
"e": 1237,
"s": 1211,
"text": "Following is the syntax β"
},
{
"code": null,
"e": 1276,
"s": 1237,
"text": "public DateTime AddHours (double hrs);"
},
{
"code": null,
"e": 1373,
"s": 1276,
"text": "Above, hrs are the number of hours to be added. The value can be negative to subtract the hours."
},
{
"code": null,
"e": 1443,
"s": 1373,
"text": "Let us now see an example to implement the DateTime.AddHours() method"
},
{
"code": null,
"e": 1784,
"s": 1443,
"text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = new DateTime(2019, 11, 2, 9, 0, 10);\n DateTime d2 = d1.AddHours(2);\n System.Console.WriteLine(\"Initial DateTime = {0:dd} {0:y}, {0:t} \", d1);\n System.Console.WriteLine(\"\\nNew DateTime (After adding hours) = {0:dd} {0:y}, {0:t} \", d2);\n }\n}"
},
{
"code": null,
"e": 1825,
"s": 1784,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1933,
"s": 1825,
"text": "Initial DateTime = 02 November 2019, 9:00 AM\nNew DateTime (After adding hours) = 02 November 2019, 11:00 AM"
},
{
"code": null,
"e": 2010,
"s": 1933,
"text": "Let us now see another example to implement the DateTime.AddHours() method β"
},
{
"code": null,
"e": 2357,
"s": 2010,
"text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = new DateTime(2019, 10, 5, 9, 0, 10);\n DateTime d2 = d1.AddHours(-5);\n System.Console.WriteLine(\"Initial DateTime = {0:dd} {0:y}, {0:t} \", d1);\n System.Console.WriteLine(\"\\nNew DateTime (After subtracting hours) = {0:dd} {0:y}, {0:t} \", d2);\n }\n}"
},
{
"code": null,
"e": 2398,
"s": 2357,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2508,
"s": 2398,
"text": "Initial DateTime = 05 October 2019, 9:00 AM\nNew DateTime (After subtracting hours) = 05 October 2019, 4:00 AM"
}
] |
Given a sorted array and a number x, find the pair in array whose sum is closest to x - GeeksforGeeks
|
31 Oct, 2021
Given a sorted array and a number x, find a pair in an array whose sum is closest to x.
Examples:
Input: arr[] = {10, 22, 28, 29, 30, 40}, x = 54
Output: 22 and 30
Input: arr[] = {1, 3, 4, 7, 10}, x = 15
Output: 4 and 10
A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between pair sum and x is minimum). Finally, print the closest pair. The time complexity of this solution is O(n2)
An efficient solution can find the pair in O(n) time. The idea is similar to method 1 of this post. The following is a detailed algorithm.
1) Initialize a variable diff as infinite (Diff is used to store the
difference between pair and x). We need to find the minimum diff.
2) Initialize two index variables l and r in the given sorted array.
(a) Initialize first to the leftmost index: l = 0
(b) Initialize second the rightmost index: r = n-1
3) Loop while l < r.
(a) If abs(arr[l] + arr[r] - sum) < diff then
update diff and result
(b) If(arr[l] + arr[r] < sum ) then l++
(c) Else r--
Following is the implementation of the above algorithm.
C++14
Java
Python3
C#
PHP
Javascript
// Simple C++ program to find the pair with sum closest to a given no.#include <bits/stdc++.h>using namespace std; // Prints the pair with sum closest to xvoid printClosest(int arr[], int n, int x){ int res_l, res_r; // To store indexes of result pair // Initialize left and right indexes and difference between // pair sum and x int l = 0, r = n-1, diff = INT_MAX; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the closest pair so far if (abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];} // Driver program to test above functionsint main(){ int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; int n = sizeof(arr)/sizeof(arr[0]); printClosest(arr, n, x); return 0;}// Code By Mayur Patil
// Java program to find pair with sum closest to ximport java.io.*;import java.util.*;import java.lang.Math; class CloseSum { // Prints the pair with sum closest to x static void printClosest(int arr[], int n, int x) { int res_l=0, res_r=0; // To store indexes of result pair // Initialize left and right indexes and difference between // pair sum and x int l = 0, r = n-1, diff = Integer.MAX_VALUE; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the closest pair so far if (Math.abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } System.out.println(" The closest pair is "+arr[res_l]+" and "+ arr[res_r]);} // Driver program to test above function public static void main(String[] args) { int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; int n = arr.length; printClosest(arr, n, x); }}/*This code is contributed by Devesh Agrawal*/
# Python3 program to find the pair# with sum# closest to a given no. # A sufficiently large value greater# than any# element in the input arrayMAX_VAL = 1000000000 #Prints the pair with sum closest to x def printClosest(arr, n, x): # To store indexes of result pair res_l, res_r = 0, 0 #Initialize left and right indexes # and difference between # pair sum and x l, r, diff = 0, n-1, MAX_VAL # While there are elements between l and r while r > l: # Check if this pair is closer than the # closest pair so far if abs(arr[l] + arr[r] - x) < diff: res_l = l res_r = r diff = abs(arr[l] + arr[r] - x) if arr[l] + arr[r] > x: # If this pair has more sum, move to # smaller values. r -= 1 else: # Move to larger values l += 1 print('The closest pair is {} and {}' .format(arr[res_l], arr[res_r])) # Driver code to test aboveif __name__ == "__main__": arr = [10, 22, 28, 29, 30, 40] n = len(arr) x=54 printClosest(arr, n, x) # This code is contributed by Tuhin Patra
// C# program to find pair with sum closest to xusing System; class GFG { // Prints the pair with sum closest to x static void printClosest(int []arr, int n, int x) { // To store indexes of result pair int res_l = 0, res_r = 0; // Initialize left and right indexes and // difference between pair sum and x int l = 0, r = n-1, diff = int.MaxValue; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the // closest pair so far if (Math.Abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.Abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to // smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } Console.Write(" The closest pair is " + arr[res_l] + " and " + arr[res_r]); } // Driver program to test above function public static void Main() { int []arr = {10, 22, 28, 29, 30, 40}; int x = 54; int n = arr.Length; printClosest(arr, n, x); }} // This code is contributed by nitin mittal.
<?php// Simple PHP program to find the// pair with sum closest to a// given no. // Prints the pair with// sum closest to xfunction printClosest($arr, $n, $x){ // To store indexes // of result pair $res_l; $res_r; // Initialize left and right // indexes and difference between // pair sum and x $l = 0; $r = $n - 1; $diff = PHP_INT_MAX; // While there are elements // between l and r while ($r > $l) { // Check if this pair is closer // than the closest pair so far if (abs($arr[$l] + $arr[$r] - $x) < $diff) { $res_l = $l; $res_r = $r; $diff = abs($arr[$l] + $arr[$r] - $x); } // If this pair has more sum, // move to smaller values. if ($arr[$l] + $arr[$r] > $x) $r--; // Move to larger values else $l++; } echo " The closest pair is " , $arr[$res_l] ," and " , $arr[$res_r];} // Driver Code $arr = array(10, 22, 28, 29, 30, 40); $x = 54; $n = count($arr); printClosest($arr, $n, $x); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find pair// with sum closest to x // Prints the pair with sum closest to x function printClosest(arr,n,x) { // To store indexes of result pair let res_l=0, res_r=0; // Initialize left and right indexes // and difference between // pair sum and x let l = 0, r = n-1, diff = Number.MAX_VALUE; // While there are elements // between l and r while (r > l) { // Check if this pair is closer // than the closest pair so far if (Math.abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(arr[l] + arr[r] - x); } // If this pair has more sum, // move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } document.write( " The closest pair is "+arr[res_l]+" and "+ arr[res_r] );} // Driver program to test above function let arr = [10, 22, 28, 29, 30, 40], x = 54; let n = arr.length; printClosest(arr, n, x); // This code is contributed by sravan kumar </script>
The closest pair is 22 and 30
Time Complexity: O(n), where n is the length of an Array.
https://www.youtube.com/watch?v=QMWBRnolFCU
This article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
vt_m
TuhinPatra
bhavyaupadhyay2000
swtdrmz58
sravankumar8128
akshaysingh98088
mayur_patil
two-pointer-algorithm
Arrays
Searching
Sorting
two-pointer-algorithm
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
|
[
{
"code": null,
"e": 26978,
"s": 26950,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 27066,
"s": 26978,
"text": "Given a sorted array and a number x, find a pair in an array whose sum is closest to x."
},
{
"code": null,
"e": 27076,
"s": 27066,
"text": "Examples:"
},
{
"code": null,
"e": 27200,
"s": 27076,
"text": "Input: arr[] = {10, 22, 28, 29, 30, 40}, x = 54\nOutput: 22 and 30\n\nInput: arr[] = {1, 3, 4, 7, 10}, x = 15\nOutput: 4 and 10"
},
{
"code": null,
"e": 27419,
"s": 27200,
"text": "A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between pair sum and x is minimum). Finally, print the closest pair. The time complexity of this solution is O(n2)"
},
{
"code": null,
"e": 27559,
"s": 27419,
"text": "An efficient solution can find the pair in O(n) time. The idea is similar to method 1 of this post. The following is a detailed algorithm. "
},
{
"code": null,
"e": 28071,
"s": 27559,
"text": "1) Initialize a variable diff as infinite (Diff is used to store the \n difference between pair and x). We need to find the minimum diff.\n2) Initialize two index variables l and r in the given sorted array.\n (a) Initialize first to the leftmost index: l = 0\n (b) Initialize second the rightmost index: r = n-1\n3) Loop while l < r.\n (a) If abs(arr[l] + arr[r] - sum) < diff then \n update diff and result \n (b) If(arr[l] + arr[r] < sum ) then l++\n (c) Else r-- "
},
{
"code": null,
"e": 28127,
"s": 28071,
"text": "Following is the implementation of the above algorithm."
},
{
"code": null,
"e": 28133,
"s": 28127,
"text": "C++14"
},
{
"code": null,
"e": 28138,
"s": 28133,
"text": "Java"
},
{
"code": null,
"e": 28146,
"s": 28138,
"text": "Python3"
},
{
"code": null,
"e": 28149,
"s": 28146,
"text": "C#"
},
{
"code": null,
"e": 28153,
"s": 28149,
"text": "PHP"
},
{
"code": null,
"e": 28164,
"s": 28153,
"text": "Javascript"
},
{
"code": "// Simple C++ program to find the pair with sum closest to a given no.#include <bits/stdc++.h>using namespace std; // Prints the pair with sum closest to xvoid printClosest(int arr[], int n, int x){ int res_l, res_r; // To store indexes of result pair // Initialize left and right indexes and difference between // pair sum and x int l = 0, r = n-1, diff = INT_MAX; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the closest pair so far if (abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } cout <<\" The closest pair is \" << arr[res_l] << \" and \" << arr[res_r];} // Driver program to test above functionsint main(){ int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; int n = sizeof(arr)/sizeof(arr[0]); printClosest(arr, n, x); return 0;}// Code By Mayur Patil",
"e": 29270,
"s": 28164,
"text": null
},
{
"code": "// Java program to find pair with sum closest to ximport java.io.*;import java.util.*;import java.lang.Math; class CloseSum { // Prints the pair with sum closest to x static void printClosest(int arr[], int n, int x) { int res_l=0, res_r=0; // To store indexes of result pair // Initialize left and right indexes and difference between // pair sum and x int l = 0, r = n-1, diff = Integer.MAX_VALUE; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the closest pair so far if (Math.abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } System.out.println(\" The closest pair is \"+arr[res_l]+\" and \"+ arr[res_r]);} // Driver program to test above function public static void main(String[] args) { int arr[] = {10, 22, 28, 29, 30, 40}, x = 54; int n = arr.length; printClosest(arr, n, x); }}/*This code is contributed by Devesh Agrawal*/",
"e": 30597,
"s": 29270,
"text": null
},
{
"code": "# Python3 program to find the pair# with sum# closest to a given no. # A sufficiently large value greater# than any# element in the input arrayMAX_VAL = 1000000000 #Prints the pair with sum closest to x def printClosest(arr, n, x): # To store indexes of result pair res_l, res_r = 0, 0 #Initialize left and right indexes # and difference between # pair sum and x l, r, diff = 0, n-1, MAX_VAL # While there are elements between l and r while r > l: # Check if this pair is closer than the # closest pair so far if abs(arr[l] + arr[r] - x) < diff: res_l = l res_r = r diff = abs(arr[l] + arr[r] - x) if arr[l] + arr[r] > x: # If this pair has more sum, move to # smaller values. r -= 1 else: # Move to larger values l += 1 print('The closest pair is {} and {}' .format(arr[res_l], arr[res_r])) # Driver code to test aboveif __name__ == \"__main__\": arr = [10, 22, 28, 29, 30, 40] n = len(arr) x=54 printClosest(arr, n, x) # This code is contributed by Tuhin Patra",
"e": 31747,
"s": 30597,
"text": null
},
{
"code": "// C# program to find pair with sum closest to xusing System; class GFG { // Prints the pair with sum closest to x static void printClosest(int []arr, int n, int x) { // To store indexes of result pair int res_l = 0, res_r = 0; // Initialize left and right indexes and // difference between pair sum and x int l = 0, r = n-1, diff = int.MaxValue; // While there are elements between l and r while (r > l) { // Check if this pair is closer than the // closest pair so far if (Math.Abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.Abs(arr[l] + arr[r] - x); } // If this pair has more sum, move to // smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } Console.Write(\" The closest pair is \" + arr[res_l] + \" and \" + arr[res_r]); } // Driver program to test above function public static void Main() { int []arr = {10, 22, 28, 29, 30, 40}; int x = 54; int n = arr.Length; printClosest(arr, n, x); }} // This code is contributed by nitin mittal.",
"e": 33095,
"s": 31747,
"text": null
},
{
"code": "<?php// Simple PHP program to find the// pair with sum closest to a// given no. // Prints the pair with// sum closest to xfunction printClosest($arr, $n, $x){ // To store indexes // of result pair $res_l; $res_r; // Initialize left and right // indexes and difference between // pair sum and x $l = 0; $r = $n - 1; $diff = PHP_INT_MAX; // While there are elements // between l and r while ($r > $l) { // Check if this pair is closer // than the closest pair so far if (abs($arr[$l] + $arr[$r] - $x) < $diff) { $res_l = $l; $res_r = $r; $diff = abs($arr[$l] + $arr[$r] - $x); } // If this pair has more sum, // move to smaller values. if ($arr[$l] + $arr[$r] > $x) $r--; // Move to larger values else $l++; } echo \" The closest pair is \" , $arr[$res_l] ,\" and \" , $arr[$res_r];} // Driver Code $arr = array(10, 22, 28, 29, 30, 40); $x = 54; $n = count($arr); printClosest($arr, $n, $x); // This code is contributed by anuj_67.?>",
"e": 34304,
"s": 33095,
"text": null
},
{
"code": "<script> // JavaScript program to find pair// with sum closest to x // Prints the pair with sum closest to x function printClosest(arr,n,x) { // To store indexes of result pair let res_l=0, res_r=0; // Initialize left and right indexes // and difference between // pair sum and x let l = 0, r = n-1, diff = Number.MAX_VALUE; // While there are elements // between l and r while (r > l) { // Check if this pair is closer // than the closest pair so far if (Math.abs(arr[l] + arr[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(arr[l] + arr[r] - x); } // If this pair has more sum, // move to smaller values. if (arr[l] + arr[r] > x) r--; else // Move to larger values l++; } document.write( \" The closest pair is \"+arr[res_l]+\" and \"+ arr[res_r] );} // Driver program to test above function let arr = [10, 22, 28, 29, 30, 40], x = 54; let n = arr.length; printClosest(arr, n, x); // This code is contributed by sravan kumar </script>",
"e": 35567,
"s": 34304,
"text": null
},
{
"code": null,
"e": 35598,
"s": 35567,
"text": " The closest pair is 22 and 30"
},
{
"code": null,
"e": 35656,
"s": 35598,
"text": "Time Complexity: O(n), where n is the length of an Array."
},
{
"code": null,
"e": 35700,
"s": 35656,
"text": "https://www.youtube.com/watch?v=QMWBRnolFCU"
},
{
"code": null,
"e": 35863,
"s": 35700,
"text": "This article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 35876,
"s": 35863,
"text": "nitin mittal"
},
{
"code": null,
"e": 35881,
"s": 35876,
"text": "vt_m"
},
{
"code": null,
"e": 35892,
"s": 35881,
"text": "TuhinPatra"
},
{
"code": null,
"e": 35911,
"s": 35892,
"text": "bhavyaupadhyay2000"
},
{
"code": null,
"e": 35921,
"s": 35911,
"text": "swtdrmz58"
},
{
"code": null,
"e": 35937,
"s": 35921,
"text": "sravankumar8128"
},
{
"code": null,
"e": 35954,
"s": 35937,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 35966,
"s": 35954,
"text": "mayur_patil"
},
{
"code": null,
"e": 35988,
"s": 35966,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 35995,
"s": 35988,
"text": "Arrays"
},
{
"code": null,
"e": 36005,
"s": 35995,
"text": "Searching"
},
{
"code": null,
"e": 36013,
"s": 36005,
"text": "Sorting"
},
{
"code": null,
"e": 36035,
"s": 36013,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 36042,
"s": 36035,
"text": "Arrays"
},
{
"code": null,
"e": 36052,
"s": 36042,
"text": "Searching"
},
{
"code": null,
"e": 36060,
"s": 36052,
"text": "Sorting"
},
{
"code": null,
"e": 36158,
"s": 36060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36226,
"s": 36158,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36270,
"s": 36226,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36318,
"s": 36270,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36341,
"s": 36318,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36373,
"s": 36341,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36387,
"s": 36373,
"text": "Binary Search"
},
{
"code": null,
"e": 36455,
"s": 36387,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36469,
"s": 36455,
"text": "Linear Search"
},
{
"code": null,
"e": 36517,
"s": 36469,
"text": "Search an element in a sorted and rotated array"
}
] |
Tryit Editor v3.7
|
Tryit: Several !important rules
|
[] |
Why singleton class is always sealed in C#?
|
The sealed keyword means that the class cannot be inherited from. Declaring constructors private means that instances of the class cannot be created.
You can have a base class with a private constructor, but still inherit from that base class, define some public constructors, and effectively instantiate that base class.
Constructors are not inherited (so the derived class won't have all private constructors just because the base class does), and that derived classes always call the base class constructors first.
Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.
static class Program {
static void Main(string[] args){
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails("From Student");
Singleton fromEmployee = Singleton.GetInstance;
fromEmployee.PrintDetails("From Employee");
Console.WriteLine("-------------------------------------");
Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
derivedObj.PrintDetails("From Derived");
Console.ReadLine();
}
}
public class Singleton {
private static int counter = 0;
private static object obj = new object();
private Singleton() {
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
private static Singleton instance = null;
public static Singleton GetInstance{
get {
if (instance == null)
instance = new Singleton();
return instance;
}
}
public void PrintDetails(string message){
Console.WriteLine(message);
}
public class DerivedSingleton : Singleton {
}
}
|
[
{
"code": null,
"e": 1212,
"s": 1062,
"text": "The sealed keyword means that the class cannot be inherited from. Declaring constructors private means that instances of the class cannot be created."
},
{
"code": null,
"e": 1384,
"s": 1212,
"text": "You can have a base class with a private constructor, but still inherit from that base class, define some public constructors, and effectively instantiate that base class."
},
{
"code": null,
"e": 1580,
"s": 1384,
"text": "Constructors are not inherited (so the derived class won't have all private constructors just because the base class does), and that derived classes always call the base class constructors first."
},
{
"code": null,
"e": 1752,
"s": 1580,
"text": "Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class."
},
{
"code": null,
"e": 2810,
"s": 1752,
"text": "static class Program {\n static void Main(string[] args){\n Singleton fromStudent = Singleton.GetInstance;\n fromStudent.PrintDetails(\"From Student\");\n\n Singleton fromEmployee = Singleton.GetInstance;\n fromEmployee.PrintDetails(\"From Employee\");\n\n Console.WriteLine(\"-------------------------------------\");\n\n Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();\n derivedObj.PrintDetails(\"From Derived\");\n Console.ReadLine();\n }\n}\npublic class Singleton {\n private static int counter = 0;\n private static object obj = new object();\n\n private Singleton() {\n counter++;\n Console.WriteLine(\"Counter Value \" + counter.ToString());\n }\n private static Singleton instance = null;\n\n public static Singleton GetInstance{\n get {\n if (instance == null)\n instance = new Singleton();\n return instance;\n }\n }\n\n public void PrintDetails(string message){\n Console.WriteLine(message);\n }\n\n public class DerivedSingleton : Singleton {\n }\n}"
}
] |
Average of Squares of Natural Numbers?
|
The average of the square of Natural Number is calculated by adding all the squares up to n natural numbers and then dividing it by the number.
Average of square of first 2 natural numbers is 2.5 ,
12 + 22 = 5 => 5/2 = 2.5.
There are two methods for calculating this is programming β
Using Loops
Using Formula
Calculating average of square of natural numbers using loops
This logic works by finding the squares of all natural numbers. By loop from 1 to n finding square of each and adding to the sum variable. Then dividing this sum by n.
Program to find the sum of squares of natural numbers β
Live Demo
#include <stdio.h>
int main() {
int n = 2;
float sum = 0;
for (int i = 1; i <= n; i++) {
sum = sum + (i * i);
}
float average = sum/n;
printf("The average of the square of %d natural numbers is %f", n,average);
return 0;
}
The average of the square of 2 natural numbers is 2.500000
Calculating average of square of natural numbers using formula.
There are mathematical formulas to make calculations easy. For calculating the sum of squares of natural numbers the formula is β n*(n+1)*((2*n)+1)/6β diving this by the number n gives the formula : β (n+1)*((2*n)+1)/6β.
Program to find the sum of squares of natural numbers β
Live Demo
#include <stdio.h>
int main() {
int n = 2;
float average = ((n+1)*((2*n)+1)/6);
printf("The average of the square of %d natural numbers is %f", n,average);
return 0;
}
The average of the square of 2 natural numbers is 2.500000
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "The average of the square of Natural Number is calculated by adding all the squares up to n natural numbers and then dividing it by the number."
},
{
"code": null,
"e": 1260,
"s": 1206,
"text": "Average of square of first 2 natural numbers is 2.5 ,"
},
{
"code": null,
"e": 1286,
"s": 1260,
"text": "12 + 22 = 5 => 5/2 = 2.5."
},
{
"code": null,
"e": 1346,
"s": 1286,
"text": "There are two methods for calculating this is programming β"
},
{
"code": null,
"e": 1358,
"s": 1346,
"text": "Using Loops"
},
{
"code": null,
"e": 1372,
"s": 1358,
"text": "Using Formula"
},
{
"code": null,
"e": 1433,
"s": 1372,
"text": "Calculating average of square of natural numbers using loops"
},
{
"code": null,
"e": 1601,
"s": 1433,
"text": "This logic works by finding the squares of all natural numbers. By loop from 1 to n finding square of each and adding to the sum variable. Then dividing this sum by n."
},
{
"code": null,
"e": 1657,
"s": 1601,
"text": "Program to find the sum of squares of natural numbers β"
},
{
"code": null,
"e": 1668,
"s": 1657,
"text": " Live Demo"
},
{
"code": null,
"e": 1918,
"s": 1668,
"text": "#include <stdio.h>\nint main() {\n int n = 2;\n float sum = 0;\n for (int i = 1; i <= n; i++) {\n sum = sum + (i * i);\n }\n float average = sum/n;\n printf(\"The average of the square of %d natural numbers is %f\", n,average);\n return 0;\n}"
},
{
"code": null,
"e": 1977,
"s": 1918,
"text": "The average of the square of 2 natural numbers is 2.500000"
},
{
"code": null,
"e": 2042,
"s": 1977,
"text": "Calculating average of square of natural numbers using formula. "
},
{
"code": null,
"e": 2263,
"s": 2042,
"text": "There are mathematical formulas to make calculations easy. For calculating the sum of squares of natural numbers the formula is β n*(n+1)*((2*n)+1)/6β diving this by the number n gives the formula : β (n+1)*((2*n)+1)/6β."
},
{
"code": null,
"e": 2319,
"s": 2263,
"text": "Program to find the sum of squares of natural numbers β"
},
{
"code": null,
"e": 2330,
"s": 2319,
"text": " Live Demo"
},
{
"code": null,
"e": 2510,
"s": 2330,
"text": "#include <stdio.h>\nint main() {\n int n = 2;\n float average = ((n+1)*((2*n)+1)/6);\n printf(\"The average of the square of %d natural numbers is %f\", n,average);\n return 0;\n}"
},
{
"code": null,
"e": 2569,
"s": 2510,
"text": "The average of the square of 2 natural numbers is 2.500000"
}
] |
Churn Prediction. Churn prediction with XGBoost Binary... | by BarΔ±sΜ§ Karaman | Towards Data Science
|
This series of articles was designed to explain how to use Python in a simplistic way to fuel your companyβs growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning.
I will cover all the topics in the following nine articles:
1- Know Your Metrics
2- Customer Segmentation
3- Customer Lifetime Value Prediction
4- Churn Prediction
5- Predicting Next Purchase Day
6- Predicting Sales
7- Market Response Models
8- Uplift Modeling
9- A/B Testing Design and Execution
Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:
Sometimes you gotta run before you can walk β Tony Stark
As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only.
Alright, letβs start.
In the last three sections of Data Driven Growth series, we have discovered tracking essential metrics, customer segmentation, and predicting the lifetime value programmatically. Since we know our best customers by segmentation and lifetime value prediction, we should also work hard on retaining them. Thatβs what makes Retention Rate is one of the most critical metrics.
Retention Rate is an indication of how good is your product market fit (PMF). If your PMF is not satisfactory, you should see your customers churning very soon. One of the powerful tools to improve Retention Rate (hence the PMF) is Churn Prediction. By using this technique, you can easily find out who is likely to churn in the given period. In this article, we will use a Telco dataset and go over the following steps to develop a Churn Prediction model:
Exploratory data analysis
Feature engineering
Investigating how the features affect Retention by using Logistic Regression
Building a classification model with XGBoost
We start with checking out how our data looks like and visualize how it interacts with our label (churned or not?). Letβs start with importing our data and print the first ten rows:
df_data = pd.read_csv('churn_data.csv')df_data.head(10)
Output:
A better way to see all the columns and their data type is using .info() method:
It seems like our data fall under two categories:
Categorical features: gender, streaming tv, payment method &, etc.
Numerical features: tenure, monthly charges, total charges
Now starting from the categorical ones, we shed light on all features and see how helpful they are to identify if a customer is going to churn.
As a side note, in the dataset we have, Churn column is string with Yes/No values. We convert it to integer to make it easier to use in our analysis.
df_data.loc[df_data.Churn=='No','Churn'] = 0 df_data.loc[df_data.Churn=='Yes','Churn'] = 1
Gender
By using the code block below, we easily visualize how Churn Rate (1-Retention Rate) looks like for each value:
df_plot = df_data.groupby('gender').Churn.mean().reset_index()plot_data = [ go.Bar( x=df_plot['gender'], y=df_plot['Churn'], width = [0.5, 0.5], marker=dict( color=['green', 'blue']) )]plot_layout = go.Layout( xaxis={"type": "category"}, yaxis={"title": "Churn Rate"}, title='Gender', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)
Output:
Gender breakdown for the churn rate:
Female customers are more likely to churn vs. male customers, but the difference is minimal (~0.8%).
Letβs replicate this for all categorical columns. To not repeat what we did for gender, you can find the code needed for all below:
Now we go over the features which show the most significant difference across their values:
Internet Service
This chart reveals customers who have Fiber optic as Internet Service are more likely to churn. I normally expect Fiber optic customers to churn less due to they use a more premium service. But this can happen due to high prices, competition, customer service, and many other reasons.
Contract
As expected, the shorter contract means higher churn rate.
Tech Support
Customers donβt use Tech Support are more like to churn (~25% difference).
Payment Method
Automating the payment makes the customer more likely to retain in your platform (~30% difference).
Others
Letβs show some of the other featuresβ graphs here for the reference:
We are done with the categorical features. Letβs see how numerical features look like:
Tenure
To see the trend between Tenure and average Churn Rate, letβs build a scatter plot:
df_plot = df_data.groupby('tenure').Churn.mean().reset_index()plot_data = [ go.Scatter( x=df_plot['tenure'], y=df_plot['Churn'], mode='markers', name='Low', marker= dict(size= 7, line= dict(width=1), color= 'blue', opacity= 0.8 ), )]plot_layout = go.Layout( yaxis= {'title': "Churn Rate"}, xaxis= {'title': "Tenure"}, title='Tenure based Churn rate', plot_bgcolor = "rgb(243,243,243)", paper_bgcolor = "rgb(243,243,243)", )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)
Super apparent that the higher tenure means lower Churn Rate. We are going to apply the same for Monthly and Total Charges:
Output:
Unfortunately, there is no trend between Churn Rate and Monthly & Total Charges.
In this section, we are going to transform our raw features to extract more information from them. Our strategy is as follows:
1- Group the numerical columns by using clustering techniques
2- Apply Label Encoder to categorical features which are binary
3- Apply get_dummies() to categorical features which have multiple values
Numerical Columns
As we know from the EDA section, We have three numerical columns:
Tenure
Monthly Charges
Total Charges
We are going to apply the following steps to create groups:
Using Elbow Method to identify the appropriate number of clustersApplying K-means logic to the selected column and change the namingObserve the profile of clusters
Using Elbow Method to identify the appropriate number of clusters
Applying K-means logic to the selected column and change the naming
Observe the profile of clusters
Letβs check how this works for Tenure in practice:
Cluster profiles:
We have 3 clusters with 7.5, 33.9 and 63 as their average Tenure.
Churn Rate for each cluster:
This is how it looks after applying the same for Monthly & Total Charges:
Monthly Charge:
Total Charge:
Categorical Columns
Label Encoder converts categorical columns to numerical by simply assigning integers to distinct values. For instance, the column gender has two values: Female & Male. Label encoder will convert it to 1 and 0.
get_dummies() method creates new columns out of categorical ones by assigning 0 & 1s (you can find the exact explanation in our previous article)
Letβs see both in practice:
#import Label Encoderfrom sklearn.preprocessing import LabelEncoderle = LabelEncoder()dummy_columns = [] #array for multiple value columnsfor column in df_data.columns: if df_data[column].dtype == object and column != 'customerID': if df_data[column].nunique() == 2: #apply Label Encoder for binary ones df_data[column] = le.fit_transform(df_data[column]) else: dummy_columns.append(column)#apply get dummies for selected columnsdf_data = pd.get_dummies(data = df_data,columns = dummy_columns)
Check out how the data looks like for the selected columns:
As you can see easily, gender & Partner columns became numerical ones, and we have three new columns for TenureCluster.
It is time to fit a logistic regression model and extract insights to make better business decisions.
Predicting churn is a binary classification problem. Customers either churn or retain in a given period. Along with being a robust model, Logistic Regression provides interpretable outcomes too. As we did before, letβs sort out our steps to follow for building a Logistic Regression model:
Prepare the data (inputs for the model)Fit the model and see the model summary
Prepare the data (inputs for the model)
Fit the model and see the model summary
And the summary looks like below:
We have two important outcomes from this report. When you prepare a Churn Prediction model, you will face with the questions below:
1- Which characteristics make customers churn or retain?
2- What are the most critical ones? What should we focus on?
For the first question, you should look at the 4th column (P>|z|). If the absolute p-value is smaller than 0.05, it means, that feature affects Churn in a statistically significant way. Examples are:
SeniorCitizen
InternetService_DSL
OnlineSecurity_NO
Then the second question. We want to reduce the Churn Rate, where we should start? The scientific version of this question is;
Which feature will bring the best ROI if I increase/decrease it by one unit?
That question can be answered by looking at the coef column. Exponential coef gives us the expected change in Churn Rate if we change it by one unit. If we apply the code below, we will see the transformed version of all coefficients:
np.exp(res.params)
As an example, one unit change in Monthly Charge means ~3.4% improvement in the odds for churning if we keep everything else constant. From the table above, we can quickly identify which features are more important.
Now, everything is ready for building our classification model.
To fit XGBoost to our data, we should prepare features (X) and label(y) sets and do the train & test split.
#create feature set and labelsX = df_data.drop(['Churn','customerID'],axis=1)y = df_data.Churn#train and test splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=56)#building the model & printing the scorexgb_model = xgb.XGBClassifier(max_depth=5, learning_rate=0.08, objective= 'binary:logistic',n_jobs=-1).fit(X_train, y_train)print('Accuracy of XGB classifier on training set: {:.2f}' .format(xgb_model.score(X_train, y_train)))print('Accuracy of XGB classifier on test set: {:.2f}' .format(xgb_model.score(X_test[X_train.columns], y_test)))
By using this simple model, we have achieved 81% accuracy:
Our actual Churn Rate in the dataset was 26.5% (reflects as 73.5% for model performance). This shows our model is a useful one. Better to check our classification model to see where exactly our model fails.
y_pred = xgb_model.predict(X_test)print(classification_report(y_test, y_pred))
We can interpret the report above as if our model tells us, 100 customers will churn, 67 of it will churn (0.67 precision). And actually, there are around 220 customers who will churn (0.45 recall). Especially recall is the main problem here, and we can improve our modelβs overall performance by:
Adding more data (we have around 2k rows for this example)
Adding more features
More feature engineering
Trying other models
Hyper-parameter tuning
Moving forward, letβs see how our model works in detail. First off, we want to know which features our model exactly used from the dataset. Also, which were the most important ones?
For addressing this question, we can use the code below:
from xgboost import plot_importancefig, ax = plt.subplots(figsize=(10,8))plot_importance(xgb_model, ax=ax)
We can see that our model assigned more importance to TotalCharges and MonthlyCharges compared to others.
Finally, the best way to use this model is assigning Churn Probability for each customer, create segments, and build strategies on top of that. To get the churn probability from our model, utilize the code block below:
df_data['proba'] = xgb_model.predict_proba(df_data[X_train.columns])[:,1]
Our dataset looks like below at the end:
Now we know if there are likely to churn customers in our best segments (recall part 2 and part 3) and we can build actions based on it. In the next article, we are going to focus on predicting the next purchase day of customers.
You can find the Jupyter Notebook for this part here.
To discuss growth marketing & data science, go ahead and book a free session with me here.
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "This series of articles was designed to explain how to use Python in a simplistic way to fuel your companyβs growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning."
},
{
"code": null,
"e": 483,
"s": 423,
"text": "I will cover all the topics in the following nine articles:"
},
{
"code": null,
"e": 504,
"s": 483,
"text": "1- Know Your Metrics"
},
{
"code": null,
"e": 529,
"s": 504,
"text": "2- Customer Segmentation"
},
{
"code": null,
"e": 567,
"s": 529,
"text": "3- Customer Lifetime Value Prediction"
},
{
"code": null,
"e": 587,
"s": 567,
"text": "4- Churn Prediction"
},
{
"code": null,
"e": 619,
"s": 587,
"text": "5- Predicting Next Purchase Day"
},
{
"code": null,
"e": 639,
"s": 619,
"text": "6- Predicting Sales"
},
{
"code": null,
"e": 665,
"s": 639,
"text": "7- Market Response Models"
},
{
"code": null,
"e": 684,
"s": 665,
"text": "8- Uplift Modeling"
},
{
"code": null,
"e": 720,
"s": 684,
"text": "9- A/B Testing Design and Execution"
},
{
"code": null,
"e": 1070,
"s": 720,
"text": "Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:"
},
{
"code": null,
"e": 1127,
"s": 1070,
"text": "Sometimes you gotta run before you can walk β Tony Stark"
},
{
"code": null,
"e": 1268,
"s": 1127,
"text": "As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only."
},
{
"code": null,
"e": 1290,
"s": 1268,
"text": "Alright, letβs start."
},
{
"code": null,
"e": 1663,
"s": 1290,
"text": "In the last three sections of Data Driven Growth series, we have discovered tracking essential metrics, customer segmentation, and predicting the lifetime value programmatically. Since we know our best customers by segmentation and lifetime value prediction, we should also work hard on retaining them. Thatβs what makes Retention Rate is one of the most critical metrics."
},
{
"code": null,
"e": 2120,
"s": 1663,
"text": "Retention Rate is an indication of how good is your product market fit (PMF). If your PMF is not satisfactory, you should see your customers churning very soon. One of the powerful tools to improve Retention Rate (hence the PMF) is Churn Prediction. By using this technique, you can easily find out who is likely to churn in the given period. In this article, we will use a Telco dataset and go over the following steps to develop a Churn Prediction model:"
},
{
"code": null,
"e": 2146,
"s": 2120,
"text": "Exploratory data analysis"
},
{
"code": null,
"e": 2166,
"s": 2146,
"text": "Feature engineering"
},
{
"code": null,
"e": 2243,
"s": 2166,
"text": "Investigating how the features affect Retention by using Logistic Regression"
},
{
"code": null,
"e": 2288,
"s": 2243,
"text": "Building a classification model with XGBoost"
},
{
"code": null,
"e": 2470,
"s": 2288,
"text": "We start with checking out how our data looks like and visualize how it interacts with our label (churned or not?). Letβs start with importing our data and print the first ten rows:"
},
{
"code": null,
"e": 2526,
"s": 2470,
"text": "df_data = pd.read_csv('churn_data.csv')df_data.head(10)"
},
{
"code": null,
"e": 2534,
"s": 2526,
"text": "Output:"
},
{
"code": null,
"e": 2615,
"s": 2534,
"text": "A better way to see all the columns and their data type is using .info() method:"
},
{
"code": null,
"e": 2665,
"s": 2615,
"text": "It seems like our data fall under two categories:"
},
{
"code": null,
"e": 2732,
"s": 2665,
"text": "Categorical features: gender, streaming tv, payment method &, etc."
},
{
"code": null,
"e": 2791,
"s": 2732,
"text": "Numerical features: tenure, monthly charges, total charges"
},
{
"code": null,
"e": 2935,
"s": 2791,
"text": "Now starting from the categorical ones, we shed light on all features and see how helpful they are to identify if a customer is going to churn."
},
{
"code": null,
"e": 3085,
"s": 2935,
"text": "As a side note, in the dataset we have, Churn column is string with Yes/No values. We convert it to integer to make it easier to use in our analysis."
},
{
"code": null,
"e": 3176,
"s": 3085,
"text": "df_data.loc[df_data.Churn=='No','Churn'] = 0 df_data.loc[df_data.Churn=='Yes','Churn'] = 1"
},
{
"code": null,
"e": 3183,
"s": 3176,
"text": "Gender"
},
{
"code": null,
"e": 3295,
"s": 3183,
"text": "By using the code block below, we easily visualize how Churn Rate (1-Retention Rate) looks like for each value:"
},
{
"code": null,
"e": 3801,
"s": 3295,
"text": "df_plot = df_data.groupby('gender').Churn.mean().reset_index()plot_data = [ go.Bar( x=df_plot['gender'], y=df_plot['Churn'], width = [0.5, 0.5], marker=dict( color=['green', 'blue']) )]plot_layout = go.Layout( xaxis={\"type\": \"category\"}, yaxis={\"title\": \"Churn Rate\"}, title='Gender', plot_bgcolor = 'rgb(243,243,243)', paper_bgcolor = 'rgb(243,243,243)', )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)"
},
{
"code": null,
"e": 3809,
"s": 3801,
"text": "Output:"
},
{
"code": null,
"e": 3846,
"s": 3809,
"text": "Gender breakdown for the churn rate:"
},
{
"code": null,
"e": 3947,
"s": 3846,
"text": "Female customers are more likely to churn vs. male customers, but the difference is minimal (~0.8%)."
},
{
"code": null,
"e": 4079,
"s": 3947,
"text": "Letβs replicate this for all categorical columns. To not repeat what we did for gender, you can find the code needed for all below:"
},
{
"code": null,
"e": 4171,
"s": 4079,
"text": "Now we go over the features which show the most significant difference across their values:"
},
{
"code": null,
"e": 4188,
"s": 4171,
"text": "Internet Service"
},
{
"code": null,
"e": 4473,
"s": 4188,
"text": "This chart reveals customers who have Fiber optic as Internet Service are more likely to churn. I normally expect Fiber optic customers to churn less due to they use a more premium service. But this can happen due to high prices, competition, customer service, and many other reasons."
},
{
"code": null,
"e": 4482,
"s": 4473,
"text": "Contract"
},
{
"code": null,
"e": 4541,
"s": 4482,
"text": "As expected, the shorter contract means higher churn rate."
},
{
"code": null,
"e": 4554,
"s": 4541,
"text": "Tech Support"
},
{
"code": null,
"e": 4629,
"s": 4554,
"text": "Customers donβt use Tech Support are more like to churn (~25% difference)."
},
{
"code": null,
"e": 4644,
"s": 4629,
"text": "Payment Method"
},
{
"code": null,
"e": 4744,
"s": 4644,
"text": "Automating the payment makes the customer more likely to retain in your platform (~30% difference)."
},
{
"code": null,
"e": 4751,
"s": 4744,
"text": "Others"
},
{
"code": null,
"e": 4821,
"s": 4751,
"text": "Letβs show some of the other featuresβ graphs here for the reference:"
},
{
"code": null,
"e": 4908,
"s": 4821,
"text": "We are done with the categorical features. Letβs see how numerical features look like:"
},
{
"code": null,
"e": 4915,
"s": 4908,
"text": "Tenure"
},
{
"code": null,
"e": 4999,
"s": 4915,
"text": "To see the trend between Tenure and average Churn Rate, letβs build a scatter plot:"
},
{
"code": null,
"e": 5614,
"s": 4999,
"text": "df_plot = df_data.groupby('tenure').Churn.mean().reset_index()plot_data = [ go.Scatter( x=df_plot['tenure'], y=df_plot['Churn'], mode='markers', name='Low', marker= dict(size= 7, line= dict(width=1), color= 'blue', opacity= 0.8 ), )]plot_layout = go.Layout( yaxis= {'title': \"Churn Rate\"}, xaxis= {'title': \"Tenure\"}, title='Tenure based Churn rate', plot_bgcolor = \"rgb(243,243,243)\", paper_bgcolor = \"rgb(243,243,243)\", )fig = go.Figure(data=plot_data, layout=plot_layout)pyoff.iplot(fig)"
},
{
"code": null,
"e": 5738,
"s": 5614,
"text": "Super apparent that the higher tenure means lower Churn Rate. We are going to apply the same for Monthly and Total Charges:"
},
{
"code": null,
"e": 5746,
"s": 5738,
"text": "Output:"
},
{
"code": null,
"e": 5827,
"s": 5746,
"text": "Unfortunately, there is no trend between Churn Rate and Monthly & Total Charges."
},
{
"code": null,
"e": 5954,
"s": 5827,
"text": "In this section, we are going to transform our raw features to extract more information from them. Our strategy is as follows:"
},
{
"code": null,
"e": 6016,
"s": 5954,
"text": "1- Group the numerical columns by using clustering techniques"
},
{
"code": null,
"e": 6080,
"s": 6016,
"text": "2- Apply Label Encoder to categorical features which are binary"
},
{
"code": null,
"e": 6154,
"s": 6080,
"text": "3- Apply get_dummies() to categorical features which have multiple values"
},
{
"code": null,
"e": 6172,
"s": 6154,
"text": "Numerical Columns"
},
{
"code": null,
"e": 6238,
"s": 6172,
"text": "As we know from the EDA section, We have three numerical columns:"
},
{
"code": null,
"e": 6245,
"s": 6238,
"text": "Tenure"
},
{
"code": null,
"e": 6261,
"s": 6245,
"text": "Monthly Charges"
},
{
"code": null,
"e": 6275,
"s": 6261,
"text": "Total Charges"
},
{
"code": null,
"e": 6335,
"s": 6275,
"text": "We are going to apply the following steps to create groups:"
},
{
"code": null,
"e": 6499,
"s": 6335,
"text": "Using Elbow Method to identify the appropriate number of clustersApplying K-means logic to the selected column and change the namingObserve the profile of clusters"
},
{
"code": null,
"e": 6565,
"s": 6499,
"text": "Using Elbow Method to identify the appropriate number of clusters"
},
{
"code": null,
"e": 6633,
"s": 6565,
"text": "Applying K-means logic to the selected column and change the naming"
},
{
"code": null,
"e": 6665,
"s": 6633,
"text": "Observe the profile of clusters"
},
{
"code": null,
"e": 6716,
"s": 6665,
"text": "Letβs check how this works for Tenure in practice:"
},
{
"code": null,
"e": 6734,
"s": 6716,
"text": "Cluster profiles:"
},
{
"code": null,
"e": 6800,
"s": 6734,
"text": "We have 3 clusters with 7.5, 33.9 and 63 as their average Tenure."
},
{
"code": null,
"e": 6829,
"s": 6800,
"text": "Churn Rate for each cluster:"
},
{
"code": null,
"e": 6903,
"s": 6829,
"text": "This is how it looks after applying the same for Monthly & Total Charges:"
},
{
"code": null,
"e": 6919,
"s": 6903,
"text": "Monthly Charge:"
},
{
"code": null,
"e": 6933,
"s": 6919,
"text": "Total Charge:"
},
{
"code": null,
"e": 6953,
"s": 6933,
"text": "Categorical Columns"
},
{
"code": null,
"e": 7163,
"s": 6953,
"text": "Label Encoder converts categorical columns to numerical by simply assigning integers to distinct values. For instance, the column gender has two values: Female & Male. Label encoder will convert it to 1 and 0."
},
{
"code": null,
"e": 7309,
"s": 7163,
"text": "get_dummies() method creates new columns out of categorical ones by assigning 0 & 1s (you can find the exact explanation in our previous article)"
},
{
"code": null,
"e": 7337,
"s": 7309,
"text": "Letβs see both in practice:"
},
{
"code": null,
"e": 7882,
"s": 7337,
"text": "#import Label Encoderfrom sklearn.preprocessing import LabelEncoderle = LabelEncoder()dummy_columns = [] #array for multiple value columnsfor column in df_data.columns: if df_data[column].dtype == object and column != 'customerID': if df_data[column].nunique() == 2: #apply Label Encoder for binary ones df_data[column] = le.fit_transform(df_data[column]) else: dummy_columns.append(column)#apply get dummies for selected columnsdf_data = pd.get_dummies(data = df_data,columns = dummy_columns)"
},
{
"code": null,
"e": 7942,
"s": 7882,
"text": "Check out how the data looks like for the selected columns:"
},
{
"code": null,
"e": 8062,
"s": 7942,
"text": "As you can see easily, gender & Partner columns became numerical ones, and we have three new columns for TenureCluster."
},
{
"code": null,
"e": 8164,
"s": 8062,
"text": "It is time to fit a logistic regression model and extract insights to make better business decisions."
},
{
"code": null,
"e": 8454,
"s": 8164,
"text": "Predicting churn is a binary classification problem. Customers either churn or retain in a given period. Along with being a robust model, Logistic Regression provides interpretable outcomes too. As we did before, letβs sort out our steps to follow for building a Logistic Regression model:"
},
{
"code": null,
"e": 8533,
"s": 8454,
"text": "Prepare the data (inputs for the model)Fit the model and see the model summary"
},
{
"code": null,
"e": 8573,
"s": 8533,
"text": "Prepare the data (inputs for the model)"
},
{
"code": null,
"e": 8613,
"s": 8573,
"text": "Fit the model and see the model summary"
},
{
"code": null,
"e": 8647,
"s": 8613,
"text": "And the summary looks like below:"
},
{
"code": null,
"e": 8779,
"s": 8647,
"text": "We have two important outcomes from this report. When you prepare a Churn Prediction model, you will face with the questions below:"
},
{
"code": null,
"e": 8836,
"s": 8779,
"text": "1- Which characteristics make customers churn or retain?"
},
{
"code": null,
"e": 8897,
"s": 8836,
"text": "2- What are the most critical ones? What should we focus on?"
},
{
"code": null,
"e": 9097,
"s": 8897,
"text": "For the first question, you should look at the 4th column (P>|z|). If the absolute p-value is smaller than 0.05, it means, that feature affects Churn in a statistically significant way. Examples are:"
},
{
"code": null,
"e": 9111,
"s": 9097,
"text": "SeniorCitizen"
},
{
"code": null,
"e": 9131,
"s": 9111,
"text": "InternetService_DSL"
},
{
"code": null,
"e": 9149,
"s": 9131,
"text": "OnlineSecurity_NO"
},
{
"code": null,
"e": 9276,
"s": 9149,
"text": "Then the second question. We want to reduce the Churn Rate, where we should start? The scientific version of this question is;"
},
{
"code": null,
"e": 9353,
"s": 9276,
"text": "Which feature will bring the best ROI if I increase/decrease it by one unit?"
},
{
"code": null,
"e": 9588,
"s": 9353,
"text": "That question can be answered by looking at the coef column. Exponential coef gives us the expected change in Churn Rate if we change it by one unit. If we apply the code below, we will see the transformed version of all coefficients:"
},
{
"code": null,
"e": 9607,
"s": 9588,
"text": "np.exp(res.params)"
},
{
"code": null,
"e": 9823,
"s": 9607,
"text": "As an example, one unit change in Monthly Charge means ~3.4% improvement in the odds for churning if we keep everything else constant. From the table above, we can quickly identify which features are more important."
},
{
"code": null,
"e": 9887,
"s": 9823,
"text": "Now, everything is ready for building our classification model."
},
{
"code": null,
"e": 9995,
"s": 9887,
"text": "To fit XGBoost to our data, we should prepare features (X) and label(y) sets and do the train & test split."
},
{
"code": null,
"e": 10592,
"s": 9995,
"text": "#create feature set and labelsX = df_data.drop(['Churn','customerID'],axis=1)y = df_data.Churn#train and test splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=56)#building the model & printing the scorexgb_model = xgb.XGBClassifier(max_depth=5, learning_rate=0.08, objective= 'binary:logistic',n_jobs=-1).fit(X_train, y_train)print('Accuracy of XGB classifier on training set: {:.2f}' .format(xgb_model.score(X_train, y_train)))print('Accuracy of XGB classifier on test set: {:.2f}' .format(xgb_model.score(X_test[X_train.columns], y_test)))"
},
{
"code": null,
"e": 10651,
"s": 10592,
"text": "By using this simple model, we have achieved 81% accuracy:"
},
{
"code": null,
"e": 10858,
"s": 10651,
"text": "Our actual Churn Rate in the dataset was 26.5% (reflects as 73.5% for model performance). This shows our model is a useful one. Better to check our classification model to see where exactly our model fails."
},
{
"code": null,
"e": 10937,
"s": 10858,
"text": "y_pred = xgb_model.predict(X_test)print(classification_report(y_test, y_pred))"
},
{
"code": null,
"e": 11235,
"s": 10937,
"text": "We can interpret the report above as if our model tells us, 100 customers will churn, 67 of it will churn (0.67 precision). And actually, there are around 220 customers who will churn (0.45 recall). Especially recall is the main problem here, and we can improve our modelβs overall performance by:"
},
{
"code": null,
"e": 11294,
"s": 11235,
"text": "Adding more data (we have around 2k rows for this example)"
},
{
"code": null,
"e": 11315,
"s": 11294,
"text": "Adding more features"
},
{
"code": null,
"e": 11340,
"s": 11315,
"text": "More feature engineering"
},
{
"code": null,
"e": 11360,
"s": 11340,
"text": "Trying other models"
},
{
"code": null,
"e": 11383,
"s": 11360,
"text": "Hyper-parameter tuning"
},
{
"code": null,
"e": 11565,
"s": 11383,
"text": "Moving forward, letβs see how our model works in detail. First off, we want to know which features our model exactly used from the dataset. Also, which were the most important ones?"
},
{
"code": null,
"e": 11622,
"s": 11565,
"text": "For addressing this question, we can use the code below:"
},
{
"code": null,
"e": 11729,
"s": 11622,
"text": "from xgboost import plot_importancefig, ax = plt.subplots(figsize=(10,8))plot_importance(xgb_model, ax=ax)"
},
{
"code": null,
"e": 11835,
"s": 11729,
"text": "We can see that our model assigned more importance to TotalCharges and MonthlyCharges compared to others."
},
{
"code": null,
"e": 12054,
"s": 11835,
"text": "Finally, the best way to use this model is assigning Churn Probability for each customer, create segments, and build strategies on top of that. To get the churn probability from our model, utilize the code block below:"
},
{
"code": null,
"e": 12128,
"s": 12054,
"text": "df_data['proba'] = xgb_model.predict_proba(df_data[X_train.columns])[:,1]"
},
{
"code": null,
"e": 12169,
"s": 12128,
"text": "Our dataset looks like below at the end:"
},
{
"code": null,
"e": 12399,
"s": 12169,
"text": "Now we know if there are likely to churn customers in our best segments (recall part 2 and part 3) and we can build actions based on it. In the next article, we are going to focus on predicting the next purchase day of customers."
},
{
"code": null,
"e": 12453,
"s": 12399,
"text": "You can find the Jupyter Notebook for this part here."
}
] |
Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
|
We have to write a function that takes in an array and returns an object with two properties
namely positive and negative. They both should be an array containing all positive and negative
items respectively from the array.
This one is quite straightforward, we will use the Array.prototype.reduce() method to pick
desired elements and put them into an object of two arrays.
const arr = [
[12, -45, 65, 76, -76, 87, -98],
[54, -65, -98, -23, 78, -9, 1, 3],
[87, -98, 3, -2, 123, -877, 22, -5, 23, -67]
];
const splitArray = (arr) => {
return arr.reduce((acc, val) => {
if(val < 0){
acc['negative'].push(val);
} else {
acc['positive'].push(val);
}
return acc;
}, {
positive: [],
negative: []
})
};
for(let i = 0; i < arr.length; i++){
console.log(splitArray(arr[i]));
}
The output in the console will be β
{ positive: [ 12, 65, 76, 87 ], negative: [ -45, -76, -98 ] }
{ positive: [ 54, 78, 1, 3 ], negative: [ -65, -98, -23, -9 ] }
{
positive: [ 87, 3, 123, 22, 23 ],
negative: [ -98, -2, -877, -5, -67 ]
}
|
[
{
"code": null,
"e": 1286,
"s": 1062,
"text": "We have to write a function that takes in an array and returns an object with two properties\nnamely positive and negative. They both should be an array containing all positive and negative\nitems respectively from the array."
},
{
"code": null,
"e": 1437,
"s": 1286,
"text": "This one is quite straightforward, we will use the Array.prototype.reduce() method to pick\ndesired elements and put them into an object of two arrays."
},
{
"code": null,
"e": 1921,
"s": 1437,
"text": "const arr = [\n [12, -45, 65, 76, -76, 87, -98],\n [54, -65, -98, -23, 78, -9, 1, 3],\n [87, -98, 3, -2, 123, -877, 22, -5, 23, -67]\n];\nconst splitArray = (arr) => {\n return arr.reduce((acc, val) => {\n if(val < 0){\n acc['negative'].push(val);\n } else {\n acc['positive'].push(val);\n }\n return acc;\n }, {\n positive: [],\n negative: []\n })\n };\n for(let i = 0; i < arr.length; i++){\n console.log(splitArray(arr[i]));\n}"
},
{
"code": null,
"e": 1957,
"s": 1921,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 2164,
"s": 1957,
"text": "{ positive: [ 12, 65, 76, 87 ], negative: [ -45, -76, -98 ] }\n{ positive: [ 54, 78, 1, 3 ], negative: [ -65, -98, -23, -9 ] }\n{\n positive: [ 87, 3, 123, 22, 23 ],\n negative: [ -98, -2, -877, -5, -67 ]\n}"
}
] |
Apex - SOQL
|
This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject.
Like SOSL, it cannot search across multiple objects but it does support nested queries.
Consider our ongoing example of Chemical Company. Suppose, we need a list of records which are created today and whose customer name is not 'test'. In this case, we will have to use the SOQL query as given below β
// fetching the Records via SOQL
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
InvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM
APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != 'Test'];
// SOQL query for given criteria
// Printing the fetched records
System.debug('We have total '+InvoiceList.size()+' Records in List');
for (APEX_Invoice__c objInvoice: InvoiceList) {
System.debug('Record Value is '+objInvoice);
// Printing the Record fetched
}
You can run the SOQL query via the Query Editor in the Developer console as shown below.
Run the query given below in the Developer Console. Search for the Invoice records created today.
SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c
WHERE createdDate = today
You must select the fields for which you need the values, otherwise, it can throw run time errors.
This is one of the most important parts in SFDC as many times we need to traverse through the parent child object relationship
Also, there may be cases when you need to insert two associated objects records in Database. For example, Invoice object has relationship with the Customer object and hence one Customer can have many invoices.
Suppose, you are creating the invoice and then you need to relate this invoice to Customer. You can use the following code for this functionality β
// Now create the invoice record and relate it with the Customer object
// Before executing this, please create a Customer Records with Name 'Customer
// Creation Test'
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
// Relating Invoice to customer via id field of Customer object
objInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name =
'Customer Creation Test' LIMIT 1].id;
objInvoice.APEX_Status__c = 'Pending';
insert objInvoice; //Creating Invoice
System.debug('Newly Created Invoice'+objInvoice); //Newly created invoice
Execute this code snippet in the Developer Console. Once executed, copy the Id of invoice from the Developer console and then open the same in SFDC as shown below. You can see that the Parent record has already been assigned to Invoice record as shown below.
Let us now consider an example wherein, all the invoices related to particular customer record need to be in one place. For this, you must know the child relationship name. To see the child relationship name, go to the field detail page on the child object and check the "Child Relationship" value. In our example, it is invoices appended by __r at the end.
In this example, we will need to set up data, create a customer with name as 'ABC Customer' record and then add 3 invoices to that customer.
Now, we will fetch the invoices the Customer 'ABC Customer' has. Following is the query for the same β
// Fetching Child Records using SOQL
List<apex_customer__c> ListCustomers = [SELECT Name, Id,
(SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = 'ABC Customer'];
// Query for fetching the Child records along with Parent
System.debug('ListCustomers '+ListCustomers); // Parent Record
List<apex_invoice__c> ListOfInvoices = ListCustomers[0].Invoices__r;
// By this notation, you could fetch the child records and save it in List
System.debug('ListOfInvoices values of Child '+ListOfInvoices);
// Child records
You can see the Record values in the Debug logs.
Suppose, you need to fetch the Customer Name of Invoice the creation date of which is today, then you can use the query given below for the same β
Fetch the Parent record's value along with the child object.
// Fetching Parent Record Field value using SOQL
List<apex_invoice__c> ListOfInvoicesWithCustomerName = new List<apex_invoice__c>();
ListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name
FROM APEX_Invoice__c LIMIT 10];
// Fetching the Parent record's values
for (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) {
System.debug('Invoice Customer Name is '+objInv.APEX_Customer__r.Name);
// Will print the values, all the Customer Records will be printed
}
Here we have used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you have to append the __r at the end of the Parent field and then you can fetch the parent field value.
SOQL does have aggregate function as we have in SQL. Aggregate functions allow us to roll up and summarize the data. Let us now understand the function in detail.
Suppose, you wanted to know that what is the average revenue we are getting from Customer 'ABC Customer', then you can use this function to take up the average.
// Getting Average of all the invoices for a Perticular Customer
AggregateResult[] groupedResults = [SELECT
AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE
APEX_Customer__r.Name = 'ABC Customer'];
Object avgPaidAmount = groupedResults[0].get('averageAmount');
System.debug('Total Average Amount Received From Customer ABC is '+avgPaidAmount);
Check the output in Debug logs. Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a readonly sObject and is only used for query results. It is useful when we need to generate the Report on Large data.
There are other aggregate functions as well which you can be used to perform data
summary.
MIN() β This can be used to find the minimum value
MAX() β This can be used to find the maximum value.
You can use the Apex variable in SOQL query to fetch the desired results. Apex variables
can be referenced by the Colon (:) notation.
// Apex Variable Reference
String CustomerName = 'ABC Customer';
List<apex_customer__c> ListCustomer = [SELECT Id, Name FROM APEX_Customer__c
WHERE Name = :CustomerName];
// Query Using Apex variable
System.debug('ListCustomer Name'+ListCustomer); // Customer Name
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2198,
"s": 2052,
"text": "This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject."
},
{
"code": null,
"e": 2286,
"s": 2198,
"text": "Like SOSL, it cannot search across multiple objects but it does support nested queries."
},
{
"code": null,
"e": 2500,
"s": 2286,
"text": "Consider our ongoing example of Chemical Company. Suppose, we need a list of records which are created today and whose customer name is not 'test'. In this case, we will have to use the SOQL query as given below β"
},
{
"code": null,
"e": 3026,
"s": 2500,
"text": "// fetching the Records via SOQL\nList<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\nInvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM\n APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != 'Test'];\n// SOQL query for given criteria\n\n// Printing the fetched records\nSystem.debug('We have total '+InvoiceList.size()+' Records in List');\n\nfor (APEX_Invoice__c objInvoice: InvoiceList) {\n System.debug('Record Value is '+objInvoice); \n // Printing the Record fetched\n}"
},
{
"code": null,
"e": 3115,
"s": 3026,
"text": "You can run the SOQL query via the Query Editor in the Developer console as shown below."
},
{
"code": null,
"e": 3213,
"s": 3115,
"text": "Run the query given below in the Developer Console. Search for the Invoice records created today."
},
{
"code": null,
"e": 3318,
"s": 3213,
"text": "SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c\n WHERE createdDate = today"
},
{
"code": null,
"e": 3417,
"s": 3318,
"text": "You must select the fields for which you need the values, otherwise, it can throw run time errors."
},
{
"code": null,
"e": 3544,
"s": 3417,
"text": "This is one of the most important parts in SFDC as many times we need to traverse through the parent child object relationship"
},
{
"code": null,
"e": 3754,
"s": 3544,
"text": "Also, there may be cases when you need to insert two associated objects records in Database. For example, Invoice object has relationship with the Customer object and hence one Customer can have many invoices."
},
{
"code": null,
"e": 3902,
"s": 3754,
"text": "Suppose, you are creating the invoice and then you need to relate this invoice to Customer. You can use the following code for this functionality β"
},
{
"code": null,
"e": 4458,
"s": 3902,
"text": "// Now create the invoice record and relate it with the Customer object\n// Before executing this, please create a Customer Records with Name 'Customer\n// Creation Test'\nAPEX_Invoice__c objInvoice = new APEX_Invoice__c();\n\n// Relating Invoice to customer via id field of Customer object\nobjInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name =\n 'Customer Creation Test' LIMIT 1].id;\nobjInvoice.APEX_Status__c = 'Pending';\ninsert objInvoice; //Creating Invoice\nSystem.debug('Newly Created Invoice'+objInvoice); //Newly created invoice"
},
{
"code": null,
"e": 4717,
"s": 4458,
"text": "Execute this code snippet in the Developer Console. Once executed, copy the Id of invoice from the Developer console and then open the same in SFDC as shown below. You can see that the Parent record has already been assigned to Invoice record as shown below."
},
{
"code": null,
"e": 5075,
"s": 4717,
"text": "Let us now consider an example wherein, all the invoices related to particular customer record need to be in one place. For this, you must know the child relationship name. To see the child relationship name, go to the field detail page on the child object and check the \"Child Relationship\" value. In our example, it is invoices appended by __r at the end."
},
{
"code": null,
"e": 5216,
"s": 5075,
"text": "In this example, we will need to set up data, create a customer with name as 'ABC Customer' record and then add 3 invoices to that customer."
},
{
"code": null,
"e": 5319,
"s": 5216,
"text": "Now, we will fetch the invoices the Customer 'ABC Customer' has. Following is the query for the same β"
},
{
"code": null,
"e": 5852,
"s": 5319,
"text": "// Fetching Child Records using SOQL\nList<apex_customer__c> ListCustomers = [SELECT Name, Id, \n (SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = 'ABC Customer'];\n\n// Query for fetching the Child records along with Parent\nSystem.debug('ListCustomers '+ListCustomers); // Parent Record\n\nList<apex_invoice__c> ListOfInvoices = ListCustomers[0].Invoices__r;\n// By this notation, you could fetch the child records and save it in List\nSystem.debug('ListOfInvoices values of Child '+ListOfInvoices);\n// Child records"
},
{
"code": null,
"e": 5901,
"s": 5852,
"text": "You can see the Record values in the Debug logs."
},
{
"code": null,
"e": 6048,
"s": 5901,
"text": "Suppose, you need to fetch the Customer Name of Invoice the creation date of which is today, then you can use the query given below for the same β"
},
{
"code": null,
"e": 6109,
"s": 6048,
"text": "Fetch the Parent record's value along with the child object."
},
{
"code": null,
"e": 6601,
"s": 6109,
"text": "// Fetching Parent Record Field value using SOQL\nList<apex_invoice__c> ListOfInvoicesWithCustomerName = new List<apex_invoice__c>();\nListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name \n FROM APEX_Invoice__c LIMIT 10];\n\n// Fetching the Parent record's values\nfor (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) {\n System.debug('Invoice Customer Name is '+objInv.APEX_Customer__r.Name);\n // Will print the values, all the Customer Records will be printed\n}"
},
{
"code": null,
"e": 6817,
"s": 6601,
"text": "Here we have used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you have to append the __r at the end of the Parent field and then you can fetch the parent field value."
},
{
"code": null,
"e": 6980,
"s": 6817,
"text": "SOQL does have aggregate function as we have in SQL. Aggregate functions allow us to roll up and summarize the data. Let us now understand the function in detail."
},
{
"code": null,
"e": 7141,
"s": 6980,
"text": "Suppose, you wanted to know that what is the average revenue we are getting from Customer 'ABC Customer', then you can use this function to take up the average."
},
{
"code": null,
"e": 7507,
"s": 7141,
"text": "// Getting Average of all the invoices for a Perticular Customer\nAggregateResult[] groupedResults = [SELECT\n AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE\n APEX_Customer__r.Name = 'ABC Customer'];\nObject avgPaidAmount = groupedResults[0].get('averageAmount');\nSystem.debug('Total Average Amount Received From Customer ABC is '+avgPaidAmount);"
},
{
"code": null,
"e": 7793,
"s": 7507,
"text": "Check the output in Debug logs. Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a readonly sObject and is only used for query results. It is useful when we need to generate the Report on Large data."
},
{
"code": null,
"e": 7884,
"s": 7793,
"text": "There are other aggregate functions as well which you can be used to perform data\nsummary."
},
{
"code": null,
"e": 7935,
"s": 7884,
"text": "MIN() β This can be used to find the minimum value"
},
{
"code": null,
"e": 7987,
"s": 7935,
"text": "MAX() β This can be used to find the maximum value."
},
{
"code": null,
"e": 8121,
"s": 7987,
"text": "You can use the Apex variable in SOQL query to fetch the desired results. Apex variables\ncan be referenced by the Colon (:) notation."
},
{
"code": null,
"e": 8390,
"s": 8121,
"text": "// Apex Variable Reference\nString CustomerName = 'ABC Customer';\nList<apex_customer__c> ListCustomer = [SELECT Id, Name FROM APEX_Customer__c\n WHERE Name = :CustomerName];\n\n// Query Using Apex variable\nSystem.debug('ListCustomer Name'+ListCustomer); // Customer Name"
},
{
"code": null,
"e": 8423,
"s": 8390,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8436,
"s": 8423,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 8468,
"s": 8436,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8476,
"s": 8468,
"text": " Uplatz"
},
{
"code": null,
"e": 8509,
"s": 8476,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8534,
"s": 8509,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 8567,
"s": 8534,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8582,
"s": 8567,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 8615,
"s": 8582,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8628,
"s": 8615,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 8663,
"s": 8628,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8675,
"s": 8663,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 8682,
"s": 8675,
"text": " Print"
},
{
"code": null,
"e": 8693,
"s": 8682,
"text": " Add Notes"
}
] |
What are variable arguments in java?
|
While defining a method, In general, we will specify the arguments it accepts along with the type as β
myMethod(int a, String b){
}
Suppose if you need to accept more than one variable of the same type you need to specify the variables one after the other as β
myMethod(int a, int b, int c){
}
You can also pass a variable number of arguments of a particular type, to a method. These are known as variable arguments or, varargs. They are represented by three dots (...)
public myMethod(int ... a) {
// method body
}
Once you use variable arguments as a parameter method while calling you can pass as many numbers of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments.
Live Demo
public class Sample{
void demomethod(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
public static void main(String args[] ){
new Sample().demomethod("Ram", "Rahim", "Robert");
new Sample().demomethod("Krishna", "Kasyap");
new Sample().demomethod();
}
}
Ram
Rahim
Robert
Krishna
Kasyap
Live Demo
public class VarargsExample{
void demoMethod(String name, int age, int... marks) {
System.out.println();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.print("Marks: ");
for (int m: marks) {
System.out.print(m+" ");
}
}
public static void main(String args[] ){
VarargsExample obj = new VarargsExample();
obj.demoMethod("Krishna", 23, 90, 95, 80, 69 );
obj.demoMethod("Vishnu", 22, 91, 75, 94 );
obj.demoMethod("Kasyap", 25, 85, 82);
obj.demoMethod("Vani", 25, 93);
}
}
Name: Krishna
Age: 23
Marks: 90 95 80 69
Name: Vishnu
Age: 22
Marks: 91 75 94
Name: Kasyap
Age: 25
Marks: 85 82
Name: Vani
Age: 25
Marks: 93
Rules to follow while using varargs in Java β
We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated.
We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated.
In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated.
In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated.
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "While defining a method, In general, we will specify the arguments it accepts along with the type as β"
},
{
"code": null,
"e": 1194,
"s": 1165,
"text": "myMethod(int a, String b){\n}"
},
{
"code": null,
"e": 1323,
"s": 1194,
"text": "Suppose if you need to accept more than one variable of the same type you need to specify the variables one after the other as β"
},
{
"code": null,
"e": 1356,
"s": 1323,
"text": "myMethod(int a, int b, int c){\n}"
},
{
"code": null,
"e": 1532,
"s": 1356,
"text": "You can also pass a variable number of arguments of a particular type, to a method. These are known as variable arguments or, varargs. They are represented by three dots (...)"
},
{
"code": null,
"e": 1581,
"s": 1532,
"text": "public myMethod(int ... a) {\n // method body\n}"
},
{
"code": null,
"e": 1804,
"s": 1581,
"text": "Once you use variable arguments as a parameter method while calling you can pass as many numbers of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments."
},
{
"code": null,
"e": 1815,
"s": 1804,
"text": " Live Demo"
},
{
"code": null,
"e": 2145,
"s": 1815,
"text": "public class Sample{\n void demomethod(String... args) {\n for (String arg : args) {\n System.out.println(arg);\n }\n }\n public static void main(String args[] ){\n new Sample().demomethod(\"Ram\", \"Rahim\", \"Robert\");\n new Sample().demomethod(\"Krishna\", \"Kasyap\");\n new Sample().demomethod();\n }\n}"
},
{
"code": null,
"e": 2177,
"s": 2145,
"text": "Ram\nRahim\nRobert\nKrishna\nKasyap"
},
{
"code": null,
"e": 2188,
"s": 2177,
"text": " Live Demo"
},
{
"code": null,
"e": 2776,
"s": 2188,
"text": "public class VarargsExample{\n void demoMethod(String name, int age, int... marks) {\n System.out.println();\n System.out.println(\"Name: \"+name);\n System.out.println(\"Age: \"+age);\n System.out.print(\"Marks: \");\n for (int m: marks) {\n System.out.print(m+\" \");\n }\n }\n public static void main(String args[] ){\n VarargsExample obj = new VarargsExample();\n obj.demoMethod(\"Krishna\", 23, 90, 95, 80, 69 );\n obj.demoMethod(\"Vishnu\", 22, 91, 75, 94 );\n obj.demoMethod(\"Kasyap\", 25, 85, 82);\n obj.demoMethod(\"Vani\", 25, 93);\n }\n}"
},
{
"code": null,
"e": 2917,
"s": 2776,
"text": "Name: Krishna\nAge: 23\nMarks: 90 95 80 69\nName: Vishnu\nAge: 22\nMarks: 91 75 94\nName: Kasyap\nAge: 25\nMarks: 85 82\nName: Vani\nAge: 25\nMarks: 93"
},
{
"code": null,
"e": 2963,
"s": 2917,
"text": "Rules to follow while using varargs in Java β"
},
{
"code": null,
"e": 3100,
"s": 2963,
"text": "We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated."
},
{
"code": null,
"e": 3237,
"s": 3100,
"text": "We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated."
},
{
"code": null,
"e": 3350,
"s": 3237,
"text": "In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated."
},
{
"code": null,
"e": 3463,
"s": 3350,
"text": "In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated."
}
] |
How to increase the width of the median line in boxplot using ggplot2 in R?
|
The default width of the median line is wider than the rest of the lines that represent minimum, first quartile, third quartile or maximum but we can make it a little wider to make it more appealing. This can be done with the help of fatten argument inside geom_boxplot function, the default value of fatten is 2.
Live Demo
Consider the below data frame β
x<βsample(c("A","B","C"),20,replace=TRUE)
y<βrnorm(20,5,1.24)
df<βdata.frame(x,y)
df
x y
1 A 4.740834
2 C 5.365280
3 B 5.250932
4 B 5.764159
5 B 4.053119
6 B 4.241961
7 B 6.285087
8 C 5.513231
9 B 5.888086
10 B 4.479830
11 C 4.217874
12 A 6.366376
13 C 6.278470
14 C 4.721193
15 B 5.387542
16 B 6.683681
17 B 6.153023
18 A 4.695209
19 C 5.715360
20 A 5.948239
Loading ggplot2 package and creating the boxplots β
library(ggplot2)
ggplot(df,aes(x,y))+geom_boxplot()
Creating the boxplots with wider median lines β
ggplot(df,aes(x,y))+geom_boxplot(fatten=3)s
ggplot(df,aes(x,y))+geom_boxplot(fatten=6)
|
[
{
"code": null,
"e": 1376,
"s": 1062,
"text": "The default width of the median line is wider than the rest of the lines that represent minimum, first quartile, third quartile or maximum but we can make it a little wider to make it more appealing. This can be done with the help of fatten argument inside geom_boxplot function, the default value of fatten is 2."
},
{
"code": null,
"e": 1387,
"s": 1376,
"text": " Live Demo"
},
{
"code": null,
"e": 1419,
"s": 1387,
"text": "Consider the below data frame β"
},
{
"code": null,
"e": 1504,
"s": 1419,
"text": "x<βsample(c(\"A\",\"B\",\"C\"),20,replace=TRUE)\ny<βrnorm(20,5,1.24)\ndf<βdata.frame(x,y)\ndf"
},
{
"code": null,
"e": 1785,
"s": 1504,
"text": " x y\n1 A 4.740834\n2 C 5.365280\n3 B 5.250932\n4 B 5.764159\n5 B 4.053119\n6 B 4.241961\n7 B 6.285087\n8 C 5.513231\n9 B 5.888086\n10 B 4.479830\n11 C 4.217874\n12 A 6.366376\n13 C 6.278470\n14 C 4.721193\n15 B 5.387542\n16 B 6.683681\n17 B 6.153023\n18 A 4.695209\n19 C 5.715360\n20 A 5.948239"
},
{
"code": null,
"e": 1837,
"s": 1785,
"text": "Loading ggplot2 package and creating the boxplots β"
},
{
"code": null,
"e": 1889,
"s": 1837,
"text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_boxplot()"
},
{
"code": null,
"e": 1937,
"s": 1889,
"text": "Creating the boxplots with wider median lines β"
},
{
"code": null,
"e": 1981,
"s": 1937,
"text": "ggplot(df,aes(x,y))+geom_boxplot(fatten=3)s"
},
{
"code": null,
"e": 2024,
"s": 1981,
"text": "ggplot(df,aes(x,y))+geom_boxplot(fatten=6)"
}
] |
5 Outlier Detection Techniques that every βData Enthusiastβ Must Know | by Prakhar Mishra | Towards Data Science
|
Outliers are those observations that differ strongly(different properties) from the other data points in the sample of a population. In this blog, we will go through 5 Outlier Detection techniques that every βData Enthusiastβ must know. But before that letβs take a look and understand the source of outliers.
There are multiple reasons why there can be outliers in the dataset, like Human errors(Wrong data entry), Measurement errors(System/Tool error), Data manipulation error(Faulty data preprocessing error), Sampling errors(creating samples from heterogeneous sources), etc. Importantly, detecting and treating these Outliers is important for learning a robust and generalizable machine learning system.
The Z-score(also called the standard score) is an important concept in statistics that indicates how far away a certain point is from the mean. By applying Z-transformation we shift the distribution and make it 0 mean with unit standard deviation. For example β A Z-score of 2 would mean the data point is 2 standard deviation away from the mean.
Also, z-score of any data point can be calculated as shown below β
Z-score(i) = (x(i) -mean) / standard deviation
It assumes that the data is normally distributed and hence the % of data points that lie between -/+1 stdev. is ~68%, -/+2 stdev. is ~95% and -/+3 stdev. is ~99.7%. Hence, if the Z-score is >3 we can safely mark that point to be an outlier. Refer to below fig.
You can implement it using python as shown below β
import numpy as npdata = [1, 2, 3, 2, 1, 100, 1, 2, 3, 2, 1]threshold = 3mean = np.mean(data)std = np.std(data)z_score_outlier = [i for i in data if (i-mean)/std > threshold]print (z_score_outlier)>> 100 (outlier)
You can also use in-built functions provided by Scikit learn and Scipy in Python. (Link in the Resources section)
In Local Outlier Factor (LOF), the idea revolves around the concept of local regions. Here, we calculate and compare the local density of the focus point with the local density of its neighbours. If we find that the local density of the focus point is very low compared to its neighbours, that would kind of hint that the focus point is isolated in that space and is a potential outlier. The algorithm depends on the hyperparameter K, which decides upon the number of neighbours to consider when calculating the local density. This value is bounded between 0 (no neighbour) and the total points (all points being neighbour) in the space.
The local density function is defined as the reciprocal of average reachability distance, where, average reachability distance is defined as the average distance from the focus point to all points in the neighbour.
LOF = average local density of neighbors / local density of focus point
If,
LOF β 1 similar density as neighbors
LOF < 1 higher density than neighbors (normal point)
LOF > 1 lower density than neighbors (anomaly)
Also, the below diagram shows the calculation of LOF and Local Density for a sample focus point(dark blue) in the space. Here, K=3(neighbours), d(distance) can be calculated as euclidean, manhattan, etc.
You can implement it using pythonβs Scikit-learn library as shown below β
from sklearn.neighbors import LocalOutlierFactordata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]lof = LocalOutlierFactor(n_neighbors=2, metric='manhattan')prediction = lof.fit_predict(data)>> [ 1, 1, 1, 1, -1, 1]
Please feel free to explore the library for hyper-parameter tuning, etc.(Link in the Resources section)
Also, if you want to keep enjoying reading awesome articles related to Data Science and Machine Learning, you can always purchase the Medium membership through my referral link :)
I already have a pretty detailed blog post on Geometric Models for Outlier Detection, where I primarily focus on Angle-Based Techniques(ABOD) and Depth-Based Techniques(Convex Hull). You can check it out here. The below figure shows a pictorial view for both the techniques detecting outliers β
Isolation Forest is a tree-based algorithm that tries to find out outliers based on the concept of decision boundaries(just like we have for decision trees). The idea over here is to keep splitting the data at random thresholds and feature till every point gets isolated(itβs like overfitting a decision tree on a dataset). Once the isolation is achieved we chunk out points that got isolated pretty early during this process. And we mark these points as potential outliers. If you see this intuitively, the farther a point is from the majority, the easier it gets to isolate, whereas, isolating the points that are part of a group would require more cuts to isolate every point.
If you see in the fig. below, we randomly select feature and value to where we cut. And just after 4 cuts, we were able to isolate the outlier points, which means, these nodes would be occurring very early during our tree construction phase.
You can implement it using pythonβs Scikit-learn library as shown below β
from sklearn.ensemble import IsolationForestdata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]iforest = IsolationForest(n_estimators=5)iforest.fit(data)actual_data = [[1, 1.5]]iforest.predict(actual_data)>> 1 (Normal)outlier_data = [[45, 55]]iforest.predict(outlier_data)>> -1 (Outlier)
Please feel free to explore the library for hyper-parameter tuning, etc.(Link in the Resources section)
Autoencoders are Neural network architectures that are trained to reproduce the input itself. It consists of two trainable components namely β Encoder and Decoder. Where the goal of the encoder is to learn a latent representation of the input(original dimension to low dimension) and the goal of the decoder is to learn to reconstruct the input from this latent representation(low dimension to original dimension). So for the autoencoder to work well, both of these components should optimize on their respective tasks.
Autoencoders are widely used for detecting anomalies. A typical intuition behind how this works is that if a point in feature space lies far away from the majority of the points(meaning it holds different properties, for example β dog images clustered around a certain part of the feature space and cow image lies pretty far from that cluster), in such cases, the autoencoder learns the dog distribution (because of the count of dog images would be very high compared to cows β thatβs why itβs an anomaly, hence model would majorly focus on learning the dog cluster). This means, the model would be able to more or less correctly re-generate the dog images leading to low loss values, whereas, for the cow image it would generate high loss(because thatβs something odd it saw for the first time and the weights it has learnt is mostly to reconstruct dog images). We use these reconstruction loss values as the anomaly scores, so Higher the scores, the higher the chances of input being an anomaly.
In the figure below β Consider green dots as dogs and blue dot as cows. We train our system with this input distribution and expect it to output the same. But we can see that the model more or less perfectly re-generated the yellow dots but could not fit well for the blue one(as it was not in the same feature range as yellowβs)
In the figure below β During inference when we give a yellow dot to our model, itβs able to re-generate it will less error(signal for normal point), whereas for blue one it returns a high error(signal for anomaly/outlier) due to incompetence to re-generate the same.
You can implement it using pythonβs PyOD library. I recommend you to follow this blogpost for the same.(Link in the Resources section)
In Outlier Detection using In-degree Number (ODIN), we calculate the in-degree for each of the data points. Here, in-degree is defined as the number of nearest neighbour sets to this point belongs. Higher this value, the more the confidence of this point belonging to some dense region in the space. Whereas, on the other side, a lesser value of this would mean that itβs not part of many nearest neighbour sets and is kind of isolated in the space. You can think of this method to be the reverse of KNN.
Here in the figure, we set the value of k(nearest neighbours)=3, the redpoint belong to just one nearest neighbour set which is of bluepoint, whereas, all other points are part of more than 1 nearest neighbour sets. Hence, we conclude that redpoint is an outlier.
You can implement it using pythonβs package-outlier library as shown below β
import package_outlier as podata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]result = po.LocalOutlierFactorOutlier(data)print (result)
Please feel free to explore the library for hyper-parameter tuning, etc. (Link in the Resources section)
Also if research papers interest you then you can checkout some research paper summaries that I have written.
PyOD: https://pypi.org/project/pyod/Scikit-Learn: https://scikit-learn.org/stable/index.htmlpackage-outlier: https://pypi.org/project/package-outlier/
PyOD: https://pypi.org/project/pyod/
Scikit-Learn: https://scikit-learn.org/stable/index.html
package-outlier: https://pypi.org/project/package-outlier/
I hope you enjoyed reading this. If youβd like to support me as a writer, consider signing up to become a Medium member. Itβs just $5 a month and you get unlimited access to Medium.
Thatβs it for this blog. Thank you for your time!
|
[
{
"code": null,
"e": 482,
"s": 172,
"text": "Outliers are those observations that differ strongly(different properties) from the other data points in the sample of a population. In this blog, we will go through 5 Outlier Detection techniques that every βData Enthusiastβ must know. But before that letβs take a look and understand the source of outliers."
},
{
"code": null,
"e": 881,
"s": 482,
"text": "There are multiple reasons why there can be outliers in the dataset, like Human errors(Wrong data entry), Measurement errors(System/Tool error), Data manipulation error(Faulty data preprocessing error), Sampling errors(creating samples from heterogeneous sources), etc. Importantly, detecting and treating these Outliers is important for learning a robust and generalizable machine learning system."
},
{
"code": null,
"e": 1228,
"s": 881,
"text": "The Z-score(also called the standard score) is an important concept in statistics that indicates how far away a certain point is from the mean. By applying Z-transformation we shift the distribution and make it 0 mean with unit standard deviation. For example β A Z-score of 2 would mean the data point is 2 standard deviation away from the mean."
},
{
"code": null,
"e": 1295,
"s": 1228,
"text": "Also, z-score of any data point can be calculated as shown below β"
},
{
"code": null,
"e": 1342,
"s": 1295,
"text": "Z-score(i) = (x(i) -mean) / standard deviation"
},
{
"code": null,
"e": 1603,
"s": 1342,
"text": "It assumes that the data is normally distributed and hence the % of data points that lie between -/+1 stdev. is ~68%, -/+2 stdev. is ~95% and -/+3 stdev. is ~99.7%. Hence, if the Z-score is >3 we can safely mark that point to be an outlier. Refer to below fig."
},
{
"code": null,
"e": 1654,
"s": 1603,
"text": "You can implement it using python as shown below β"
},
{
"code": null,
"e": 1870,
"s": 1654,
"text": "import numpy as npdata = [1, 2, 3, 2, 1, 100, 1, 2, 3, 2, 1]threshold = 3mean = np.mean(data)std = np.std(data)z_score_outlier = [i for i in data if (i-mean)/std > threshold]print (z_score_outlier)>> 100 (outlier)"
},
{
"code": null,
"e": 1984,
"s": 1870,
"text": "You can also use in-built functions provided by Scikit learn and Scipy in Python. (Link in the Resources section)"
},
{
"code": null,
"e": 2622,
"s": 1984,
"text": "In Local Outlier Factor (LOF), the idea revolves around the concept of local regions. Here, we calculate and compare the local density of the focus point with the local density of its neighbours. If we find that the local density of the focus point is very low compared to its neighbours, that would kind of hint that the focus point is isolated in that space and is a potential outlier. The algorithm depends on the hyperparameter K, which decides upon the number of neighbours to consider when calculating the local density. This value is bounded between 0 (no neighbour) and the total points (all points being neighbour) in the space."
},
{
"code": null,
"e": 2837,
"s": 2622,
"text": "The local density function is defined as the reciprocal of average reachability distance, where, average reachability distance is defined as the average distance from the focus point to all points in the neighbour."
},
{
"code": null,
"e": 2909,
"s": 2837,
"text": "LOF = average local density of neighbors / local density of focus point"
},
{
"code": null,
"e": 2913,
"s": 2909,
"text": "If,"
},
{
"code": null,
"e": 2950,
"s": 2913,
"text": "LOF β 1 similar density as neighbors"
},
{
"code": null,
"e": 3003,
"s": 2950,
"text": "LOF < 1 higher density than neighbors (normal point)"
},
{
"code": null,
"e": 3050,
"s": 3003,
"text": "LOF > 1 lower density than neighbors (anomaly)"
},
{
"code": null,
"e": 3254,
"s": 3050,
"text": "Also, the below diagram shows the calculation of LOF and Local Density for a sample focus point(dark blue) in the space. Here, K=3(neighbours), d(distance) can be calculated as euclidean, manhattan, etc."
},
{
"code": null,
"e": 3328,
"s": 3254,
"text": "You can implement it using pythonβs Scikit-learn library as shown below β"
},
{
"code": null,
"e": 3558,
"s": 3328,
"text": "from sklearn.neighbors import LocalOutlierFactordata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]lof = LocalOutlierFactor(n_neighbors=2, metric='manhattan')prediction = lof.fit_predict(data)>> [ 1, 1, 1, 1, -1, 1]"
},
{
"code": null,
"e": 3662,
"s": 3558,
"text": "Please feel free to explore the library for hyper-parameter tuning, etc.(Link in the Resources section)"
},
{
"code": null,
"e": 3842,
"s": 3662,
"text": "Also, if you want to keep enjoying reading awesome articles related to Data Science and Machine Learning, you can always purchase the Medium membership through my referral link :)"
},
{
"code": null,
"e": 4137,
"s": 3842,
"text": "I already have a pretty detailed blog post on Geometric Models for Outlier Detection, where I primarily focus on Angle-Based Techniques(ABOD) and Depth-Based Techniques(Convex Hull). You can check it out here. The below figure shows a pictorial view for both the techniques detecting outliers β"
},
{
"code": null,
"e": 4817,
"s": 4137,
"text": "Isolation Forest is a tree-based algorithm that tries to find out outliers based on the concept of decision boundaries(just like we have for decision trees). The idea over here is to keep splitting the data at random thresholds and feature till every point gets isolated(itβs like overfitting a decision tree on a dataset). Once the isolation is achieved we chunk out points that got isolated pretty early during this process. And we mark these points as potential outliers. If you see this intuitively, the farther a point is from the majority, the easier it gets to isolate, whereas, isolating the points that are part of a group would require more cuts to isolate every point."
},
{
"code": null,
"e": 5059,
"s": 4817,
"text": "If you see in the fig. below, we randomly select feature and value to where we cut. And just after 4 cuts, we were able to isolate the outlier points, which means, these nodes would be occurring very early during our tree construction phase."
},
{
"code": null,
"e": 5133,
"s": 5059,
"text": "You can implement it using pythonβs Scikit-learn library as shown below β"
},
{
"code": null,
"e": 5435,
"s": 5133,
"text": "from sklearn.ensemble import IsolationForestdata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]iforest = IsolationForest(n_estimators=5)iforest.fit(data)actual_data = [[1, 1.5]]iforest.predict(actual_data)>> 1 (Normal)outlier_data = [[45, 55]]iforest.predict(outlier_data)>> -1 (Outlier)"
},
{
"code": null,
"e": 5539,
"s": 5435,
"text": "Please feel free to explore the library for hyper-parameter tuning, etc.(Link in the Resources section)"
},
{
"code": null,
"e": 6059,
"s": 5539,
"text": "Autoencoders are Neural network architectures that are trained to reproduce the input itself. It consists of two trainable components namely β Encoder and Decoder. Where the goal of the encoder is to learn a latent representation of the input(original dimension to low dimension) and the goal of the decoder is to learn to reconstruct the input from this latent representation(low dimension to original dimension). So for the autoencoder to work well, both of these components should optimize on their respective tasks."
},
{
"code": null,
"e": 7057,
"s": 6059,
"text": "Autoencoders are widely used for detecting anomalies. A typical intuition behind how this works is that if a point in feature space lies far away from the majority of the points(meaning it holds different properties, for example β dog images clustered around a certain part of the feature space and cow image lies pretty far from that cluster), in such cases, the autoencoder learns the dog distribution (because of the count of dog images would be very high compared to cows β thatβs why itβs an anomaly, hence model would majorly focus on learning the dog cluster). This means, the model would be able to more or less correctly re-generate the dog images leading to low loss values, whereas, for the cow image it would generate high loss(because thatβs something odd it saw for the first time and the weights it has learnt is mostly to reconstruct dog images). We use these reconstruction loss values as the anomaly scores, so Higher the scores, the higher the chances of input being an anomaly."
},
{
"code": null,
"e": 7387,
"s": 7057,
"text": "In the figure below β Consider green dots as dogs and blue dot as cows. We train our system with this input distribution and expect it to output the same. But we can see that the model more or less perfectly re-generated the yellow dots but could not fit well for the blue one(as it was not in the same feature range as yellowβs)"
},
{
"code": null,
"e": 7654,
"s": 7387,
"text": "In the figure below β During inference when we give a yellow dot to our model, itβs able to re-generate it will less error(signal for normal point), whereas for blue one it returns a high error(signal for anomaly/outlier) due to incompetence to re-generate the same."
},
{
"code": null,
"e": 7789,
"s": 7654,
"text": "You can implement it using pythonβs PyOD library. I recommend you to follow this blogpost for the same.(Link in the Resources section)"
},
{
"code": null,
"e": 8294,
"s": 7789,
"text": "In Outlier Detection using In-degree Number (ODIN), we calculate the in-degree for each of the data points. Here, in-degree is defined as the number of nearest neighbour sets to this point belongs. Higher this value, the more the confidence of this point belonging to some dense region in the space. Whereas, on the other side, a lesser value of this would mean that itβs not part of many nearest neighbour sets and is kind of isolated in the space. You can think of this method to be the reverse of KNN."
},
{
"code": null,
"e": 8558,
"s": 8294,
"text": "Here in the figure, we set the value of k(nearest neighbours)=3, the redpoint belong to just one nearest neighbour set which is of bluepoint, whereas, all other points are part of more than 1 nearest neighbour sets. Hence, we conclude that redpoint is an outlier."
},
{
"code": null,
"e": 8635,
"s": 8558,
"text": "You can implement it using pythonβs package-outlier library as shown below β"
},
{
"code": null,
"e": 8782,
"s": 8635,
"text": "import package_outlier as podata = [[1, 1], [2, 2.1], [1, 2], [2, 1], [50, 35], [2, 1.5]]result = po.LocalOutlierFactorOutlier(data)print (result)"
},
{
"code": null,
"e": 8887,
"s": 8782,
"text": "Please feel free to explore the library for hyper-parameter tuning, etc. (Link in the Resources section)"
},
{
"code": null,
"e": 8997,
"s": 8887,
"text": "Also if research papers interest you then you can checkout some research paper summaries that I have written."
},
{
"code": null,
"e": 9148,
"s": 8997,
"text": "PyOD: https://pypi.org/project/pyod/Scikit-Learn: https://scikit-learn.org/stable/index.htmlpackage-outlier: https://pypi.org/project/package-outlier/"
},
{
"code": null,
"e": 9185,
"s": 9148,
"text": "PyOD: https://pypi.org/project/pyod/"
},
{
"code": null,
"e": 9242,
"s": 9185,
"text": "Scikit-Learn: https://scikit-learn.org/stable/index.html"
},
{
"code": null,
"e": 9301,
"s": 9242,
"text": "package-outlier: https://pypi.org/project/package-outlier/"
},
{
"code": null,
"e": 9483,
"s": 9301,
"text": "I hope you enjoyed reading this. If youβd like to support me as a writer, consider signing up to become a Medium member. Itβs just $5 a month and you get unlimited access to Medium."
}
] |
What is the use of the Configure() method of startup class in C# Asp.net Core?
|
The configure method is present inside startup class of ASP.NET Core application
The Configure method is a place where you can configure application request pipeline
for your application using IApplicationBuilder instance that is provided by the built-in
IoC container
The Configure method by default has these three parameters IApplicationBuilder,
IWebHostEnvironment and ILoggerFactory .
At run time, the ConfigureServices method is called before the Configure method.
This is to register custom service with the IoC container which can be used in
Configure method.
IWebHostEnvironment :Provides information about the web hosting environment an
application is running in.
IApplicationBuilder:Defines a class that provides the mechanisms to configure an
application's request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
if (env.IsDevelopment()){
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>{
endpoints.MapRazorPages();
});
}
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "The configure method is present inside startup class of ASP.NET Core application"
},
{
"code": null,
"e": 1331,
"s": 1143,
"text": "The Configure method is a place where you can configure application request pipeline\nfor your application using IApplicationBuilder instance that is provided by the built-in\nIoC container"
},
{
"code": null,
"e": 1452,
"s": 1331,
"text": "The Configure method by default has these three parameters IApplicationBuilder,\nIWebHostEnvironment and ILoggerFactory ."
},
{
"code": null,
"e": 1630,
"s": 1452,
"text": "At run time, the ConfigureServices method is called before the Configure method.\nThis is to register custom service with the IoC container which can be used in\nConfigure method."
},
{
"code": null,
"e": 1736,
"s": 1630,
"text": "IWebHostEnvironment :Provides information about the web hosting environment an\napplication is running in."
},
{
"code": null,
"e": 1849,
"s": 1736,
"text": "IApplicationBuilder:Defines a class that provides the mechanisms to configure an\napplication's request pipeline."
},
{
"code": null,
"e": 2248,
"s": 1849,
"text": "public void Configure(IApplicationBuilder app, IWebHostEnvironment env){\n if (env.IsDevelopment()){\n app.UseDeveloperExceptionPage();\n } else {\n app.UseExceptionHandler(\"/Error\");\n app.UseHsts();\n }\n app.UseHttpsRedirection();\n app.UseStaticFiles();\n app.UseRouting();\n app.UseAuthorization();\n app.UseEndpoints(endpoints =>{\n endpoints.MapRazorPages();\n });\n}"
}
] |
How to find row minimum for an R data frame?
|
Data analysis is a difficult task because it has so much variation in terms of the smaller objectives of a big project. One of the smallest tasks could be finding the minimum value in each row contained in a data frame. For this purpose, we cam use apply function and pass the FUN argument as min so that we can get minimum values.
Consider the below data frame β
Live Demo
set.seed(101)
x1<-rpois(20,1)
x2<-rpois(20,2)
x3<-rpois(20,5)
df1<-data.frame(x1,x2,x3)
df1
x1 x2 x3
1 1 3 4
2 0 5 5
3 1 1 6
4 1 2 4
5 0 4 4
6 0 3 3
7 1 0 2
8 0 1 8
9 1 2 7
10 1 2 2
11 2 2 2
12 1 1 4
13 1 1 6
14 3 1 6
15 1 2 5
16 1 4 7
17 2 1 6
18 0 3 5
19 1 0 6
20 0 4 5
Creating a new column Min for minimum of each row β
df1$Min<-apply(df1,1,FUN=min)
df1
x1 x2 x3 Min
1 1 3 4 1
2 0 5 5 0
3 1 1 6 1
4 1 2 4 1
5 0 4 4 0
6 0 3 3 0
7 1 0 2 0
8 0 1 8 0
9 1 2 7 1
10 1 2 2 1
11 2 2 2 2
12 1 1 4 1
13 1 1 6 1
14 3 1 6 1
15 1 2 5 1
16 1 4 7 1
17 2 1 6 1
18 0 3 5 0
19 1 0 6 0
20 0 4 5 0
Letβs have a look at another example β
Live Demo
y1<-sample(0:9,20,replace=TRUE)
y2<-sample(0:9,20,replace=TRUE)
y3<-sample(0:9,20,replace=TRUE)
y4<-sample(0:9,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2
y1 y2 y3 y4
1 7 2 6 1
2 9 5 4 6
3 9 7 5 0
4 6 5 0 8
5 2 4 7 1
6 1 7 9 1
7 3 2 0 4
8 3 3 3 6
9 5 9 3 7
10 4 3 1 2
11 7 1 7 8
12 5 8 2 5
13 1 0 4 2
14 5 0 7 8
15 0 2 6 5
16 7 4 4 5
17 3 5 7 9
18 5 8 1 4
19 5 0 9 1
20 3 1 3 1
Creating a new column Minimum for minimum of each row β
df2$Minimum<-apply(df2,1,FUN=min)
df2
y1 y2 y3 y4 Minimum
1 8 9 9 3 3
2 4 4 6 5 4
3 0 1 8 2 0
4 2 8 8 4 2
5 9 1 8 6 1
6 8 4 4 1 1
7 2 2 1 3 1
8 9 8 6 3 3
9 3 9 8 8 3
10 1 6 9 8 1
11 0 3 4 2 0
12 5 0 7 6 0
13 8 7 4 7 4
14 1 3 5 2 1
15 1 7 8 1 1
16 0 9 5 5 0
17 5 9 8 0 0
18 5 3 2 3 2
19 1 3 9 7 1
20 8 2 6 2 2
|
[
{
"code": null,
"e": 1394,
"s": 1062,
"text": "Data analysis is a difficult task because it has so much variation in terms of the smaller objectives of a big project. One of the smallest tasks could be finding the minimum value in each row contained in a data frame. For this purpose, we cam use apply function and pass the FUN argument as min so that we can get minimum values."
},
{
"code": null,
"e": 1426,
"s": 1394,
"text": "Consider the below data frame β"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": " Live Demo"
},
{
"code": null,
"e": 1529,
"s": 1437,
"text": "set.seed(101)\nx1<-rpois(20,1)\nx2<-rpois(20,2)\nx3<-rpois(20,5)\ndf1<-data.frame(x1,x2,x3)\ndf1"
},
{
"code": null,
"e": 1711,
"s": 1529,
"text": " x1 x2 x3\n1 1 3 4\n2 0 5 5\n3 1 1 6\n4 1 2 4\n5 0 4 4\n6 0 3 3\n7 1 0 2\n8 0 1 8\n9 1 2 7\n10 1 2 2\n11 2 2 2\n12 1 1 4\n13 1 1 6\n14 3 1 6\n15 1 2 5\n16 1 4 7\n17 2 1 6\n18 0 3 5\n19 1 0 6\n20 0 4 5"
},
{
"code": null,
"e": 1763,
"s": 1711,
"text": "Creating a new column Min for minimum of each row β"
},
{
"code": null,
"e": 1797,
"s": 1763,
"text": "df1$Min<-apply(df1,1,FUN=min)\ndf1"
},
{
"code": null,
"e": 2021,
"s": 1797,
"text": "x1 x2 x3 Min\n1 1 3 4 1\n2 0 5 5 0\n3 1 1 6 1\n4 1 2 4 1\n5 0 4 4 0\n6 0 3 3 0\n7 1 0 2 0\n8 0 1 8 0\n9 1 2 7 1\n10 1 2 2 1\n11 2 2 2 2\n12 1 1 4 1\n13 1 1 6 1\n14 3 1 6 1\n15 1 2 5 1\n16 1 4 7 1\n17 2 1 6 1\n18 0 3 5 0\n19 1 0 6 0\n20 0 4 5 0"
},
{
"code": null,
"e": 2060,
"s": 2021,
"text": "Letβs have a look at another example β"
},
{
"code": null,
"e": 2071,
"s": 2060,
"text": " Live Demo"
},
{
"code": null,
"e": 2232,
"s": 2071,
"text": "y1<-sample(0:9,20,replace=TRUE)\ny2<-sample(0:9,20,replace=TRUE)\ny3<-sample(0:9,20,replace=TRUE)\ny4<-sample(0:9,20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2"
},
{
"code": null,
"e": 2479,
"s": 2232,
"text": " y1 y2 y3 y4\n1 7 2 6 1\n2 9 5 4 6\n3 9 7 5 0\n4 6 5 0 8\n5 2 4 7 1\n6 1 7 9 1\n7 3 2 0 4\n8 3 3 3 6\n9 5 9 3 7\n10 4 3 1 2\n11 7 1 7 8\n12 5 8 2 5\n13 1 0 4 2\n14 5 0 7 8\n15 0 2 6 5\n16 7 4 4 5\n17 3 5 7 9\n18 5 8 1 4\n19 5 0 9 1\n20 3 1 3 1"
},
{
"code": null,
"e": 2535,
"s": 2479,
"text": "Creating a new column Minimum for minimum of each row β"
},
{
"code": null,
"e": 2573,
"s": 2535,
"text": "df2$Minimum<-apply(df2,1,FUN=min)\ndf2"
},
{
"code": null,
"e": 2905,
"s": 2573,
"text": " y1 y2 y3 y4 Minimum\n1 8 9 9 3 3\n2 4 4 6 5 4\n3 0 1 8 2 0\n4 2 8 8 4 2\n5 9 1 8 6 1\n6 8 4 4 1 1\n7 2 2 1 3 1\n8 9 8 6 3 3\n9 3 9 8 8 3\n10 1 6 9 8 1\n11 0 3 4 2 0\n12 5 0 7 6 0\n13 8 7 4 7 4\n14 1 3 5 2 1\n15 1 7 8 1 1\n16 0 9 5 5 0\n17 5 9 8 0 0\n18 5 3 2 3 2\n19 1 3 9 7 1\n20 8 2 6 2 2"
}
] |
How to Format a Hard Disk on Linux OS
|
In this article, we will learn how to add a new hard disk drive to Linux OS, Assuming the drive is visible to the BIOS, it should automatically be detected by the operating system. Typically, the disk drives in a system is assigned to a device name beginning with βhdβ or βsdβ followed by a letter to indicate the device number. For example, the first device might be /dev/sda, the second /dev/sdb and so on.
The following is the output from a system with only one physical disk drive.
# ls /dev/sd*
/dev/sda /dev/sda1 /dev/sda2 /dev/sdb
This shows that the disk drive represented by /dev/sda is itself divided into 2 partitions, represented by /dev/sda1 and /dev/sda2. As shown above, the new hard drive has been assigned to the device file /dev/sdb. Currently the drive has no partitions shown (because we have yet to create any).
At this point we have a choice of creating partitions and file systems on the new drive and mounting them for access or adding the disk as a physical volume as part of a volume group. To perform the former continues with this article.
The next step is to create one or more Linux partitions on the new disk drive. This is achieved using the fdisk utility which takes as a command-line argument the device to be partitioned
# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0xd1082b01.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)
WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
switch off the mode (command 'c') and change display units to
sectors (command 'u').
Command (m for help):
As instructed, switch off DOS compatible mode and change the units to sectors by entering the c and u commands:
Command (m for help): c
DOS Compatibility flag is not set
Command (m for help): u
Changing display/entry units to sectors
In order to view the current partitions on the disk enter the p command:
Command (m for help): p
Disk /dev/sdb: 34.4 GB, 34359738368 bytes
255 heads, 63 sectors/track, 4177 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xd1082b01
Device Boot Start End Blocks Id System
As we can see from the above fdisk output the disk currently has no partitions because it is a previously unused disk. The next step is to create a new partition on the disk, a task which is performed by entering n (for new partition) and p (for primary partition):
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4):
In this example, we plan to create one partition which will be partition 1. Next, we need to specify where the partition will begin and end. Since this is the first partition we need it to start at the first available sector and since we want to use the entire disk we specify the last sector as the end.
Note: If you wish to create multiple partitions you can specify the size of each partition by sectors, bytes, kilobytes or megabytes.
Partition number (1-4): 1
First sector (2048-67108863, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-67108863, default 67108863):
Using default value 67108863
Now that we have specified the partition we need to write it to the disk using the w command:
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
If we now look at the devices again, we will see that the new partition is visible as /dev/sdb1:
# ls /dev/sd*
/dev/sda /dev/sda1 /dev/sda2 /dev/sdb /dev/sdb1
The next step is to create a filesystem on our new partition.
We now have a new disk installed, it is visible to RHEL 6 and we have configured a Linux partition on the disk. The next step is to create a Linux file system on the partition so that the operating system can use it to store files and data. The easiest way to create a file system on a partition is to use the mkfs.ext4 utility which takes as arguments the label and the partition device:
# /sbin/mkfs.ext4 -L /backup /dev/sdb1
mke2fs 1.41.12 (17-May-2010)
Filesystem label=/backup
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
2097152 inodes, 8388352 blocks
419417 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
256 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,4096000, 7962624
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem checks automatically after 36 mounts or 180 days, whichever comes first.
Use tune2fs -c or -i to override.
Now that we have created a new filesystem on the Linux partition of our new disk drive, we need to mount it so that it is accessible. In order to do this we need to create a mount point. A mount point is simply a directory or folder into which the filesystem will be mounted. For the purposes of this example, we will create a /data directory to match our filesystem label (although it is not necessary that these values match):
# mkdir /data
The filesystem may then be manually mounted using the mount command:
# mount /dev/sdb1 /data
Running the mount command with no arguments shows us all currently mounted filesystems (including our new filesystem):
# mount
/dev/mapper/vg_rhel6-lv_root on / type ext4 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:object_r:tmpfs_t:s0")
/dev/sda1 on /boot type ext4 (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)
/dev/sr0 on /media/RHEL_6.0 x86_64 Disc 1 type iso9660 (ro,nosuid,nodev,uhelper=udisks,uid=500,gid=500,iocharset=utf8,mode=0400,dmode=0500)
/dev/sdb1 on /data type ext4 (rw)
In order to configure the system so that the new disk is automatically mounted at the time boot we need an entry to be added to the /etc/fstab file.
The below is the sample configuration file which shows an fstab file configured to auto mount our /backup partition:
/dev/mapper/vg_rhel6-lv_root / ext4 defaults 1 1
UUID=4a9886f5-9545-406a-a694-04a60b24df84 /boot ext4 defaults 1 2
/dev/mapper/vg_rhel6-lv_swap swap swap defaults 0 0
tmpfs /dev/shm tmpfs defaults 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
sysfs /sys sysfs defaults 0 0
proc /proc proc defaults 0 0
LABEL=/backup /backup ext4 defaults 1 2
Conclusion: After this configuration and setup we can able to add a new hard disk drive, format & mount also able to auto mount the new drive even after the reboot of the system. Which will help the users or system administrators provide the Linux OS with more free space.
|
[
{
"code": null,
"e": 1471,
"s": 1062,
"text": "In this article, we will learn how to add a new hard disk drive to Linux OS, Assuming the drive is visible to the BIOS, it should automatically be detected by the operating system. Typically, the disk drives in a system is assigned to a device name beginning with βhdβ or βsdβ followed by a letter to indicate the device number. For example, the first device might be /dev/sda, the second /dev/sdb and so on."
},
{
"code": null,
"e": 1548,
"s": 1471,
"text": "The following is the output from a system with only one physical disk drive."
},
{
"code": null,
"e": 1600,
"s": 1548,
"text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2 /dev/sdb"
},
{
"code": null,
"e": 1895,
"s": 1600,
"text": "This shows that the disk drive represented by /dev/sda is itself divided into 2 partitions, represented by /dev/sda1 and /dev/sda2. As shown above, the new hard drive has been assigned to the device file /dev/sdb. Currently the drive has no partitions shown (because we have yet to create any)."
},
{
"code": null,
"e": 2130,
"s": 1895,
"text": "At this point we have a choice of creating partitions and file systems on the new drive and mounting them for access or adding the disk as a physical volume as part of a volume group. To perform the former continues with this article."
},
{
"code": null,
"e": 2318,
"s": 2130,
"text": "The next step is to create one or more Linux partitions on the new disk drive. This is achieved using the fdisk utility which takes as a command-line argument the device to be partitioned"
},
{
"code": null,
"e": 3536,
"s": 2318,
"text": "# fdisk /dev/sdb\nDevice contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel\nBuilding a new DOS disklabel with disk identifier 0xd1082b01.\nChanges will remain in memory only, until you decide to write them.\nAfter that, of course, the previous content won't be recoverable.\n\nWarning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)\nWARNING: DOS-compatible mode is deprecated. It's strongly recommended to\n switch off the mode (command 'c') and change display units to\n sectors (command 'u').\n\nCommand (m for help):\nAs instructed, switch off DOS compatible mode and change the units to sectors by entering the c and u commands:\nCommand (m for help): c\nDOS Compatibility flag is not set\nCommand (m for help): u\nChanging display/entry units to sectors\nIn order to view the current partitions on the disk enter the p command:\nCommand (m for help): p\nDisk /dev/sdb: 34.4 GB, 34359738368 bytes\n255 heads, 63 sectors/track, 4177 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0xd1082b01\n Device Boot Start End Blocks Id System"
},
{
"code": null,
"e": 3802,
"s": 3536,
"text": "As we can see from the above fdisk output the disk currently has no partitions because it is a previously unused disk. The next step is to create a new partition on the disk, a task which is performed by entering n (for new partition) and p (for primary partition):"
},
{
"code": null,
"e": 3913,
"s": 3802,
"text": "Command (m for help): n\nCommand action\n e extended\n p primary partition (1-4)\n p\nPartition number (1-4):"
},
{
"code": null,
"e": 4218,
"s": 3913,
"text": "In this example, we plan to create one partition which will be partition 1. Next, we need to specify where the partition will begin and end. Since this is the first partition we need it to start at the first available sector and since we want to use the entire disk we specify the last sector as the end."
},
{
"code": null,
"e": 4352,
"s": 4218,
"text": "Note: If you wish to create multiple partitions you can specify the size of each partition by sectors, bytes, kilobytes or megabytes."
},
{
"code": null,
"e": 4765,
"s": 4352,
"text": "Partition number (1-4): 1\nFirst sector (2048-67108863, default 2048):\nUsing default value 2048\nLast sector, +sectors or +size{K,M,G} (2048-67108863, default 67108863):\nUsing default value 67108863\n\nNow that we have specified the partition we need to write it to the disk using the w command:\nCommand (m for help): w\nThe partition table has been altered!\nCalling ioctl() to re-read partition table.\nSyncing disks."
},
{
"code": null,
"e": 4862,
"s": 4765,
"text": "If we now look at the devices again, we will see that the new partition is visible as /dev/sdb1:"
},
{
"code": null,
"e": 4924,
"s": 4862,
"text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2 /dev/sdb /dev/sdb1"
},
{
"code": null,
"e": 4986,
"s": 4924,
"text": "The next step is to create a filesystem on our new partition."
},
{
"code": null,
"e": 5375,
"s": 4986,
"text": "We now have a new disk installed, it is visible to RHEL 6 and we have configured a Linux partition on the disk. The next step is to create a Linux file system on the partition so that the operating system can use it to store files and data. The easiest way to create a file system on a partition is to use the mkfs.ext4 utility which takes as arguments the label and the partition device:"
},
{
"code": null,
"e": 6176,
"s": 5375,
"text": "# /sbin/mkfs.ext4 -L /backup /dev/sdb1\nmke2fs 1.41.12 (17-May-2010)\nFilesystem label=/backup\nOS type: Linux\nBlock size=4096 (log=2)\nFragment size=4096 (log=2)\nStride=0 blocks, Stripe width=0 blocks\n2097152 inodes, 8388352 blocks\n419417 blocks (5.00%) reserved for the super user\nFirst data block=0\nMaximum filesystem blocks=4294967296\n256 block groups\n32768 blocks per group, 32768 fragments per group\n8192 inodes per group\nSuperblock backups stored on blocks:\n32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,4096000, 7962624\nWriting inode tables: done\nCreating journal (32768 blocks): done\nWriting superblocks and filesystem accounting information: done\nThis filesystem checks automatically after 36 mounts or 180 days, whichever comes first.\nUse tune2fs -c or -i to override."
},
{
"code": null,
"e": 6605,
"s": 6176,
"text": "Now that we have created a new filesystem on the Linux partition of our new disk drive, we need to mount it so that it is accessible. In order to do this we need to create a mount point. A mount point is simply a directory or folder into which the filesystem will be mounted. For the purposes of this example, we will create a /data directory to match our filesystem label (although it is not necessary that these values match):"
},
{
"code": null,
"e": 6619,
"s": 6605,
"text": "# mkdir /data"
},
{
"code": null,
"e": 6688,
"s": 6619,
"text": "The filesystem may then be manually mounted using the mount command:"
},
{
"code": null,
"e": 6712,
"s": 6688,
"text": "# mount /dev/sdb1 /data"
},
{
"code": null,
"e": 6831,
"s": 6712,
"text": "Running the mount command with no arguments shows us all currently mounted filesystems (including our new filesystem):"
},
{
"code": null,
"e": 7393,
"s": 6831,
"text": "# mount\n/dev/mapper/vg_rhel6-lv_root on / type ext4 (rw)\nproc on /proc type proc (rw)\nsysfs on /sys type sysfs (rw)\ndevpts on /dev/pts type devpts (rw,gid=5,mode=620)\ntmpfs on /dev/shm type tmpfs (rw,rootcontext=\"system_u:object_r:tmpfs_t:s0\")\n/dev/sda1 on /boot type ext4 (rw)\nnone on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)\nsunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)\n/dev/sr0 on /media/RHEL_6.0 x86_64 Disc 1 type iso9660 (ro,nosuid,nodev,uhelper=udisks,uid=500,gid=500,iocharset=utf8,mode=0400,dmode=0500)\n/dev/sdb1 on /data type ext4 (rw)"
},
{
"code": null,
"e": 7542,
"s": 7393,
"text": "In order to configure the system so that the new disk is automatically mounted at the time boot we need an entry to be added to the /etc/fstab file."
},
{
"code": null,
"e": 7659,
"s": 7542,
"text": "The below is the sample configuration file which shows an fstab file configured to auto mount our /backup partition:"
},
{
"code": null,
"e": 8127,
"s": 7659,
"text": "/dev/mapper/vg_rhel6-lv_root / ext4 defaults 1 1\nUUID=4a9886f5-9545-406a-a694-04a60b24df84 /boot ext4 defaults 1 2\n/dev/mapper/vg_rhel6-lv_swap swap swap defaults 0 0\n\ntmpfs /dev/shm tmpfs defaults 0 0\ndevpts /dev/pts devpts gid=5,mode=620 0 0\nsysfs /sys sysfs defaults 0 0\nproc /proc proc defaults 0 0\nLABEL=/backup /backup ext4 defaults 1 2"
},
{
"code": null,
"e": 8400,
"s": 8127,
"text": "Conclusion: After this configuration and setup we can able to add a new hard disk drive, format & mount also able to auto mount the new drive even after the reboot of the system. Which will help the users or system administrators provide the Linux OS with more free space."
}
] |
Fibonacci Heap | Set 1 (Introduction)
|
28 Jun, 2022
Heaps are mainly used for implementing priority queue. We have discussed below heaps in previous posts.
Binary Heap
Binomial Heap
In terms of Time Complexity, Fibonacci Heap beats both Binary and Binomial Heaps.
Below are amortized time complexities of Fibonacci Heap.
1) Find Min: Ξ(1) [Same as both Binary and Binomial]
2) Delete Min: O(Log n) [Ξ(Log n) in both Binary and Binomial]
3) Insert: Ξ(1) [Ξ(Log n) in Binary and Ξ(1) in Binomial]
4) Decrease-Key: Ξ(1) [Ξ(Log n) in both Binary and Binomial]
5) Merge: Ξ(1) [Ξ(m Log n) or Ξ(m+n) in Binary and
Ξ(Log n) in Binomial]
Like Binomial Heap, Fibonacci Heap is a collection of trees with min-heap or max-heap property. In Fibonacci Heap, trees can have any shape even all trees can be single nodes (This is unlike Binomial Heap where every tree has to be Binomial Tree).
Below is an example Fibonacci Heap taken from here.
Fibonacci Heap maintains a pointer to minimum value (which is root of a tree). All tree roots are connected using circular doubly linked list, so all of them can be accessed using single βminβ pointer.
The main idea is to execute operations in βlazyβ way. For example merge operation simply links two heaps, insert operation simply adds a new tree with single node. The operation extract minimum is the most complicated operation. It does delayed work of consolidating trees. This makes delete also complicated as delete first decreases key to minus infinite, then calls extract minimum.
Below are some interesting facts about Fibonacci Heap
The reduced time complexity of Decrease-Key has importance in Dijkstra and Prim algorithms. With Binary Heap, time complexity of these algorithms is O(VLogV + ELogV). If Fibonacci Heap is used, then time complexity is improved to O(VLogV + E)Although Fibonacci Heap looks promising time complexity wise, it has been found slow in practice as hidden constants are high (Source Wiki).Fibonacci heap are mainly called so because Fibonacci numbers are used in the running time analysis. Also, every node in Fibonacci Heap has degree at most O(log n) and the size of a subtree rooted in a node of degree k is at least Fk+2, where Fk is the kth Fibonacci number.
The reduced time complexity of Decrease-Key has importance in Dijkstra and Prim algorithms. With Binary Heap, time complexity of these algorithms is O(VLogV + ELogV). If Fibonacci Heap is used, then time complexity is improved to O(VLogV + E)
Although Fibonacci Heap looks promising time complexity wise, it has been found slow in practice as hidden constants are high (Source Wiki).
Fibonacci heap are mainly called so because Fibonacci numbers are used in the running time analysis. Also, every node in Fibonacci Heap has degree at most O(log n) and the size of a subtree rooted in a node of degree k is at least Fk+2, where Fk is the kth Fibonacci number.
We will soon be discussing Fibonacci Heap operations in detail.
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
abhinavvce06
hardikkoriintern
Fibonacci
Advanced Data Structure
Heap
Fibonacci
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Introduction of B-Tree
Red-Black Tree | Set 1 (Introduction)
HeapSort
K'th Smallest/Largest Element in Unsorted Array | Set 1
Introduction to Data Structures
Huffman Coding | Greedy Algo-3
Sliding Window Maximum (Maximum of all subarrays of size k)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 159,
"s": 54,
"text": "Heaps are mainly used for implementing priority queue. We have discussed below heaps in previous posts. "
},
{
"code": null,
"e": 172,
"s": 159,
"text": "Binary Heap "
},
{
"code": null,
"e": 187,
"s": 172,
"text": "Binomial Heap "
},
{
"code": null,
"e": 270,
"s": 187,
"text": "In terms of Time Complexity, Fibonacci Heap beats both Binary and Binomial Heaps. "
},
{
"code": null,
"e": 328,
"s": 270,
"text": "Below are amortized time complexities of Fibonacci Heap. "
},
{
"code": null,
"e": 704,
"s": 328,
"text": "1) Find Min: Ξ(1) [Same as both Binary and Binomial]\n2) Delete Min: O(Log n) [Ξ(Log n) in both Binary and Binomial]\n3) Insert: Ξ(1) [Ξ(Log n) in Binary and Ξ(1) in Binomial]\n4) Decrease-Key: Ξ(1) [Ξ(Log n) in both Binary and Binomial]\n5) Merge: Ξ(1) [Ξ(m Log n) or Ξ(m+n) in Binary and\n Ξ(Log n) in Binomial]"
},
{
"code": null,
"e": 953,
"s": 704,
"text": "Like Binomial Heap, Fibonacci Heap is a collection of trees with min-heap or max-heap property. In Fibonacci Heap, trees can have any shape even all trees can be single nodes (This is unlike Binomial Heap where every tree has to be Binomial Tree). "
},
{
"code": null,
"e": 1006,
"s": 953,
"text": "Below is an example Fibonacci Heap taken from here. "
},
{
"code": null,
"e": 1209,
"s": 1006,
"text": "Fibonacci Heap maintains a pointer to minimum value (which is root of a tree). All tree roots are connected using circular doubly linked list, so all of them can be accessed using single βminβ pointer. "
},
{
"code": null,
"e": 1596,
"s": 1209,
"text": "The main idea is to execute operations in βlazyβ way. For example merge operation simply links two heaps, insert operation simply adds a new tree with single node. The operation extract minimum is the most complicated operation. It does delayed work of consolidating trees. This makes delete also complicated as delete first decreases key to minus infinite, then calls extract minimum. "
},
{
"code": null,
"e": 1651,
"s": 1596,
"text": "Below are some interesting facts about Fibonacci Heap "
},
{
"code": null,
"e": 2308,
"s": 1651,
"text": "The reduced time complexity of Decrease-Key has importance in Dijkstra and Prim algorithms. With Binary Heap, time complexity of these algorithms is O(VLogV + ELogV). If Fibonacci Heap is used, then time complexity is improved to O(VLogV + E)Although Fibonacci Heap looks promising time complexity wise, it has been found slow in practice as hidden constants are high (Source Wiki).Fibonacci heap are mainly called so because Fibonacci numbers are used in the running time analysis. Also, every node in Fibonacci Heap has degree at most O(log n) and the size of a subtree rooted in a node of degree k is at least Fk+2, where Fk is the kth Fibonacci number."
},
{
"code": null,
"e": 2551,
"s": 2308,
"text": "The reduced time complexity of Decrease-Key has importance in Dijkstra and Prim algorithms. With Binary Heap, time complexity of these algorithms is O(VLogV + ELogV). If Fibonacci Heap is used, then time complexity is improved to O(VLogV + E)"
},
{
"code": null,
"e": 2692,
"s": 2551,
"text": "Although Fibonacci Heap looks promising time complexity wise, it has been found slow in practice as hidden constants are high (Source Wiki)."
},
{
"code": null,
"e": 2967,
"s": 2692,
"text": "Fibonacci heap are mainly called so because Fibonacci numbers are used in the running time analysis. Also, every node in Fibonacci Heap has degree at most O(log n) and the size of a subtree rooted in a node of degree k is at least Fk+2, where Fk is the kth Fibonacci number."
},
{
"code": null,
"e": 3032,
"s": 2967,
"text": "We will soon be discussing Fibonacci Heap operations in detail. "
},
{
"code": null,
"e": 3196,
"s": 3032,
"text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3209,
"s": 3196,
"text": "abhinavvce06"
},
{
"code": null,
"e": 3226,
"s": 3209,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 3236,
"s": 3226,
"text": "Fibonacci"
},
{
"code": null,
"e": 3260,
"s": 3236,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 3265,
"s": 3260,
"text": "Heap"
},
{
"code": null,
"e": 3275,
"s": 3265,
"text": "Fibonacci"
},
{
"code": null,
"e": 3280,
"s": 3275,
"text": "Heap"
},
{
"code": null,
"e": 3378,
"s": 3280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3407,
"s": 3378,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 3434,
"s": 3407,
"text": "Trie | (Insert and Search)"
},
{
"code": null,
"e": 3459,
"s": 3434,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 3482,
"s": 3459,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 3520,
"s": 3482,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 3529,
"s": 3520,
"text": "HeapSort"
},
{
"code": null,
"e": 3585,
"s": 3529,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 3617,
"s": 3585,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 3648,
"s": 3617,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Flatten BST to sorted list | Increasing order
|
17 Dec, 2021
Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where βHβ is the height of BST.
Examples:
Input:
5
/ \
3 7
/ \ / \
2 4 6 8
Output: 2 3 4 5 6 7 8
Input:
1
\
2
\
3
\
4
\
5
Output: 1 2 3 4 5
Approach: A simple approach will be to recreate the BST from its in-order traversal. This will take O(N) extra space where N is the number of nodes in BST.
To improve upon that, we will simulate in-order traversal of a binary tree as follows:
Create a dummy node.Create a variable called βprevβ and make it point to the dummy node.Perform in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr
Create a dummy node.
Create a variable called βprevβ and make it point to the dummy node.
Perform in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr
Set prev -> right = curr
Set prev -> left = NULL
Set prev = curr
This will improve the space complexity to O(H) in worst case as in-order traversal takes O(H) extra space.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
Python3
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to print flattened// binary Treevoid print(node* parent){ node* curr = parent; while (curr != NULL) cout << curr->data << " ", curr = curr->right;} // Function to perform in-order traversal// recursivelyvoid inorder(node* curr, node*& prev){ // Base case if (curr == NULL) return; inorder(curr->left, prev); prev->left = NULL; prev->right = curr; prev = curr; inorder(curr->right, prev);} // Function to flatten binary tree using// level order traversalnode* flatten(node* parent){ // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // Calling in-order traversal inorder(parent, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Calling required function print(flatten(root)); return 0;}
// Java implementation of the// above approachimport java.util.*;class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { System.out.print(curr.data + " "); curr = curr.right; }} static node prev; // Function to perform// in-order traversalstatic void Inorder(node curr){ // Base case if (curr == null) return; Inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; Inorder(curr.right);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Debojyoti Mandal
// C# implementation of the// above approachusing System;public class Program{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { Console.Write(curr.data + " "); curr = curr.right; }} static node prev; // Function to perform// in-order traversalstatic void Inorder(node curr){ // Base case if (curr == null) return; Inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; Inorder(curr.right);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void Main(string[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by rrrtnx.
<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} let prev; // Function to print flattened// binary Treefunction print(parent){ let curr = parent; while (curr != null) { document.write(curr.data + " "); curr = curr.right; }} // Function to perform in-order traversal// recursivelyfunction inorder(curr){ // Base case if (curr == null) return; inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; inorder(curr.right);} // Function to flatten binary tree using// level order traversalfunction flatten(parent){ // Dummy node let dummy = new node(-1); // Pointer to previous element prev = dummy; // Calling in-order traversal inorder(parent); prev.left = null; prev.right = null; let ret = dummy.right; // Delete dummy node return ret;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Calling required functionprint(flatten(root)); // This code is contributed by divyeshrabadiya07 </script>
# Python3 implementation of the approach global prev# Node of the binary treeclass node : def __init__(self, data): self.data = data self.left = None self.right = None # Function to print flattened# binary Treedef printTree(parent): curr = parent while (curr != None): print(curr.data,end=' ') curr = curr.right # Function to perform in-order traversal# recursivelydef inorder(curr): global prev # Base case if (curr == None): return inorder(curr.left) prev.left = None prev.right = curr prev = curr inorder(curr.right) # Function to flatten binary tree using# level order traversaldef flatten(parent): global prev # Dummy node dummy = node(-1) # Pointer to previous element prev = dummy # Calling in-order traversal inorder(parent) prev.left = None prev.right = None ret = dummy.right # Delete dummy node return ret # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) # Calling required function printTree(flatten(root))
2 3 4 5 6 7 8
Time Complexity: O(N)Auxiliary Space: O(N)
divyeshrabadiya07
mahinsagotra18
pankajsharmagfg
jyoti369
rrrtnx
amartyaghoshgfg
Algorithms
Binary Search Tree
Tree
Binary Search Tree
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Find postorder traversal of BST from preorder traversal
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 337,
"s": 54,
"text": "Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where βHβ is the height of BST."
},
{
"code": null,
"e": 348,
"s": 337,
"text": "Examples: "
},
{
"code": null,
"e": 589,
"s": 348,
"text": "Input: \n 5 \n / \\ \n 3 7 \n / \\ / \\ \n 2 4 6 8\nOutput: 2 3 4 5 6 7 8\nInput:\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\nOutput: 1 2 3 4 5"
},
{
"code": null,
"e": 746,
"s": 589,
"text": "Approach: A simple approach will be to recreate the BST from its in-order traversal. This will take O(N) extra space where N is the number of nodes in BST. "
},
{
"code": null,
"e": 835,
"s": 746,
"text": "To improve upon that, we will simulate in-order traversal of a binary tree as follows: "
},
{
"code": null,
"e": 1031,
"s": 835,
"text": "Create a dummy node.Create a variable called βprevβ and make it point to the dummy node.Perform in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr"
},
{
"code": null,
"e": 1052,
"s": 1031,
"text": "Create a dummy node."
},
{
"code": null,
"e": 1121,
"s": 1052,
"text": "Create a variable called βprevβ and make it point to the dummy node."
},
{
"code": null,
"e": 1229,
"s": 1121,
"text": "Perform in-order traversal and at each step. Set prev -> right = currSet prev -> left = NULLSet prev = curr"
},
{
"code": null,
"e": 1254,
"s": 1229,
"text": "Set prev -> right = curr"
},
{
"code": null,
"e": 1278,
"s": 1254,
"text": "Set prev -> left = NULL"
},
{
"code": null,
"e": 1294,
"s": 1278,
"text": "Set prev = curr"
},
{
"code": null,
"e": 1401,
"s": 1294,
"text": "This will improve the space complexity to O(H) in worst case as in-order traversal takes O(H) extra space."
},
{
"code": null,
"e": 1453,
"s": 1401,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1457,
"s": 1453,
"text": "C++"
},
{
"code": null,
"e": 1462,
"s": 1457,
"text": "Java"
},
{
"code": null,
"e": 1465,
"s": 1462,
"text": "C#"
},
{
"code": null,
"e": 1476,
"s": 1465,
"text": "Javascript"
},
{
"code": null,
"e": 1484,
"s": 1476,
"text": "Python3"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to print flattened// binary Treevoid print(node* parent){ node* curr = parent; while (curr != NULL) cout << curr->data << \" \", curr = curr->right;} // Function to perform in-order traversal// recursivelyvoid inorder(node* curr, node*& prev){ // Base case if (curr == NULL) return; inorder(curr->left, prev); prev->left = NULL; prev->right = curr; prev = curr; inorder(curr->right, prev);} // Function to flatten binary tree using// level order traversalnode* flatten(node* parent){ // Dummy node node* dummy = new node(-1); // Pointer to previous element node* prev = dummy; // Calling in-order traversal inorder(parent, prev); prev->left = NULL; prev->right = NULL; node* ret = dummy->right; // Delete dummy node delete dummy; return ret;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Calling required function print(flatten(root)); return 0;}",
"e": 2912,
"s": 1484,
"text": null
},
{
"code": "// Java implementation of the// above approachimport java.util.*;class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { System.out.print(curr.data + \" \"); curr = curr.right; }} static node prev; // Function to perform// in-order traversalstatic void Inorder(node curr){ // Base case if (curr == null) return; Inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; Inorder(curr.right);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by Debojyoti Mandal",
"e": 4319,
"s": 2912,
"text": null
},
{
"code": "// C# implementation of the// above approachusing System;public class Program{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to print flattened// binary treestatic void print(node parent){ node curr = parent; while (curr != null) { Console.Write(curr.data + \" \"); curr = curr.right; }} static node prev; // Function to perform// in-order traversalstatic void Inorder(node curr){ // Base case if (curr == null) return; Inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; Inorder(curr.right);} // Function to flatten binary// tree using level order// traversalstatic node flatten(node parent){ // Dummy node node dummy = new node(-1); // Pointer to previous // element prev = dummy; // Calling in-order // traversal Inorder(parent); prev.left = null; prev.right = null; node ret = dummy.right; // Delete dummy node //delete dummy; return ret;} // Driver codepublic static void Main(string[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); // Calling required function print(flatten(root));}} // This code is contributed by rrrtnx.",
"e": 5744,
"s": 4319,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} let prev; // Function to print flattened// binary Treefunction print(parent){ let curr = parent; while (curr != null) { document.write(curr.data + \" \"); curr = curr.right; }} // Function to perform in-order traversal// recursivelyfunction inorder(curr){ // Base case if (curr == null) return; inorder(curr.left); prev.left = null; prev.right = curr; prev = curr; inorder(curr.right);} // Function to flatten binary tree using// level order traversalfunction flatten(parent){ // Dummy node let dummy = new node(-1); // Pointer to previous element prev = dummy; // Calling in-order traversal inorder(parent); prev.left = null; prev.right = null; let ret = dummy.right; // Delete dummy node return ret;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Calling required functionprint(flatten(root)); // This code is contributed by divyeshrabadiya07 </script>",
"e": 7071,
"s": 5744,
"text": null
},
{
"code": "# Python3 implementation of the approach global prev# Node of the binary treeclass node : def __init__(self, data): self.data = data self.left = None self.right = None # Function to print flattened# binary Treedef printTree(parent): curr = parent while (curr != None): print(curr.data,end=' ') curr = curr.right # Function to perform in-order traversal# recursivelydef inorder(curr): global prev # Base case if (curr == None): return inorder(curr.left) prev.left = None prev.right = curr prev = curr inorder(curr.right) # Function to flatten binary tree using# level order traversaldef flatten(parent): global prev # Dummy node dummy = node(-1) # Pointer to previous element prev = dummy # Calling in-order traversal inorder(parent) prev.left = None prev.right = None ret = dummy.right # Delete dummy node return ret # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) # Calling required function printTree(flatten(root))",
"e": 8293,
"s": 7071,
"text": null
},
{
"code": null,
"e": 8307,
"s": 8293,
"text": "2 3 4 5 6 7 8"
},
{
"code": null,
"e": 8352,
"s": 8309,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 8370,
"s": 8352,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 8385,
"s": 8370,
"text": "mahinsagotra18"
},
{
"code": null,
"e": 8401,
"s": 8385,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8410,
"s": 8401,
"text": "jyoti369"
},
{
"code": null,
"e": 8417,
"s": 8410,
"text": "rrrtnx"
},
{
"code": null,
"e": 8433,
"s": 8417,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 8444,
"s": 8433,
"text": "Algorithms"
},
{
"code": null,
"e": 8463,
"s": 8444,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 8468,
"s": 8463,
"text": "Tree"
},
{
"code": null,
"e": 8487,
"s": 8468,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 8492,
"s": 8487,
"text": "Tree"
},
{
"code": null,
"e": 8503,
"s": 8492,
"text": "Algorithms"
},
{
"code": null,
"e": 8601,
"s": 8503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8626,
"s": 8601,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 8675,
"s": 8626,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 8713,
"s": 8675,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 8764,
"s": 8713,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 8800,
"s": 8764,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 8850,
"s": 8800,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 8879,
"s": 8850,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 8915,
"s": 8879,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 8965,
"s": 8915,
"text": "A program to check if a binary tree is BST or not"
}
] |
strtof function in C
|
22 Jul, 2019
Parses the C-string str(assumed) interpreting its content as a floating-point number (according to the current locale ) and returns its value as a float. If endptr(end pointer) is not a null pointer, the function also sets the value of endptr to point to the first character after the number.
Syntax:
strtof(const char* str, char **endptr)
Parameters:
str : String object with the representation of floating point number
endptr : Reference to an already allocated object of type char*,
whose value is set by the function to the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
Return Value : On success, the function returns the
converted floating-point number as a value of type float.
// C code to convert string having// floating point as its content// using strtof function #include <stdio.h>#include <stdlib.h> // Header file containing strtof function int main(){ // Character array to be parsed char array[] = "365.25 7.0"; // Character end pointer char* pend; // f1 variable to store float value float f1 = strtof(array, &pend); // f2 variable to store float value float f2 = strtof(pend, NULL); // Printing parsed float values of f1 and f2 printf("%.2f\n%.2f\n", f1, f2); // Performing operation on the values returned printf(" One year has %.2f weeks \n", f1 / f2); return 0;}
Output:
365.25
7.0
One year has 52.18 weeks
This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 345,
"s": 52,
"text": "Parses the C-string str(assumed) interpreting its content as a floating-point number (according to the current locale ) and returns its value as a float. If endptr(end pointer) is not a null pointer, the function also sets the value of endptr to point to the first character after the number."
},
{
"code": null,
"e": 353,
"s": 345,
"text": "Syntax:"
},
{
"code": null,
"e": 814,
"s": 353,
"text": "strtof(const char* str, char **endptr)\nParameters:\nstr : String object with the representation of floating point number\nendptr : Reference to an already allocated object of type char*, \nwhose value is set by the function to the next character in str after the numerical value.\nThis parameter can also be a null pointer, in which case it is not used.\nReturn Value : On success, the function returns the\n converted floating-point number as a value of type float."
},
{
"code": "// C code to convert string having// floating point as its content// using strtof function #include <stdio.h>#include <stdlib.h> // Header file containing strtof function int main(){ // Character array to be parsed char array[] = \"365.25 7.0\"; // Character end pointer char* pend; // f1 variable to store float value float f1 = strtof(array, &pend); // f2 variable to store float value float f2 = strtof(pend, NULL); // Printing parsed float values of f1 and f2 printf(\"%.2f\\n%.2f\\n\", f1, f2); // Performing operation on the values returned printf(\" One year has %.2f weeks \\n\", f1 / f2); return 0;}",
"e": 1467,
"s": 814,
"text": null
},
{
"code": null,
"e": 1475,
"s": 1467,
"text": "Output:"
},
{
"code": null,
"e": 1511,
"s": 1475,
"text": "365.25\n7.0\nOne year has 52.18 weeks"
},
{
"code": null,
"e": 1812,
"s": 1511,
"text": "This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1937,
"s": 1812,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1948,
"s": 1937,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1958,
"s": 1948,
"text": "C-Library"
},
{
"code": null,
"e": 1969,
"s": 1958,
"text": "C Language"
},
{
"code": null,
"e": 2067,
"s": 1969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2084,
"s": 2067,
"text": "Substring in C++"
},
{
"code": null,
"e": 2119,
"s": 2084,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2141,
"s": 2119,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2187,
"s": 2141,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2232,
"s": 2187,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2257,
"s": 2232,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2305,
"s": 2257,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2333,
"s": 2305,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2360,
"s": 2333,
"text": "Enumeration (or enum) in C"
}
] |
Mahotas β Haar Transform
|
10 Jun, 2021
In this article we will see how we can do image haar transform in mahotas. The haar wavelet is a sequence of rescaled βsquare-shapedβ functions which together form a wavelet family or basis. Wavelet analysis is similar to Fourier analysis in that it allows a target function over an interval to be represented in terms of an orthonormal basis. The Haar sequence is now recognised as the first known wavelet basis and extensively used as a teaching example. In this tutorial we will use βluispedroβ image, below is the command to load it.
mahotas.demos.load('luispedro')
Below is the luispedro image
In order to do this we will use mahotas.haar method
Syntax : mahotas.haar(img)Argument : It takes image object as argumentReturn : It returns image object
Note : Input image should be filtered or should be loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
image = image[:, :, 0]
Example 1:
Python3
# importing various librariesimport numpy as npimport mahotasimport mahotas.demosfrom mahotas.thresholding import soft_thresholdfrom pylab import imshow, showfrom os import path # loading imagef = mahotas.demos.load('luispedro', as_grey = True) # showing imageprint("Image") imshow(f)show() # haar transformh = mahotas.haar(f) # showing imageprint("Image with haar transform")imshow(h)show()
Output :
Example 2:
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, 0] # showing imageprint("Image") imshow(img)show() # haar transformh = mahotas.haar(img) # showing imageprint("Image with haar transform")imshow(h)show()
Output :
arorakashish0911
Python-Mahotas
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": "\n10 Jun, 2021"
},
{
"code": null,
"e": 568,
"s": 28,
"text": "In this article we will see how we can do image haar transform in mahotas. The haar wavelet is a sequence of rescaled βsquare-shapedβ functions which together form a wavelet family or basis. Wavelet analysis is similar to Fourier analysis in that it allows a target function over an interval to be represented in terms of an orthonormal basis. The Haar sequence is now recognised as the first known wavelet basis and extensively used as a teaching example. In this tutorial we will use βluispedroβ image, below is the command to load it. "
},
{
"code": null,
"e": 600,
"s": 568,
"text": "mahotas.demos.load('luispedro')"
},
{
"code": null,
"e": 631,
"s": 600,
"text": "Below is the luispedro image "
},
{
"code": null,
"e": 685,
"s": 631,
"text": "In order to do this we will use mahotas.haar method "
},
{
"code": null,
"e": 790,
"s": 685,
"text": "Syntax : mahotas.haar(img)Argument : It takes image object as argumentReturn : It returns image object "
},
{
"code": null,
"e": 1011,
"s": 790,
"text": "Note : Input image should be filtered or should be loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this "
},
{
"code": null,
"e": 1034,
"s": 1011,
"text": "image = image[:, :, 0]"
},
{
"code": null,
"e": 1047,
"s": 1034,
"text": "Example 1: "
},
{
"code": null,
"e": 1055,
"s": 1047,
"text": "Python3"
},
{
"code": "# importing various librariesimport numpy as npimport mahotasimport mahotas.demosfrom mahotas.thresholding import soft_thresholdfrom pylab import imshow, showfrom os import path # loading imagef = mahotas.demos.load('luispedro', as_grey = True) # showing imageprint(\"Image\") imshow(f)show() # haar transformh = mahotas.haar(f) # showing imageprint(\"Image with haar transform\")imshow(h)show()",
"e": 1448,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": "Output : "
},
{
"code": null,
"e": 1472,
"s": 1459,
"text": "Example 2: "
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Python3"
},
{
"code": "# importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, 0] # showing imageprint(\"Image\") imshow(img)show() # haar transformh = mahotas.haar(img) # showing imageprint(\"Image with haar transform\")imshow(h)show()",
"e": 1824,
"s": 1480,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1824,
"text": "Output : "
},
{
"code": null,
"e": 1854,
"s": 1837,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1869,
"s": 1854,
"text": "Python-Mahotas"
},
{
"code": null,
"e": 1876,
"s": 1869,
"text": "Python"
},
{
"code": null,
"e": 1974,
"s": 1876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2006,
"s": 1974,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2033,
"s": 2006,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2054,
"s": 2033,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2077,
"s": 2054,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2133,
"s": 2077,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2164,
"s": 2133,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2206,
"s": 2164,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2248,
"s": 2206,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2287,
"s": 2248,
"text": "Python | Get unique values from a list"
}
] |
Recursive selection sort for singly linked list | Swapping node links
|
30 Mar, 2022
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data.
Examples:
Input : 10 -> 12 -> 8 -> 4 -> 6
Output : 4 -> 6 -> 8 -> 10 -> 12
In Selection Sort, we first find the minimum element, swap it with the beginning node and recur for the remaining list. Below is the recursive implementation of these steps for the linked list.
recurSelectionSort(head)
if head->next == NULL
return head
Initialize min = head
Initialize beforeMin = NULL
Initialize ptr = head
while ptr->next != NULL
if min->data > ptr->next->data
min = ptr->next
beforeMin = ptr
ptr = ptr->next
if min != head
swapNodes(&head, head, min, beforeMin)
head->next = recurSelectionSort(head->next)
return head
swapNodes(head_ref, currX, currY, prevY)
head_ref = currY
prevY->next = currX
Initialize temp = currY->next
currY->next = currX->next
currX->next = temp
The swapNodes(head_ref, currX, currY, prevY) is based on the approach discussed here but it has been modified accordingly for the implementation of this post.
C++
Java
Python
C#
Javascript
// C++ implementation of recursive selection sort// for singly linked list | Swapping node links#include <bits/stdc++.h>using namespace std; // A Linked list nodestruct Node { int data; struct Node* next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datavoid swapNodes(struct Node** head_ref, struct Node* currX, struct Node* currY, struct Node* prevY){ // make 'currY' as new head *head_ref = currY; // adjust links prevY->next = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} // function to sort the linked list using// recursive selection sort techniquestruct Node* recurSelectionSort(struct Node* head){ // if there is only a single node if (head->next == NULL) return head; // 'min' - pointer to store the node having // minimum data value struct Node* min = head; // 'beforeMin' - pointer to store node previous // to 'min' node struct Node* beforeMin = NULL; struct Node* ptr; // traverse the list till the last node for (ptr = head; ptr->next != NULL; ptr = ptr->next) { // if true, then update 'min' and 'beforeMin' if (ptr->next->data < min->data) { min = ptr->next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) swapNodes(&head, head, min, beforeMin); // recursively sort the remaining list head->next = recurSelectionSort(head->next); return head;} // function to sort the given linked listvoid sort(struct Node** head_ref){ // if list is empty if ((*head_ref) == NULL) return; // sort the list using recursive selection // sort technique *head_ref = recurSelectionSort(*head_ref);} // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list to the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node;} // function to print the linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 10->12->8->4->6 push(&head, 6); push(&head, 4); push(&head, 8); push(&head, 12); push(&head, 10); cout << "Linked list before sorting:n"; printList(head); // sort the linked list sort(&head); cout << "\nLinked list after sorting:n"; printList(head); return 0;}
// Java implementation of recursive selection sort// for singly linked list | Swapping node linksclass GFG{ // A Linked list nodestatic class Node{ int data; Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes( Node head_ref, Node currX, Node currY, Node prevY){ // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers Node temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort( Node head){ // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value Node min = head; // 'beforeMin' - pointer to store node previous // to 'min' node Node beforeMin = null; Node ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head;} // function to sort the given linked liststatic Node sort( Node head_ref){ // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to print the linked liststatic void printList( Node head){ while (head != null) { System.out.print( head.data + " "); head = head.next; }} // Driver codepublic static void main(String args[]){ Node head = null; // create linked list 10.12.8.4.6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); System.out.println( "Linked list before sorting:"); printList(head); // sort the linked list head = sort(head); System.out.print( "\nLinked list after sorting:"); printList(head);}} // This code is contributed by Arnab Kundu
# Python implementation of recursive selection sort# for singly linked list | Swapping node links # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to swap nodes 'currX' and 'currY' in a# linked list without swapping datadef swapNodes(head_ref, currX, currY, prevY) : # make 'currY' as new head head_ref = currY # adjust links prevY.next = currX # Swap next pointers temp = currY.next currY.next = currX.next currX.next = temp return head_ref # function to sort the linked list using# recursive selection sort techniquedef recurSelectionSort( head) : # if there is only a single node if (head.next == None) : return head # 'min' - pointer to store the node having # minimum data value min = head # 'beforeMin' - pointer to store node previous # to 'min' node beforeMin = None ptr = head # traverse the list till the last node while ( ptr.next != None ) : # if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) : min = ptr.next beforeMin = ptr ptr = ptr.next # if 'min' and 'head' are not same, # swap the head node with the 'min' node if (min != head) : head = swapNodes(head, head, min, beforeMin) # recursively sort the remaining list head.next = recurSelectionSort(head.next) return head # function to sort the given linked listdef sort( head_ref) : # if list is empty if ((head_ref) == None) : return None # sort the list using recursive selection # sort technique head_ref = recurSelectionSort(head_ref) return head_ref # function to insert a node at the# beginning of the linked listdef push( head_ref, new_data) : # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # function to print the linked listdef printList( head) : while (head != None) : print( head.data ,end = " ") head = head.next # Driver codehead = None # create linked list 10.12.8.4.6head = push(head, 6)head = push(head, 4)head = push(head, 8)head = push(head, 12)head = push(head, 10) print( "Linked list before sorting:")printList(head) # sort the linked listhead = sort(head) print( "\nLinked list after sorting:")printList(head) # This code is contributed by Arnab Kundu
// C# implementation of recursive selection sort// for singly linked list | Swapping node linksusing System;public class GFG{ // A Linked list nodepublic class Node{ public int data; public Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes(Node head_ref, Node currX, Node currY, Node prevY){ // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers Node temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort(Node head){ // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value Node min = head; // 'beforeMin' - pointer to store node // previous to 'min' node Node beforeMin = null; Node ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head;} // function to sort the given linked liststatic Node sort( Node head_ref){ // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to print the linked liststatic void printList( Node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; }} // Driver codepublic static void Main(String []args){ Node head = null; // create linked list 10->12->8->4->6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); Console.WriteLine("Linked list before sorting:"); printList(head); // sort the linked list head = sort(head); Console.Write("\nLinked list after sorting:"); printList(head);}} // This code is contributed by Princi Singh
<script>// javascript implementation of recursive selection sort// for singly linked list | Swapping node links // A Linked list node class Node { constructor(val) { this.data = val; this.next = null; } } // function to swap nodes 'currX' and 'currY' in a // linked list without swapping data function swapNodes(head_ref, currX, currY, prevY) { // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers var temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref; } // function to sort the linked list using // recursive selection sort technique function recurSelectionSort(head) { // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value var min = head; // 'beforeMin' - pointer to store node previous // to 'min' node var beforeMin = null; var ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head; } // function to sort the given linked list function sort(head_ref) { // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref; } // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to print the linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code var head = null; // create linked list 10.12.8.4.6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); document.write("Linked list before sorting:<br/>"); printList(head); // sort the linked list head = sort(head); document.write("<br/>Linked list after sorting:<br/>"); printList(head); // This code is contributed by todaysgaurav</script>
Output:
Linked list before sorting:
10 12 8 4 6
Linked list after sorting:
4 6 8 10 12
Time Complexity: O(n2)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
andrew1234
princi singh
todaysgaurav
khushboogoyal499
rohan07
Linked-List-Sorting
Linked List
Sorting
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 275,
"s": 52,
"text": "Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. "
},
{
"code": null,
"e": 286,
"s": 275,
"text": "Examples: "
},
{
"code": null,
"e": 352,
"s": 286,
"text": "Input : 10 -> 12 -> 8 -> 4 -> 6\nOutput : 4 -> 6 -> 8 -> 10 -> 12 "
},
{
"code": null,
"e": 547,
"s": 352,
"text": "In Selection Sort, we first find the minimum element, swap it with the beginning node and recur for the remaining list. Below is the recursive implementation of these steps for the linked list. "
},
{
"code": null,
"e": 1186,
"s": 547,
"text": "recurSelectionSort(head)\n if head->next == NULL\n return head\n Initialize min = head\n Initialize beforeMin = NULL\n Initialize ptr = head\n \n while ptr->next != NULL \n if min->data > ptr->next->data\n min = ptr->next\n beforeMin = ptr\n ptr = ptr->next \n \n if min != head\n swapNodes(&head, head, min, beforeMin)\n \n head->next = recurSelectionSort(head->next)\n return head\n\nswapNodes(head_ref, currX, currY, prevY)\n head_ref = currY\n prevY->next = currX\n\n Initialize temp = currY->next\n currY->next = currX->next\n currX->next = temp "
},
{
"code": null,
"e": 1346,
"s": 1186,
"text": "The swapNodes(head_ref, currX, currY, prevY) is based on the approach discussed here but it has been modified accordingly for the implementation of this post. "
},
{
"code": null,
"e": 1350,
"s": 1346,
"text": "C++"
},
{
"code": null,
"e": 1355,
"s": 1350,
"text": "Java"
},
{
"code": null,
"e": 1362,
"s": 1355,
"text": "Python"
},
{
"code": null,
"e": 1365,
"s": 1362,
"text": "C#"
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": "Javascript"
},
{
"code": "// C++ implementation of recursive selection sort// for singly linked list | Swapping node links#include <bits/stdc++.h>using namespace std; // A Linked list nodestruct Node { int data; struct Node* next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datavoid swapNodes(struct Node** head_ref, struct Node* currX, struct Node* currY, struct Node* prevY){ // make 'currY' as new head *head_ref = currY; // adjust links prevY->next = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} // function to sort the linked list using// recursive selection sort techniquestruct Node* recurSelectionSort(struct Node* head){ // if there is only a single node if (head->next == NULL) return head; // 'min' - pointer to store the node having // minimum data value struct Node* min = head; // 'beforeMin' - pointer to store node previous // to 'min' node struct Node* beforeMin = NULL; struct Node* ptr; // traverse the list till the last node for (ptr = head; ptr->next != NULL; ptr = ptr->next) { // if true, then update 'min' and 'beforeMin' if (ptr->next->data < min->data) { min = ptr->next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) swapNodes(&head, head, min, beforeMin); // recursively sort the remaining list head->next = recurSelectionSort(head->next); return head;} // function to sort the given linked listvoid sort(struct Node** head_ref){ // if list is empty if ((*head_ref) == NULL) return; // sort the list using recursive selection // sort technique *head_ref = recurSelectionSort(*head_ref);} // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list to the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node;} // function to print the linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 10->12->8->4->6 push(&head, 6); push(&head, 4); push(&head, 8); push(&head, 12); push(&head, 10); cout << \"Linked list before sorting:n\"; printList(head); // sort the linked list sort(&head); cout << \"\\nLinked list after sorting:n\"; printList(head); return 0;}",
"e": 4207,
"s": 1376,
"text": null
},
{
"code": "// Java implementation of recursive selection sort// for singly linked list | Swapping node linksclass GFG{ // A Linked list nodestatic class Node{ int data; Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes( Node head_ref, Node currX, Node currY, Node prevY){ // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers Node temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort( Node head){ // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value Node min = head; // 'beforeMin' - pointer to store node previous // to 'min' node Node beforeMin = null; Node ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head;} // function to sort the given linked liststatic Node sort( Node head_ref){ // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push( Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to print the linked liststatic void printList( Node head){ while (head != null) { System.out.print( head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String args[]){ Node head = null; // create linked list 10.12.8.4.6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); System.out.println( \"Linked list before sorting:\"); printList(head); // sort the linked list head = sort(head); System.out.print( \"\\nLinked list after sorting:\"); printList(head);}} // This code is contributed by Arnab Kundu",
"e": 7058,
"s": 4207,
"text": null
},
{
"code": "# Python implementation of recursive selection sort# for singly linked list | Swapping node links # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to swap nodes 'currX' and 'currY' in a# linked list without swapping datadef swapNodes(head_ref, currX, currY, prevY) : # make 'currY' as new head head_ref = currY # adjust links prevY.next = currX # Swap next pointers temp = currY.next currY.next = currX.next currX.next = temp return head_ref # function to sort the linked list using# recursive selection sort techniquedef recurSelectionSort( head) : # if there is only a single node if (head.next == None) : return head # 'min' - pointer to store the node having # minimum data value min = head # 'beforeMin' - pointer to store node previous # to 'min' node beforeMin = None ptr = head # traverse the list till the last node while ( ptr.next != None ) : # if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) : min = ptr.next beforeMin = ptr ptr = ptr.next # if 'min' and 'head' are not same, # swap the head node with the 'min' node if (min != head) : head = swapNodes(head, head, min, beforeMin) # recursively sort the remaining list head.next = recurSelectionSort(head.next) return head # function to sort the given linked listdef sort( head_ref) : # if list is empty if ((head_ref) == None) : return None # sort the list using recursive selection # sort technique head_ref = recurSelectionSort(head_ref) return head_ref # function to insert a node at the# beginning of the linked listdef push( head_ref, new_data) : # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # function to print the linked listdef printList( head) : while (head != None) : print( head.data ,end = \" \") head = head.next # Driver codehead = None # create linked list 10.12.8.4.6head = push(head, 6)head = push(head, 4)head = push(head, 8)head = push(head, 12)head = push(head, 10) print( \"Linked list before sorting:\")printList(head) # sort the linked listhead = sort(head) print( \"\\nLinked list after sorting:\")printList(head) # This code is contributed by Arnab Kundu",
"e": 9628,
"s": 7058,
"text": null
},
{
"code": "// C# implementation of recursive selection sort// for singly linked list | Swapping node linksusing System;public class GFG{ // A Linked list nodepublic class Node{ public int data; public Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes(Node head_ref, Node currX, Node currY, Node prevY){ // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers Node temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort(Node head){ // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value Node min = head; // 'beforeMin' - pointer to store node // previous to 'min' node Node beforeMin = null; Node ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head;} // function to sort the given linked liststatic Node sort( Node head_ref){ // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to print the linked liststatic void printList( Node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String []args){ Node head = null; // create linked list 10->12->8->4->6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); Console.WriteLine(\"Linked list before sorting:\"); printList(head); // sort the linked list head = sort(head); Console.Write(\"\\nLinked list after sorting:\"); printList(head);}} // This code is contributed by Princi Singh",
"e": 12522,
"s": 9628,
"text": null
},
{
"code": "<script>// javascript implementation of recursive selection sort// for singly linked list | Swapping node links // A Linked list node class Node { constructor(val) { this.data = val; this.next = null; } } // function to swap nodes 'currX' and 'currY' in a // linked list without swapping data function swapNodes(head_ref, currX, currY, prevY) { // make 'currY' as new head head_ref = currY; // adjust links prevY.next = currX; // Swap next pointers var temp = currY.next; currY.next = currX.next; currX.next = temp; return head_ref; } // function to sort the linked list using // recursive selection sort technique function recurSelectionSort(head) { // if there is only a single node if (head.next == null) return head; // 'min' - pointer to store the node having // minimum data value var min = head; // 'beforeMin' - pointer to store node previous // to 'min' node var beforeMin = null; var ptr; // traverse the list till the last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // if true, then update 'min' and 'beforeMin' if (ptr.next.data < min.data) { min = ptr.next; beforeMin = ptr; } } // if 'min' and 'head' are not same, // swap the head node with the 'min' node if (min != head) head = swapNodes(head, head, min, beforeMin); // recursively sort the remaining list head.next = recurSelectionSort(head.next); return head; } // function to sort the given linked list function sort(head_ref) { // if list is empty if ((head_ref) == null) return null; // sort the list using recursive selection // sort technique head_ref = recurSelectionSort(head_ref); return head_ref; } // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list to the new node new_node.next = (head_ref); // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to print the linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code var head = null; // create linked list 10.12.8.4.6 head = push(head, 6); head = push(head, 4); head = push(head, 8); head = push(head, 12); head = push(head, 10); document.write(\"Linked list before sorting:<br/>\"); printList(head); // sort the linked list head = sort(head); document.write(\"<br/>Linked list after sorting:<br/>\"); printList(head); // This code is contributed by todaysgaurav</script>",
"e": 15667,
"s": 12522,
"text": null
},
{
"code": null,
"e": 15676,
"s": 15667,
"text": "Output: "
},
{
"code": null,
"e": 15755,
"s": 15676,
"text": "Linked list before sorting:\n10 12 8 4 6\nLinked list after sorting:\n4 6 8 10 12"
},
{
"code": null,
"e": 15778,
"s": 15755,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 15800,
"s": 15778,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 16222,
"s": 15800,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 16233,
"s": 16222,
"text": "andrew1234"
},
{
"code": null,
"e": 16246,
"s": 16233,
"text": "princi singh"
},
{
"code": null,
"e": 16259,
"s": 16246,
"text": "todaysgaurav"
},
{
"code": null,
"e": 16276,
"s": 16259,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 16284,
"s": 16276,
"text": "rohan07"
},
{
"code": null,
"e": 16304,
"s": 16284,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 16316,
"s": 16304,
"text": "Linked List"
},
{
"code": null,
"e": 16324,
"s": 16316,
"text": "Sorting"
},
{
"code": null,
"e": 16336,
"s": 16324,
"text": "Linked List"
},
{
"code": null,
"e": 16344,
"s": 16336,
"text": "Sorting"
}
] |
oct() function in Python
|
22 Sep, 2021
Python oct() function is one of the built-in methods, it takes an integer and returns the octal representation in a string format.
Syntax : oct(x)
Parameters :
x β Must be an integer number and can be in either binary, decimal or hexadecimal format.
Returns : octal representation of the value.
Errors and Exceptions :
TypeError : Returns TypeError when anything other than integer type constants are passed as parameters.
Python3
# Python3 program to demonstrate# the use of oct() function print("The octal representation of 23 is " + oct(23)) print("The octal representation of the" " ascii value of 'z' is " + oct(ord('z'))) # Binary representation of a number# can be passed as a parameter # For 23, Binary is 0b10111print("The octal representation of the binary" " of 23 is " + oct(0b10111)) # For 23, Hexadecimal is 0x17print("The octal representation of the binary" " of 23 is " + oct(0x17))
Output:
The octal representation of 23 is 0o27
The octal representation of the ascii value of 'z' is 0o172
The octal representation of the binary of 23 is 0o27
The octal representation of the binary of 23 is 0o27
Python3
# Python3 program demonstrating TypeError print("The Octal representation of 29.5 is " + oct(29.5)) '''# Python doesn't have anything like float.oct()# to directly convert a floating type constant# to its octal representation. Conversion of a# floating-point value to it's octal is done manually.'''
Output :
Traceback (most recent call last):
File "/home/5bf02b72de26687389763e9133669972.py", line 3, in
print("The Octal representation of 29.5 is "+oct(29.5))
TypeError: 'float' object cannot be interpreted as an integer
Applications: oct() is used in all types of standard conversion. For example, Conversion from decimal to octal, binary to octal, hexadecimal to octal forms respectively.
Python3
# TypeConversions from decimal and binary# to their respective octal representations # The choices present to the userprint("a. Hexadecimal to Octal ")print("b. Decimal to Octal")print("c. Binary to Octal") # Function generates octal representation# from it's binary fromdef bin_to_oct(): print("Enter your input in BIN format :-") # taking user input as binary string and # then using int() to convert it into it's # respective decimal format x = int(input(), 2) print("Octal form of " + str(x) + " is " + oct(x)) # Function generates octal representation# of it's hexadecimal form passed as value.def hex_to_oct(): print("Enter your input in HEX format :-") # taking user input as hexadecimal string and # then using int() to convert it into it's # respective decimal format x = int(input(), 16) print("Octal form of " + str(x) + " is " + oct(x)) # Function converts decimal form to it's# respective octal representationdef decimal_to_oct(): print("Enter a number with base-10 format :-") # taking a simple user input and # converting it to an integer x = int(input()) print("Octal form of " + str(x) + " is " + oct(x)) # Driver Codech = input("Enter your choice :-\n") if ch is 'a': hex_to_oct()elif ch is 'b': decimal_to_oct()elif ch is 'c': bin_to_oct()
Output :
a. Hexadecimal to Octal
b. Decimal to Octal
c. Binary to Octal
Enter your choice :-
a
Enter your input in HEX format :-
0x13
Octal form of 19 is 0o23
Python3
class math: num = 76 def __index__(self): return self.num def __int__(self): return self.numobj = math()print(oct(obj))
Output:
0o114
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 185,
"s": 54,
"text": "Python oct() function is one of the built-in methods, it takes an integer and returns the octal representation in a string format."
},
{
"code": null,
"e": 201,
"s": 185,
"text": "Syntax : oct(x)"
},
{
"code": null,
"e": 214,
"s": 201,
"text": "Parameters :"
},
{
"code": null,
"e": 304,
"s": 214,
"text": "x β Must be an integer number and can be in either binary, decimal or hexadecimal format."
},
{
"code": null,
"e": 349,
"s": 304,
"text": "Returns : octal representation of the value."
},
{
"code": null,
"e": 374,
"s": 349,
"text": "Errors and Exceptions : "
},
{
"code": null,
"e": 478,
"s": 374,
"text": "TypeError : Returns TypeError when anything other than integer type constants are passed as parameters."
},
{
"code": null,
"e": 486,
"s": 478,
"text": "Python3"
},
{
"code": "# Python3 program to demonstrate# the use of oct() function print(\"The octal representation of 23 is \" + oct(23)) print(\"The octal representation of the\" \" ascii value of 'z' is \" + oct(ord('z'))) # Binary representation of a number# can be passed as a parameter # For 23, Binary is 0b10111print(\"The octal representation of the binary\" \" of 23 is \" + oct(0b10111)) # For 23, Hexadecimal is 0x17print(\"The octal representation of the binary\" \" of 23 is \" + oct(0x17))",
"e": 969,
"s": 486,
"text": null
},
{
"code": null,
"e": 977,
"s": 969,
"text": "Output:"
},
{
"code": null,
"e": 1182,
"s": 977,
"text": "The octal representation of 23 is 0o27\nThe octal representation of the ascii value of 'z' is 0o172\nThe octal representation of the binary of 23 is 0o27\nThe octal representation of the binary of 23 is 0o27"
},
{
"code": null,
"e": 1190,
"s": 1182,
"text": "Python3"
},
{
"code": "# Python3 program demonstrating TypeError print(\"The Octal representation of 29.5 is \" + oct(29.5)) '''# Python doesn't have anything like float.oct()# to directly convert a floating type constant# to its octal representation. Conversion of a# floating-point value to it's octal is done manually.'''",
"e": 1490,
"s": 1190,
"text": null
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "Output : "
},
{
"code": null,
"e": 1721,
"s": 1500,
"text": "Traceback (most recent call last):\n File \"/home/5bf02b72de26687389763e9133669972.py\", line 3, in \n print(\"The Octal representation of 29.5 is \"+oct(29.5))\nTypeError: 'float' object cannot be interpreted as an integer"
},
{
"code": null,
"e": 1893,
"s": 1721,
"text": "Applications: oct() is used in all types of standard conversion. For example, Conversion from decimal to octal, binary to octal, hexadecimal to octal forms respectively. "
},
{
"code": null,
"e": 1901,
"s": 1893,
"text": "Python3"
},
{
"code": "# TypeConversions from decimal and binary# to their respective octal representations # The choices present to the userprint(\"a. Hexadecimal to Octal \")print(\"b. Decimal to Octal\")print(\"c. Binary to Octal\") # Function generates octal representation# from it's binary fromdef bin_to_oct(): print(\"Enter your input in BIN format :-\") # taking user input as binary string and # then using int() to convert it into it's # respective decimal format x = int(input(), 2) print(\"Octal form of \" + str(x) + \" is \" + oct(x)) # Function generates octal representation# of it's hexadecimal form passed as value.def hex_to_oct(): print(\"Enter your input in HEX format :-\") # taking user input as hexadecimal string and # then using int() to convert it into it's # respective decimal format x = int(input(), 16) print(\"Octal form of \" + str(x) + \" is \" + oct(x)) # Function converts decimal form to it's# respective octal representationdef decimal_to_oct(): print(\"Enter a number with base-10 format :-\") # taking a simple user input and # converting it to an integer x = int(input()) print(\"Octal form of \" + str(x) + \" is \" + oct(x)) # Driver Codech = input(\"Enter your choice :-\\n\") if ch is 'a': hex_to_oct()elif ch is 'b': decimal_to_oct()elif ch is 'c': bin_to_oct()",
"e": 3228,
"s": 1901,
"text": null
},
{
"code": null,
"e": 3238,
"s": 3228,
"text": "Output : "
},
{
"code": null,
"e": 3389,
"s": 3238,
"text": "a. Hexadecimal to Octal \nb. Decimal to Octal\nc. Binary to Octal\nEnter your choice :-\na\nEnter your input in HEX format :-\n0x13\nOctal form of 19 is 0o23"
},
{
"code": null,
"e": 3397,
"s": 3389,
"text": "Python3"
},
{
"code": "class math: num = 76 def __index__(self): return self.num def __int__(self): return self.numobj = math()print(oct(obj))",
"e": 3540,
"s": 3397,
"text": null
},
{
"code": null,
"e": 3548,
"s": 3540,
"text": "Output:"
},
{
"code": null,
"e": 3554,
"s": 3548,
"text": "0o114"
},
{
"code": null,
"e": 3567,
"s": 3554,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3593,
"s": 3567,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 3600,
"s": 3593,
"text": "Python"
}
] |
Node.js fs.access() Method
|
27 Jan, 2022
The fs.access() method is used to test the permissions of a given file or directory. The permissions to be checked can be specified as a parameter using file access constants. It is also possible to check multiple file permissions by using the bitwise OR operator to create a mask with more than one file constant.Note: It is not recommended to use the fs.access() method to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile(), because it introduces a race condition since the file state may be changed by other processes after the test.
Syntax:
fs.access( path, mode, callback )
Parameters: This method accepts three parameters as mentioned above and described below:
path: It is a String, Buffer or URL that denotes the path of the file or directory for which the permission has to be tested.
mode: It is an integer value that denotes the permission to be tested for. The logical OR operator can be used to separate multiple permission. It can have the values fs.constants.F_OK, fs.constants.R_OK, fs.constants.W_OK and fs.constants.X_OK. It is an optional parameter. The default value is fs.constants.F_OK.
callback: It is a function that would be called when the method is executed. err: It is an error that would be thrown if the method fails.
err: It is an error that would be thrown if the method fails.
Below examples illustrate the fs.access() method in Node.js:Example 1: This example shows the testing of the read and write permission of a file.
javascript
// Node.js program to demonstrate the// fs.access() method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log("Giving only read permission to the user");fs.chmodSync("example_file.txt", fs.constants.S_IRUSR); // Test the read permissionfs.access('example_file.txt', fs.constants.R_OK, (err) => { console.log('\n> Checking Permission for reading the file'); if (err) console.error('No Read access'); else console.log('File can be read');}); // Test both the read and write permissionsfs.access('example_file.txt', fs.constants.R_OK | fs.constants.W_OK, (err) => { console.log('\n> Checking Permission for reading" + " and writing to file'); if (err) console.error('No Read and Write access'); else console.log('File can be read and written');});
Output:
Giving only read permission to the user
> Checking Permission for reading the file
File can be read
> Checking Permission for reading and writing to file
No Read and Write access
Example 2: This example shows the testing of a file if it exists.
javascript
// Node.js program to demonstrate the// fs.access() method // Import the filesystem moduleconst fs = require('fs'); // Test the if the file existsfs.access('example_file.txt', fs.constants.F_OK, (err) => { console.log('\n> Checking if the file exists'); if (err) { console.error('File does not exist'); // Create the file console.log('\nCreating the file'); fs.writeFileSync("example_file2.txt", "Test File"); // Test the if the file exists again fs.access('example_file2.txt', fs.constants.F_OK, (err) => { console.log('\n> Checking if the file exists'); if (err) console.error('File does not exist'); else { console.log('File does exist'); } }); } else { console.log('File does exist'); }});
Output:
> Checking if the file exists
File does not exist
Creating the file
> Checking if the file exists
File does exist
Reference: https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback
kalrap615
simranarora5sos
Node.js-fs-module
Node.js
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": "\n27 Jan, 2022"
},
{
"code": null,
"e": 611,
"s": 28,
"text": "The fs.access() method is used to test the permissions of a given file or directory. The permissions to be checked can be specified as a parameter using file access constants. It is also possible to check multiple file permissions by using the bitwise OR operator to create a mask with more than one file constant.Note: It is not recommended to use the fs.access() method to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile(), because it introduces a race condition since the file state may be changed by other processes after the test. "
},
{
"code": null,
"e": 621,
"s": 611,
"text": "Syntax: "
},
{
"code": null,
"e": 655,
"s": 621,
"text": "fs.access( path, mode, callback )"
},
{
"code": null,
"e": 746,
"s": 655,
"text": "Parameters: This method accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 872,
"s": 746,
"text": "path: It is a String, Buffer or URL that denotes the path of the file or directory for which the permission has to be tested."
},
{
"code": null,
"e": 1187,
"s": 872,
"text": "mode: It is an integer value that denotes the permission to be tested for. The logical OR operator can be used to separate multiple permission. It can have the values fs.constants.F_OK, fs.constants.R_OK, fs.constants.W_OK and fs.constants.X_OK. It is an optional parameter. The default value is fs.constants.F_OK."
},
{
"code": null,
"e": 1326,
"s": 1187,
"text": "callback: It is a function that would be called when the method is executed. err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 1388,
"s": 1326,
"text": "err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 1535,
"s": 1388,
"text": "Below examples illustrate the fs.access() method in Node.js:Example 1: This example shows the testing of the read and write permission of a file. "
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.access() method // Import the filesystem moduleconst fs = require('fs'); // Allowing only read permissionconsole.log(\"Giving only read permission to the user\");fs.chmodSync(\"example_file.txt\", fs.constants.S_IRUSR); // Test the read permissionfs.access('example_file.txt', fs.constants.R_OK, (err) => { console.log('\\n> Checking Permission for reading the file'); if (err) console.error('No Read access'); else console.log('File can be read');}); // Test both the read and write permissionsfs.access('example_file.txt', fs.constants.R_OK | fs.constants.W_OK, (err) => { console.log('\\n> Checking Permission for reading\" + \" and writing to file'); if (err) console.error('No Read and Write access'); else console.log('File can be read and written');});",
"e": 2401,
"s": 1546,
"text": null
},
{
"code": null,
"e": 2411,
"s": 2401,
"text": "Output: "
},
{
"code": null,
"e": 2592,
"s": 2411,
"text": "Giving only read permission to the user\n\n> Checking Permission for reading the file\nFile can be read\n\n> Checking Permission for reading and writing to file\nNo Read and Write access"
},
{
"code": null,
"e": 2658,
"s": 2592,
"text": "Example 2: This example shows the testing of a file if it exists."
},
{
"code": null,
"e": 2669,
"s": 2658,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.access() method // Import the filesystem moduleconst fs = require('fs'); // Test the if the file existsfs.access('example_file.txt', fs.constants.F_OK, (err) => { console.log('\\n> Checking if the file exists'); if (err) { console.error('File does not exist'); // Create the file console.log('\\nCreating the file'); fs.writeFileSync(\"example_file2.txt\", \"Test File\"); // Test the if the file exists again fs.access('example_file2.txt', fs.constants.F_OK, (err) => { console.log('\\n> Checking if the file exists'); if (err) console.error('File does not exist'); else { console.log('File does exist'); } }); } else { console.log('File does exist'); }});",
"e": 3432,
"s": 2669,
"text": null
},
{
"code": null,
"e": 3441,
"s": 3432,
"text": "Output: "
},
{
"code": null,
"e": 3557,
"s": 3441,
"text": "> Checking if the file exists\nFile does not exist\n\nCreating the file\n\n> Checking if the file exists\nFile does exist"
},
{
"code": null,
"e": 3631,
"s": 3557,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback"
},
{
"code": null,
"e": 3641,
"s": 3631,
"text": "kalrap615"
},
{
"code": null,
"e": 3657,
"s": 3641,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3675,
"s": 3657,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 3683,
"s": 3675,
"text": "Node.js"
},
{
"code": null,
"e": 3700,
"s": 3683,
"text": "Web Technologies"
}
] |
Decrypt PDF using Java
|
02 Nov, 2020
We can Decrypt any PDF using Java by using the external library PDFBox. We can Decrypt and remove the Access Permission from any PDF using JAVA, but we must remember the Owner Password of the PDF to Decrypt it, otherwise, we can not decrypt it.
Approach:
In this program, you will see how you can take an encrypted PDF file as input and how you can decrypt it to access or to read the PDF file. You will see the PDFBox library used for the following procedure.
Input : Encrypted PDF file
Output : Decrypted PDF file
Maven Dependency for PDFBox :
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
1. Load the PDF Document
Load the PDF file using load() static method (we can access it by using the class name) of class PDDocument. The load() method will accept the PDF file as a parameter. Here Owner Password is compulsory otherwise we can not Decrypt it.
File f = new File("path_of_PDFfile");
PDDocument pdd = PDDocument.load("object_of_file","Owner_password");
2. Call βsetAllSecurityToBeRemoved(bool)β method
After loading PDF file call setAllSecurityToBeRemoved(bool) method using object of PDDocument class. It will remove the Access Permission from PDF and allow all users to access it. In setAllSecurityToBeRemoved(bool) pass boolean(True/False) as a parameter. Pass true if we want to perform Decryption operation otherwise false.
PDDocument_object.setAllSecurityToBeRemoved(true);
3. Save and Close File
After Decrypting the PDF save and close the file to make a change in it.
PDDocument_object.save("path_of_PDFfile");
PDDocument_object.close();
Executable Code to Decrypt PDF:
Java
import java.io.File;import java.io.IOException;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial; public class Decrypt_pdf { public static void main(String[] args) throws IOException { // select a file for Decryption operation File file = new File("D:\\Bluetooth\\Encrypted.pdf"); // Load the PDF file PDDocument pdd = PDDocument.load(file, "12345"); // removing all security from PDF file pdd.setAllSecurityToBeRemoved(true); // Save the PDF file pdd.save(file); // Close the PDF file pdd.close(); System.out.println("Decryption Done..."); }}
Output:
Decryption Done...
Letβs have a look at the given below screenshots for a better understanding and you will see how you can decrypt the given PDF file and access to read it. In this screenshot, you will see a PDF encrypted file that is password protected which means you simply need permission or password to grant access to the PDF file.
#Before Decryption
Once you entered the correct password then you will be able to access and read the PDF file. Now, If you want to decrypt it by using Java code then you need to write code as shown and need to execute the following program as shown in the screenshot given below.
#Code snippet
Now, After the successful execution of the above program then you donβt need any password to access the PDF file which means your PDF file is decrypted now and you can directly access and read it.
#After Decryption
Here is the video where you will see the decryption procedure and you will see exactly how it will work. So, in this way you can change access permission of any PDF which will allow all users to access it easily.
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 297,
"s": 52,
"text": "We can Decrypt any PDF using Java by using the external library PDFBox. We can Decrypt and remove the Access Permission from any PDF using JAVA, but we must remember the Owner Password of the PDF to Decrypt it, otherwise, we can not decrypt it."
},
{
"code": null,
"e": 307,
"s": 297,
"text": "Approach:"
},
{
"code": null,
"e": 514,
"s": 307,
"text": "In this program, you will see how you can take an encrypted PDF file as input and how you can decrypt it to access or to read the PDF file. You will see the PDFBox library used for the following procedure."
},
{
"code": null,
"e": 574,
"s": 514,
"text": "Input : Encrypted PDF file\nOutput : Decrypted PDF file \n"
},
{
"code": null,
"e": 604,
"s": 574,
"text": "Maven Dependency for PDFBox :"
},
{
"code": null,
"e": 727,
"s": 604,
"text": "<dependency>\n<groupId>org.apache.pdfbox</groupId>\n<artifactId>pdfbox</artifactId>\n<version>2.0.21</version>\n</dependency>\n"
},
{
"code": null,
"e": 752,
"s": 727,
"text": "1. Load the PDF Document"
},
{
"code": null,
"e": 987,
"s": 752,
"text": "Load the PDF file using load() static method (we can access it by using the class name) of class PDDocument. The load() method will accept the PDF file as a parameter. Here Owner Password is compulsory otherwise we can not Decrypt it."
},
{
"code": null,
"e": 1095,
"s": 987,
"text": "File f = new File(\"path_of_PDFfile\");\nPDDocument pdd = PDDocument.load(\"object_of_file\",\"Owner_password\");\n"
},
{
"code": null,
"e": 1144,
"s": 1095,
"text": "2. Call βsetAllSecurityToBeRemoved(bool)β method"
},
{
"code": null,
"e": 1472,
"s": 1144,
"text": "After loading PDF file call setAllSecurityToBeRemoved(bool) method using object of PDDocument class. It will remove the Access Permission from PDF and allow all users to access it. In setAllSecurityToBeRemoved(bool) pass boolean(True/False) as a parameter. Pass true if we want to perform Decryption operation otherwise false. "
},
{
"code": null,
"e": 1524,
"s": 1472,
"text": "PDDocument_object.setAllSecurityToBeRemoved(true);\n"
},
{
"code": null,
"e": 1547,
"s": 1524,
"text": "3. Save and Close File"
},
{
"code": null,
"e": 1621,
"s": 1547,
"text": "After Decrypting the PDF save and close the file to make a change in it. "
},
{
"code": null,
"e": 1692,
"s": 1621,
"text": "PDDocument_object.save(\"path_of_PDFfile\");\nPDDocument_object.close();\n"
},
{
"code": null,
"e": 1725,
"s": 1692,
"text": "Executable Code to Decrypt PDF: "
},
{
"code": null,
"e": 1730,
"s": 1725,
"text": "Java"
},
{
"code": "import java.io.File;import java.io.IOException;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.encryption.StandardDecryptionMaterial; public class Decrypt_pdf { public static void main(String[] args) throws IOException { // select a file for Decryption operation File file = new File(\"D:\\\\Bluetooth\\\\Encrypted.pdf\"); // Load the PDF file PDDocument pdd = PDDocument.load(file, \"12345\"); // removing all security from PDF file pdd.setAllSecurityToBeRemoved(true); // Save the PDF file pdd.save(file); // Close the PDF file pdd.close(); System.out.println(\"Decryption Done...\"); }}",
"e": 2443,
"s": 1730,
"text": null
},
{
"code": null,
"e": 2451,
"s": 2443,
"text": "Output:"
},
{
"code": null,
"e": 2470,
"s": 2451,
"text": "Decryption Done..."
},
{
"code": null,
"e": 2792,
"s": 2470,
"text": "Letβs have a look at the given below screenshots for a better understanding and you will see how you can decrypt the given PDF file and access to read it. In this screenshot, you will see a PDF encrypted file that is password protected which means you simply need permission or password to grant access to the PDF file. "
},
{
"code": null,
"e": 2811,
"s": 2792,
"text": "#Before Decryption"
},
{
"code": null,
"e": 3073,
"s": 2811,
"text": "Once you entered the correct password then you will be able to access and read the PDF file. Now, If you want to decrypt it by using Java code then you need to write code as shown and need to execute the following program as shown in the screenshot given below."
},
{
"code": null,
"e": 3087,
"s": 3073,
"text": "#Code snippet"
},
{
"code": null,
"e": 3284,
"s": 3087,
"text": "Now, After the successful execution of the above program then you donβt need any password to access the PDF file which means your PDF file is decrypted now and you can directly access and read it."
},
{
"code": null,
"e": 3302,
"s": 3284,
"text": "#After Decryption"
},
{
"code": null,
"e": 3519,
"s": 3304,
"text": "Here is the video where you will see the decryption procedure and you will see exactly how it will work. So, in this way you can change access permission of any PDF which will allow all users to access it easily. "
},
{
"code": null,
"e": 3524,
"s": 3519,
"text": "Java"
},
{
"code": null,
"e": 3538,
"s": 3524,
"text": "Java Programs"
},
{
"code": null,
"e": 3543,
"s": 3538,
"text": "Java"
},
{
"code": null,
"e": 3641,
"s": 3543,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3656,
"s": 3641,
"text": "Stream In Java"
},
{
"code": null,
"e": 3677,
"s": 3656,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3698,
"s": 3677,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3717,
"s": 3698,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3734,
"s": 3717,
"text": "Generics in Java"
},
{
"code": null,
"e": 3760,
"s": 3734,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3794,
"s": 3760,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3841,
"s": 3794,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3879,
"s": 3841,
"text": "Factory method design pattern in Java"
}
] |
Python β Print dictionary of list values
|
28 Nov, 2021
In this article, we will print a dictionary of list values. Dictionary of list values means a dictionary contains values as a list of dictionaries
Example:
{βkey1β: [{βkey1β²: value,......,βkey nβ: value}........{βkey1β²: value,......,βkey nβ: value}}],
ββββββββ
ββββββββ
βkeynβ: [{βkey1β²: value,......,βkey nβ: value}........{βkey1β²: value,......,βkey nβ: value}}]}
So we have to get the dictionaries present in the list according to the key. We can get this by using dict.items().
Syntax:
d.items()
we can iterate over the dictionary using for loop
for key,values in data.items():
for i in values:
print(key," : ",i)
Example 1: Python code to create a dictionary with student names as key and values as subject details
Python3
# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': "java", 'marks': 98}, {'subject2': "PHP", 'marks': 89}], 'manoj': [{'subject1': "java", 'marks': 78}, {'subject2': "PHP", 'marks': 79}]} # get the list of data# using items() methodfor key, values in data.items(): for i in values: print(key, " : ", i)
Output:
manoja : {'subject1': 'java', 'marks': 98}
manoja : {'subject2': 'PHP', 'marks': 89}
manoj : {'subject1': 'java', 'marks': 78}
manoj : {'subject2': 'PHP', 'marks': 79}
Example 2:
Python3
# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': "java", 'marks': 98}, {'subject2': "PHP", 'marks': 89}], 'manoj': [{'subject1': "java", 'marks': 78}, {'subject2': "PHP", 'marks': 79}], 'ramya': [{'subject1': "html", 'marks': 78}]} # get the list of data# using items() methodfor key, values in data.items(): for i in values: print(key, " : ", i)
Output:
manoja : {'subject1': 'java', 'marks': 98}
manoja : {'subject2': 'PHP', 'marks': 89}
manoj : {'subject1': 'java', 'marks': 78}
manoj : {'subject2': 'PHP', 'marks': 79}
ramya : {'subject1': 'html', 'marks': 78}
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 176,
"s": 28,
"text": "In this article, we will print a dictionary of list values. Dictionary of list values means a dictionary contains values as a list of dictionaries"
},
{
"code": null,
"e": 185,
"s": 176,
"text": "Example:"
},
{
"code": null,
"e": 281,
"s": 185,
"text": "{βkey1β: [{βkey1β²: value,......,βkey nβ: value}........{βkey1β²: value,......,βkey nβ: value}}],"
},
{
"code": null,
"e": 290,
"s": 281,
"text": "ββββββββ"
},
{
"code": null,
"e": 299,
"s": 290,
"text": "ββββββββ"
},
{
"code": null,
"e": 394,
"s": 299,
"text": "βkeynβ: [{βkey1β²: value,......,βkey nβ: value}........{βkey1β²: value,......,βkey nβ: value}}]}"
},
{
"code": null,
"e": 510,
"s": 394,
"text": "So we have to get the dictionaries present in the list according to the key. We can get this by using dict.items()."
},
{
"code": null,
"e": 518,
"s": 510,
"text": "Syntax:"
},
{
"code": null,
"e": 528,
"s": 518,
"text": "d.items()"
},
{
"code": null,
"e": 578,
"s": 528,
"text": "we can iterate over the dictionary using for loop"
},
{
"code": null,
"e": 661,
"s": 578,
"text": "for key,values in data.items():\n for i in values:\n print(key,\" : \",i)"
},
{
"code": null,
"e": 763,
"s": 661,
"text": "Example 1: Python code to create a dictionary with student names as key and values as subject details"
},
{
"code": null,
"e": 771,
"s": 763,
"text": "Python3"
},
{
"code": "# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': \"java\", 'marks': 98}, {'subject2': \"PHP\", 'marks': 89}], 'manoj': [{'subject1': \"java\", 'marks': 78}, {'subject2': \"PHP\", 'marks': 79}]} # get the list of data# using items() methodfor key, values in data.items(): for i in values: print(key, \" : \", i)",
"e": 1185,
"s": 771,
"text": null
},
{
"code": null,
"e": 1193,
"s": 1185,
"text": "Output:"
},
{
"code": null,
"e": 1369,
"s": 1193,
"text": "manoja : {'subject1': 'java', 'marks': 98}\nmanoja : {'subject2': 'PHP', 'marks': 89}\nmanoj : {'subject1': 'java', 'marks': 78}\nmanoj : {'subject2': 'PHP', 'marks': 79}"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": "Example 2:"
},
{
"code": null,
"e": 1388,
"s": 1380,
"text": "Python3"
},
{
"code": "# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': \"java\", 'marks': 98}, {'subject2': \"PHP\", 'marks': 89}], 'manoj': [{'subject1': \"java\", 'marks': 78}, {'subject2': \"PHP\", 'marks': 79}], 'ramya': [{'subject1': \"html\", 'marks': 78}]} # get the list of data# using items() methodfor key, values in data.items(): for i in values: print(key, \" : \", i)",
"e": 1854,
"s": 1388,
"text": null
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Output:"
},
{
"code": null,
"e": 2082,
"s": 1862,
"text": "manoja : {'subject1': 'java', 'marks': 98}\nmanoja : {'subject2': 'PHP', 'marks': 89}\nmanoj : {'subject1': 'java', 'marks': 78}\nmanoj : {'subject2': 'PHP', 'marks': 79}\nramya : {'subject1': 'html', 'marks': 78}"
},
{
"code": null,
"e": 2089,
"s": 2082,
"text": "Picked"
},
{
"code": null,
"e": 2116,
"s": 2089,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2128,
"s": 2116,
"text": "python-dict"
},
{
"code": null,
"e": 2135,
"s": 2128,
"text": "Python"
},
{
"code": null,
"e": 2151,
"s": 2135,
"text": "Python Programs"
},
{
"code": null,
"e": 2163,
"s": 2151,
"text": "python-dict"
},
{
"code": null,
"e": 2261,
"s": 2163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2293,
"s": 2261,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2320,
"s": 2293,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2341,
"s": 2320,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2372,
"s": 2341,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2428,
"s": 2372,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2450,
"s": 2428,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2489,
"s": 2450,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2527,
"s": 2489,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2576,
"s": 2527,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Maximum Subarray Sum possible by replacing an Array element by its Square
|
23 Jun, 2022
Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square.
Examples:
Input: a[] = {1, -5, 8, 12, -8} Output: 152 Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possible subarray sum in the array.Input: a[] = {-1, -2, -3} Output: 9 Explanation:
Naive Approach: The simplest approach to solve the problem is to replace every element with its square and for each of them, find the maximum subarray sum using Kadaneβs algorithm. Finally, print the maximum possible subarray sum obtained. Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Dynamic Programming. Follow the steps below to solve the problem:
Initialize memoization table dp[][] where:
dp[i][0]: Stores the maximum subarray sum that can be obtained including ith element and without squaring any array element.
dp[i][1]: Stores the maximum subarray sum that can be including ith element and squaring one of the array elements
Therefore, the recurrence relations are:
dp[i][0] = max(dp[i-1][0] + a[i], a[i]), that is, either extend the previous subarray ending at i β 1th index or start a new subarray from ith index.dp[i][1] = max(a[i]2, dp[i-1][0] + a[i]2, dp[i-1][1] + a[i]), that is, either start new subarray from ith index or extend previous subarray by adding a[i]2 to dp[i β 1][0] or add a[i] to dp[i β 1][1]
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 maximum subarray// sum possibleint getMaxSum(int a[], int n){ int dp[n][2]; // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = max(dp[0][0], dp[0][1]); for(int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = max(max_sum, dp[i][1]); max_sum = max(max_sum, dp[i][0]); } // Return answer return max_sum;} // Driver Codeint32_t main(){ int n = 5; int a[] = { 1, -5, 8, 12, -8 }; // Function call cout << getMaxSum(a, n) << endl; return 0;} // This code is contributed by rutvik_56
// Java Program to implement// the above approachimport java.io.*; class GFG { // Function to find the maximum subarray // sum possible public static int getMaxSum(int a[], int n) { int dp[][] = new int[n][2]; // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = Math.max(dp[0][0], dp[0][1]); for (int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = Math.max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = Math.max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.max(max_sum, dp[i][1]); max_sum = Math.max(max_sum, dp[i][0]); } // Return answer return max_sum; } // Driver Code public static void main(String[] args) { int n = 5; int a[] = { 1, -5, 8, 12, -8 }; // Function call System.out.println(getMaxSum(a, n)); }}
# Python3 program to implement# the above approach # Function to find the maximum subarray# sum possibledef getMaxSum(a, n): dp = [[0 for x in range(2)] for y in range(n)] # Stores sum without squaring dp[0][0] = a[0] # Stores sum squaring dp[0][1] = a[0] * a[0] # Stores the maximum subarray sum max_sum = max(dp[0][0], dp[0][1]) for i in range(1, n): # Either extend the subarray # or start a new subarray dp[i][0] = max(a[i], dp[i - 1][0] + a[i]) # Either extend previous squared # subarray or start a new subarray # by squaring the current element dp[i][1] = max(dp[i - 1][1] + a[i], a[i] * a[i]) dp[i][1] = max(dp[i][1], dp[i - 1][0] + a[i] * a[i]) # Update maximum subarray sum max_sum = max(max_sum, dp[i][1]) max_sum = max(max_sum, dp[i][0]) # Return answer return max_sum # Driver Coden = 5a = [ 1, -5, 8, 12, -8 ] # Function callprint(getMaxSum(a, n)) # This code is contributed by Shivam Singh
// C# program to implement// the above approachusing System; class GFG{ // Function to find the maximum subarray// sum possiblepublic static int getMaxSum(int []a, int n){ int [,]dp = new int[n, 2]; // Stores sum without squaring dp[0, 0] = a[0]; // Stores sum squaring dp[0, 1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = Math.Max(dp[0, 0], dp[0, 1]); for(int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i, 0] = Math.Max(a[i], dp[i - 1, 0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i, 1] = Math.Max(dp[i - 1, 1] + a[i], a[i] * a[i]); dp[i, 1] = Math.Max(dp[i, 1], dp[i - 1, 0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.Max(max_sum, dp[i, 1]); max_sum = Math.Max(max_sum, dp[i, 0]); } // Return answer return max_sum;} // Driver Codepublic static void Main(String[] args){ int n = 5; int []a = { 1, -5, 8, 12, -8 }; // Function call Console.WriteLine(getMaxSum(a, n));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program for the above approach // Function to find the maximum subarray // sum possible function getMaxSum(a, n) { let dp = new Array(n); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum let max_sum = Math.max(dp[0][0], dp[0][1]); for (let i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = Math.max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = Math.max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.max(max_sum, dp[i][1]); max_sum = Math.max(max_sum, dp[i][0]); } // Return answer return max_sum; } // Driver Code let n = 5; let a = [ 1, -5, 8, 12, -8 ]; // Function call document.write(getMaxSum(a, n)); </script>
152
Time Complexity: O(N) Auxiliary Space: O(N)
SHIVAMSINGH67
princiraj1992
rutvik_56
susmitakundugoaldanga
nayanmanojgupta
jainlovely450
Kadane
Memoization
subarray-sum
Arrays
Dynamic Programming
Mathematical
Searching
Arrays
Searching
Dynamic Programming
Mathematical
Kadane
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 214,
"s": 52,
"text": "Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square."
},
{
"code": null,
"e": 224,
"s": 214,
"text": "Examples:"
},
{
"code": null,
"e": 430,
"s": 224,
"text": "Input: a[] = {1, -5, 8, 12, -8} Output: 152 Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possible subarray sum in the array.Input: a[] = {-1, -2, -3} Output: 9 Explanation:"
},
{
"code": null,
"e": 715,
"s": 430,
"text": "Naive Approach: The simplest approach to solve the problem is to replace every element with its square and for each of them, find the maximum subarray sum using Kadaneβs algorithm. Finally, print the maximum possible subarray sum obtained. Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 843,
"s": 715,
"text": "Efficient Approach: The above approach can be optimized using Dynamic Programming. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 886,
"s": 843,
"text": "Initialize memoization table dp[][] where:"
},
{
"code": null,
"e": 1011,
"s": 886,
"text": "dp[i][0]: Stores the maximum subarray sum that can be obtained including ith element and without squaring any array element."
},
{
"code": null,
"e": 1126,
"s": 1011,
"text": "dp[i][1]: Stores the maximum subarray sum that can be including ith element and squaring one of the array elements"
},
{
"code": null,
"e": 1167,
"s": 1126,
"text": "Therefore, the recurrence relations are:"
},
{
"code": null,
"e": 1517,
"s": 1167,
"text": "dp[i][0] = max(dp[i-1][0] + a[i], a[i]), that is, either extend the previous subarray ending at i β 1th index or start a new subarray from ith index.dp[i][1] = max(a[i]2, dp[i-1][0] + a[i]2, dp[i-1][1] + a[i]), that is, either start new subarray from ith index or extend previous subarray by adding a[i]2 to dp[i β 1][0] or add a[i] to dp[i β 1][1] "
},
{
"code": null,
"e": 1568,
"s": 1517,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1572,
"s": 1568,
"text": "C++"
},
{
"code": null,
"e": 1577,
"s": 1572,
"text": "Java"
},
{
"code": null,
"e": 1585,
"s": 1577,
"text": "Python3"
},
{
"code": null,
"e": 1588,
"s": 1585,
"text": "C#"
},
{
"code": null,
"e": 1599,
"s": 1588,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h> using namespace std; // Function to find the maximum subarray// sum possibleint getMaxSum(int a[], int n){ int dp[n][2]; // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = max(dp[0][0], dp[0][1]); for(int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = max(max_sum, dp[i][1]); max_sum = max(max_sum, dp[i][0]); } // Return answer return max_sum;} // Driver Codeint32_t main(){ int n = 5; int a[] = { 1, -5, 8, 12, -8 }; // Function call cout << getMaxSum(a, n) << endl; return 0;} // This code is contributed by rutvik_56",
"e": 2860,
"s": 1599,
"text": null
},
{
"code": "// Java Program to implement// the above approachimport java.io.*; class GFG { // Function to find the maximum subarray // sum possible public static int getMaxSum(int a[], int n) { int dp[][] = new int[n][2]; // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = Math.max(dp[0][0], dp[0][1]); for (int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = Math.max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = Math.max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.max(max_sum, dp[i][1]); max_sum = Math.max(max_sum, dp[i][0]); } // Return answer return max_sum; } // Driver Code public static void main(String[] args) { int n = 5; int a[] = { 1, -5, 8, 12, -8 }; // Function call System.out.println(getMaxSum(a, n)); }}",
"e": 4264,
"s": 2860,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find the maximum subarray# sum possibledef getMaxSum(a, n): dp = [[0 for x in range(2)] for y in range(n)] # Stores sum without squaring dp[0][0] = a[0] # Stores sum squaring dp[0][1] = a[0] * a[0] # Stores the maximum subarray sum max_sum = max(dp[0][0], dp[0][1]) for i in range(1, n): # Either extend the subarray # or start a new subarray dp[i][0] = max(a[i], dp[i - 1][0] + a[i]) # Either extend previous squared # subarray or start a new subarray # by squaring the current element dp[i][1] = max(dp[i - 1][1] + a[i], a[i] * a[i]) dp[i][1] = max(dp[i][1], dp[i - 1][0] + a[i] * a[i]) # Update maximum subarray sum max_sum = max(max_sum, dp[i][1]) max_sum = max(max_sum, dp[i][0]) # Return answer return max_sum # Driver Coden = 5a = [ 1, -5, 8, 12, -8 ] # Function callprint(getMaxSum(a, n)) # This code is contributed by Shivam Singh",
"e": 5381,
"s": 4264,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the maximum subarray// sum possiblepublic static int getMaxSum(int []a, int n){ int [,]dp = new int[n, 2]; // Stores sum without squaring dp[0, 0] = a[0]; // Stores sum squaring dp[0, 1] = a[0] * a[0]; // Stores the maximum subarray sum int max_sum = Math.Max(dp[0, 0], dp[0, 1]); for(int i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i, 0] = Math.Max(a[i], dp[i - 1, 0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i, 1] = Math.Max(dp[i - 1, 1] + a[i], a[i] * a[i]); dp[i, 1] = Math.Max(dp[i, 1], dp[i - 1, 0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.Max(max_sum, dp[i, 1]); max_sum = Math.Max(max_sum, dp[i, 0]); } // Return answer return max_sum;} // Driver Codepublic static void Main(String[] args){ int n = 5; int []a = { 1, -5, 8, 12, -8 }; // Function call Console.WriteLine(getMaxSum(a, n));}} // This code is contributed by PrinciRaj1992",
"e": 6695,
"s": 5381,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the maximum subarray // sum possible function getMaxSum(a, n) { let dp = new Array(n); // Loop to create 2D array using 1D array for (var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // Stores sum without squaring dp[0][0] = a[0]; // Stores sum squaring dp[0][1] = a[0] * a[0]; // Stores the maximum subarray sum let max_sum = Math.max(dp[0][0], dp[0][1]); for (let i = 1; i < n; i++) { // Either extend the subarray // or start a new subarray dp[i][0] = Math.max(a[i], dp[i - 1][0] + a[i]); // Either extend previous squared // subarray or start a new subarray // by squaring the current element dp[i][1] = Math.max(dp[i - 1][1] + a[i], a[i] * a[i]); dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + a[i] * a[i]); // Update maximum subarray sum max_sum = Math.max(max_sum, dp[i][1]); max_sum = Math.max(max_sum, dp[i][0]); } // Return answer return max_sum; } // Driver Code let n = 5; let a = [ 1, -5, 8, 12, -8 ]; // Function call document.write(getMaxSum(a, n)); </script>",
"e": 8159,
"s": 6695,
"text": null
},
{
"code": null,
"e": 8163,
"s": 8159,
"text": "152"
},
{
"code": null,
"e": 8210,
"s": 8165,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 8224,
"s": 8210,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 8238,
"s": 8224,
"text": "princiraj1992"
},
{
"code": null,
"e": 8248,
"s": 8238,
"text": "rutvik_56"
},
{
"code": null,
"e": 8270,
"s": 8248,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8286,
"s": 8270,
"text": "nayanmanojgupta"
},
{
"code": null,
"e": 8300,
"s": 8286,
"text": "jainlovely450"
},
{
"code": null,
"e": 8307,
"s": 8300,
"text": "Kadane"
},
{
"code": null,
"e": 8319,
"s": 8307,
"text": "Memoization"
},
{
"code": null,
"e": 8332,
"s": 8319,
"text": "subarray-sum"
},
{
"code": null,
"e": 8339,
"s": 8332,
"text": "Arrays"
},
{
"code": null,
"e": 8359,
"s": 8339,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8372,
"s": 8359,
"text": "Mathematical"
},
{
"code": null,
"e": 8382,
"s": 8372,
"text": "Searching"
},
{
"code": null,
"e": 8389,
"s": 8382,
"text": "Arrays"
},
{
"code": null,
"e": 8399,
"s": 8389,
"text": "Searching"
},
{
"code": null,
"e": 8419,
"s": 8399,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8432,
"s": 8419,
"text": "Mathematical"
},
{
"code": null,
"e": 8439,
"s": 8432,
"text": "Kadane"
},
{
"code": null,
"e": 8537,
"s": 8439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8605,
"s": 8537,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8649,
"s": 8605,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8681,
"s": 8649,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 8729,
"s": 8681,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8743,
"s": 8729,
"text": "Linear Search"
},
{
"code": null,
"e": 8773,
"s": 8743,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 8802,
"s": 8773,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 8836,
"s": 8802,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 8863,
"s": 8836,
"text": "Subset Sum Problem | DP-25"
}
] |
Java Code for Moving Text | Applet | Thread
|
06 Jun, 2018
Before reading this article you need to know the Java Applet Basics and Java.lang.Thread class in Java .
In this article we shall be explaining the code to display moving text in Java. To print the string in the window we will use the drawString() method from java.awt package. The drawString method takes three arguments :
drawString(string, x, y)
string : This parameter takes the string to be displayed.x : This parameters takes the x co-ordinates where the string will be displayedon the screen.y : This parameter takes the y co-ordinates where the string will be displayedon the screen.
string : This parameter takes the string to be displayed.
x : This parameters takes the x co-ordinates where the string will be displayedon the screen.
y : This parameter takes the y co-ordinates where the string will be displayedon the screen.
We will be printing the string at (x, y) co-ordinates and then update the x co-ordinate and then repaint the screen again.
/*<APPLET code = "GFG.class" width = 500 height = 500 > </APPLET> */ // Java Code to implement Moving text using// applet and thread. import java.awt.*;import java.applet.*; public class GFG extends Applet implements Runnable { private String display; private int x, y, flag; Thread t; // initializing // called when the applet is // started. public void init() { display = "GeeksforGeeks"; x = 100; y = 100; flag = 1; // creating thread t = new Thread(this, "MyThread"); // start thread t.start(); } // update the x co-ordinate public void update() { x = x + 10 * flag; if (x > 300) flag = -1; if (x < 100) flag = 1; } // run public void run() { while (true) { // Repainting the screen // calls the paint function repaint(); update(); try { // creating a pause of 1 second // so that the movement is recognizable Thread.sleep(1000); } catch (InterruptedException ie) { System.out.println(ie); } } } // drawString public void paint(Graphics g) { g.drawString(display, x, y); }}
Output :
Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need.
java-applet
Java Programs
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Overview of Data Structures | Set 1 (Linear Data Structures)
vector::push_back() and vector::pop_back() in C++ STL
Top 10 algorithms in Interview Questions
Virtualization In Cloud Computing and Types
Program for nth Catalan Number
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jun, 2018"
},
{
"code": null,
"e": 158,
"s": 53,
"text": "Before reading this article you need to know the Java Applet Basics and Java.lang.Thread class in Java ."
},
{
"code": null,
"e": 377,
"s": 158,
"text": "In this article we shall be explaining the code to display moving text in Java. To print the string in the window we will use the drawString() method from java.awt package. The drawString method takes three arguments :"
},
{
"code": null,
"e": 402,
"s": 377,
"text": "drawString(string, x, y)"
},
{
"code": null,
"e": 645,
"s": 402,
"text": "string : This parameter takes the string to be displayed.x : This parameters takes the x co-ordinates where the string will be displayedon the screen.y : This parameter takes the y co-ordinates where the string will be displayedon the screen."
},
{
"code": null,
"e": 703,
"s": 645,
"text": "string : This parameter takes the string to be displayed."
},
{
"code": null,
"e": 797,
"s": 703,
"text": "x : This parameters takes the x co-ordinates where the string will be displayedon the screen."
},
{
"code": null,
"e": 890,
"s": 797,
"text": "y : This parameter takes the y co-ordinates where the string will be displayedon the screen."
},
{
"code": null,
"e": 1013,
"s": 890,
"text": "We will be printing the string at (x, y) co-ordinates and then update the x co-ordinate and then repaint the screen again."
},
{
"code": "/*<APPLET code = \"GFG.class\" width = 500 height = 500 > </APPLET> */ // Java Code to implement Moving text using// applet and thread. import java.awt.*;import java.applet.*; public class GFG extends Applet implements Runnable { private String display; private int x, y, flag; Thread t; // initializing // called when the applet is // started. public void init() { display = \"GeeksforGeeks\"; x = 100; y = 100; flag = 1; // creating thread t = new Thread(this, \"MyThread\"); // start thread t.start(); } // update the x co-ordinate public void update() { x = x + 10 * flag; if (x > 300) flag = -1; if (x < 100) flag = 1; } // run public void run() { while (true) { // Repainting the screen // calls the paint function repaint(); update(); try { // creating a pause of 1 second // so that the movement is recognizable Thread.sleep(1000); } catch (InterruptedException ie) { System.out.println(ie); } } } // drawString public void paint(Graphics g) { g.drawString(display, x, y); }}",
"e": 2348,
"s": 1013,
"text": null
},
{
"code": null,
"e": 2357,
"s": 2348,
"text": "Output :"
},
{
"code": null,
"e": 2621,
"s": 2357,
"text": "Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need."
},
{
"code": null,
"e": 2633,
"s": 2621,
"text": "java-applet"
},
{
"code": null,
"e": 2647,
"s": 2633,
"text": "Java Programs"
},
{
"code": null,
"e": 2652,
"s": 2647,
"text": "Misc"
},
{
"code": null,
"e": 2657,
"s": 2652,
"text": "Misc"
},
{
"code": null,
"e": 2662,
"s": 2657,
"text": "Misc"
},
{
"code": null,
"e": 2760,
"s": 2662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2808,
"s": 2760,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 2847,
"s": 2808,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 2898,
"s": 2847,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 2932,
"s": 2898,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 2979,
"s": 2932,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 3040,
"s": 2979,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 3094,
"s": 3040,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 3135,
"s": 3094,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 3179,
"s": 3135,
"text": "Virtualization In Cloud Computing and Types"
}
] |
Tryit Editor v3.7
|
Tryit: Styling textarea
|
[] |
How to get services on remote computers with PowerShell?
|
To get service on the remote computer(s), simply you need to add parameter β ComputerName and provide remote servers computer name or IP address.
In the below example, we are getting services information on remote computer Win7 which has Automatic start-type.
Get-Service -ComputerName Win7 | Where{$_.StartType -eq "Automatic"}
Similarly, you can connect multiple computers separated by comma (,) in β ComputerName parameter.
Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq "Automatic"}
If you need to identify on which particular computer(s), services exist, you can use the machinename property. In the above example, we are adding a machine name property in Pipeline.
Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq "Automatic"} |
Select MachineName, Name, Status
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "To get service on the remote computer(s), simply you need to add parameter β ComputerName and provide remote servers computer name or IP address."
},
{
"code": null,
"e": 1322,
"s": 1208,
"text": "In the below example, we are getting services information on remote computer Win7 which has Automatic start-type."
},
{
"code": null,
"e": 1391,
"s": 1322,
"text": "Get-Service -ComputerName Win7 | Where{$_.StartType -eq \"Automatic\"}"
},
{
"code": null,
"e": 1489,
"s": 1391,
"text": "Similarly, you can connect multiple computers separated by comma (,) in β ComputerName parameter."
},
{
"code": null,
"e": 1566,
"s": 1489,
"text": "Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq \"Automatic\"}"
},
{
"code": null,
"e": 1750,
"s": 1566,
"text": "If you need to identify on which particular computer(s), services exist, you can use the machinename property. In the above example, we are adding a machine name property in Pipeline."
},
{
"code": null,
"e": 1862,
"s": 1750,
"text": "Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq \"Automatic\"} |\nSelect MachineName, Name, Status"
}
] |
How to update a timestamp field of a MySQL table?
|
Let us first create a table β
mysql> create table DemoTable
-> (
-> PunchOut timestamp,
-> PunchStatus tinyint(1)
-> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable values('2019-01-31 6:30:10',1);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('2019-02-06 4:10:13',0);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2018-12-16 03:00:30',0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('2016-11-25 02:10:00',1);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statemen β
mysql> select *from DemoTable;
+---------------------+-------------+
| PunchOut | PunchStatus |
+---------------------+-------------+
| 2019-01-31 06:30:10 | 1 |
| 2019-02-06 04:10:13 | 0 |
| 2018-12-16 03:00:30 | 0 |
| 2016-11-25 02:10:00 | 1 |
+---------------------+-------------+
4 rows in set (0.00 sec)
Here is the query to update the timestamp field of a MySQL table. We have set current date to the fields with PunchStatus 0 β
Note β Current date and time is 2019-06-30 13:43:45
mysql> update DemoTable set PunchOut=now() where PunchStatus=0;
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again β
mysql> select *from DemoTable;
+---------------------+-------------+
| PunchOut | PunchStatus |
+---------------------+-------------+
| 2019-01-31 06:30:10 | 1 |
| 2019-06-30 13:43:45 | 0 |
| 2019-06-30 13:43:45 | 0 |
| 2016-11-25 02:10:00 | 1 |
+---------------------+-------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table β"
},
{
"code": null,
"e": 1231,
"s": 1092,
"text": "mysql> create table DemoTable\n -> (\n -> PunchOut timestamp,\n -> PunchStatus tinyint(1)\n -> );\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 1287,
"s": 1231,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1680,
"s": 1287,
"text": "mysql> insert into DemoTable values('2019-01-31 6:30:10',1);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into DemoTable values('2019-02-06 4:10:13',0);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('2018-12-16 03:00:30',0);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable values('2016-11-25 02:10:00',1);\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 1739,
"s": 1680,
"text": "Display all records from the table using select statemen β"
},
{
"code": null,
"e": 1770,
"s": 1739,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2099,
"s": 1770,
"text": "+---------------------+-------------+\n| PunchOut | PunchStatus |\n+---------------------+-------------+\n| 2019-01-31 06:30:10 | 1 |\n| 2019-02-06 04:10:13 | 0 |\n| 2018-12-16 03:00:30 | 0 |\n| 2016-11-25 02:10:00 | 1 |\n+---------------------+-------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2225,
"s": 2099,
"text": "Here is the query to update the timestamp field of a MySQL table. We have set current date to the fields with PunchStatus 0 β"
},
{
"code": null,
"e": 2277,
"s": 2225,
"text": "Note β Current date and time is 2019-06-30 13:43:45"
},
{
"code": null,
"e": 2418,
"s": 2277,
"text": "mysql> update DemoTable set PunchOut=now() where PunchStatus=0;\nQuery OK, 2 rows affected (0.19 sec)\nRows matched: 2 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2462,
"s": 2418,
"text": "Let us check the table records once again β"
},
{
"code": null,
"e": 2493,
"s": 2462,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2822,
"s": 2493,
"text": "+---------------------+-------------+\n| PunchOut | PunchStatus |\n+---------------------+-------------+\n| 2019-01-31 06:30:10 | 1 |\n| 2019-06-30 13:43:45 | 0 |\n| 2019-06-30 13:43:45 | 0 |\n| 2016-11-25 02:10:00 | 1 |\n+---------------------+-------------+\n4 rows in set (0.00 sec)"
}
] |
Python - Bernoulli Distribution
|
The Bernoulli distribution is a special case of the Binomial distribution where a single experiment is conducted so that the number of observation is 1. So, the Bernoulli distribution therefore describes events having exactly two outcomes.
We use various functions in numpy library to mathematically calculate the values for a bernoulli distribution. Histograms are created over which we plot the probability distribution curve.
from scipy.stats import bernoulli
import seaborn as sb
data_bern = bernoulli.rvs(size=1000,p=0.6)
ax = sb.distplot(data_bern,
kde=True,
color='crimson',
hist_kws={"linewidth": 25,'alpha':1})
ax.set(xlabel='Bernouli', ylabel='Frequency')
Its output is as follows β
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": 2770,
"s": 2529,
"text": "The Bernoulli distribution is a special case of the Binomial distribution where a single experiment is conducted so that the number of observation is 1. So, the Bernoulli distribution therefore describes events having exactly two outcomes.\n"
},
{
"code": null,
"e": 2960,
"s": 2770,
"text": "We use various functions in numpy library to mathematically calculate the values for a bernoulli distribution. Histograms are created over which we plot the probability distribution curve. "
},
{
"code": null,
"e": 3252,
"s": 2960,
"text": "from scipy.stats import bernoulli\nimport seaborn as sb\n\ndata_bern = bernoulli.rvs(size=1000,p=0.6)\nax = sb.distplot(data_bern,\n kde=True,\n color='crimson',\n hist_kws={\"linewidth\": 25,'alpha':1})\nax.set(xlabel='Bernouli', ylabel='Frequency')"
},
{
"code": null,
"e": 3279,
"s": 3252,
"text": "Its output is as follows β"
},
{
"code": null,
"e": 3316,
"s": 3279,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3332,
"s": 3316,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3365,
"s": 3332,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3384,
"s": 3365,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3419,
"s": 3384,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3441,
"s": 3419,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3475,
"s": 3441,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3503,
"s": 3475,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3538,
"s": 3503,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3552,
"s": 3538,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3585,
"s": 3552,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3602,
"s": 3585,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3609,
"s": 3602,
"text": " Print"
},
{
"code": null,
"e": 3620,
"s": 3609,
"text": " Add Notes"
}
] |
Docker Image tags and how to use them
|
Docker Image tags are simple labels or aliases given to a docker image before or after building an image to describe that particular image. It can be the version of the project or the container, features of the image, technologies used in the image or pretty much anything you want. It plays a key role in the overall software development life cycle because it helps you keep track of the different parts of your project as well as help you in version management of the product.
While pulling an image, you can specify the tag of the image you want or if not specified, it will pull the latest tagged image automatically. Let us see the two most common ways, where tagging comes into picture while you are working with docker images.
When you are trying to build an image using the docker build command, you can specify the tag along with the image name to build the image with that specific tag. You can use the βt flag to do so. Check out the command below to tag an image while building it.
When you are trying to build an image using the docker build command, you can specify the tag along with the image name to build the image with that specific tag. You can use the βt flag to do so. Check out the command below to tag an image while building it.
sudo docker build βt <username>/<imageβname>:<tagβname>.
What the above command does is, it searches for the dockerfile in the docker build context which you have set as the current directory by using the dot, using that dockerfile it builds the image and specifies the tag which you specified. However, specifying a tag name is not mandatory if you are using the above command. You can also build the image without specifying the tag.
You can also use the tag command to tag an already existing image. You can do so, by using the below command.
You can also use the tag command to tag an already existing image. You can do so, by using the below command.
sudo docker tag <imageβid> <imageβname>/<tagβname>
The command stated above lets you tag an image using the image ID. You can find the image ID of a particular image using the docker images command.
If you donβt specify any tag while pulling an image, it will automatically pull the latest version of the image. See the examples below.
Inside the dockerfile, if you use β
FROM python
It will automatically embed a latest tag (python:latest) and will pull the latest python image from the docker registry.
However, if you write β
FROM python:3
It will pull python 3 from the docker registry.
Note that if you want to pull all the tagged versions associated with an image, you can use the βa flag along with the docker pull command
sudo docker pull ubuntu βa
This will pull all the available tagger versions of the image named ubuntu.
To conclude, tagging an image is very useful when you are simultaneously working with several images. It gives you better version control and management over your project. It lets you keep track of the major changes that you make in your project. Itβs always a better practice to tag your image when you build it.
One last thing to discuss is about the tag called latest. When you donβt specify a tag to an image, by default docker puts the latest tag to your image so that when you try to pull the image back, by default it serves you with the image having the latest tag.
|
[
{
"code": null,
"e": 1541,
"s": 1062,
"text": "Docker Image tags are simple labels or aliases given to a docker image before or after building an image to describe that particular image. It can be the version of the project or the container, features of the image, technologies used in the image or pretty much anything you want. It plays a key role in the overall software development life cycle because it helps you keep track of the different parts of your project as well as help you in version management of the product."
},
{
"code": null,
"e": 1796,
"s": 1541,
"text": "While pulling an image, you can specify the tag of the image you want or if not specified, it will pull the latest tagged image automatically. Let us see the two most common ways, where tagging comes into picture while you are working with docker images."
},
{
"code": null,
"e": 2056,
"s": 1796,
"text": "When you are trying to build an image using the docker build command, you can specify the tag along with the image name to build the image with that specific tag. You can use the βt flag to do so. Check out the command below to tag an image while building it."
},
{
"code": null,
"e": 2316,
"s": 2056,
"text": "When you are trying to build an image using the docker build command, you can specify the tag along with the image name to build the image with that specific tag. You can use the βt flag to do so. Check out the command below to tag an image while building it."
},
{
"code": null,
"e": 2373,
"s": 2316,
"text": "sudo docker build βt <username>/<imageβname>:<tagβname>."
},
{
"code": null,
"e": 2752,
"s": 2373,
"text": "What the above command does is, it searches for the dockerfile in the docker build context which you have set as the current directory by using the dot, using that dockerfile it builds the image and specifies the tag which you specified. However, specifying a tag name is not mandatory if you are using the above command. You can also build the image without specifying the tag."
},
{
"code": null,
"e": 2862,
"s": 2752,
"text": "You can also use the tag command to tag an already existing image. You can do so, by using the below command."
},
{
"code": null,
"e": 2972,
"s": 2862,
"text": "You can also use the tag command to tag an already existing image. You can do so, by using the below command."
},
{
"code": null,
"e": 3023,
"s": 2972,
"text": "sudo docker tag <imageβid> <imageβname>/<tagβname>"
},
{
"code": null,
"e": 3171,
"s": 3023,
"text": "The command stated above lets you tag an image using the image ID. You can find the image ID of a particular image using the docker images command."
},
{
"code": null,
"e": 3308,
"s": 3171,
"text": "If you donβt specify any tag while pulling an image, it will automatically pull the latest version of the image. See the examples below."
},
{
"code": null,
"e": 3344,
"s": 3308,
"text": "Inside the dockerfile, if you use β"
},
{
"code": null,
"e": 3356,
"s": 3344,
"text": "FROM python"
},
{
"code": null,
"e": 3477,
"s": 3356,
"text": "It will automatically embed a latest tag (python:latest) and will pull the latest python image from the docker registry."
},
{
"code": null,
"e": 3501,
"s": 3477,
"text": "However, if you write β"
},
{
"code": null,
"e": 3516,
"s": 3501,
"text": "FROM python:3\n"
},
{
"code": null,
"e": 3564,
"s": 3516,
"text": "It will pull python 3 from the docker registry."
},
{
"code": null,
"e": 3703,
"s": 3564,
"text": "Note that if you want to pull all the tagged versions associated with an image, you can use the βa flag along with the docker pull command"
},
{
"code": null,
"e": 3730,
"s": 3703,
"text": "sudo docker pull ubuntu βa"
},
{
"code": null,
"e": 3806,
"s": 3730,
"text": "This will pull all the available tagger versions of the image named ubuntu."
},
{
"code": null,
"e": 4120,
"s": 3806,
"text": "To conclude, tagging an image is very useful when you are simultaneously working with several images. It gives you better version control and management over your project. It lets you keep track of the major changes that you make in your project. Itβs always a better practice to tag your image when you build it."
},
{
"code": null,
"e": 4380,
"s": 4120,
"text": "One last thing to discuss is about the tag called latest. When you donβt specify a tag to an image, by default docker puts the latest tag to your image so that when you try to pull the image back, by default it serves you with the image having the latest tag."
}
] |
Anagram | Practice | GeeksforGeeks
|
Given two stringsaandbconsisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other.
Example 1:
Input:a = geeksforgeeks, b = forgeeksgeeks
Output: YES
Explanation: Both the string have samecharacters with
same frequency. So, both are anagrams.
Example 2:
Input:a = allergy, b = allergic
Output: NO
Explanation:Characters in both the strings are
not same, so they are not anagrams.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isAnagram() which takes the string a and string b as input parameter and check if the two strings are an anagram of each other. The function returns true if the strings are anagram else it returns false.
Note: In python, you have to return True or False.
Expected Time Complexity:O(|a|+|b|).
Expected Auxiliary Space:O(Number of distinct characters).
Note: |s| represents the length of string s.
Constraints:
1 β€ |a|,|b| β€ 105
0
ravinuthalavamsikrishna14 hours ago
def isAnagram(self,a,b): #code here l=[0]*26 l1=[0]*26 for i in a: l[ord(i)-97]+=1 for i in b: l1[ord(i)-97]+=1 if l==l1: return True return False
0
sachinsharma291113 days ago
def isAnagram(self,a,b): #code here x=list(a) y=list(b) x.sort() y.sort() if x==y: return True return False
+1
meenuchidam3 days ago
def isAnagram(self,a,b): l1=list(a) l2=list(b) l1.sort() l2.sort() l1.sort() c=str(l1) d=str(l2) if c==d: return True else: return False
0
reeteshmeena
This comment was deleted.
0
surajraj207535 days ago
#java code
class Solution{ //Function is to check whether two strings are anagram of each other or not. public static boolean isAnagram(String a,String b) { int p=a.length(); int q=a.length(); if(p==q){ char[] a1=a.toLowerCase().toCharArray(); char[] b1=b.toLowerCase().toCharArray(); Arrays.sort(a1); Arrays.sort(b1); if(Arrays.equals(a1,b1)){ return true; }else{ return false; } }else{ return false; } // Your code here }}
0
ayushmahobia015 days ago
bool isAnagram(string a, string b){ // Your code here sort(a.begin(),a.end()); sort(b.begin(),b.end()); int n1= a.length(); int n2 =b.length(); if(n1!=n2) { return false; } for(int i=0;i<n1;i++){ if(a[i]!=b[i]) { return false; } } return true; }
0
shashankshekhar8891 week ago
def isAnagram(self,a,b):
for i in a:
b=b.replace(i,"",1)
if len(b)==0:
return True
else:
return False
0
jay12501 week ago
#easy python
class Solution: #Function is to check whether two strings are anagram of each other or not. def isAnagram(self,a,b): #code here return True if sorted(a) == sorted(b) else False
0
souminmohanty1 week ago
JAVA CODE
------------
public static String sort(String a){ char temp[] = a.toCharArray(); Arrays.sort(temp); return new String(temp); } public static boolean isAnagram(String a,String b) { // Your code here String k = sort(a); String m = sort(b); if(k.equals(m)) return true; else return false; }
0
sailendrachettri1 week ago
C++ solution
bool isAnagram(string a, string b){
// Your code here
// cout<<a <<" "<<b<<endl;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
// cout<<a <<" "<<b<<endl;
if(a == b) return true;
return false;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 558,
"s": 238,
"text": "Given two stringsaandbconsisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other."
},
{
"code": null,
"e": 569,
"s": 558,
"text": "Example 1:"
},
{
"code": null,
"e": 725,
"s": 569,
"text": "Input:a = geeksforgeeks, b = forgeeksgeeks\nOutput: YES\nExplanation: Both the string have samecharacters with\n same frequency. So, both are anagrams."
},
{
"code": null,
"e": 736,
"s": 725,
"text": "Example 2:"
},
{
"code": null,
"e": 871,
"s": 736,
"text": "Input:a = allergy, b = allergic\nOutput: NO\nExplanation:Characters in both the strings are \n not same, so they are not anagrams."
},
{
"code": null,
"e": 1172,
"s": 871,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isAnagram() which takes the string a and string b as input parameter and check if the two strings are an anagram of each other. The function returns true if the strings are anagram else it returns false."
},
{
"code": null,
"e": 1223,
"s": 1172,
"text": "Note: In python, you have to return True or False."
},
{
"code": null,
"e": 1319,
"s": 1223,
"text": "Expected Time Complexity:O(|a|+|b|).\nExpected Auxiliary Space:O(Number of distinct characters)."
},
{
"code": null,
"e": 1364,
"s": 1319,
"text": "Note: |s| represents the length of string s."
},
{
"code": null,
"e": 1395,
"s": 1364,
"text": "Constraints:\n1 β€ |a|,|b| β€ 105"
},
{
"code": null,
"e": 1397,
"s": 1395,
"text": "0"
},
{
"code": null,
"e": 1433,
"s": 1397,
"text": "ravinuthalavamsikrishna14 hours ago"
},
{
"code": null,
"e": 1656,
"s": 1433,
"text": " def isAnagram(self,a,b): #code here l=[0]*26 l1=[0]*26 for i in a: l[ord(i)-97]+=1 for i in b: l1[ord(i)-97]+=1 if l==l1: return True return False"
},
{
"code": null,
"e": 1658,
"s": 1656,
"text": "0"
},
{
"code": null,
"e": 1686,
"s": 1658,
"text": "sachinsharma291113 days ago"
},
{
"code": null,
"e": 1846,
"s": 1686,
"text": "def isAnagram(self,a,b): #code here x=list(a) y=list(b) x.sort() y.sort() if x==y: return True return False"
},
{
"code": null,
"e": 1849,
"s": 1846,
"text": "+1"
},
{
"code": null,
"e": 1871,
"s": 1849,
"text": "meenuchidam3 days ago"
},
{
"code": null,
"e": 2082,
"s": 1871,
"text": "def isAnagram(self,a,b): l1=list(a) l2=list(b) l1.sort() l2.sort() l1.sort() c=str(l1) d=str(l2) if c==d: return True else: return False"
},
{
"code": null,
"e": 2084,
"s": 2082,
"text": "0"
},
{
"code": null,
"e": 2097,
"s": 2084,
"text": "reeteshmeena"
},
{
"code": null,
"e": 2123,
"s": 2097,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2125,
"s": 2123,
"text": "0"
},
{
"code": null,
"e": 2149,
"s": 2125,
"text": "surajraj207535 days ago"
},
{
"code": null,
"e": 2160,
"s": 2149,
"text": "#java code"
},
{
"code": null,
"e": 2744,
"s": 2160,
"text": "class Solution{ //Function is to check whether two strings are anagram of each other or not. public static boolean isAnagram(String a,String b) { int p=a.length(); int q=a.length(); if(p==q){ char[] a1=a.toLowerCase().toCharArray(); char[] b1=b.toLowerCase().toCharArray(); Arrays.sort(a1); Arrays.sort(b1); if(Arrays.equals(a1,b1)){ return true; }else{ return false; } }else{ return false; } // Your code here }}"
},
{
"code": null,
"e": 2746,
"s": 2744,
"text": "0"
},
{
"code": null,
"e": 2771,
"s": 2746,
"text": "ayushmahobia015 days ago"
},
{
"code": null,
"e": 3153,
"s": 2771,
"text": "bool isAnagram(string a, string b){ // Your code here sort(a.begin(),a.end()); sort(b.begin(),b.end()); int n1= a.length(); int n2 =b.length(); if(n1!=n2) { return false; } for(int i=0;i<n1;i++){ if(a[i]!=b[i]) { return false; } } return true; }"
},
{
"code": null,
"e": 3155,
"s": 3153,
"text": "0"
},
{
"code": null,
"e": 3184,
"s": 3155,
"text": "shashankshekhar8891 week ago"
},
{
"code": null,
"e": 3346,
"s": 3184,
"text": "def isAnagram(self,a,b):\n for i in a:\n b=b.replace(i,\"\",1)\n if len(b)==0:\n return True\n else:\n return False"
},
{
"code": null,
"e": 3348,
"s": 3346,
"text": "0"
},
{
"code": null,
"e": 3366,
"s": 3348,
"text": "jay12501 week ago"
},
{
"code": null,
"e": 3380,
"s": 3366,
"text": "#easy python "
},
{
"code": null,
"e": 3576,
"s": 3380,
"text": "class Solution: #Function is to check whether two strings are anagram of each other or not. def isAnagram(self,a,b): #code here return True if sorted(a) == sorted(b) else False"
},
{
"code": null,
"e": 3578,
"s": 3576,
"text": "0"
},
{
"code": null,
"e": 3602,
"s": 3578,
"text": "souminmohanty1 week ago"
},
{
"code": null,
"e": 3613,
"s": 3602,
"text": "JAVA CODE "
},
{
"code": null,
"e": 3626,
"s": 3613,
"text": "------------"
},
{
"code": null,
"e": 3995,
"s": 3626,
"text": "public static String sort(String a){ char temp[] = a.toCharArray(); Arrays.sort(temp); return new String(temp); } public static boolean isAnagram(String a,String b) { // Your code here String k = sort(a); String m = sort(b); if(k.equals(m)) return true; else return false; }"
},
{
"code": null,
"e": 3997,
"s": 3995,
"text": "0"
},
{
"code": null,
"e": 4024,
"s": 3997,
"text": "sailendrachettri1 week ago"
},
{
"code": null,
"e": 4037,
"s": 4024,
"text": "C++ solution"
},
{
"code": null,
"e": 4342,
"s": 4037,
"text": "bool isAnagram(string a, string b){\n \n // Your code here\n // cout<<a <<\" \"<<b<<endl;\n \n sort(a.begin(), a.end());\n sort(b.begin(), b.end());\n \n // cout<<a <<\" \"<<b<<endl;\n \n if(a == b) return true;\n return false;\n \n }"
},
{
"code": null,
"e": 4488,
"s": 4342,
"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": 4524,
"s": 4488,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4534,
"s": 4524,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4544,
"s": 4534,
"text": "\nContest\n"
},
{
"code": null,
"e": 4607,
"s": 4544,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4755,
"s": 4607,
"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": 4963,
"s": 4755,
"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": 5069,
"s": 4963,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Initialize Matrix in Python - GeeksforGeeks
|
19 Feb, 2022
There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it. We can do it using list comprehension, concatenation feature of * operator and few other ways.
Method 0: 2 list comprehensions
Python3
rows = 3cols = 2 mat = [[0 for _ in range(cols)] for _ in range(rows)]print(f'matrix of dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
matrix of dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]
modified matrix is [[1, 2], [3, 4], [5, 6]]
addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336
addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400
addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 1: 1 list comprehension inside and 1 concatenation operation outside
Python3
rows = 3cols = 2 mat = [[0 for _ in range(cols)]]*rowsprint(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]
modified matrix is [[5, 6], [5, 6], [5, 6]]
addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464
addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464
addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 2: 1 list comprehension outside and 1 concatenation operation inside
Python3
rows = 3cols = 2 mat = [[0]*cols for _ in range(rows)]print(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]
modified matrix is [[1, 2], [3, 4], [5, 6]]
addr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336
addr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400
addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Method 3: 2 concatenation operations
Python3
rows = 3cols = 2 mat = [[0]*cols]*rowsprint(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')
matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]
modified matrix is [[5, 6], [5, 6], [5, 6]]
addr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464
addr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464
addr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464
Here we can see that output of Method 1 & Method 3 are *unexpected*.
We expected all rows in mat to be all different after we assigned them with 1,2,3,4,5,6 respectively. But in Method1 & Method3 they are all equal to [5,6]. This shows that essentially mat[0],mat[1] & mat[2] are all referencing the same memory which can further be seen by checking their addresses using the id function in python.
Hence be very careful while using (*) operator.
To understand it further we can use 3 dimensional arrays to and there we will have 2^3 possibilities of arranging list comprehension and concatenation operator. This is an exercise I leave for the reader to perform.
If working with numpy then we can do it using reshape method.
Python3
import numpy as np rows = 3cols = 2size = rows*cols mat = np.array([0]*size).reshape(rows,cols)
Pushpak_Jalan
thatti sreenivasulu
chhabradhanvi
raahilbadiani
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24594,
"s": 24566,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 24869,
"s": 24594,
"text": "There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it. We can do it using list comprehension, concatenation feature of * operator and few other ways."
},
{
"code": null,
"e": 24901,
"s": 24869,
"text": "Method 0: 2 list comprehensions"
},
{
"code": null,
"e": 24909,
"s": 24901,
"text": "Python3"
},
{
"code": "rows = 3cols = 2 mat = [[0 for _ in range(cols)] for _ in range(rows)]print(f'matrix of dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')",
"e": 25470,
"s": 24909,
"text": null
},
{
"code": null,
"e": 25734,
"s": 25470,
"text": "matrix of dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]\nmodified matrix is [[1, 2], [3, 4], [5, 6]]\naddr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336\naddr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400\naddr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464\n"
},
{
"code": null,
"e": 25812,
"s": 25734,
"text": "Method 1: 1 list comprehension inside and 1 concatenation operation outside"
},
{
"code": null,
"e": 25820,
"s": 25812,
"text": "Python3"
},
{
"code": "rows = 3cols = 2 mat = [[0 for _ in range(cols)]]*rowsprint(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')",
"e": 26367,
"s": 25820,
"text": null
},
{
"code": null,
"e": 26633,
"s": 26367,
"text": "matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]\nmodified matrix is [[5, 6], [5, 6], [5, 6]]\naddr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464\naddr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464\naddr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464\n"
},
{
"code": null,
"e": 26711,
"s": 26633,
"text": "Method 2: 1 list comprehension outside and 1 concatenation operation inside"
},
{
"code": null,
"e": 26719,
"s": 26711,
"text": "Python3"
},
{
"code": "rows = 3cols = 2 mat = [[0]*cols for _ in range(rows)]print(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')",
"e": 27266,
"s": 26719,
"text": null
},
{
"code": null,
"e": 27532,
"s": 27266,
"text": "matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]\nmodified matrix is [[1, 2], [3, 4], [5, 6]]\naddr(mat[0][0]) = 11094304, addr(mat[0][1]) = 11094336\naddr(mat[1][0]) = 11094368, addr(mat[1][1]) = 11094400\naddr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464\n"
},
{
"code": null,
"e": 27569,
"s": 27532,
"text": "Method 3: 2 concatenation operations"
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Python3"
},
{
"code": "rows = 3cols = 2 mat = [[0]*cols]*rowsprint(f'matrix with dimension {rows} x {cols} is {mat}') # editing the individual elementsmat[0][0], mat[0][1] = 1,2mat[1][0], mat[1][1] = 3,4mat[2][0], mat[2][1] = 5,6print(f'modified matrix is {mat}') # checking the memory address of first element of a rowprint(f'addr(mat[0][0]) = {id(mat[0][0])}, addr(mat[0][1]) = {id(mat[0][1])}')print(f'addr(mat[1][0]) = {id(mat[1][0])}, addr(mat[1][1]) = {id(mat[1][1])}')print(f'addr(mat[2][0]) = {id(mat[2][0])}, addr(mat[2][1]) = {id(mat[2][1])}')",
"e": 28108,
"s": 27577,
"text": null
},
{
"code": null,
"e": 28374,
"s": 28108,
"text": "matrix with dimension 3 x 2 is [[0, 0], [0, 0], [0, 0]]\nmodified matrix is [[5, 6], [5, 6], [5, 6]]\naddr(mat[0][0]) = 11094432, addr(mat[0][1]) = 11094464\naddr(mat[1][0]) = 11094432, addr(mat[1][1]) = 11094464\naddr(mat[2][0]) = 11094432, addr(mat[2][1]) = 11094464\n"
},
{
"code": null,
"e": 28444,
"s": 28374,
"text": "Here we can see that output of Method 1 & Method 3 are *unexpected*. "
},
{
"code": null,
"e": 28775,
"s": 28444,
"text": "We expected all rows in mat to be all different after we assigned them with 1,2,3,4,5,6 respectively. But in Method1 & Method3 they are all equal to [5,6]. This shows that essentially mat[0],mat[1] & mat[2] are all referencing the same memory which can further be seen by checking their addresses using the id function in python. "
},
{
"code": null,
"e": 28826,
"s": 28775,
"text": " Hence be very careful while using (*) operator. "
},
{
"code": null,
"e": 29043,
"s": 28826,
"text": "To understand it further we can use 3 dimensional arrays to and there we will have 2^3 possibilities of arranging list comprehension and concatenation operator. This is an exercise I leave for the reader to perform."
},
{
"code": null,
"e": 29105,
"s": 29043,
"text": "If working with numpy then we can do it using reshape method."
},
{
"code": null,
"e": 29113,
"s": 29105,
"text": "Python3"
},
{
"code": "import numpy as np rows = 3cols = 2size = rows*cols mat = np.array([0]*size).reshape(rows,cols)",
"e": 29209,
"s": 29113,
"text": null
},
{
"code": null,
"e": 29223,
"s": 29209,
"text": "Pushpak_Jalan"
},
{
"code": null,
"e": 29243,
"s": 29223,
"text": "thatti sreenivasulu"
},
{
"code": null,
"e": 29257,
"s": 29243,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 29271,
"s": 29257,
"text": "raahilbadiani"
},
{
"code": null,
"e": 29292,
"s": 29271,
"text": "Python list-programs"
},
{
"code": null,
"e": 29314,
"s": 29292,
"text": "Python matrix-program"
},
{
"code": null,
"e": 29321,
"s": 29314,
"text": "Python"
},
{
"code": null,
"e": 29337,
"s": 29321,
"text": "Python Programs"
},
{
"code": null,
"e": 29435,
"s": 29337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29444,
"s": 29435,
"text": "Comments"
},
{
"code": null,
"e": 29457,
"s": 29444,
"text": "Old Comments"
},
{
"code": null,
"e": 29475,
"s": 29457,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29507,
"s": 29475,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29542,
"s": 29507,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29564,
"s": 29542,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29594,
"s": 29564,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29637,
"s": 29594,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29659,
"s": 29637,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29698,
"s": 29659,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29744,
"s": 29698,
"text": "Python | Split string into list of characters"
}
] |
Reverse a sublist of linked list - GeeksforGeeks
|
18 Apr, 2022
We are given a linked list and positions m and n. We need to reverse the linked list from position m to n.
Examples:
Input : 10->20->30->40->50->60->70->NULL
m = 3, n = 6
Output : 10->20->60->50->40->30->70->NULL
Input : 1->2->3->4->5->6->NULL
m = 2, n = 4
Output : 1->4->3->2->5->6->NULL
To reverse the linked list from position m to n, we find addresses of start and end position of the linked list by running a loop, and then we unlink this part from the rest of the list and then use the normal linked list reverse function which we have earlier used for reversing the complete linked list, and use it to reverse the portion of the linked list which need to be reversed. After reversal, we again attach the portion reversed to the main list.
C++
C
Python3
// C++ program to reverse a linked list// from position m to position n#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node { int data; struct Node* next;}; // function used to reverse a linked liststruct Node* reverse(struct Node* head){ struct Node* prev = NULL; struct Node* curr = head; while (curr) { struct Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev;} // function used to reverse a linked list from position m to nNode* reverseBetween(Node* head, int m, int n){ if (m == n) return head; // revs and revend is start and end respectively of the // portion of the linked list which need to be reversed. // revs_prev is previous of starting position and // revend_next is next of end of list to be reversed. Node *revs = NULL, *revs_prev = NULL; Node *revend = NULL, *revend_next = NULL; // Find values of above pointers. int i = 1; Node* curr = head; while (curr && i <= n) { if (i < m) revs_prev = curr; if (i == m) revs = curr; if (i == n) { revend = curr; revend_next = curr->next; } curr = curr->next; i++; } revend->next = NULL; // Reverse linked list starting with revs. revend = reverse(revs); // If starting position was not head if (revs_prev) revs_prev->next = revend; // If starting position was head else head = revend; revs->next = revend_next; return head;} void print(struct Node* head){ while (head != NULL) { cout<<head->data<<" "; head = head->next; } cout<<endl;} // function to add a new node at the// beginning of the listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ struct Node* head = NULL; push(&head, 70); push(&head, 60); push(&head, 50); push(&head, 40); push(&head, 30); push(&head, 20); push(&head, 10); reverseBetween(head, 3, 6); print(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to reverse a linked list// from position m to position n#include <stdio.h>#include <stdlib.h> // Linked list nodetypedef struct Node { int data; struct Node* next;} Node; // function used to reverse a linked listNode* reverse(Node* head){ Node* prev = NULL; Node* curr = head; while (curr) { Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev;} // function used to reverse a linked list from position m to nNode* reverseBetween(Node* head, int m, int n){ if (m == n) return head; // revs and revend is start and end respectively of the // portion of the linked list which need to be reversed. // revs_prev is previous of starting position and // revend_next is next of end of list to be reversed. Node *revs = NULL, *revs_prev = NULL; Node *revend = NULL, *revend_next = NULL; // Find values of above pointers. int i = 1; Node* curr = head; while (curr && i <= n) { if (i < m) revs_prev = curr; if (i == m) revs = curr; if (i == n) { revend = curr; revend_next = curr->next; } curr = curr->next; i++; } revend->next = NULL; // Reverse linked list starting with revs. revend = reverse(revs); // If starting position was not head if (revs_prev) revs_prev->next = revend; // If starting position was head else head = revend; revs->next = revend_next; return head;} void print(Node* head){ while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n");} // function to add a new node at the beginning of the listvoid push(Node** head_ref, int new_data){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ Node* head = NULL; push(&head, 70); push(&head, 60); push(&head, 50); push(&head, 40); push(&head, 30); push(&head, 20); push(&head, 10); reverseBetween(head, 3, 6); print(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to reverse a linked list# from position m to position n # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # The standard reverse function used# to reverse a linked listdef reverse(head): prev = None curr = head while (curr): next = curr.next curr.next = prev prev = curr curr = next return prev # Function used to reverse a linked list# from position m to n which uses reverse# functiondef reverseBetween(head, m, n): if (m == n): return head # revs and revend is start and end respectively # of the portion of the linked list which # need to be reversed. revs_prev is previous # of starting position and revend_next is next # of end of list to be reversed. revs = None revs_prev = None revend = None revend_next = None # Find values of above pointers. i = 1 curr = head while (curr and i <= n): if (i < m): revs_prev = curr if (i == m): revs = curr if (i == n): revend = curr revend_next = curr.next curr = curr.next i += 1 revend.next = None # Reverse linked list starting with # revs. revend = reverse(revs) # If starting position was not head if (revs_prev): revs_prev.next = revend # If starting position was head else: head = revend revs.next = revend_next return head def prints(head): while (head != None): print(head.data, end = ' ') head = head.next print() # Function to add a new node at the# beginning of the listdef push(head_ref, new_data): new_node = Node(new_data) new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Driver codeif __name__=='__main__': head = None head = push(head, 70) head = push(head, 60) head = push(head, 50) head = push(head, 40) head = push(head, 30) head = push(head, 20) head = push(head, 10) reverseBetween(head, 3, 6) prints(head) # This code is contributed by rutvik_56
Output:
10 20 60 50 40 30 70
This article is contributed by Akshit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
rutvik_56
Reverse
Linked List
Linked List
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a Linked List node at a given position
Queue - Linked List Implementation
Implement a stack using singly linked list
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)
Remove duplicates from a sorted linked list
Find Length of a Linked List (Iterative and Recursive)
Function to check if a singly linked list is palindrome
Write a function to delete a Linked List
Search an element in a Linked List (Iterative and Recursive)
|
[
{
"code": null,
"e": 24297,
"s": 24269,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24404,
"s": 24297,
"text": "We are given a linked list and positions m and n. We need to reverse the linked list from position m to n."
},
{
"code": null,
"e": 24416,
"s": 24404,
"text": "Examples: "
},
{
"code": null,
"e": 24608,
"s": 24416,
"text": "Input : 10->20->30->40->50->60->70->NULL\n m = 3, n = 6\nOutput : 10->20->60->50->40->30->70->NULL\n\nInput : 1->2->3->4->5->6->NULL \n m = 2, n = 4\nOutput : 1->4->3->2->5->6->NULL"
},
{
"code": null,
"e": 25065,
"s": 24608,
"text": "To reverse the linked list from position m to n, we find addresses of start and end position of the linked list by running a loop, and then we unlink this part from the rest of the list and then use the normal linked list reverse function which we have earlier used for reversing the complete linked list, and use it to reverse the portion of the linked list which need to be reversed. After reversal, we again attach the portion reversed to the main list."
},
{
"code": null,
"e": 25069,
"s": 25065,
"text": "C++"
},
{
"code": null,
"e": 25071,
"s": 25069,
"text": "C"
},
{
"code": null,
"e": 25079,
"s": 25071,
"text": "Python3"
},
{
"code": "// C++ program to reverse a linked list// from position m to position n#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node { int data; struct Node* next;}; // function used to reverse a linked liststruct Node* reverse(struct Node* head){ struct Node* prev = NULL; struct Node* curr = head; while (curr) { struct Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev;} // function used to reverse a linked list from position m to nNode* reverseBetween(Node* head, int m, int n){ if (m == n) return head; // revs and revend is start and end respectively of the // portion of the linked list which need to be reversed. // revs_prev is previous of starting position and // revend_next is next of end of list to be reversed. Node *revs = NULL, *revs_prev = NULL; Node *revend = NULL, *revend_next = NULL; // Find values of above pointers. int i = 1; Node* curr = head; while (curr && i <= n) { if (i < m) revs_prev = curr; if (i == m) revs = curr; if (i == n) { revend = curr; revend_next = curr->next; } curr = curr->next; i++; } revend->next = NULL; // Reverse linked list starting with revs. revend = reverse(revs); // If starting position was not head if (revs_prev) revs_prev->next = revend; // If starting position was head else head = revend; revs->next = revend_next; return head;} void print(struct Node* head){ while (head != NULL) { cout<<head->data<<\" \"; head = head->next; } cout<<endl;} // function to add a new node at the// beginning of the listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ struct Node* head = NULL; push(&head, 70); push(&head, 60); push(&head, 50); push(&head, 40); push(&head, 30); push(&head, 20); push(&head, 10); reverseBetween(head, 3, 6); print(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 27327,
"s": 25079,
"text": null
},
{
"code": "// C program to reverse a linked list// from position m to position n#include <stdio.h>#include <stdlib.h> // Linked list nodetypedef struct Node { int data; struct Node* next;} Node; // function used to reverse a linked listNode* reverse(Node* head){ Node* prev = NULL; Node* curr = head; while (curr) { Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev;} // function used to reverse a linked list from position m to nNode* reverseBetween(Node* head, int m, int n){ if (m == n) return head; // revs and revend is start and end respectively of the // portion of the linked list which need to be reversed. // revs_prev is previous of starting position and // revend_next is next of end of list to be reversed. Node *revs = NULL, *revs_prev = NULL; Node *revend = NULL, *revend_next = NULL; // Find values of above pointers. int i = 1; Node* curr = head; while (curr && i <= n) { if (i < m) revs_prev = curr; if (i == m) revs = curr; if (i == n) { revend = curr; revend_next = curr->next; } curr = curr->next; i++; } revend->next = NULL; // Reverse linked list starting with revs. revend = reverse(revs); // If starting position was not head if (revs_prev) revs_prev->next = revend; // If starting position was head else head = revend; revs->next = revend_next; return head;} void print(Node* head){ while (head != NULL) { printf(\"%d \", head->data); head = head->next; } printf(\"\\n\");} // function to add a new node at the beginning of the listvoid push(Node** head_ref, int new_data){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Driver codeint main(){ Node* head = NULL; push(&head, 70); push(&head, 60); push(&head, 50); push(&head, 40); push(&head, 30); push(&head, 20); push(&head, 10); reverseBetween(head, 3, 6); print(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 29539,
"s": 27327,
"text": null
},
{
"code": "# Python3 program to reverse a linked list# from position m to position n # Linked list nodeclass Node: def __init__(self, data): self.data = data self.next = None # The standard reverse function used# to reverse a linked listdef reverse(head): prev = None curr = head while (curr): next = curr.next curr.next = prev prev = curr curr = next return prev # Function used to reverse a linked list# from position m to n which uses reverse# functiondef reverseBetween(head, m, n): if (m == n): return head # revs and revend is start and end respectively # of the portion of the linked list which # need to be reversed. revs_prev is previous # of starting position and revend_next is next # of end of list to be reversed. revs = None revs_prev = None revend = None revend_next = None # Find values of above pointers. i = 1 curr = head while (curr and i <= n): if (i < m): revs_prev = curr if (i == m): revs = curr if (i == n): revend = curr revend_next = curr.next curr = curr.next i += 1 revend.next = None # Reverse linked list starting with # revs. revend = reverse(revs) # If starting position was not head if (revs_prev): revs_prev.next = revend # If starting position was head else: head = revend revs.next = revend_next return head def prints(head): while (head != None): print(head.data, end = ' ') head = head.next print() # Function to add a new node at the# beginning of the listdef push(head_ref, new_data): new_node = Node(new_data) new_node.data = new_data new_node.next = (head_ref) (head_ref) = new_node return head_ref # Driver codeif __name__=='__main__': head = None head = push(head, 70) head = push(head, 60) head = push(head, 50) head = push(head, 40) head = push(head, 30) head = push(head, 20) head = push(head, 10) reverseBetween(head, 3, 6) prints(head) # This code is contributed by rutvik_56",
"e": 31735,
"s": 29539,
"text": null
},
{
"code": null,
"e": 31743,
"s": 31735,
"text": "Output:"
},
{
"code": null,
"e": 31764,
"s": 31743,
"text": "10 20 60 50 40 30 70"
},
{
"code": null,
"e": 32187,
"s": 31764,
"text": "This article is contributed by Akshit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32200,
"s": 32187,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32210,
"s": 32200,
"text": "rutvik_56"
},
{
"code": null,
"e": 32218,
"s": 32210,
"text": "Reverse"
},
{
"code": null,
"e": 32230,
"s": 32218,
"text": "Linked List"
},
{
"code": null,
"e": 32242,
"s": 32230,
"text": "Linked List"
},
{
"code": null,
"e": 32250,
"s": 32242,
"text": "Reverse"
},
{
"code": null,
"e": 32348,
"s": 32250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32357,
"s": 32348,
"text": "Comments"
},
{
"code": null,
"e": 32370,
"s": 32357,
"text": "Old Comments"
},
{
"code": null,
"e": 32416,
"s": 32370,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 32451,
"s": 32416,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 32494,
"s": 32451,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 32541,
"s": 32494,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 32602,
"s": 32541,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 32646,
"s": 32602,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 32701,
"s": 32646,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 32757,
"s": 32701,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 32798,
"s": 32757,
"text": "Write a function to delete a Linked List"
}
] |
Explain cherry picking in Git
|
Cherry picking is a way to choose specific commits from one branch and apply them to another branch. This is useful when you want to select specific changes from a pull request.
git cherry-pick {commit_hash}
The above command will cherry pick the commit associated with the specified commit hash to the current branch.
From the above commits shown in the diagram, we need to apply only commit F1 from the feature branch to the master branch.
In this case, the master branch after cherry picking will look as below.
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ git init
Initialized empty Git repository in E:/tut_repo/.git/
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello>hello.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add .
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -m 'hello'
[master (root-commit) cac1d77] hello
1 file changed, 1 insertion(+)
create mode 100644 hello.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello 2 >> hello.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -am 'c2'
[master 4f10a5d] c2
1 file changed, 1 insertion(+)
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git branch feature
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git switch feature
Switched to branch 'feature'
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ echo world>world.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git add .
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git commit -m 'F1'
[feature 9b5ddf0] F1
1 file changed, 1 insertion(+)
create mode 100644 world.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ echo world again>>world.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git commit -am 'F2'
[feature 629c15d] F2
1 file changed, 1 insertion(+)
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git checkout master
Switched to branch 'master'
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 629c15d (feature) F2
* 9b5ddf0 F1
* 4f10a5d (HEAD -> master) c2
* cac1d77 hello
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello3>>hello.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -am 'C3'
[master 81cdced] C3
1 file changed, 1 insertion(+)
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 81cdced (HEAD -> master) C3
| * 629c15d (feature) F2
| * 9b5ddf0 F1
|/
* 4f10a5d c2
* cac1d77 hello
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git cherry-pick 9b5ddf0
[master 693bff8] F1
Date: Tue Mar 30 13:43:50 2021 +0530
1 file changed, 1 insertion(+)
create mode 100644 world.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 693bff8 (HEAD -> master) F1
* 81cdced C3
| * 629c15d (feature) F2
| * 9b5ddf0 F1
|/
* 4f10a5d c2
* cac1d77 hello
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ ls
hello.txt world.txt
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ cat world.txt
world
|
[
{
"code": null,
"e": 1240,
"s": 1062,
"text": "Cherry picking is a way to choose specific commits from one branch and apply them to another branch. This is useful when you want to select specific changes from a pull request."
},
{
"code": null,
"e": 1270,
"s": 1240,
"text": "git cherry-pick {commit_hash}"
},
{
"code": null,
"e": 1381,
"s": 1270,
"text": "The above command will cherry pick the commit associated with the specified commit hash to the current branch."
},
{
"code": null,
"e": 1504,
"s": 1381,
"text": "From the above commits shown in the diagram, we need to apply only commit F1 from the feature branch to the master branch."
},
{
"code": null,
"e": 1577,
"s": 1504,
"text": "In this case, the master branch after cherry picking will look as below."
},
{
"code": null,
"e": 4112,
"s": 1577,
"text": "$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo\n$ git init\nInitialized empty Git repository in E:/tut_repo/.git/\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo hello>hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -m 'hello'\n[master (root-commit) cac1d77] hello\n1 file changed, 1 insertion(+)\ncreate mode 100644 hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo hello 2 >> hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -am 'c2'\n[master 4f10a5d] c2\n1 file changed, 1 insertion(+)\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git branch feature\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git switch feature\nSwitched to branch 'feature'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ echo world>world.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git add .\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git commit -m 'F1'\n[feature 9b5ddf0] F1\n1 file changed, 1 insertion(+)\ncreate mode 100644 world.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ echo world again>>world.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git commit -am 'F2'\n[feature 629c15d] F2\n1 file changed, 1 insertion(+)\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)\n$ git checkout master\nSwitched to branch 'master'\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* 629c15d (feature) F2\n* 9b5ddf0 F1\n* 4f10a5d (HEAD -> master) c2\n* cac1d77 hello\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ echo hello3>>hello.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git commit -am 'C3'\n[master 81cdced] C3\n1 file changed, 1 insertion(+)\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* 81cdced (HEAD -> master) C3\n| * 629c15d (feature) F2\n| * 9b5ddf0 F1\n|/\n* 4f10a5d c2\n* cac1d77 hello\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git cherry-pick 9b5ddf0\n[master 693bff8] F1\nDate: Tue Mar 30 13:43:50 2021 +0530\n1 file changed, 1 insertion(+)\ncreate mode 100644 world.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ git log --oneline --all --graph\n* 693bff8 (HEAD -> master) F1\n* 81cdced C3\n| * 629c15d (feature) F2\n| * 9b5ddf0 F1\n|/\n* 4f10a5d c2\n* cac1d77 hello\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ ls\nhello.txt world.txt\n\n$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)\n$ cat world.txt\nworld"
}
] |
DB2 - LDAP
|
LDAP is Lightweight Directory Access Protocol. LDAP is a global directory service, industry-standard protocol, which is based on client-server model and runs on a layer above the TCP/IP stack. The LDAP provides a facility to connect to, access, modify, and search the internet directory.
The LDAP servers contain information which is organized in the form of a directory tree. The clients ask server to provide information or to perform some operation on a particular information. The server answers the client by providing required information if it has one, or it refers the client to another server for action on required information. The client then acquires the desired information from another server.
The tree structure of directory is maintained same across all the participating servers. This is a prominent feature of LDAP directory service. Hence, irrespective of which server is referred to by the client, the client always gets required information in an error-free manner. Here, we use LDAP to authenticate IBM DB2 as a replacement of operating system authentication.
There are two types of LDAP:
Transparent
Plug-in
Transparent
Plug-in
Let us see how to configure a transparent LDAP.
To start with configuration of transparent LDAP, you need to configure the LDAP server.
Create a SLAPD.conf file, which contains all the information about users and group object in the LDAP. When you install LDAP server, by default it is configured with basic LDAP directory tree on your machine.
The table shown below indicates the file configuration after modification.
The text highlighted with yellow the code box means for the following:
DBA user-id = βdb2my1β, group = βdb1my1admβ, password= βdb2my1β Admin user-id = βmy1admβ, group = βdbmy1ctlβ.
# base dn: example.com
dn: dc=example,dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
# pc box db
dn: dc=db697,dc=example,dc=com
dc: db697
o: db697
objectClass: organization
objectClass: dcObject
#
# Group: dbadm
#
dn: cn=dbmy1adm,dc=db697,dc=example,dc=com
cn: dbmy1adm
objectClass: top
objectClass: posixGroup
gidNumber: 400
objectClass: groupOfNames
member: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com
memberUid: db2my1
#
# User: db2
#
dn: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com
cn: db2my1
sn: db2my1
uid: db2my1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 400
gidNumber: 400
loginShell: /bin/csh
homeDirectory: /db2/db2my1
#
# Group: dbctl
#
dn: cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: dbmy1ctl
objectClass: top
objectClass: posixGroup
gidNumber: 404
objectClass: groupOfNames
member: uid=my1adm,cn=dbmy1adm,dc=db697,dc=example,dc=com
memberUid: my1adm
#
# User: adm
#
dn: uid=my1adm,cn=dbmy1ctl,dc=db697,dc=example,dc=com
cn: my1adm
sn: my1adm
uid: my1adm
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 404
gidNumber: 404
loginShell: /bin/csh
homeDirectory: /home/my1adm
Save the above file with name β/var/lib/slapd.confβ, then execute this file by following command to add these values into LDAP Server. This is a linux command; not a db2 command.
ldapadd r- -D βcn=Manager,dc=example,dc=comβ βW βf
/var/lib/slapd.conf
After registering the DB2 users and the DB2 group at the LDAP Server, logon to the particular user where you have installed instance and database. You need to configure LDAP client to confirm to client where your server is located, be it remote or local.
The LDAP Client configuration is saved in the file βldap.confβ. There are two files available for configuration parameters, one is common and the other is specific. You should find the first one at β/etc/ldap.confβ and the latter is located at β/etc/openldap/ldap.confβ.
The following data is available in common LDAP client configuration file
# File: /etc/ldap.conf
# The file contains lots of more entries and many of them
# are comments. You show only the interesting values for now
host localhost
base dc=example,dc=com
ldap_version 3
pam_password crypt
pam_filter objectclass=posixAccount
nss_map_attribute uniqueMember member
nss_base_passwd dc=example,dc=com
nss_base_shadow dc=example,dc=com
nss_base_group dc=example,dc=com
You need to change the location of server and domain information according to the DB2 configuration. If we are using server in same system then mention it as βlocalhostβ at βhostβ and at βbaseβ you can configure which is mentioned in βSLAPD.confβ file for LDAP server.
Pluggable Authentication Model (PAM) is an API for authentication services. This is common interface for LDAP authentication with an encrypted password and special LDAP object of type posixAccount. All LDAP objects of this type represent an abstraction of an account with portable Operating System Interface (POSIX) attributes.
Network Security Services (NSS) is a set of libraries to support cross-platform development of security-enabled client and server applications. This includes libraries like SSL, TLS, PKCS S/MIME and other security standards.
You need to specify the base DN for this interface and two additional mapping attributes. OpenLDAP client configuration file contains the entries given below:
host localhost
base dc=example,dc=com
Till this you just define the host of LDAP serve and the base DN.
After you configured your LDAP Server and LDAP Client, verify both for communication.
Step1: Check your Local LDAP server is running. Using below command:
ps -ef | grep -i ldap
This command should list the LDAP deamon which represents your LDAP server:
/usr/lib/openldap/slapd -h ldap:/// -u ldap -g ldap -o slp=on
This indicates that you LDAP server is running and is waiting for request from clients. If there is no such process for previous commands you can start LDAP server with the βrcldapβ command.
rcldap start
When the server starts, you can monitor this in the file β/var/log/messages/ by issuing the following command.
tail βf /var/log/messages
The ldapsearch command opens a connection to an LDAP server, binds to it and performs a search query which can be specified by using special parameters β-xβ connect to your LDAP server with a simple authentication mechanism by using the βx parameter instead of a more complex mechanism like Simple Authentication and Security Layer (SASL)
ldapsearch βx
LDAP server should reply with a response given below, containing all of your LDAP entries in a LDAP Data Interchange Format(LDIF).
# extended LDIF
#
# LDAPv3
# base <> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
# example.com
dn: dc=example,
dc=com dc: example
o: example
objectClass: organization
objectClass: dcObject
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1
After working with LDAP server and client, you need to configure our DB2 database for use with LDAP. Let us discuss, how you can install and configure your database to use our LDAP environment for the DB2 user authentication process.
IBM provides a free package with LDAP plug-ins for DB2. The DB2 package includes three DB2 security plug-ins for each of the following:
server side authentication
client side authentication
group lookup
Depending upon your requirements, you can use any of the three plug-ins or all of them. This plugin do not support environments where some users are defined in LDAP and others in the operating Systems. If you decide to use the LDAP plug-ins, you need to define all users associated with the database in the LDAP server. The same principle applies to the group plug-in.
You have to decide which plug-ins are mandatory for our system. The client authentication plug-ins used in scenarios where the user ID and the password validation supplied on a CONNECT or ATTACH statement occurs on the client system. So the database manager configuration parameters SRVCON_AUTH or AUTHENTICATION need to be set to the value CLIENT. The client authentication is difficult to secure and is not generally recommended. Server plug-in is generally recommended because it performs a server side validation of user IDs and passwords, if the client executes a CONNECT or ATTACH statement and this is secure way. The server plug-in also provides a way to map LDAP user IDs DB2 authorization IDs.
Now you can start installation and configuration of the DB2 security plug-ins, you need to think about the required directory information tree for DB2. DB2 uses indirect authorization which means that a user belongs to a group and this group was granted with fewer authorities. You need to define all DB2 users and DB2 groups in LDAP directory.
The LDIF file openldap.ldif should contain the code below:
#
# LDAP root object
# example.com
#
dn: dc=example,
dc=com
dc: example
o: example
objectClass: organization
objectClass: dcObject
#
# db2 groups
#
dn: cn=dasadm1,dc=example,dc=com
cn: dasadm1
objectClass: top
objectClass: posixGroup
gidNumber: 300
objectClass: groupOfNames
member: uid=dasusr1,cn=dasadm1,dc=example,dc=com
memberUid: dasusr1
dn: cn=db2grp1,dc=example,dc=com
cn: db2grp1
objectClass: top
objectClass: posixGroup
gidNumber: 301
objectClass: groupOfNames
member: uid=db2inst2,cn=db2grp1,dc=example,dc=com memberUid: db2inst2
dn: cn=db2fgrp1,dc=example,dc=com
cn: db2fgrp1
objectClass: top
objectClass: posixGroup
gidNumber: 302
objectClass: groupOfNames
member: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
memberUid: db2fenc1
#
# db2 users
#
dn: uid=dasusr1,
cn=dasadm1,
dc=example,dc=com
cn: dasusr1
sn: dasusr1
uid: dasusr1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 300
gidNumber: 300
loginShell: /bin/bash
homeDirectory: /home/dasusr1
dn: uid=db2inst2,cn=db2grp1,dc=example,dc=com
cn: db2inst2
sn: db2inst2
uid: db2inst2
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 301
gidNumber: 301
loginShell: /bin/bash
homeDirectory: /home/db2inst2
dn: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com
cn: db2fenc1
sn: db2fenc1
uid: db2fenc1
objectClass: top
objectClass: inetOrgPerson
objectClass: posixAccount
uidNumber: 303
gidNumber: 303
loginShell: /bin/bash
homeDirectory: /home/db2fenc1
Create a file named βdb2.ldifβ and paste the above example into it. Using this file, add the defined structures to your LDAP directory.
To add the DB2 users and DB2 groups to the LDAP directory, you need to bind the user as βrootdnβ to the LDAP server in order to get the exact privileges.
Execute the following syntaxes to fill the LDAP information directory with all our objects defined in the LDIF file βdb2.ldifβ
ldapadd βx βD βcn=Manager, dc=example,dc=comβ βW βf <path>/db2.ldif
Perform the search result with more parameter
ldapsearch βx |more
Creating instance for our LDAP user db2inst2. This user requires home directory with two empty files inside the home directory. Before you create a new instance, you need to create a user who will be the owner of the instance.
After creating the instance user, you should have to create the file β.profileβ and β.loginβ in user home directory, which will be modified by DB2. To create this file in the directory, execute the following command:
mkdir /home/db2inst2
mkdir /home/db2inst2/.login
mkdir /home/db2inst2/.profile
You have registered all users and groups related with DB2 in LDAP directory, now you can create an instance with the name βdb2inst2β with the instance owner id βdb2inst2β and use the fenced user id βdb2fenc1β, which is needed for running user defined functions (UDFs)or stored procedures.
/opt/ibm/db2/V10.1/instance/db2icrt βu db2fenc1 db2inst2
DBI1070I Program db2icrt completed successfully.
Now check the instance home directory. You can see new sub-directory called βsqllibβ and the .profile and .login files customized for DB2 usage.
Copy the required LDAP plug-ins to the appropriate DB2 directory:
cp ///v10/IBMLDAPauthserver.so
/home/db2inst2/sqllib/security/plugin/server/.
cp ///v10/IBMLDAPgroups.so
/home/db2inst2/sqllib/security/plugin/group/.
Once the plug-ins are copied to the specified directory, you toned to login to DB2 instance owner and change the database manager configuration to use these plug-ins.
Su β db2inst2
db2inst2> db2 update dbm cfg using svrcon_pw_plugin
IBMLDAPauthserver
db2inst2> db2 update dbm cfg using group_plugin
IBMLDAPgroups
db2inst2> db2 update dbm cfg using authentication
SERVER_ENCRYPT
db2inst2> db2stop
db2inst2> db2start
This modification comes into effect after you start DB2 instance. After restarting the instance, you need to install and configure the main DB2 LDAP configuration file named βIBMLDAPSecurity.iniβ to make DB2 plug-ins work with the current LDAP configuration.
IBMLDAPSecurity.ini file contains
;-----------------------------------------------------------
; SERVER RELATED VALUES
;-----------------------------------------------------------
; Name of your LDAP server(s).
; This is a space separated list of LDAP server addresses,
; with an optional port number for each one:
; host1[:port] [host2:[port2] ... ]
; The default port number is 389, or 636 if SSL is enabled.
LDAP_HOST = my.ldap.server
;-----------------------------------------------------------
; USER RELATED VALUES
;-----------------------------------------------------------
rs
; LDAP object class used for use USER_OBJECTCLASS = posixAccount
; LDAP user attribute that represents the "userid"
; This attribute is combined with the USER_OBJECTCLASS and
; USER_BASEDN (if specified) to construct an LDAP search
; filter when a user issues a DB2 CONNECT statement with an
; unqualified userid. For example, using the default values
; in this configuration file, (db2 connect to MYDB user bob
; using bobpass) results in the following search filter:
OrgPerson)(uid=bob)
; &(objectClass=inet USERID_ATTRIBUTE = uid
representing the DB2 authorization ID
; LDAP user attribute, AUTHID_ATTRIBUTE = uid
;-----------------------------------------------------------
; GROUP RELATED VALUES
;-----------------------------------------------------------
ps
; LDAP object class used for grou GROUP_OBJECTCLASS = groupOfNames
at represents the name of the group
; LDAP group attribute th GROUPNAME_ATTRIBUTE = cn
; Determines the method used to find the group memberships
; for a user. Possible values are:
; SEARCH_BY_DN - Search for groups that list the user as
; a member. Membership is indicated by the
; group attribute defined as
; GROUP_LOOKUP_ATTRIBUTE.
; USER_ATTRIBUTE - A user's groups are listed as attributes
; of the user object itself. Search for the
; user attribute defined as
TRIBUTE to get the groups.
; GROUP_LOOKUP_AT GROUP_LOOKUP_METHOD = SEARCH_BY_DN
; GROUP_LOOKUP_ATTRIBUTE
; Name of the attribute used to determine group membership,
; as described above.
llGroups
; GROUP_LOOKUP_ATTRIBUTE = ibm-a GROUP_LOOKUP_ATTRIBUTE = member
Now locate the file IBMLDAPSecurity.ini file in the current instance directory. Copy the above sample contents into the same.
Cp
//db2_ldap_pkg/IBMLDAPSecurity.ini
/home/db2inst2/sqllib/cfg/
Now you need to restart your DB2 instance, using two syntaxes given below:
db2inst2> db2stop
Db2inst2> db2start
At this point, if you try βdb2startβ command, you will get security error message. Because, DB2 security configuration is not yet correctly configured for your LDAP environment.
Keep LDAP_HOST name handy, which is configured in slapd.conf file.
Now edit IMBLDAPSecurity.ini file and type the LDAP_HOST name. The LDAP_HOST name in both the said files must be identical.
The contents of file are as shown below:
;-----------------------------------------------------------
; SERVER RELATED VALUES
;-----------------------------------------------------------
LDAP_HOST = localhost
;-----------------------------------------------------------
; USER RELATED VALUES
----------------------------
;-------------------------------
USER_OBJECTCLASS = posixAccount
USER_BASEDN = dc=example,dc=com
USERID_ATTRIBUTE = uid
AUTHID_ATTRIBUTE = uid
;-----------------------------------------------------------
; GROUP RELATED VALUES
;-----------------------------------------------------------
GROUP_OBJECTCLASS = groupOfNames
GROUP_BASEDN = dc=example,dc=com
GROUPNAME_ATTRIBUTE = cn
GROUP_LOOKUP_METHOD = SEARCH_BY_DN
GROUP_LOOKUP_ATTRIBUTE = member
After changing these values, LDAP immediately takes effect and your DB2 environment with LDAP works perfectly.
You can logout and login again to βdb2inst2β user.
Now your instance is working with LDAP directory.
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2216,
"s": 1928,
"text": "LDAP is Lightweight Directory Access Protocol. LDAP is a global directory service, industry-standard protocol, which is based on client-server model and runs on a layer above the TCP/IP stack. The LDAP provides a facility to connect to, access, modify, and search the internet directory."
},
{
"code": null,
"e": 2636,
"s": 2216,
"text": "The LDAP servers contain information which is organized in the form of a directory tree. The clients ask server to provide information or to perform some operation on a particular information. The server answers the client by providing required information if it has one, or it refers the client to another server for action on required information. The client then acquires the desired information from another server."
},
{
"code": null,
"e": 3010,
"s": 2636,
"text": "The tree structure of directory is maintained same across all the participating servers. This is a prominent feature of LDAP directory service. Hence, irrespective of which server is referred to by the client, the client always gets required information in an error-free manner. Here, we use LDAP to authenticate IBM DB2 as a replacement of operating system authentication."
},
{
"code": null,
"e": 3039,
"s": 3010,
"text": "There are two types of LDAP:"
},
{
"code": null,
"e": 3061,
"s": 3039,
"text": "\nTransparent\nPlug-in\n"
},
{
"code": null,
"e": 3073,
"s": 3061,
"text": "Transparent"
},
{
"code": null,
"e": 3081,
"s": 3073,
"text": "Plug-in"
},
{
"code": null,
"e": 3129,
"s": 3081,
"text": "Let us see how to configure a transparent LDAP."
},
{
"code": null,
"e": 3217,
"s": 3129,
"text": "To start with configuration of transparent LDAP, you need to configure the LDAP server."
},
{
"code": null,
"e": 3426,
"s": 3217,
"text": "Create a SLAPD.conf file, which contains all the information about users and group object in the LDAP. When you install LDAP server, by default it is configured with basic LDAP directory tree on your machine."
},
{
"code": null,
"e": 3501,
"s": 3426,
"text": "The table shown below indicates the file configuration after modification."
},
{
"code": null,
"e": 3572,
"s": 3501,
"text": "The text highlighted with yellow the code box means for the following:"
},
{
"code": null,
"e": 3682,
"s": 3572,
"text": "DBA user-id = βdb2my1β, group = βdb1my1admβ, password= βdb2my1β Admin user-id = βmy1admβ, group = βdbmy1ctlβ."
},
{
"code": null,
"e": 4941,
"s": 3682,
"text": "# base dn: example.com \ndn: dc=example,dc=com \ndc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n# pc box db \ndn: dc=db697,dc=example,dc=com \ndc: db697 \no: db697 \nobjectClass: organization \nobjectClass: dcObject \n# \n# Group: dbadm \n# \ndn: cn=dbmy1adm,dc=db697,dc=example,dc=com \ncn: dbmy1adm \nobjectClass: top \nobjectClass: posixGroup \ngidNumber: 400 \nobjectClass: groupOfNames \nmember: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com \nmemberUid: db2my1 \n# \n# User: db2 \n# \ndn: uid=db2my1,cn=dbmy1adm,dc=db697,dc=example,dc=com \ncn: db2my1 \nsn: db2my1 \nuid: db2my1 \nobjectClass: top \nobjectClass: inetOrgPerson \nobjectClass: posixAccount \nuidNumber: 400 \ngidNumber: 400 \nloginShell: /bin/csh \nhomeDirectory: /db2/db2my1 \n# \n# Group: dbctl \n# \ndn: cn=dbmy1ctl,dc=db697,dc=example,dc=com \ncn: dbmy1ctl \nobjectClass: top \nobjectClass: posixGroup \ngidNumber: 404 \nobjectClass: groupOfNames \nmember: uid=my1adm,cn=dbmy1adm,dc=db697,dc=example,dc=com \nmemberUid: my1adm \n# \n# User: adm \n# \ndn: uid=my1adm,cn=dbmy1ctl,dc=db697,dc=example,dc=com \ncn: my1adm \nsn: my1adm \nuid: my1adm \nobjectClass: top \nobjectClass: inetOrgPerson \nobjectClass: posixAccount \nuidNumber: 404 \ngidNumber: 404 \nloginShell: /bin/csh \nhomeDirectory: /home/my1adm "
},
{
"code": null,
"e": 5120,
"s": 4941,
"text": "Save the above file with name β/var/lib/slapd.confβ, then execute this file by following command to add these values into LDAP Server. This is a linux command; not a db2 command."
},
{
"code": null,
"e": 5193,
"s": 5120,
"text": "ldapadd r- -D βcn=Manager,dc=example,dc=comβ βW βf \n/var/lib/slapd.conf "
},
{
"code": null,
"e": 5448,
"s": 5193,
"text": "After registering the DB2 users and the DB2 group at the LDAP Server, logon to the particular user where you have installed instance and database. You need to configure LDAP client to confirm to client where your server is located, be it remote or local."
},
{
"code": null,
"e": 5722,
"s": 5448,
"text": "The LDAP Client configuration is saved in the file βldap.confβ. There are two files available for configuration parameters, one is common and the other is specific. You should find the first one at β/etc/ldap.confβ and the latter is located at β/etc/openldap/ldap.confβ."
},
{
"code": null,
"e": 5795,
"s": 5722,
"text": "The following data is available in common LDAP client configuration file"
},
{
"code": null,
"e": 6206,
"s": 5795,
"text": "# File: /etc/ldap.conf \n# The file contains lots of more entries and many of them \n# are comments. You show only the interesting values for now \nhost localhost \nbase dc=example,dc=com \nldap_version 3 \npam_password crypt \npam_filter objectclass=posixAccount \nnss_map_attribute uniqueMember member \nnss_base_passwd dc=example,dc=com \nnss_base_shadow dc=example,dc=com \nnss_base_group dc=example,dc=com "
},
{
"code": null,
"e": 6475,
"s": 6206,
"text": "You need to change the location of server and domain information according to the DB2 configuration. If we are using server in same system then mention it as βlocalhostβ at βhostβ and at βbaseβ you can configure which is mentioned in βSLAPD.confβ file for LDAP server."
},
{
"code": null,
"e": 6803,
"s": 6475,
"text": "Pluggable Authentication Model (PAM) is an API for authentication services. This is common interface for LDAP authentication with an encrypted password and special LDAP object of type posixAccount. All LDAP objects of this type represent an abstraction of an account with portable Operating System Interface (POSIX) attributes."
},
{
"code": null,
"e": 7028,
"s": 6803,
"text": "Network Security Services (NSS) is a set of libraries to support cross-platform development of security-enabled client and server applications. This includes libraries like SSL, TLS, PKCS S/MIME and other security standards."
},
{
"code": null,
"e": 7187,
"s": 7028,
"text": "You need to specify the base DN for this interface and two additional mapping attributes. OpenLDAP client configuration file contains the entries given below:"
},
{
"code": null,
"e": 7227,
"s": 7187,
"text": "host localhost \nbase dc=example,dc=com"
},
{
"code": null,
"e": 7293,
"s": 7227,
"text": "Till this you just define the host of LDAP serve and the base DN."
},
{
"code": null,
"e": 7379,
"s": 7293,
"text": "After you configured your LDAP Server and LDAP Client, verify both for communication."
},
{
"code": null,
"e": 7448,
"s": 7379,
"text": "Step1: Check your Local LDAP server is running. Using below command:"
},
{
"code": null,
"e": 7470,
"s": 7448,
"text": "ps -ef | grep -i ldap"
},
{
"code": null,
"e": 7546,
"s": 7470,
"text": "This command should list the LDAP deamon which represents your LDAP server:"
},
{
"code": null,
"e": 7608,
"s": 7546,
"text": "/usr/lib/openldap/slapd -h ldap:/// -u ldap -g ldap -o slp=on"
},
{
"code": null,
"e": 7799,
"s": 7608,
"text": "This indicates that you LDAP server is running and is waiting for request from clients. If there is no such process for previous commands you can start LDAP server with the βrcldapβ command."
},
{
"code": null,
"e": 7813,
"s": 7799,
"text": "rcldap start "
},
{
"code": null,
"e": 7924,
"s": 7813,
"text": "When the server starts, you can monitor this in the file β/var/log/messages/ by issuing the following command."
},
{
"code": null,
"e": 7951,
"s": 7924,
"text": "tail βf /var/log/messages "
},
{
"code": null,
"e": 8290,
"s": 7951,
"text": "The ldapsearch command opens a connection to an LDAP server, binds to it and performs a search query which can be specified by using special parameters β-xβ connect to your LDAP server with a simple authentication mechanism by using the βx parameter instead of a more complex mechanism like Simple Authentication and Security Layer (SASL)"
},
{
"code": null,
"e": 8306,
"s": 8290,
"text": "ldapsearch βx "
},
{
"code": null,
"e": 8437,
"s": 8306,
"text": "LDAP server should reply with a response given below, containing all of your LDAP entries in a LDAP Data Interchange Format(LDIF)."
},
{
"code": null,
"e": 8755,
"s": 8437,
"text": "# extended LDIF \n# \n# LDAPv3 \n# base <> with scope subtree \n# filter: (objectclass=*) \n# requesting: ALL \n# example.com \ndn: dc=example,\ndc=com dc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n# search result \nsearch: 2 \nresult: 0 Success \n# numResponses: 2 \n# numEntries: 1 "
},
{
"code": null,
"e": 8990,
"s": 8755,
"text": "After working with LDAP server and client, you need to configure our DB2 database for use with LDAP. Let us discuss, how you can install and configure your database to use our LDAP environment for the DB2 user authentication process."
},
{
"code": null,
"e": 9126,
"s": 8990,
"text": "IBM provides a free package with LDAP plug-ins for DB2. The DB2 package includes three DB2 security plug-ins for each of the following:"
},
{
"code": null,
"e": 9153,
"s": 9126,
"text": "server side authentication"
},
{
"code": null,
"e": 9180,
"s": 9153,
"text": "client side authentication"
},
{
"code": null,
"e": 9193,
"s": 9180,
"text": "group lookup"
},
{
"code": null,
"e": 9562,
"s": 9193,
"text": "Depending upon your requirements, you can use any of the three plug-ins or all of them. This plugin do not support environments where some users are defined in LDAP and others in the operating Systems. If you decide to use the LDAP plug-ins, you need to define all users associated with the database in the LDAP server. The same principle applies to the group plug-in."
},
{
"code": null,
"e": 10266,
"s": 9562,
"text": "You have to decide which plug-ins are mandatory for our system. The client authentication plug-ins used in scenarios where the user ID and the password validation supplied on a CONNECT or ATTACH statement occurs on the client system. So the database manager configuration parameters SRVCON_AUTH or AUTHENTICATION need to be set to the value CLIENT. The client authentication is difficult to secure and is not generally recommended. Server plug-in is generally recommended because it performs a server side validation of user IDs and passwords, if the client executes a CONNECT or ATTACH statement and this is secure way. The server plug-in also provides a way to map LDAP user IDs DB2 authorization IDs."
},
{
"code": null,
"e": 10611,
"s": 10266,
"text": "Now you can start installation and configuration of the DB2 security plug-ins, you need to think about the required directory information tree for DB2. DB2 uses indirect authorization which means that a user belongs to a group and this group was granted with fewer authorities. You need to define all DB2 users and DB2 groups in LDAP directory."
},
{
"code": null,
"e": 10670,
"s": 10611,
"text": "The LDIF file openldap.ldif should contain the code below:"
},
{
"code": null,
"e": 12339,
"s": 10670,
"text": "# \n# LDAP root object \n# example.com \n# \ndn: dc=example,\ndc=com \ndc: example \no: example \nobjectClass: organization \nobjectClass: dcObject \n # \n # db2 groups \n # \n dn: cn=dasadm1,dc=example,dc=com \n cn: dasadm1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 300 \n objectClass: groupOfNames \n member: uid=dasusr1,cn=dasadm1,dc=example,dc=com \n memberUid: dasusr1 \n dn: cn=db2grp1,dc=example,dc=com \n cn: db2grp1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 301 \n objectClass: groupOfNames \n member: uid=db2inst2,cn=db2grp1,dc=example,dc=com memberUid: db2inst2 \n dn: cn=db2fgrp1,dc=example,dc=com \n cn: db2fgrp1 \n objectClass: top \n objectClass: posixGroup \n gidNumber: 302 \n objectClass: groupOfNames \n member: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com \n memberUid: db2fenc1 \n # \n # db2 users \n # \n dn: uid=dasusr1,\n cn=dasadm1,\n dc=example,dc=com \n cn: dasusr1 \n sn: dasusr1 \n uid: dasusr1 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 300 \n gidNumber: 300 \n loginShell: /bin/bash \n homeDirectory: /home/dasusr1 \n dn: uid=db2inst2,cn=db2grp1,dc=example,dc=com \n cn: db2inst2 \n sn: db2inst2 \n uid: db2inst2 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 301 \n gidNumber: 301 \n loginShell: /bin/bash \n homeDirectory: /home/db2inst2 \n dn: uid=db2fenc1,cn=db2fgrp1,dc=example,dc=com \n cn: db2fenc1 \n sn: db2fenc1 \n uid: db2fenc1 \n objectClass: top \n objectClass: inetOrgPerson \n objectClass: posixAccount \n uidNumber: 303 \n gidNumber: 303 \n loginShell: /bin/bash \n homeDirectory: /home/db2fenc1 \n "
},
{
"code": null,
"e": 12475,
"s": 12339,
"text": "Create a file named βdb2.ldifβ and paste the above example into it. Using this file, add the defined structures to your LDAP directory."
},
{
"code": null,
"e": 12629,
"s": 12475,
"text": "To add the DB2 users and DB2 groups to the LDAP directory, you need to bind the user as βrootdnβ to the LDAP server in order to get the exact privileges."
},
{
"code": null,
"e": 12756,
"s": 12629,
"text": "Execute the following syntaxes to fill the LDAP information directory with all our objects defined in the LDIF file βdb2.ldifβ"
},
{
"code": null,
"e": 12825,
"s": 12756,
"text": "ldapadd βx βD βcn=Manager, dc=example,dc=comβ βW βf <path>/db2.ldif "
},
{
"code": null,
"e": 12871,
"s": 12825,
"text": "Perform the search result with more parameter"
},
{
"code": null,
"e": 12892,
"s": 12871,
"text": "ldapsearch βx |more "
},
{
"code": null,
"e": 13119,
"s": 12892,
"text": "Creating instance for our LDAP user db2inst2. This user requires home directory with two empty files inside the home directory. Before you create a new instance, you need to create a user who will be the owner of the instance."
},
{
"code": null,
"e": 13337,
"s": 13119,
"text": "After creating the instance user, you should have to create the file β.profileβ and β.loginβ in user home directory, which will be modified by DB2. To create this file in the directory, execute the following command:"
},
{
"code": null,
"e": 13421,
"s": 13337,
"text": "mkdir /home/db2inst2 \nmkdir /home/db2inst2/.login \nmkdir /home/db2inst2/.profile "
},
{
"code": null,
"e": 13710,
"s": 13421,
"text": "You have registered all users and groups related with DB2 in LDAP directory, now you can create an instance with the name βdb2inst2β with the instance owner id βdb2inst2β and use the fenced user id βdb2fenc1β, which is needed for running user defined functions (UDFs)or stored procedures."
},
{
"code": null,
"e": 13820,
"s": 13710,
"text": "/opt/ibm/db2/V10.1/instance/db2icrt βu db2fenc1 db2inst2 \nDBI1070I Program db2icrt completed successfully. "
},
{
"code": null,
"e": 13965,
"s": 13820,
"text": "Now check the instance home directory. You can see new sub-directory called βsqllibβ and the .profile and .login files customized for DB2 usage."
},
{
"code": null,
"e": 14031,
"s": 13965,
"text": "Copy the required LDAP plug-ins to the appropriate DB2 directory:"
},
{
"code": null,
"e": 14210,
"s": 14031,
"text": "cp ///v10/IBMLDAPauthserver.so \n/home/db2inst2/sqllib/security/plugin/server/. \n \ncp ///v10/IBMLDAPgroups.so \n/home/db2inst2/sqllib/security/plugin/group/."
},
{
"code": null,
"e": 14377,
"s": 14210,
"text": "Once the plug-ins are copied to the specified directory, you toned to login to DB2 instance owner and change the database manager configuration to use these plug-ins."
},
{
"code": null,
"e": 14636,
"s": 14377,
"text": "Su β db2inst2 \ndb2inst2> db2 update dbm cfg using svrcon_pw_plugin \nIBMLDAPauthserver \ndb2inst2> db2 update dbm cfg using group_plugin \nIBMLDAPgroups \ndb2inst2> db2 update dbm cfg using authentication \nSERVER_ENCRYPT \ndb2inst2> db2stop \ndb2inst2> db2start "
},
{
"code": null,
"e": 14895,
"s": 14636,
"text": "This modification comes into effect after you start DB2 instance. After restarting the instance, you need to install and configure the main DB2 LDAP configuration file named βIBMLDAPSecurity.iniβ to make DB2 plug-ins work with the current LDAP configuration."
},
{
"code": null,
"e": 14929,
"s": 14895,
"text": "IBMLDAPSecurity.ini file contains"
},
{
"code": null,
"e": 17134,
"s": 14929,
"text": ";----------------------------------------------------------- \n; SERVER RELATED VALUES \n;----------------------------------------------------------- \n; Name of your LDAP server(s). \n; This is a space separated list of LDAP server addresses, \n; with an optional port number for each one: \n; host1[:port] [host2:[port2] ... ] \n; The default port number is 389, or 636 if SSL is enabled. \nLDAP_HOST = my.ldap.server \n;----------------------------------------------------------- \n; USER RELATED VALUES \n;----------------------------------------------------------- \nrs \n; LDAP object class used for use USER_OBJECTCLASS = posixAccount \n; LDAP user attribute that represents the \"userid\" \n; This attribute is combined with the USER_OBJECTCLASS and \n; USER_BASEDN (if specified) to construct an LDAP search \n; filter when a user issues a DB2 CONNECT statement with an \n; unqualified userid. For example, using the default values \n; in this configuration file, (db2 connect to MYDB user bob \n; using bobpass) results in the following search filter: \nOrgPerson)(uid=bob) \n; &(objectClass=inet USERID_ATTRIBUTE = uid \nrepresenting the DB2 authorization ID \n; LDAP user attribute, AUTHID_ATTRIBUTE = uid \n;----------------------------------------------------------- \n; GROUP RELATED VALUES \n;----------------------------------------------------------- \nps \n; LDAP object class used for grou GROUP_OBJECTCLASS = groupOfNames \nat represents the name of the group \n; LDAP group attribute th GROUPNAME_ATTRIBUTE = cn \n; Determines the method used to find the group memberships \n; for a user. Possible values are: \n; SEARCH_BY_DN - Search for groups that list the user as \n; a member. Membership is indicated by the \n; group attribute defined as \n; GROUP_LOOKUP_ATTRIBUTE. \n; USER_ATTRIBUTE - A user's groups are listed as attributes \n; of the user object itself. Search for the \n; user attribute defined as \nTRIBUTE to get the groups. \n; GROUP_LOOKUP_AT GROUP_LOOKUP_METHOD = SEARCH_BY_DN \n; GROUP_LOOKUP_ATTRIBUTE \n; Name of the attribute used to determine group membership, \n; as described above. \nllGroups \n; GROUP_LOOKUP_ATTRIBUTE = ibm-a GROUP_LOOKUP_ATTRIBUTE = member "
},
{
"code": null,
"e": 17260,
"s": 17134,
"text": "Now locate the file IBMLDAPSecurity.ini file in the current instance directory. Copy the above sample contents into the same."
},
{
"code": null,
"e": 17329,
"s": 17260,
"text": "Cp \n//db2_ldap_pkg/IBMLDAPSecurity.ini \n/home/db2inst2/sqllib/cfg/ "
},
{
"code": null,
"e": 17404,
"s": 17329,
"text": "Now you need to restart your DB2 instance, using two syntaxes given below:"
},
{
"code": null,
"e": 17444,
"s": 17404,
"text": "db2inst2> db2stop \n\nDb2inst2> db2start "
},
{
"code": null,
"e": 17622,
"s": 17444,
"text": "At this point, if you try βdb2startβ command, you will get security error message. Because, DB2 security configuration is not yet correctly configured for your LDAP environment."
},
{
"code": null,
"e": 17689,
"s": 17622,
"text": "Keep LDAP_HOST name handy, which is configured in slapd.conf file."
},
{
"code": null,
"e": 17813,
"s": 17689,
"text": "Now edit IMBLDAPSecurity.ini file and type the LDAP_HOST name. The LDAP_HOST name in both the said files must be identical."
},
{
"code": null,
"e": 17854,
"s": 17813,
"text": "The contents of file are as shown below:"
},
{
"code": null,
"e": 18735,
"s": 17854,
"text": " ;----------------------------------------------------------- \n ; SERVER RELATED VALUES \n ;----------------------------------------------------------- \n LDAP_HOST = localhost \n ;----------------------------------------------------------- \n ; USER RELATED VALUES \n ---------------------------- \n ;------------------------------- \n USER_OBJECTCLASS = posixAccount \n USER_BASEDN = dc=example,dc=com \n USERID_ATTRIBUTE = uid \n AUTHID_ATTRIBUTE = uid \n ;----------------------------------------------------------- \n ; GROUP RELATED VALUES \n ;----------------------------------------------------------- \n GROUP_OBJECTCLASS = groupOfNames \n\t GROUP_BASEDN = dc=example,dc=com \n GROUPNAME_ATTRIBUTE = cn \n GROUP_LOOKUP_METHOD = SEARCH_BY_DN \n GROUP_LOOKUP_ATTRIBUTE = member "
},
{
"code": null,
"e": 18846,
"s": 18735,
"text": "After changing these values, LDAP immediately takes effect and your DB2 environment with LDAP works perfectly."
},
{
"code": null,
"e": 18897,
"s": 18846,
"text": "You can logout and login again to βdb2inst2β user."
},
{
"code": null,
"e": 18947,
"s": 18897,
"text": "Now your instance is working with LDAP directory."
},
{
"code": null,
"e": 18982,
"s": 18947,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 18997,
"s": 18982,
"text": " Nishant Malik"
},
{
"code": null,
"e": 19032,
"s": 18997,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 19047,
"s": 19032,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 19083,
"s": 19047,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 19098,
"s": 19083,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 19131,
"s": 19098,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 19146,
"s": 19131,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 19179,
"s": 19146,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 19198,
"s": 19179,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 19235,
"s": 19198,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 19254,
"s": 19235,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 19261,
"s": 19254,
"text": " Print"
},
{
"code": null,
"e": 19272,
"s": 19261,
"text": " Add Notes"
}
] |
Extract Rows/Columns from A Dataframe in Python & R | by Yufeng | Towards Data Science
|
Iβve been working with data for long. However, I sometimes still need to google βHow to extract rows/columns from a data frame in Python/R?β when I change from one language environment to the other.
I am pretty sure that I have done the same for thousands of times, but it seems that my brain refuses to store the commands in memory.
You must know my feeling if you need to work with R and Python simultaneously for data manipulation.
Therefore, I would like to summarize in this article the usage of R and Python in extracting rows/columns from a data frame and make a simple cheat sheet image for the people who need it.
To note, I will only use Pandas in Python and basic functions in R for the purpose of comparing the command lines side by side. Some comprehensive library, βdplyrβ for example, is not considered. And I am trying my best to keep the article short.
Letβs begin.
We will use a toy dataset of Allen Iversonβs game stats in the entire article. The dimension and head of the data frame are shown below.
# Rdim(df)head(df)
# Pythondf.shapedf.head()
First, letβs extract the rows from the data frame in both R and Python. In R, it is done by simple indexing, but in Python, it is done by .iloc. Letβs check the examples below.
# R## Extract the third rowdf[3,]## Extract the first three rowsdf[1:3,]### or ###df[c(1,2,3),]
which yields,
# Python## Extract the third rowdf.iloc[2]### or ###df.iloc[2,]### or ###df.iloc[2,:]## Extract the first three rowsdf.iloc[:3]### or ###df.iloc[0:3]### or ###df.iloc[0:3,:]
which yields,
Please note that in the example of extracting a single row from the data frame, the output in R is still in the data frame format, but the output in Python is in the Pandas Series format. This is an essential difference between R and Python in extracting a single row from a data frame.
Similarly, we can extract columns from the data frame.
# R## Extract the 5th columndf[,5]## Extract the first 5 columnsdf[,1:5]
which yields,
# Python## Extract the 5th columndf.iloc[:,4]## Extract the first 5 columnsdf.iloc[:,:5]### or ###df.iloc[:,0:5]
which yields,
When extracting the column, we have to put both the colon and comma in the row position within the square bracket, which is a big difference from extracting rows.
In our dataset, the row and column index of the data frame is the NBA season and Iversonβs stats, respectively. We can use those to extract specific rows/columns from the data frame.
For example, we are interested in the season 1999β2000.
# R## Extract 1999-2000 season.df["1999-00",]## Extract 1999-2000 and 2001-2002 seasons.df[c("1999-00","2000-01"),]
which yields,
# Python## Extract 1999-2000 season.df.loc["1999-00"]## Extract 1999-2000 and 2001-2002 seasons.df.loc[["1999-00","2000-01"]]
which yields,
Please note again that in Python, the output is in Pandas Series format if we extract only one row/column, but it will be Pandas DataFrame format if we extract multiple rows/columns.
When we are only interested in a subset of columns, we can also add the column index.
# R## Extract Iverson's team and minutes played in the 1999-2000 season.df["1999-00",c("Tm","MP")]
which yields,
# Python## Extract Iverson's team and minutes played in the 1999-2000 season.df.loc["1999-00",["Tm","MP"]]
which yields,
In addition to extracting rows/columns by index, we can also do the subsetting based on conditions. For example, we want to extract the seasons in which Iverson has played more than 3000 minutes.
# R## Extract MP over 3kdf[df$MP > 3000,] ## the comma cannot be omitted
which yields,
# Python## Extract MP over 3kdf.loc[df.MP > 3000,:] ## both the comma and colon can be omitted
which yields,
Of course, more complicated conditions can be passed to the square bracket, which only needs a True/False list with the length of the row number of the data frame.
For example, we want to extract the seasons in which Iversonβs true shooting percentage (TS%) is over 50%, minutes played is over 3000, and position (Pos) is either shooting guard (SG) or point guard (PG).
# R## Extract rows with TS.> 50%, MP > 3000 and Pos is SG/PG### define condition as cond_cond_ = (df$TS. > 0.5) & (df$MP > 3000) & (df$Pos %in% c("SG","PG"))df[cond_,]
which yields,
# Python## Extract rows with TS.> 50%, MP> 3000 and Pos is SG/PG### define condition as cond_cond_ = (df["TS."] > 0.5) & (df["MP"] > 3000) & (df["Pos"].isin(["SG","PG"]))df.loc[cond_,:] ## both the comma and colon can be omitted
which yields,
We can apply any kind of boolean values in the βcond_β position.
Here is the cheat sheet that I hope can save your time when you work with both Python and R as I do.
Thatβs it! A simple summary of table slicing in R/Pandas. I hope it helps!
Thank you for reading! If you like the article, please follow me on Medium. Here are some of my previous articles in data science:
|
[
{
"code": null,
"e": 371,
"s": 172,
"text": "Iβve been working with data for long. However, I sometimes still need to google βHow to extract rows/columns from a data frame in Python/R?β when I change from one language environment to the other."
},
{
"code": null,
"e": 506,
"s": 371,
"text": "I am pretty sure that I have done the same for thousands of times, but it seems that my brain refuses to store the commands in memory."
},
{
"code": null,
"e": 607,
"s": 506,
"text": "You must know my feeling if you need to work with R and Python simultaneously for data manipulation."
},
{
"code": null,
"e": 795,
"s": 607,
"text": "Therefore, I would like to summarize in this article the usage of R and Python in extracting rows/columns from a data frame and make a simple cheat sheet image for the people who need it."
},
{
"code": null,
"e": 1042,
"s": 795,
"text": "To note, I will only use Pandas in Python and basic functions in R for the purpose of comparing the command lines side by side. Some comprehensive library, βdplyrβ for example, is not considered. And I am trying my best to keep the article short."
},
{
"code": null,
"e": 1055,
"s": 1042,
"text": "Letβs begin."
},
{
"code": null,
"e": 1192,
"s": 1055,
"text": "We will use a toy dataset of Allen Iversonβs game stats in the entire article. The dimension and head of the data frame are shown below."
},
{
"code": null,
"e": 1211,
"s": 1192,
"text": "# Rdim(df)head(df)"
},
{
"code": null,
"e": 1237,
"s": 1211,
"text": "# Pythondf.shapedf.head()"
},
{
"code": null,
"e": 1414,
"s": 1237,
"text": "First, letβs extract the rows from the data frame in both R and Python. In R, it is done by simple indexing, but in Python, it is done by .iloc. Letβs check the examples below."
},
{
"code": null,
"e": 1510,
"s": 1414,
"text": "# R## Extract the third rowdf[3,]## Extract the first three rowsdf[1:3,]### or ###df[c(1,2,3),]"
},
{
"code": null,
"e": 1524,
"s": 1510,
"text": "which yields,"
},
{
"code": null,
"e": 1698,
"s": 1524,
"text": "# Python## Extract the third rowdf.iloc[2]### or ###df.iloc[2,]### or ###df.iloc[2,:]## Extract the first three rowsdf.iloc[:3]### or ###df.iloc[0:3]### or ###df.iloc[0:3,:]"
},
{
"code": null,
"e": 1712,
"s": 1698,
"text": "which yields,"
},
{
"code": null,
"e": 1999,
"s": 1712,
"text": "Please note that in the example of extracting a single row from the data frame, the output in R is still in the data frame format, but the output in Python is in the Pandas Series format. This is an essential difference between R and Python in extracting a single row from a data frame."
},
{
"code": null,
"e": 2054,
"s": 1999,
"text": "Similarly, we can extract columns from the data frame."
},
{
"code": null,
"e": 2127,
"s": 2054,
"text": "# R## Extract the 5th columndf[,5]## Extract the first 5 columnsdf[,1:5]"
},
{
"code": null,
"e": 2141,
"s": 2127,
"text": "which yields,"
},
{
"code": null,
"e": 2254,
"s": 2141,
"text": "# Python## Extract the 5th columndf.iloc[:,4]## Extract the first 5 columnsdf.iloc[:,:5]### or ###df.iloc[:,0:5]"
},
{
"code": null,
"e": 2268,
"s": 2254,
"text": "which yields,"
},
{
"code": null,
"e": 2431,
"s": 2268,
"text": "When extracting the column, we have to put both the colon and comma in the row position within the square bracket, which is a big difference from extracting rows."
},
{
"code": null,
"e": 2614,
"s": 2431,
"text": "In our dataset, the row and column index of the data frame is the NBA season and Iversonβs stats, respectively. We can use those to extract specific rows/columns from the data frame."
},
{
"code": null,
"e": 2670,
"s": 2614,
"text": "For example, we are interested in the season 1999β2000."
},
{
"code": null,
"e": 2786,
"s": 2670,
"text": "# R## Extract 1999-2000 season.df[\"1999-00\",]## Extract 1999-2000 and 2001-2002 seasons.df[c(\"1999-00\",\"2000-01\"),]"
},
{
"code": null,
"e": 2800,
"s": 2786,
"text": "which yields,"
},
{
"code": null,
"e": 2926,
"s": 2800,
"text": "# Python## Extract 1999-2000 season.df.loc[\"1999-00\"]## Extract 1999-2000 and 2001-2002 seasons.df.loc[[\"1999-00\",\"2000-01\"]]"
},
{
"code": null,
"e": 2940,
"s": 2926,
"text": "which yields,"
},
{
"code": null,
"e": 3123,
"s": 2940,
"text": "Please note again that in Python, the output is in Pandas Series format if we extract only one row/column, but it will be Pandas DataFrame format if we extract multiple rows/columns."
},
{
"code": null,
"e": 3209,
"s": 3123,
"text": "When we are only interested in a subset of columns, we can also add the column index."
},
{
"code": null,
"e": 3308,
"s": 3209,
"text": "# R## Extract Iverson's team and minutes played in the 1999-2000 season.df[\"1999-00\",c(\"Tm\",\"MP\")]"
},
{
"code": null,
"e": 3322,
"s": 3308,
"text": "which yields,"
},
{
"code": null,
"e": 3429,
"s": 3322,
"text": "# Python## Extract Iverson's team and minutes played in the 1999-2000 season.df.loc[\"1999-00\",[\"Tm\",\"MP\"]]"
},
{
"code": null,
"e": 3443,
"s": 3429,
"text": "which yields,"
},
{
"code": null,
"e": 3639,
"s": 3443,
"text": "In addition to extracting rows/columns by index, we can also do the subsetting based on conditions. For example, we want to extract the seasons in which Iverson has played more than 3000 minutes."
},
{
"code": null,
"e": 3712,
"s": 3639,
"text": "# R## Extract MP over 3kdf[df$MP > 3000,] ## the comma cannot be omitted"
},
{
"code": null,
"e": 3726,
"s": 3712,
"text": "which yields,"
},
{
"code": null,
"e": 3821,
"s": 3726,
"text": "# Python## Extract MP over 3kdf.loc[df.MP > 3000,:] ## both the comma and colon can be omitted"
},
{
"code": null,
"e": 3835,
"s": 3821,
"text": "which yields,"
},
{
"code": null,
"e": 3999,
"s": 3835,
"text": "Of course, more complicated conditions can be passed to the square bracket, which only needs a True/False list with the length of the row number of the data frame."
},
{
"code": null,
"e": 4205,
"s": 3999,
"text": "For example, we want to extract the seasons in which Iversonβs true shooting percentage (TS%) is over 50%, minutes played is over 3000, and position (Pos) is either shooting guard (SG) or point guard (PG)."
},
{
"code": null,
"e": 4373,
"s": 4205,
"text": "# R## Extract rows with TS.> 50%, MP > 3000 and Pos is SG/PG### define condition as cond_cond_ = (df$TS. > 0.5) & (df$MP > 3000) & (df$Pos %in% c(\"SG\",\"PG\"))df[cond_,]"
},
{
"code": null,
"e": 4387,
"s": 4373,
"text": "which yields,"
},
{
"code": null,
"e": 4616,
"s": 4387,
"text": "# Python## Extract rows with TS.> 50%, MP> 3000 and Pos is SG/PG### define condition as cond_cond_ = (df[\"TS.\"] > 0.5) & (df[\"MP\"] > 3000) & (df[\"Pos\"].isin([\"SG\",\"PG\"]))df.loc[cond_,:] ## both the comma and colon can be omitted"
},
{
"code": null,
"e": 4630,
"s": 4616,
"text": "which yields,"
},
{
"code": null,
"e": 4695,
"s": 4630,
"text": "We can apply any kind of boolean values in the βcond_β position."
},
{
"code": null,
"e": 4796,
"s": 4695,
"text": "Here is the cheat sheet that I hope can save your time when you work with both Python and R as I do."
},
{
"code": null,
"e": 4871,
"s": 4796,
"text": "Thatβs it! A simple summary of table slicing in R/Pandas. I hope it helps!"
}
] |
AngularJS - Filters
|
Filters are used to modify the data. They can be clubbed in expression or directives using pipe (|) character. The following list shows the commonly used filters.
uppercase
converts a text to upper case text.
lowercase
converts a text to lower case text.
currency
formats text in a currency format.
filter
filter the array to a subset of it based on provided criteria.
orderby
orders the array based on provided criteria.
Add uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | uppercase}}
Add lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Lower Case: {{student.fullName() | lowercase}}
Add currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format.
Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}
To display only required subjects, we use subjectName as filter.
Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | filter: subjectName">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
To order subjects by marks, we use orderBy marks.
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
The following example shows use of all the above mentioned filters.
<html>
<head>
<title>Angular JS Filters</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
</tr>
<tr>
<td>Enter fees: </td>
<td><input type = "text" ng-model = "student.fees"></td>
</tr>
<tr>
<td>Enter subject: </td>
<td><input type = "text" ng-model = "subjectName"></td>
</tr>
</table>
<br/>
<table border = "0">
<tr>
<td>Name in Upper Case: </td><td>{{student.fullName() | uppercase}}</td>
</tr>
<tr>
<td>Name in Lower Case: </td><td>{{student.fullName() | lowercase}}</td>
</tr>
<tr>
<td>fees: </td><td>{{student.fees | currency}}
</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<ul>
<li ng-repeat = "subject in student.subjects | filter: subjectName |orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
</td>
</tr>
</table>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
</body>
</html>
Open the file testAngularJS.htm in a web browser. See the result.
{{ subject.name + ', marks:' + subject.marks }}
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2862,
"s": 2699,
"text": "Filters are used to modify the data. They can be clubbed in expression or directives using pipe (|) character. The following list shows the commonly used filters."
},
{
"code": null,
"e": 2872,
"s": 2862,
"text": "uppercase"
},
{
"code": null,
"e": 2908,
"s": 2872,
"text": "converts a text to upper case text."
},
{
"code": null,
"e": 2918,
"s": 2908,
"text": "lowercase"
},
{
"code": null,
"e": 2954,
"s": 2918,
"text": "converts a text to lower case text."
},
{
"code": null,
"e": 2963,
"s": 2954,
"text": "currency"
},
{
"code": null,
"e": 2998,
"s": 2963,
"text": "formats text in a currency format."
},
{
"code": null,
"e": 3005,
"s": 2998,
"text": "filter"
},
{
"code": null,
"e": 3068,
"s": 3005,
"text": "filter the array to a subset of it based on provided criteria."
},
{
"code": null,
"e": 3076,
"s": 3068,
"text": "orderby"
},
{
"code": null,
"e": 3121,
"s": 3076,
"text": "orders the array based on provided criteria."
},
{
"code": null,
"e": 3261,
"s": 3121,
"text": "Add uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters."
},
{
"code": null,
"e": 3456,
"s": 3261,
"text": "Enter first name:<input type = \"text\" ng-model = \"student.firstName\">\nEnter last name: <input type = \"text\" ng-model = \"student.lastName\">\nName in Upper Case: {{student.fullName() | uppercase}}\n"
},
{
"code": null,
"e": 3598,
"s": 3456,
"text": "Add lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters."
},
{
"code": null,
"e": 3793,
"s": 3598,
"text": "Enter first name:<input type = \"text\" ng-model = \"student.firstName\">\nEnter last name: <input type = \"text\" ng-model = \"student.lastName\">\nName in Lower Case: {{student.fullName() | lowercase}}\n"
},
{
"code": null,
"e": 3939,
"s": 3793,
"text": "Add currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format."
},
{
"code": null,
"e": 4034,
"s": 3939,
"text": "Enter fees: <input type = \"text\" ng-model = \"student.fees\">\nfees: {{student.fees | currency}}\n"
},
{
"code": null,
"e": 4099,
"s": 4034,
"text": "To display only required subjects, we use subjectName as filter."
},
{
"code": null,
"e": 4316,
"s": 4099,
"text": "Enter subject: <input type = \"text\" ng-model = \"subjectName\">\nSubject:\n<ul>\n <li ng-repeat = \"subject in student.subjects | filter: subjectName\">\n {{ subject.name + ', marks:' + subject.marks }}\n </li>\n</ul>"
},
{
"code": null,
"e": 4366,
"s": 4316,
"text": "To order subjects by marks, we use orderBy marks."
},
{
"code": null,
"e": 4517,
"s": 4366,
"text": "Subject:\n<ul>\n <li ng-repeat = \"subject in student.subjects | orderBy:'marks'\">\n {{ subject.name + ', marks:' + subject.marks }}\n </li>\n</ul>"
},
{
"code": null,
"e": 4585,
"s": 4517,
"text": "The following example shows use of all the above mentioned filters."
},
{
"code": null,
"e": 7120,
"s": 4585,
"text": "<html>\n <head>\n <title>Angular JS Filters</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n \n <div ng-app = \"mainApp\" ng-controller = \"studentController\">\n <table border = \"0\">\n <tr>\n <td>Enter first name:</td>\n <td><input type = \"text\" ng-model = \"student.firstName\"></td>\n </tr>\n <tr>\n <td>Enter last name: </td>\n <td><input type = \"text\" ng-model = \"student.lastName\"></td>\n </tr>\n <tr>\n <td>Enter fees: </td>\n <td><input type = \"text\" ng-model = \"student.fees\"></td>\n </tr>\n <tr>\n <td>Enter subject: </td>\n <td><input type = \"text\" ng-model = \"subjectName\"></td>\n </tr>\n </table>\n <br/>\n \n <table border = \"0\">\n <tr>\n <td>Name in Upper Case: </td><td>{{student.fullName() | uppercase}}</td>\n </tr>\n <tr>\n <td>Name in Lower Case: </td><td>{{student.fullName() | lowercase}}</td>\n </tr>\n <tr>\n <td>fees: </td><td>{{student.fees | currency}}\n </td>\n </tr>\n <tr>\n <td>Subject:</td>\n <td>\n <ul>\n <li ng-repeat = \"subject in student.subjects | filter: subjectName |orderBy:'marks'\">\n {{ subject.name + ', marks:' + subject.marks }}\n </li>\n </ul>\n </td>\n </tr>\n </table>\n </div>\n \n <script>\n var mainApp = angular.module(\"mainApp\", []);\n \n mainApp.controller('studentController', function($scope) {\n $scope.student = {\n firstName: \"Mahesh\",\n lastName: \"Parashar\",\n fees:500,\n \n subjects:[\n {name:'Physics',marks:70},\n {name:'Chemistry',marks:80},\n {name:'Math',marks:65}\n ],\n fullName: function() {\n var studentObject;\n studentObject = $scope.student;\n return studentObject.firstName + \" \" + studentObject.lastName;\n }\n };\n });\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7186,
"s": 7120,
"text": "Open the file testAngularJS.htm in a web browser. See the result."
},
{
"code": null,
"e": 7245,
"s": 7186,
"text": "\n {{ subject.name + ', marks:' + subject.marks }}\n "
},
{
"code": null,
"e": 7280,
"s": 7245,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7294,
"s": 7280,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7329,
"s": 7294,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7349,
"s": 7329,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 7356,
"s": 7349,
"text": " Print"
},
{
"code": null,
"e": 7367,
"s": 7356,
"text": " Add Notes"
}
] |
How I can dynamically import Python module?
|
To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example,
>>> from importlib import import_module
>>> moduleName = "os"
>>> globals()[moduleName] = import_module(moduleName)
If you want to dynamically import a list of modules, you can even call this from a for loop. For example,
>>> import importlib
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
... globals()[lib] = importlib.import_module(lib)
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example,"
},
{
"code": null,
"e": 1342,
"s": 1226,
"text": ">>> from importlib import import_module\n>>> moduleName = \"os\"\n>>> globals()[moduleName] = import_module(moduleName)"
},
{
"code": null,
"e": 1448,
"s": 1342,
"text": "If you want to dynamically import a list of modules, you can even call this from a for loop. For example,"
},
{
"code": null,
"e": 1585,
"s": 1448,
"text": ">>> import importlib\n>>> modnames = [\"os\", \"sys\", \"math\"]\n>>> for lib in modnames:\n... globals()[lib] = importlib.import_module(lib)"
},
{
"code": null,
"e": 1712,
"s": 1585,
"text": "The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module."
}
] |
PHP Functions
|
The real power of PHP comes from its functions.
PHP has more
than 1000 built-in functions, and in addition you can create your own custom
functions.
PHP has over 1000 built-in functions that can be called directly, from within
a script, to perform
a specific task.
Please check out our PHP reference for a complete overview of the
PHP built-in functions.
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
A user-defined function declaration starts with the word function:
Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
Tip: Give the function a name that reflects what the
function does!
In the example below, we create a function named "writeMsg()". The opening
curly brace ( { ) indicates the beginning of the function code, and the closing
curly brace ( } ) indicates the end of the function. The function outputs "Hello
world!". To call the function, just write its name followed by brackets ():
Information can be passed to functions through arguments. An argument is just
like a variable.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names,
but an equal last name:
The following example has a function with two arguments ($fname and $year):
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically associates a data type to the variable, depending on its value.
Since the data types are not set in a strict sense, you can do things like
adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify
the expected data type when declaring a function, and by adding the strict
declaration, it will throw a "Fatal
Error" if the data type mismatches.
In the following example we try to send both a number and a string to the
function without using strict:
To specify strict we need to set declare(strict_types=1);.
This must be on the very first line of the PHP file.
In the following example we try to send both a number and a string to the
function, but here we have added the strict
declaration:
The strict declaration forces things to be used in the intended way.
The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:
To let a function return a value, use the return statement:
PHP 7 also supports Type Declarations for the return
statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a "Fatal
Error" on a type mismatch.
To declare a type for the function return, add a colon (
: ) and the type right before the opening curly
( { )bracket when declaring the function.
In the following example we specify the return type for the function:
You can specify a different return type, than the argument types, but make
sure the return is the correct type:
In PHP, arguments are usually passed by value, which means that a copy of the value is
used in the function and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change
the variable that was passed in. To turn a function argument into a reference, the &
operator is used:
Use a pass-by-reference argument to update a variable:
Create a function named myFunction.
{
echo "Hello World!";
}
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 48,
"s": 0,
"text": "The real power of PHP comes from its functions."
},
{
"code": null,
"e": 151,
"s": 48,
"text": "PHP has more \nthan 1000 built-in functions, and in addition you can create your own custom \nfunctions."
},
{
"code": null,
"e": 269,
"s": 151,
"text": "PHP has over 1000 built-in functions that can be called directly, from within \na script, to perform \na specific task."
},
{
"code": null,
"e": 359,
"s": 269,
"text": "Please check out our PHP reference for a complete overview of the\nPHP built-in functions."
},
{
"code": null,
"e": 440,
"s": 359,
"text": "Besides the built-in PHP functions, it is possible to create your own functions."
},
{
"code": null,
"e": 518,
"s": 440,
"text": "A function is a block of statements that can be used repeatedly in a program."
},
{
"code": null,
"e": 579,
"s": 518,
"text": "A function will not execute automatically when a page loads."
},
{
"code": null,
"e": 634,
"s": 579,
"text": "A function will be executed by a call to the function."
},
{
"code": null,
"e": 701,
"s": 634,
"text": "A user-defined function declaration starts with the word function:"
},
{
"code": null,
"e": 805,
"s": 701,
"text": "Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive."
},
{
"code": null,
"e": 874,
"s": 805,
"text": "Tip: Give the function a name that reflects what the \nfunction does!"
},
{
"code": null,
"e": 1189,
"s": 874,
"text": "In the example below, we create a function named \"writeMsg()\". The opening \ncurly brace ( { ) indicates the beginning of the function code, and the closing \ncurly brace ( } ) indicates the end of the function. The function outputs \"Hello \nworld!\". To call the function, just write its name followed by brackets ():"
},
{
"code": null,
"e": 1285,
"s": 1189,
"text": "Information can be passed to functions through arguments. An argument is just \nlike a variable."
},
{
"code": null,
"e": 1436,
"s": 1285,
"text": "Arguments are specified after the function name, inside the parentheses. You \ncan add as many arguments as you want, just separate them with a comma. "
},
{
"code": null,
"e": 1696,
"s": 1436,
"text": "The following example has a function with one argument ($fname). When the \nfamilyName() function is called, we also pass along a name (e.g. Jani), and the \nname is used inside the function, which outputs several different first names, \nbut an equal last name:"
},
{
"code": null,
"e": 1772,
"s": 1696,
"text": "The following example has a function with two arguments ($fname and $year):"
},
{
"code": null,
"e": 1867,
"s": 1772,
"text": "In the example above, notice that we did not have to tell PHP which data type the variable is."
},
{
"code": null,
"e": 2082,
"s": 1867,
"text": "PHP automatically associates a data type to the variable, depending on its value. \nSince the data types are not set in a strict sense, you can do things like \nadding a string to an integer without causing an error."
},
{
"code": null,
"e": 2307,
"s": 2082,
"text": "In PHP 7, type declarations were added. This gives us an option to specify \nthe expected data type when declaring a function, and by adding the strict \ndeclaration, it will throw a \"Fatal \nError\" if the data type mismatches."
},
{
"code": null,
"e": 2413,
"s": 2307,
"text": "In the following example we try to send both a number and a string to the \nfunction without using strict:"
},
{
"code": null,
"e": 2526,
"s": 2413,
"text": "To specify strict we need to set declare(strict_types=1);. \nThis must be on the very first line of the PHP file."
},
{
"code": null,
"e": 2659,
"s": 2526,
"text": "In the following example we try to send both a number and a string to the \nfunction, but here we have added the strict \ndeclaration:"
},
{
"code": null,
"e": 2728,
"s": 2659,
"text": "The strict declaration forces things to be used in the intended way."
},
{
"code": null,
"e": 2883,
"s": 2728,
"text": "The following example shows how to use a default parameter. If we call the \nfunction setHeight() without arguments it takes the default value as argument:"
},
{
"code": null,
"e": 2943,
"s": 2883,
"text": "To let a function return a value, use the return statement:"
},
{
"code": null,
"e": 3150,
"s": 2943,
"text": "PHP 7 also supports Type Declarations for the return \nstatement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a \"Fatal \nError\" on a type mismatch."
},
{
"code": null,
"e": 3298,
"s": 3150,
"text": "To declare a type for the function return, add a colon (\n: ) and the type right before the opening curly \n( { )bracket when declaring the function."
},
{
"code": null,
"e": 3368,
"s": 3298,
"text": "In the following example we specify the return type for the function:"
},
{
"code": null,
"e": 3481,
"s": 3368,
"text": "You can specify a different return type, than the argument types, but make \nsure the return is the correct type:"
},
{
"code": null,
"e": 3659,
"s": 3481,
"text": "In PHP, arguments are usually passed by value, which means that a copy of the value is\nused in the function and the variable that was passed into the function cannot be changed."
},
{
"code": null,
"e": 3847,
"s": 3659,
"text": "When a function argument is passed by reference, changes to the argument also change\nthe variable that was passed in. To turn a function argument into a reference, the &\noperator is used:"
},
{
"code": null,
"e": 3902,
"s": 3847,
"text": "Use a pass-by-reference argument to update a variable:"
},
{
"code": null,
"e": 3938,
"s": 3902,
"text": "Create a function named myFunction."
},
{
"code": null,
"e": 3967,
"s": 3938,
"text": " {\n echo \"Hello World!\";\n}\n"
},
{
"code": null,
"e": 4000,
"s": 3967,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4042,
"s": 4000,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4149,
"s": 4042,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 4168,
"s": 4149,
"text": "help@w3schools.com"
}
] |
D3.js timer() function - GeeksforGeeks
|
29 Jul, 2020
The D3.timer() function is used to run a timer function after a particular interval of time. The timer will run after a specified delay. The delay given is in milliseconds.
Syntax:
d3.timer(callback, delay);
Parameters: It takes the following two parameters.
callback: It is a function.
delay: It is the delay after which the function is executed.
Returns: It returns the Time of datatype Number.
Below given are a few examples of the above function.
Example 1:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script> <script> let func=function(elapsed) { console.log(elapsed); if (elapsed > 500){ console.log("Timer stopped") timer.stop(); } } var timer = d3.timer(func); </script></body></html>
Output:
Example 2:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!-- Fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script> <script> let func=function(e) { console.log(e); if (e>300){ console.log("Timer stopped") timer.stop(); } } // Delay of 2000ms var timer = d3.timer(func, 2000); </script></body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25535,
"s": 25507,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 25708,
"s": 25535,
"text": "The D3.timer() function is used to run a timer function after a particular interval of time. The timer will run after a specified delay. The delay given is in milliseconds."
},
{
"code": null,
"e": 25716,
"s": 25708,
"text": "Syntax:"
},
{
"code": null,
"e": 25743,
"s": 25716,
"text": "d3.timer(callback, delay);"
},
{
"code": null,
"e": 25794,
"s": 25743,
"text": "Parameters: It takes the following two parameters."
},
{
"code": null,
"e": 25822,
"s": 25794,
"text": "callback: It is a function."
},
{
"code": null,
"e": 25883,
"s": 25822,
"text": "delay: It is the delay after which the function is executed."
},
{
"code": null,
"e": 25932,
"s": 25883,
"text": "Returns: It returns the Time of datatype Number."
},
{
"code": null,
"e": 25986,
"s": 25932,
"text": "Below given are a few examples of the above function."
},
{
"code": null,
"e": 25997,
"s": 25986,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><style></style><body> <!-- Fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> let func=function(elapsed) { console.log(elapsed); if (elapsed > 500){ console.log(\"Timer stopped\") timer.stop(); } } var timer = d3.timer(func); </script></body></html>",
"e": 26553,
"s": 25997,
"text": null
},
{
"code": null,
"e": 26561,
"s": 26553,
"text": "Output:"
},
{
"code": null,
"e": 26572,
"s": 26561,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!-- Fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> let func=function(e) { console.log(e); if (e>300){ console.log(\"Timer stopped\") timer.stop(); } } // Delay of 2000ms var timer = d3.timer(func, 2000); </script></body></html>",
"e": 27245,
"s": 26572,
"text": null
},
{
"code": null,
"e": 27253,
"s": 27245,
"text": "Output:"
},
{
"code": null,
"e": 27259,
"s": 27253,
"text": "D3.js"
},
{
"code": null,
"e": 27270,
"s": 27259,
"text": "JavaScript"
},
{
"code": null,
"e": 27287,
"s": 27270,
"text": "Web Technologies"
},
{
"code": null,
"e": 27385,
"s": 27287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27425,
"s": 27385,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27470,
"s": 27425,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27531,
"s": 27470,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27603,
"s": 27531,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27655,
"s": 27603,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27695,
"s": 27655,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27728,
"s": 27695,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27773,
"s": 27728,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27816,
"s": 27773,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
numpy.loadtxt() in Python - GeeksforGeeks
|
11 Dec, 2018
numpy.load() in Python is used load data from a text file, with aim to be a fast reader for simple text files.
Note that each row in the text file must have the same number of values.
Syntax: numpy.loadtxt(fname, dtype=βfloatβ, comments=β#β, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
Parameters:fname : File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.dtype : Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.delimiter : The string used to separate values. By default, this is any whitespace.converters : A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Default: None.skiprows : Skip the first skiprows lines; default: 0.
Returns: ndarray
Code #1:
# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO c = StringIO("0 1 2 \n3 4 5")d = geek.loadtxt(c) print(d)
Output :
[[ 0. 1. 2.]
[ 3. 4. 5.]]
Code #2:
# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO c = StringIO("1, 2, 3\n4, 5, 6")x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2), unpack = True) print("x is: ", x)print("y is: ", y)print("z is: ", z)
Output :
x is: [ 1. 4.]
y is: [ 2. 5.]
z is: [ 3. 6.]
Code #3:
# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO d = StringIO("M 21 72\nF 35 58")e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')}) print(e)
Output :
[(b'M', 21, 72.) (b'F', 35, 58.)]
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25557,
"s": 25529,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 25668,
"s": 25557,
"text": "numpy.load() in Python is used load data from a text file, with aim to be a fast reader for simple text files."
},
{
"code": null,
"e": 25741,
"s": 25668,
"text": "Note that each row in the text file must have the same number of values."
},
{
"code": null,
"e": 25881,
"s": 25741,
"text": "Syntax: numpy.loadtxt(fname, dtype=βfloatβ, comments=β#β, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)"
},
{
"code": null,
"e": 26592,
"s": 25881,
"text": "Parameters:fname : File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.dtype : Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.delimiter : The string used to separate values. By default, this is any whitespace.converters : A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Default: None.skiprows : Skip the first skiprows lines; default: 0."
},
{
"code": null,
"e": 26609,
"s": 26592,
"text": "Returns: ndarray"
},
{
"code": null,
"e": 26618,
"s": 26609,
"text": "Code #1:"
},
{
"code": "# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO c = StringIO(\"0 1 2 \\n3 4 5\")d = geek.loadtxt(c) print(d)",
"e": 26812,
"s": 26618,
"text": null
},
{
"code": null,
"e": 26821,
"s": 26812,
"text": "Output :"
},
{
"code": null,
"e": 26852,
"s": 26821,
"text": "[[ 0. 1. 2.]\n [ 3. 4. 5.]]"
},
{
"code": null,
"e": 26862,
"s": 26852,
"text": " Code #2:"
},
{
"code": "# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO c = StringIO(\"1, 2, 3\\n4, 5, 6\")x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2), unpack = True) print(\"x is: \", x)print(\"y is: \", y)print(\"z is: \", z)",
"e": 27211,
"s": 26862,
"text": null
},
{
"code": null,
"e": 27220,
"s": 27211,
"text": "Output :"
},
{
"code": null,
"e": 27271,
"s": 27220,
"text": "x is: [ 1. 4.]\ny is: [ 2. 5.]\nz is: [ 3. 6.]"
},
{
"code": null,
"e": 27281,
"s": 27271,
"text": " Code #3:"
},
{
"code": "# Python program explaining # loadtxt() functionimport numpy as geek # StringIO behaves like a file objectfrom io import StringIO d = StringIO(\"M 21 72\\nF 35 58\")e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')}) print(e)",
"e": 27589,
"s": 27281,
"text": null
},
{
"code": null,
"e": 27598,
"s": 27589,
"text": "Output :"
},
{
"code": null,
"e": 27635,
"s": 27598,
"text": "[(b'M', 21, 72.) (b'F', 35, 58.)]\n"
},
{
"code": null,
"e": 27662,
"s": 27635,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 27675,
"s": 27662,
"text": "Python-numpy"
},
{
"code": null,
"e": 27682,
"s": 27675,
"text": "Python"
},
{
"code": null,
"e": 27780,
"s": 27682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27798,
"s": 27780,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27830,
"s": 27798,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27852,
"s": 27830,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27894,
"s": 27852,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27924,
"s": 27894,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27950,
"s": 27924,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27979,
"s": 27950,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28016,
"s": 27979,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28052,
"s": 28016,
"text": "Convert integer to string in Python"
}
] |
Flutter - Skeleton Text - GeeksforGeeks
|
28 Oct, 2020
In Flutter, the skeleton_text library is used to easily implement skeleton text loading animation. Its main application in a flutter app is to assure its users that the servers are working but running slow, but the content will eventually load. It also enhances the UI if the user connection is slow too.
in this article, we will be looking into the process of implementing the skeleton text to a flutter application by building a simple flutter app. To build the same follow the below steps:
Add the skeleton_text dependency to the pubspec.yaml file
Import the dependency to the main.dart file
Build a simple app structure to implement the dependency
Call the SkeletoAnimation method in the body of the app
Now, letβs look into the steps in detail:
Add the skeleton_text dependency to the dependencies section of the pubspec.yaml file as shown below:
Use the below code to import the skeleton_text dependency to the main.dart file:
import 'package:skeleton_text/skeleton_text.dart';
To give a Flutter application a simple structure with an appbar and a body, extend a StatelessWidget by forming a class as shown below:
Dart
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Skeleton Text', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), body: ), ); }}
Make use of the SkeletonAnimation method provided by the skeleton_text package to show skeleton text for a list object as shown below:
Dart
children: <Widget>[ SkeletonAnimation( child: Container( width: 70.0, height: 70.0, decoration: BoxDecoration( color: Colors.grey[300], ), ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: const EdgeInsets.only( left: 15.0, bottom: 5.0), child: SkeletonAnimation( child: Container( height: 15, width: MediaQuery.of(context).size.width * 0.6, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), Padding( padding: const EdgeInsets.only(left: 15.0), child: Padding( padding: const EdgeInsets.only(right: 5.0), child: SkeletonAnimation( child: Container( width: 60, height: 13, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), ), ],
Complete Source Code:
Dart
import 'package:flutter/material.dart';import 'package:skeleton_text/skeleton_text.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // root of the application @override Widget build(BuildContext context) { return MaterialApp( title: 'Skeleton Text', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), // list of items in body body: ListView.builder( scrollDirection: Axis.vertical, physics: BouncingScrollPhysics(), itemCount: 5, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), color: Colors.white70), child: Container( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, // SkeletonAnimation method children: <Widget>[ SkeletonAnimation( child: Container( width: 70.0, height: 70.0, decoration: BoxDecoration( color: Colors.grey[300], ), ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: const EdgeInsets.only( left: 15.0, bottom: 5.0), child: SkeletonAnimation( child: Container( height: 15, width: MediaQuery.of(context).size.width * 0.6, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), Padding( padding: const EdgeInsets.only(left: 15.0), child: Padding( padding: const EdgeInsets.only(right: 5.0), child: SkeletonAnimation( child: Container( width: 60, height: 13, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), ), ], ), ], ), ), ), ); }), ), ); }}
Output:
android
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
|
[
{
"code": null,
"e": 27159,
"s": 27131,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 27464,
"s": 27159,
"text": "In Flutter, the skeleton_text library is used to easily implement skeleton text loading animation. Its main application in a flutter app is to assure its users that the servers are working but running slow, but the content will eventually load. It also enhances the UI if the user connection is slow too."
},
{
"code": null,
"e": 27653,
"s": 27464,
"text": "in this article, we will be looking into the process of implementing the skeleton text to a flutter application by building a simple flutter app. To build the same follow the below steps:"
},
{
"code": null,
"e": 27711,
"s": 27653,
"text": "Add the skeleton_text dependency to the pubspec.yaml file"
},
{
"code": null,
"e": 27755,
"s": 27711,
"text": "Import the dependency to the main.dart file"
},
{
"code": null,
"e": 27812,
"s": 27755,
"text": "Build a simple app structure to implement the dependency"
},
{
"code": null,
"e": 27868,
"s": 27812,
"text": "Call the SkeletoAnimation method in the body of the app"
},
{
"code": null,
"e": 27910,
"s": 27868,
"text": "Now, letβs look into the steps in detail:"
},
{
"code": null,
"e": 28012,
"s": 27910,
"text": "Add the skeleton_text dependency to the dependencies section of the pubspec.yaml file as shown below:"
},
{
"code": null,
"e": 28093,
"s": 28012,
"text": "Use the below code to import the skeleton_text dependency to the main.dart file:"
},
{
"code": null,
"e": 28145,
"s": 28093,
"text": "import 'package:skeleton_text/skeleton_text.dart';\n"
},
{
"code": null,
"e": 28281,
"s": 28145,
"text": "To give a Flutter application a simple structure with an appbar and a body, extend a StatelessWidget by forming a class as shown below:"
},
{
"code": null,
"e": 28286,
"s": 28281,
"text": "Dart"
},
{
"code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Skeleton Text', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), body: ), ); }}",
"e": 28691,
"s": 28286,
"text": null
},
{
"code": null,
"e": 28826,
"s": 28691,
"text": "Make use of the SkeletonAnimation method provided by the skeleton_text package to show skeleton text for a list object as shown below:"
},
{
"code": null,
"e": 28831,
"s": 28826,
"text": "Dart"
},
{
"code": "children: <Widget>[ SkeletonAnimation( child: Container( width: 70.0, height: 70.0, decoration: BoxDecoration( color: Colors.grey[300], ), ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: const EdgeInsets.only( left: 15.0, bottom: 5.0), child: SkeletonAnimation( child: Container( height: 15, width: MediaQuery.of(context).size.width * 0.6, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), Padding( padding: const EdgeInsets.only(left: 15.0), child: Padding( padding: const EdgeInsets.only(right: 5.0), child: SkeletonAnimation( child: Container( width: 60, height: 13, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), ), ],",
"e": 31044,
"s": 28831,
"text": null
},
{
"code": null,
"e": 31066,
"s": 31044,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 31071,
"s": 31066,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:skeleton_text/skeleton_text.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // root of the application @override Widget build(BuildContext context) { return MaterialApp( title: 'Skeleton Text', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), // list of items in body body: ListView.builder( scrollDirection: Axis.vertical, physics: BouncingScrollPhysics(), itemCount: 5, itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), color: Colors.white70), child: Container( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, // SkeletonAnimation method children: <Widget>[ SkeletonAnimation( child: Container( width: 70.0, height: 70.0, decoration: BoxDecoration( color: Colors.grey[300], ), ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: const EdgeInsets.only( left: 15.0, bottom: 5.0), child: SkeletonAnimation( child: Container( height: 15, width: MediaQuery.of(context).size.width * 0.6, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), Padding( padding: const EdgeInsets.only(left: 15.0), child: Padding( padding: const EdgeInsets.only(right: 5.0), child: SkeletonAnimation( child: Container( width: 60, height: 13, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: Colors.grey[300]), ), ), ), ), ], ), ], ), ), ), ); }), ), ); }}",
"e": 34784,
"s": 31071,
"text": null
},
{
"code": null,
"e": 34792,
"s": 34784,
"text": "Output:"
},
{
"code": null,
"e": 34800,
"s": 34792,
"text": "android"
},
{
"code": null,
"e": 34816,
"s": 34800,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 34821,
"s": 34816,
"text": "Dart"
},
{
"code": null,
"e": 34829,
"s": 34821,
"text": "Flutter"
},
{
"code": null,
"e": 34927,
"s": 34829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34959,
"s": 34927,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 34987,
"s": 34959,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 35009,
"s": 34987,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 35034,
"s": 35009,
"text": "Splash Screen in Flutter"
},
{
"code": null,
"e": 35073,
"s": 35034,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 35105,
"s": 35073,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 35144,
"s": 35105,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 35170,
"s": 35144,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 35196,
"s": 35170,
"text": "Flutter - Flexible Widget"
}
] |
Delete continuous nodes with sum K from a given linked list - GeeksforGeeks
|
17 Apr, 2022
Given a singly linked list and an integer K, the task is to remove all the continuous set of nodes whose sum is K from the given linked list. Print the updated linked list after the removal. If no such deletion can occur, print the original Linked list.
Examples:
Input: Linked List: 1 -> 2 -> -3 -> 3 -> 1, K = 3
Output: -3 -> 1
Explanation:
The nodes with continuous sum 3 are:
1) 1 -> 2
2) 3
Therefore, after removing these chain of nodes Linked List becomes: -3-> 1
Input: Linked List: 1 -> 1 -> -3 -> -3 -> -2, K = 5 Output: 1 -> 1 -> -3 -> -3 -> -2 Explanation: No continuous nodes exits with sum K
Approach:
Append Node with value zero at the starting of the linked list.Traverse the given linked list.During traversal store the sum of the node value till that node with the reference of the current node in an unordered_map.If there is Node with value (sum β K) present in the unordered_map then delete all the nodes from the node corresponding to value (sum β K) stored in map to the current node and update the sum as (sum β K).If there is no Node with value (sum β K) present in the unordered_map, then stored the current sum with node in the map.
Append Node with value zero at the starting of the linked list.
Traverse the given linked list.
During traversal store the sum of the node value till that node with the reference of the current node in an unordered_map.
If there is Node with value (sum β K) present in the unordered_map then delete all the nodes from the node corresponding to value (sum β K) stored in map to the current node and update the sum as (sum β K).
If there is no Node with value (sum β K) present in the unordered_map, then stored the current sum with node in the map.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A Linked List Nodestruct ListNode { int val; ListNode* next; // Constructor ListNode(int x) : val(x) , next(NULL) { }}; // Function to create NodeListNode* getNode(int data){ ListNode* temp; temp = (ListNode*)malloc(sizeof(ListNode)); temp->val = data; temp->next = NULL; return temp;} // Function to print the Linked Listvoid printList(ListNode* head){ while (head->next) { cout << head->val << " -> "; head = head->next; } printf("%d", head->val);} // Function that removes continuous nodes// whose sum is KListNode* removeZeroSum(ListNode* head, int K){ // Root node initialise to 0 ListNode* root = new ListNode(0); // Append at the front of the given // Linked List root->next = head; // Map to store the sum and reference // of the Node unordered_map<int, ListNode*> umap; umap[0] = root; // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != NULL) { // Find sum sum += head->val; // If found value with (sum - K) if (umap.find(sum - K) != umap.end()) { ListNode* prev = umap[sum - K]; ListNode* start = prev; // Update sum sum = sum - K; int aux = sum; // Traverse till current head while (prev != head) { prev = prev->next; aux += prev->val; if (prev != head) { umap.erase(aux); } } // Update the start value to // the next value of current head start->next = head->next; } // If (sum - K) value not found else if (umap.find(sum) == umap.end()) { umap[sum] = head; } head = head->next; } // Return the value of updated // head node return root->next;} // Driver Codeint main(){ // head Node ListNode* head; // Create Linked List head = getNode(1); head->next = getNode(2); head->next->next = getNode(-3); head->next->next->next = getNode(3); head->next->next->next->next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != NULL) printList(head); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; // A Linked List Nodeclass ListNode { int val; ListNode next; // Constructor ListNode(int val) { this.val = val; this.next = null; }} class GFG { // Function to create Node static ListNode getNode(int data) { ListNode temp = new ListNode(data); return temp; } // Function to print the Linked List static void printList(ListNode head) { while (head.next != null) { System.out.print(head.val + " -> "); head = head.next; } System.out.print(head.val); } // Function that removes continuous nodes // whose sum is K static ListNode removeZeroSum(ListNode head, int K) { // Root node initialise to 0 ListNode root = new ListNode(0); // Append at the front of the given // Linked List root.next = head; // Map to store the sum and reference // of the Node Map<Integer, ListNode> umap = new HashMap<Integer, ListNode>(); umap.put(0, root); // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != null) { // Find sum sum += head.val; // If found value with (sum - K) if (umap.containsKey(sum - K)) { ListNode prev = umap.get(sum - K); ListNode start = prev; // Delete all the node // traverse till current node int aux = sum; // Update sum sum = sum - K; // Traverse till current head while (prev != head) { prev = prev.next; aux += prev.val; if (prev != head) { umap.remove(aux); } } // Update the start value to // the next value of current head start.next = head.next; } // If (sum - K) value not found else if (!umap.containsKey(sum)) { umap.put(sum, head); } head = head.next; } // Return the value of updated // head node return root.next; } // Driver code public static void main(String[] args) { // head Node ListNode head; // Create Linked List head = getNode(1); head.next = getNode(2); head.next.next = getNode(-3); head.next.next.next = getNode(3); head.next.next.next.next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != null) printList(head); }} // This code is contributed by jitin.
# Python3 program for the above approach # A Linked List Nodeclass ListNode: def __init__(self, val): self.val = val self.next = None # Function to create Nodedef getNode(data): temp = ListNode(data) temp.next = None return temp # Function to print the Linked Listdef printList(head): while (head.next): print(head.val, end=' -> ') head = head.next print(head.val, end='') # Function that removes continuous nodes# whose sum is Kdef removeZeroSum(head, K): # Root node initialise to 0 root = ListNode(0) # Append at the front of the given # Linked List root.next = head # Map to store the sum and reference # of the Node umap = dict() umap[0] = root # To store the sum while traversing sum = 0 # Traversing the Linked List while (head != None): # Find sum sum += head.val # If found value with (sum - K) if ((sum - K) in umap): prev = umap[sum - K] start = prev # Delete all the node # traverse till current node aux = sum # Update sum sum = sum - K # Traverse till current head while (prev != head): prev = prev.next aux += prev.val if (prev != head): umap.remove(aux) # Update the start value to # the next value of current head start.next = head.next # If (sum - K) value not found else: umap[sum] = head head = head.next # Return the value of updated # head node return root.next # Driver Codeif __name__ == '__main__': # Create Linked List head = getNode(1) head.next = getNode(2) head.next.next = getNode(-3) head.next.next.next = getNode(3) head.next.next.next.next = getNode(1) # Given sum K K = 5 # Function call to get head node # of the updated Linked List head = removeZeroSum(head, K) # Print the updated Linked List if(head != None): printList(head) # This code is contributed by pratham76
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; // A Linked List Nodeclass ListNode { public int val; public ListNode next; // Constructor public ListNode(int val) { this.val = val; this.next = null; }} class GFG { // Function to create Node static ListNode getNode(int data) { ListNode temp = new ListNode(data); return temp; } // Function to print the Linked List static void printList(ListNode head) { while (head.next != null) { Console.Write(head.val + " -> "); head = head.next; } Console.Write(head.val); } // Function that removes continuous nodes // whose sum is K static ListNode removeZeroSum(ListNode head, int K) { // Root node initialise to 0 ListNode root = new ListNode(0); // Append at the front of the given // Linked List root.next = head; // Map to store the sum and reference // of the Node Dictionary<int, ListNode> umap = new Dictionary<int, ListNode>(); umap.Add(0, root); // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != null) { // Find sum sum += head.val; // If found value with (sum - K) if (umap.ContainsKey(sum - K)) { ListNode prev = umap[sum - K]; ListNode start = prev; // Delete all the node // traverse till current node int aux = sum; // Update sum sum = sum - K; // Traverse till current head while (prev != head) { prev = prev.next; aux += prev.val; if (prev != head) { umap.Remove(aux); } } // Update the start value to // the next value of current head start.next = head.next; } // If (sum - K) value not found else if (!umap.ContainsKey(sum)) { umap.Add(sum, head); } head = head.next; } // Return the value of updated // head node return root.next; } // Driver code public static void Main(string[] args) { // head Node ListNode head; // Create Linked List head = getNode(1); head.next = getNode(2); head.next.next = getNode(-3); head.next.next.next = getNode(3); head.next.next.next.next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != null) printList(head); }} // This code is contributed by rutvik_56
<script> // JavaScript program for the above approach // A Linked List Nodeclass ListNode{ constructor(val){ this.val = val this.next = null }} // Function to create Nodefunction getNode(data){ let temp = new ListNode(data) temp.next = null return temp} // Function to print the Linked Listfunction printList(head){ while (head.next){ document.write(head.val,' -> ') head = head.next } document.write(head.val,'')} // Function that removes continuous nodes// whose sum is Kfunction removeZeroSum(head, K){ // Root node initialise to 0 let root = new ListNode(0) // Append at the front of the given // Linked List root.next = head // Map to store the sum and reference // of the Node let umap = new Map(); umap.set(0,root) // To store the sum while traversing let sum = 0 // Traversing the Linked List while (head != null){ // Find sum sum += head.val // If found value with (sum - K) if (umap.has(sum - K) == true){ let prev = umap.get(sum - K) let start = prev // Delete all the node // traverse till current node let aux = sum // Update sum sum = sum - K // Traverse till current head while (prev != head){ prev = prev.next aux += prev.val if (prev != head) umap.delete(aux) } // Update the start value to // the next value of current head start.next = head.next } // If (sum - K) value not found else umap.set(sum,head) head = head.next } // Return the value of updated // head node return root.next} // Driver Code // Create Linked Listlet head = getNode(1)head.next = getNode(2)head.next.next = getNode(-3)head.next.next.next = getNode(3)head.next.next.next.next = getNode(1) // Given sum Klet K = 5 // Function call to get head node// of the updated Linked Listhead = removeZeroSum(head, K) // Print the updated Linked Listif(head != null) printList(head) // This code is contributed by shinjanpatra</script>
1 -> 2 -> -3 -> 3 -> 1
Time Complexity: O(N), where N is the number of Node in the Linked List. Auxiliary Space Complexity: O(N), where N is the number of Node in the Linked List.
jithin
rutvik_56
khushboogoyal499
pratham76
khushijhawar31
surinderdawra388
sg136
shinjanpatra
Linked List
Mathematical
Write From Home
Linked List
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Linked List vs Array
Doubly Linked List | Set 1 (Introduction and Insertion)
Merge two sorted linked lists
Delete a Linked List node at a given position
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": 26383,
"s": 26355,
"text": "\n17 Apr, 2022"
},
{
"code": null,
"e": 26637,
"s": 26383,
"text": "Given a singly linked list and an integer K, the task is to remove all the continuous set of nodes whose sum is K from the given linked list. Print the updated linked list after the removal. If no such deletion can occur, print the original Linked list."
},
{
"code": null,
"e": 26649,
"s": 26637,
"text": "Examples: "
},
{
"code": null,
"e": 26700,
"s": 26649,
"text": "Input: Linked List: 1 -> 2 -> -3 -> 3 -> 1, K = 3 "
},
{
"code": null,
"e": 26717,
"s": 26700,
"text": "Output: -3 -> 1 "
},
{
"code": null,
"e": 26731,
"s": 26717,
"text": "Explanation: "
},
{
"code": null,
"e": 26769,
"s": 26731,
"text": "The nodes with continuous sum 3 are: "
},
{
"code": null,
"e": 26780,
"s": 26769,
"text": "1) 1 -> 2 "
},
{
"code": null,
"e": 26786,
"s": 26780,
"text": "2) 3 "
},
{
"code": null,
"e": 26861,
"s": 26786,
"text": "Therefore, after removing these chain of nodes Linked List becomes: -3-> 1"
},
{
"code": null,
"e": 26997,
"s": 26861,
"text": "Input: Linked List: 1 -> 1 -> -3 -> -3 -> -2, K = 5 Output: 1 -> 1 -> -3 -> -3 -> -2 Explanation: No continuous nodes exits with sum K "
},
{
"code": null,
"e": 27009,
"s": 26997,
"text": "Approach: "
},
{
"code": null,
"e": 27553,
"s": 27009,
"text": "Append Node with value zero at the starting of the linked list.Traverse the given linked list.During traversal store the sum of the node value till that node with the reference of the current node in an unordered_map.If there is Node with value (sum β K) present in the unordered_map then delete all the nodes from the node corresponding to value (sum β K) stored in map to the current node and update the sum as (sum β K).If there is no Node with value (sum β K) present in the unordered_map, then stored the current sum with node in the map."
},
{
"code": null,
"e": 27617,
"s": 27553,
"text": "Append Node with value zero at the starting of the linked list."
},
{
"code": null,
"e": 27649,
"s": 27617,
"text": "Traverse the given linked list."
},
{
"code": null,
"e": 27773,
"s": 27649,
"text": "During traversal store the sum of the node value till that node with the reference of the current node in an unordered_map."
},
{
"code": null,
"e": 27980,
"s": 27773,
"text": "If there is Node with value (sum β K) present in the unordered_map then delete all the nodes from the node corresponding to value (sum β K) stored in map to the current node and update the sum as (sum β K)."
},
{
"code": null,
"e": 28101,
"s": 27980,
"text": "If there is no Node with value (sum β K) present in the unordered_map, then stored the current sum with node in the map."
},
{
"code": null,
"e": 28153,
"s": 28101,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28157,
"s": 28153,
"text": "C++"
},
{
"code": null,
"e": 28162,
"s": 28157,
"text": "Java"
},
{
"code": null,
"e": 28170,
"s": 28162,
"text": "Python3"
},
{
"code": null,
"e": 28173,
"s": 28170,
"text": "C#"
},
{
"code": null,
"e": 28184,
"s": 28173,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // A Linked List Nodestruct ListNode { int val; ListNode* next; // Constructor ListNode(int x) : val(x) , next(NULL) { }}; // Function to create NodeListNode* getNode(int data){ ListNode* temp; temp = (ListNode*)malloc(sizeof(ListNode)); temp->val = data; temp->next = NULL; return temp;} // Function to print the Linked Listvoid printList(ListNode* head){ while (head->next) { cout << head->val << \" -> \"; head = head->next; } printf(\"%d\", head->val);} // Function that removes continuous nodes// whose sum is KListNode* removeZeroSum(ListNode* head, int K){ // Root node initialise to 0 ListNode* root = new ListNode(0); // Append at the front of the given // Linked List root->next = head; // Map to store the sum and reference // of the Node unordered_map<int, ListNode*> umap; umap[0] = root; // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != NULL) { // Find sum sum += head->val; // If found value with (sum - K) if (umap.find(sum - K) != umap.end()) { ListNode* prev = umap[sum - K]; ListNode* start = prev; // Update sum sum = sum - K; int aux = sum; // Traverse till current head while (prev != head) { prev = prev->next; aux += prev->val; if (prev != head) { umap.erase(aux); } } // Update the start value to // the next value of current head start->next = head->next; } // If (sum - K) value not found else if (umap.find(sum) == umap.end()) { umap[sum] = head; } head = head->next; } // Return the value of updated // head node return root->next;} // Driver Codeint main(){ // head Node ListNode* head; // Create Linked List head = getNode(1); head->next = getNode(2); head->next->next = getNode(-3); head->next->next->next = getNode(3); head->next->next->next->next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != NULL) printList(head); return 0;}",
"e": 30686,
"s": 28184,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; // A Linked List Nodeclass ListNode { int val; ListNode next; // Constructor ListNode(int val) { this.val = val; this.next = null; }} class GFG { // Function to create Node static ListNode getNode(int data) { ListNode temp = new ListNode(data); return temp; } // Function to print the Linked List static void printList(ListNode head) { while (head.next != null) { System.out.print(head.val + \" -> \"); head = head.next; } System.out.print(head.val); } // Function that removes continuous nodes // whose sum is K static ListNode removeZeroSum(ListNode head, int K) { // Root node initialise to 0 ListNode root = new ListNode(0); // Append at the front of the given // Linked List root.next = head; // Map to store the sum and reference // of the Node Map<Integer, ListNode> umap = new HashMap<Integer, ListNode>(); umap.put(0, root); // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != null) { // Find sum sum += head.val; // If found value with (sum - K) if (umap.containsKey(sum - K)) { ListNode prev = umap.get(sum - K); ListNode start = prev; // Delete all the node // traverse till current node int aux = sum; // Update sum sum = sum - K; // Traverse till current head while (prev != head) { prev = prev.next; aux += prev.val; if (prev != head) { umap.remove(aux); } } // Update the start value to // the next value of current head start.next = head.next; } // If (sum - K) value not found else if (!umap.containsKey(sum)) { umap.put(sum, head); } head = head.next; } // Return the value of updated // head node return root.next; } // Driver code public static void main(String[] args) { // head Node ListNode head; // Create Linked List head = getNode(1); head.next = getNode(2); head.next.next = getNode(-3); head.next.next.next = getNode(3); head.next.next.next.next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != null) printList(head); }} // This code is contributed by jitin.",
"e": 33639,
"s": 30686,
"text": null
},
{
"code": "# Python3 program for the above approach # A Linked List Nodeclass ListNode: def __init__(self, val): self.val = val self.next = None # Function to create Nodedef getNode(data): temp = ListNode(data) temp.next = None return temp # Function to print the Linked Listdef printList(head): while (head.next): print(head.val, end=' -> ') head = head.next print(head.val, end='') # Function that removes continuous nodes# whose sum is Kdef removeZeroSum(head, K): # Root node initialise to 0 root = ListNode(0) # Append at the front of the given # Linked List root.next = head # Map to store the sum and reference # of the Node umap = dict() umap[0] = root # To store the sum while traversing sum = 0 # Traversing the Linked List while (head != None): # Find sum sum += head.val # If found value with (sum - K) if ((sum - K) in umap): prev = umap[sum - K] start = prev # Delete all the node # traverse till current node aux = sum # Update sum sum = sum - K # Traverse till current head while (prev != head): prev = prev.next aux += prev.val if (prev != head): umap.remove(aux) # Update the start value to # the next value of current head start.next = head.next # If (sum - K) value not found else: umap[sum] = head head = head.next # Return the value of updated # head node return root.next # Driver Codeif __name__ == '__main__': # Create Linked List head = getNode(1) head.next = getNode(2) head.next.next = getNode(-3) head.next.next.next = getNode(3) head.next.next.next.next = getNode(1) # Given sum K K = 5 # Function call to get head node # of the updated Linked List head = removeZeroSum(head, K) # Print the updated Linked List if(head != None): printList(head) # This code is contributed by pratham76",
"e": 35764,
"s": 33639,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; // A Linked List Nodeclass ListNode { public int val; public ListNode next; // Constructor public ListNode(int val) { this.val = val; this.next = null; }} class GFG { // Function to create Node static ListNode getNode(int data) { ListNode temp = new ListNode(data); return temp; } // Function to print the Linked List static void printList(ListNode head) { while (head.next != null) { Console.Write(head.val + \" -> \"); head = head.next; } Console.Write(head.val); } // Function that removes continuous nodes // whose sum is K static ListNode removeZeroSum(ListNode head, int K) { // Root node initialise to 0 ListNode root = new ListNode(0); // Append at the front of the given // Linked List root.next = head; // Map to store the sum and reference // of the Node Dictionary<int, ListNode> umap = new Dictionary<int, ListNode>(); umap.Add(0, root); // To store the sum while traversing int sum = 0; // Traversing the Linked List while (head != null) { // Find sum sum += head.val; // If found value with (sum - K) if (umap.ContainsKey(sum - K)) { ListNode prev = umap[sum - K]; ListNode start = prev; // Delete all the node // traverse till current node int aux = sum; // Update sum sum = sum - K; // Traverse till current head while (prev != head) { prev = prev.next; aux += prev.val; if (prev != head) { umap.Remove(aux); } } // Update the start value to // the next value of current head start.next = head.next; } // If (sum - K) value not found else if (!umap.ContainsKey(sum)) { umap.Add(sum, head); } head = head.next; } // Return the value of updated // head node return root.next; } // Driver code public static void Main(string[] args) { // head Node ListNode head; // Create Linked List head = getNode(1); head.next = getNode(2); head.next.next = getNode(-3); head.next.next.next = getNode(3); head.next.next.next.next = getNode(1); // Given sum K int K = 5; // Function call to get head node // of the updated Linked List head = removeZeroSum(head, K); // Print the updated Linked List if (head != null) printList(head); }} // This code is contributed by rutvik_56",
"e": 38768,
"s": 35764,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // A Linked List Nodeclass ListNode{ constructor(val){ this.val = val this.next = null }} // Function to create Nodefunction getNode(data){ let temp = new ListNode(data) temp.next = null return temp} // Function to print the Linked Listfunction printList(head){ while (head.next){ document.write(head.val,' -> ') head = head.next } document.write(head.val,'')} // Function that removes continuous nodes// whose sum is Kfunction removeZeroSum(head, K){ // Root node initialise to 0 let root = new ListNode(0) // Append at the front of the given // Linked List root.next = head // Map to store the sum and reference // of the Node let umap = new Map(); umap.set(0,root) // To store the sum while traversing let sum = 0 // Traversing the Linked List while (head != null){ // Find sum sum += head.val // If found value with (sum - K) if (umap.has(sum - K) == true){ let prev = umap.get(sum - K) let start = prev // Delete all the node // traverse till current node let aux = sum // Update sum sum = sum - K // Traverse till current head while (prev != head){ prev = prev.next aux += prev.val if (prev != head) umap.delete(aux) } // Update the start value to // the next value of current head start.next = head.next } // If (sum - K) value not found else umap.set(sum,head) head = head.next } // Return the value of updated // head node return root.next} // Driver Code // Create Linked Listlet head = getNode(1)head.next = getNode(2)head.next.next = getNode(-3)head.next.next.next = getNode(3)head.next.next.next.next = getNode(1) // Given sum Klet K = 5 // Function call to get head node// of the updated Linked Listhead = removeZeroSum(head, K) // Print the updated Linked Listif(head != null) printList(head) // This code is contributed by shinjanpatra</script>",
"e": 40980,
"s": 38768,
"text": null
},
{
"code": null,
"e": 41003,
"s": 40980,
"text": "1 -> 2 -> -3 -> 3 -> 1"
},
{
"code": null,
"e": 41160,
"s": 41003,
"text": "Time Complexity: O(N), where N is the number of Node in the Linked List. Auxiliary Space Complexity: O(N), where N is the number of Node in the Linked List."
},
{
"code": null,
"e": 41167,
"s": 41160,
"text": "jithin"
},
{
"code": null,
"e": 41177,
"s": 41167,
"text": "rutvik_56"
},
{
"code": null,
"e": 41194,
"s": 41177,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 41204,
"s": 41194,
"text": "pratham76"
},
{
"code": null,
"e": 41219,
"s": 41204,
"text": "khushijhawar31"
},
{
"code": null,
"e": 41236,
"s": 41219,
"text": "surinderdawra388"
},
{
"code": null,
"e": 41242,
"s": 41236,
"text": "sg136"
},
{
"code": null,
"e": 41255,
"s": 41242,
"text": "shinjanpatra"
},
{
"code": null,
"e": 41267,
"s": 41255,
"text": "Linked List"
},
{
"code": null,
"e": 41280,
"s": 41267,
"text": "Mathematical"
},
{
"code": null,
"e": 41296,
"s": 41280,
"text": "Write From Home"
},
{
"code": null,
"e": 41308,
"s": 41296,
"text": "Linked List"
},
{
"code": null,
"e": 41321,
"s": 41308,
"text": "Mathematical"
},
{
"code": null,
"e": 41419,
"s": 41321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41438,
"s": 41419,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 41459,
"s": 41438,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 41515,
"s": 41459,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 41545,
"s": 41515,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 41591,
"s": 41545,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 41621,
"s": 41591,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 41681,
"s": 41621,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41696,
"s": 41681,
"text": "C++ Data Types"
},
{
"code": null,
"e": 41739,
"s": 41696,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to create bar chart in react using material UI and Devexpress ? - GeeksforGeeks
|
19 Jul, 2021
DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications.
Bar Charts: A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of the dataset. These data sets contain the numerical values of variables that represent the length or height.
Steps for creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart
npm install @material-ui/core
npm i --save @devexpress/dx-react-chart-material-ui
Step 3: After creating the ReactJS application, install the required modules using the following command.
npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart
npm install @material-ui/core
npm i --save @devexpress/dx-react-chart-material-ui
Project Structure: It will look like the following :
Project Structure
Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code.
App.js
import React from "react";import Paper from '@material-ui/core/Paper';import { ArgumentAxis, ValueAxis, Chart, BarSeries,} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument: 'Monday', value: 30 }, { argument: 'Tuesday', value: 20 }, { argument: 'Wednesday', value: 10 }, { argument: 'Thursday', value: 50 }, { argument: 'Friday', value: 60 },];return ( <Paper> <Chart data={data} > <ArgumentAxis /> <ValueAxis /> <BarSeries valueField="value" argumentField="argument" /> </Chart> </Paper>);} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
Material-UI
Picked
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26567,
"s": 26539,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 26698,
"s": 26567,
"text": "DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications."
},
{
"code": null,
"e": 27047,
"s": 26698,
"text": "Bar Charts: A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of the dataset. These data sets contain the numerical values of variables that represent the length or height."
},
{
"code": null,
"e": 27107,
"s": 27047,
"text": "Steps for creating React Application And Installing Module:"
},
{
"code": null,
"e": 27203,
"s": 27107,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername "
},
{
"code": null,
"e": 27267,
"s": 27203,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 27299,
"s": 27267,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27415,
"s": 27301,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 27516,
"s": 27415,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command."
},
{
"code": null,
"e": 27530,
"s": 27516,
"text": "cd foldername"
},
{
"code": null,
"e": 27783,
"s": 27530,
"text": "Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui"
},
{
"code": null,
"e": 27889,
"s": 27783,
"text": "Step 3: After creating the ReactJS application, install the required modules using the following command."
},
{
"code": null,
"e": 28037,
"s": 27889,
"text": "npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui"
},
{
"code": null,
"e": 28090,
"s": 28037,
"text": "Project Structure: It will look like the following :"
},
{
"code": null,
"e": 28108,
"s": 28090,
"text": "Project Structure"
},
{
"code": null,
"e": 28242,
"s": 28108,
"text": "Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code."
},
{
"code": null,
"e": 28249,
"s": 28242,
"text": "App.js"
},
{
"code": "import React from \"react\";import Paper from '@material-ui/core/Paper';import { ArgumentAxis, ValueAxis, Chart, BarSeries,} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument: 'Monday', value: 30 }, { argument: 'Tuesday', value: 20 }, { argument: 'Wednesday', value: 10 }, { argument: 'Thursday', value: 50 }, { argument: 'Friday', value: 60 },];return ( <Paper> <Chart data={data} > <ArgumentAxis /> <ValueAxis /> <BarSeries valueField=\"value\" argumentField=\"argument\" /> </Chart> </Paper>);} export default App;",
"e": 28867,
"s": 28249,
"text": null
},
{
"code": null,
"e": 28980,
"s": 28867,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28990,
"s": 28980,
"text": "npm start"
},
{
"code": null,
"e": 29089,
"s": 28990,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29096,
"s": 29089,
"text": "Output"
},
{
"code": null,
"e": 29108,
"s": 29096,
"text": "Material-UI"
},
{
"code": null,
"e": 29115,
"s": 29108,
"text": "Picked"
},
{
"code": null,
"e": 29131,
"s": 29115,
"text": "React-Questions"
},
{
"code": null,
"e": 29142,
"s": 29131,
"text": "JavaScript"
},
{
"code": null,
"e": 29150,
"s": 29142,
"text": "ReactJS"
},
{
"code": null,
"e": 29167,
"s": 29150,
"text": "Web Technologies"
},
{
"code": null,
"e": 29265,
"s": 29167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29305,
"s": 29265,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29366,
"s": 29305,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29407,
"s": 29366,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29429,
"s": 29407,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29483,
"s": 29429,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29526,
"s": 29483,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29571,
"s": 29526,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 29636,
"s": 29571,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 29704,
"s": 29636,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Program to convert Number in characters - GeeksforGeeks
|
08 Dec, 2021
Given an Integer N. The task is to convert the number in characters.
Examples:
Input: N = 74254 Output: Seven four two five four
Input: N = 23 Output: Two three
An efficient approach:
Reverse the number.Iterate through the reversed number from right to left.Extract the last digit by using modulus, then use switch case to get the corresponding word.While iterating divide the number by 10.
Reverse the number.
Iterate through the reversed number from right to left.
Extract the last digit by using modulus, then use switch case to get the corresponding word.
While iterating divide the number by 10.
C++
Java
Python3
C#
Javascript
// C++ program to convert number in characters#include<bits/stdc++.h>using namespace std;void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: cout << "one "; break; case 2: cout << "two "; break; case 3: cout << "three "; break; case 4: cout << "four "; break; case 5: cout << "five "; break; case 6: cout << "six "; break; case 7: cout << "seven "; break; case 8: cout << "eight "; break; case 9: cout << "nine "; break; case 0: cout << "zero "; break; default: cout << "inValid "; break; } // Divide the number by 10 to get the next number rev = rev / 10; }}// Driver code#include <iostream>int main(){ int n = 12345; NumbertoCharacter(n); return 0;}
// Java program to convert number in charactersclass GFG{ static void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: System.out.print("one "); break; case 2: System.out.print("two "); break; case 3: System.out.print("three "); break; case 4: System.out.print("four "); break; case 5: System.out.print("five "); break; case 6: System.out.print("six "); break; case 7: System.out.print("seven "); break; case 8: System.out.print("eight "); break; case 9: System.out.print("nine "); break; case 0: System.out.print("zero "); break; default: System.out.print("InValid "); break; } // Divide the number by 10 // to get the next number rev = rev / 10; }} // Driver codepublic static void main(String[] args){ int n = 12345; NumbertoCharacter(n);}} // This code is contributed by Amit Katiyar
# Python3 program to convert# number in charactersdef NumbertoCharacter(n): rev = 0; r = 0; # To calculate the # reverse of the number while (n > 0): # The remainder will give # the last digit of the number r = n % 10; rev = rev * 10 + r; n = n // 10; while (rev > 0): # Extract the first digit # of the reversed number r = rev % 10; # Match it with switch case switcher = { 0 : "zero ", 1 : "one ", 2 : "two ", 3 : "three ", 4 : "four ", 5 : "five ", 6 : "six ", 7 : "seven ", 8 : "eight ", 9 : "nine " } print( switcher.get(r, "InValid"), end = " ") ; # Divide the number by 10 # to get the next number rev = rev // 10; # Driver codeif __name__ == '__main__': n = 12345; NumbertoCharacter(n); # This code is contributed by gauravrajput1
// C# program to convert number in charactersusing System; class GFG{ static void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse // of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: Console.Write("one "); break; case 2: Console.Write("two "); break; case 3: Console.Write("three "); break; case 4: Console.Write("four "); break; case 5: Console.Write("five "); break; case 6: Console.Write("six "); break; case 7: Console.Write("seven "); break; case 8: Console.Write("eight "); break; case 9: Console.Write("nine "); break; case 0: Console.Write("zero "); break; default: Console.Write("inValid "); break; } // Divide the number by 10 // to get the next number rev = rev / 10; }} // Driver codepublic static void Main(String[] args){ int n = 12345; NumbertoCharacter(n);}} // This code is contributed by sapnasingh4991
<script> // JavaScript program to convert number in characters function NumbertoCharacter(n){ let rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = Math.floor(n / 10); } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: document.write("one "); break; case 2: document.write("two "); break; case 3: document.write("three "); break; case 4: document.write("four "); break; case 5: document.write("five "); break; case 6: document.write("six "); break; case 7: document.write("seven "); break; case 8: document.write("eight "); break; case 9: document.write("nine "); break; case 0: document.write("zero "); break; default: document.write("UnValid "); break; } // Divide the number by 10 // to get the next number rev = Math.floor(rev / 10); }} // Driver codelet n = 12345;NumbertoCharacter(n); // This code is contributed by patel2127 </script>
one two three four five
Time complexity: O(k) k is the length of the number. Space complexity: O(1)
amit143katiyar
sapnasingh4991
GauravRajput1
patel2127
sagar0719kumar
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Program for factorial of a number
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
|
[
{
"code": null,
"e": 25712,
"s": 25684,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25781,
"s": 25712,
"text": "Given an Integer N. The task is to convert the number in characters."
},
{
"code": null,
"e": 25792,
"s": 25781,
"text": "Examples: "
},
{
"code": null,
"e": 25842,
"s": 25792,
"text": "Input: N = 74254 Output: Seven four two five four"
},
{
"code": null,
"e": 25876,
"s": 25842,
"text": "Input: N = 23 Output: Two three "
},
{
"code": null,
"e": 25901,
"s": 25876,
"text": "An efficient approach: "
},
{
"code": null,
"e": 26108,
"s": 25901,
"text": "Reverse the number.Iterate through the reversed number from right to left.Extract the last digit by using modulus, then use switch case to get the corresponding word.While iterating divide the number by 10."
},
{
"code": null,
"e": 26128,
"s": 26108,
"text": "Reverse the number."
},
{
"code": null,
"e": 26184,
"s": 26128,
"text": "Iterate through the reversed number from right to left."
},
{
"code": null,
"e": 26277,
"s": 26184,
"text": "Extract the last digit by using modulus, then use switch case to get the corresponding word."
},
{
"code": null,
"e": 26318,
"s": 26277,
"text": "While iterating divide the number by 10."
},
{
"code": null,
"e": 26322,
"s": 26318,
"text": "C++"
},
{
"code": null,
"e": 26327,
"s": 26322,
"text": "Java"
},
{
"code": null,
"e": 26335,
"s": 26327,
"text": "Python3"
},
{
"code": null,
"e": 26338,
"s": 26335,
"text": "C#"
},
{
"code": null,
"e": 26349,
"s": 26338,
"text": "Javascript"
},
{
"code": "// C++ program to convert number in characters#include<bits/stdc++.h>using namespace std;void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: cout << \"one \"; break; case 2: cout << \"two \"; break; case 3: cout << \"three \"; break; case 4: cout << \"four \"; break; case 5: cout << \"five \"; break; case 6: cout << \"six \"; break; case 7: cout << \"seven \"; break; case 8: cout << \"eight \"; break; case 9: cout << \"nine \"; break; case 0: cout << \"zero \"; break; default: cout << \"inValid \"; break; } // Divide the number by 10 to get the next number rev = rev / 10; }}// Driver code#include <iostream>int main(){ int n = 12345; NumbertoCharacter(n); return 0;}",
"e": 27720,
"s": 26349,
"text": null
},
{
"code": "// Java program to convert number in charactersclass GFG{ static void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: System.out.print(\"one \"); break; case 2: System.out.print(\"two \"); break; case 3: System.out.print(\"three \"); break; case 4: System.out.print(\"four \"); break; case 5: System.out.print(\"five \"); break; case 6: System.out.print(\"six \"); break; case 7: System.out.print(\"seven \"); break; case 8: System.out.print(\"eight \"); break; case 9: System.out.print(\"nine \"); break; case 0: System.out.print(\"zero \"); break; default: System.out.print(\"InValid \"); break; } // Divide the number by 10 // to get the next number rev = rev / 10; }} // Driver codepublic static void main(String[] args){ int n = 12345; NumbertoCharacter(n);}} // This code is contributed by Amit Katiyar",
"e": 29271,
"s": 27720,
"text": null
},
{
"code": "# Python3 program to convert# number in charactersdef NumbertoCharacter(n): rev = 0; r = 0; # To calculate the # reverse of the number while (n > 0): # The remainder will give # the last digit of the number r = n % 10; rev = rev * 10 + r; n = n // 10; while (rev > 0): # Extract the first digit # of the reversed number r = rev % 10; # Match it with switch case switcher = { 0 : \"zero \", 1 : \"one \", 2 : \"two \", 3 : \"three \", 4 : \"four \", 5 : \"five \", 6 : \"six \", 7 : \"seven \", 8 : \"eight \", 9 : \"nine \" } print( switcher.get(r, \"InValid\"), end = \" \") ; # Divide the number by 10 # to get the next number rev = rev // 10; # Driver codeif __name__ == '__main__': n = 12345; NumbertoCharacter(n); # This code is contributed by gauravrajput1",
"e": 30316,
"s": 29271,
"text": null
},
{
"code": "// C# program to convert number in charactersusing System; class GFG{ static void NumbertoCharacter(int n){ int rev = 0, r = 0; // To calculate the reverse // of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = n / 10; } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: Console.Write(\"one \"); break; case 2: Console.Write(\"two \"); break; case 3: Console.Write(\"three \"); break; case 4: Console.Write(\"four \"); break; case 5: Console.Write(\"five \"); break; case 6: Console.Write(\"six \"); break; case 7: Console.Write(\"seven \"); break; case 8: Console.Write(\"eight \"); break; case 9: Console.Write(\"nine \"); break; case 0: Console.Write(\"zero \"); break; default: Console.Write(\"inValid \"); break; } // Divide the number by 10 // to get the next number rev = rev / 10; }} // Driver codepublic static void Main(String[] args){ int n = 12345; NumbertoCharacter(n);}} // This code is contributed by sapnasingh4991",
"e": 31999,
"s": 30316,
"text": null
},
{
"code": "<script> // JavaScript program to convert number in characters function NumbertoCharacter(n){ let rev = 0, r = 0; // To calculate the reverse of the number while (n > 0) { // The remainder will give // the last digit of the number r = n % 10; rev = rev * 10 + r; n = Math.floor(n / 10); } while (rev > 0) { // Extract the first digit // of the reversed number r = rev % 10; // Match it with switch case switch (r) { case 1: document.write(\"one \"); break; case 2: document.write(\"two \"); break; case 3: document.write(\"three \"); break; case 4: document.write(\"four \"); break; case 5: document.write(\"five \"); break; case 6: document.write(\"six \"); break; case 7: document.write(\"seven \"); break; case 8: document.write(\"eight \"); break; case 9: document.write(\"nine \"); break; case 0: document.write(\"zero \"); break; default: document.write(\"UnValid \"); break; } // Divide the number by 10 // to get the next number rev = Math.floor(rev / 10); }} // Driver codelet n = 12345;NumbertoCharacter(n); // This code is contributed by patel2127 </script>",
"e": 33511,
"s": 31999,
"text": null
},
{
"code": null,
"e": 33535,
"s": 33511,
"text": "one two three four five"
},
{
"code": null,
"e": 33614,
"s": 33537,
"text": "Time complexity: O(k) k is the length of the number. Space complexity: O(1) "
},
{
"code": null,
"e": 33629,
"s": 33614,
"text": "amit143katiyar"
},
{
"code": null,
"e": 33644,
"s": 33629,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 33658,
"s": 33644,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33668,
"s": 33658,
"text": "patel2127"
},
{
"code": null,
"e": 33683,
"s": 33668,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 33696,
"s": 33683,
"text": "Mathematical"
},
{
"code": null,
"e": 33709,
"s": 33696,
"text": "Mathematical"
},
{
"code": null,
"e": 33807,
"s": 33709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33831,
"s": 33807,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33874,
"s": 33831,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33888,
"s": 33874,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33910,
"s": 33888,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 33952,
"s": 33910,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 34025,
"s": 33952,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 34059,
"s": 34025,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34100,
"s": 34059,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 34143,
"s": 34100,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Assertions in Java - GeeksforGeeks
|
24 Jan, 2022
An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It is mainly used for testing purposes during development.
The assert statement is used with a Boolean expression and can be written in two different ways.
First way:
assert expression;
Second way:
assert expression1 : expression2;
Example:
Java
// Java program to demonstrate syntax of assertionimport java.util.Scanner; class Test { public static void main(String args[]) { int value = 15; assert value >= 20 : " Underweight"; System.out.println("value is " + value); }}
value is 15
Output:
Exception in thread "main" java.lang.AssertionError: Underweight
Enabling Assertions
By default, assertions are disabled. We need to run the code as given. The syntax for enabling assertion statement in Java source code is:
java βea Test
Or
java βenableassertions Test
Here, Test is the file name.
Disabling Assertions
The syntax for disabling assertions in java is:
java βda Test
Or
java βdisableassertions Test
Here, Test is the file name.
Why use Assertions
Wherever a programmer wants to see if his/her assumptions are wrong or not.
To make sure that an unreachable-looking code is actually unreachable.
To make sure that assumptions written in comments are right.
if ((x & 1) == 1) {
}
else // x must be even
{
assert (x % 2 == 0);
}
To make sure the default switch case is not reached.
To check the objectβs state.
At the beginning of the method
After method invocation.
Assertion Vs Normal Exception Handling
Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time.
Where to use Assertions
Arguments to private methods. Private arguments are provided by the developerβs code only and the developer may want to check his/her assumptions about arguments.
Conditional cases.
Conditions at the beginning of any method.
Where not to use Assertions
Assertions should not be used to replace error messages
Assertions should not be used to check arguments in the public methods as they may be provided by the user. Error handling should be used to handle errors provided by users.
Assertions should not be used on command line arguments.
Example:
Java
// Java program to demonstrate assertion in Javapublic class Example { public static void main(String[] args) { int age = 14; assert age <= 18 : "Cannot Vote"; System.out.println("The voter's age is " + age); }}
The voter's age is 14
This article is contributed by Rahul Aggarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25447,
"s": 25419,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25776,
"s": 25447,
"text": "An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It is mainly used for testing purposes during development. "
},
{
"code": null,
"e": 25873,
"s": 25776,
"text": "The assert statement is used with a Boolean expression and can be written in two different ways."
},
{
"code": null,
"e": 25885,
"s": 25873,
"text": "First way: "
},
{
"code": null,
"e": 25904,
"s": 25885,
"text": "assert expression;"
},
{
"code": null,
"e": 25918,
"s": 25904,
"text": "Second way: "
},
{
"code": null,
"e": 25952,
"s": 25918,
"text": "assert expression1 : expression2;"
},
{
"code": null,
"e": 25961,
"s": 25952,
"text": "Example:"
},
{
"code": null,
"e": 25966,
"s": 25961,
"text": "Java"
},
{
"code": "// Java program to demonstrate syntax of assertionimport java.util.Scanner; class Test { public static void main(String args[]) { int value = 15; assert value >= 20 : \" Underweight\"; System.out.println(\"value is \" + value); }}",
"e": 26223,
"s": 25966,
"text": null
},
{
"code": null,
"e": 26235,
"s": 26223,
"text": "value is 15"
},
{
"code": null,
"e": 26245,
"s": 26235,
"text": "Output: "
},
{
"code": null,
"e": 26310,
"s": 26245,
"text": "Exception in thread \"main\" java.lang.AssertionError: Underweight"
},
{
"code": null,
"e": 26332,
"s": 26310,
"text": "Enabling Assertions "
},
{
"code": null,
"e": 26472,
"s": 26332,
"text": "By default, assertions are disabled. We need to run the code as given. The syntax for enabling assertion statement in Java source code is: "
},
{
"code": null,
"e": 26486,
"s": 26472,
"text": "java βea Test"
},
{
"code": null,
"e": 26490,
"s": 26486,
"text": "Or "
},
{
"code": null,
"e": 26518,
"s": 26490,
"text": "java βenableassertions Test"
},
{
"code": null,
"e": 26547,
"s": 26518,
"text": "Here, Test is the file name."
},
{
"code": null,
"e": 26568,
"s": 26547,
"text": "Disabling Assertions"
},
{
"code": null,
"e": 26617,
"s": 26568,
"text": "The syntax for disabling assertions in java is: "
},
{
"code": null,
"e": 26631,
"s": 26617,
"text": "java βda Test"
},
{
"code": null,
"e": 26636,
"s": 26631,
"text": "Or "
},
{
"code": null,
"e": 26665,
"s": 26636,
"text": "java βdisableassertions Test"
},
{
"code": null,
"e": 26694,
"s": 26665,
"text": "Here, Test is the file name."
},
{
"code": null,
"e": 26714,
"s": 26694,
"text": "Why use Assertions "
},
{
"code": null,
"e": 26791,
"s": 26714,
"text": "Wherever a programmer wants to see if his/her assumptions are wrong or not. "
},
{
"code": null,
"e": 26862,
"s": 26791,
"text": "To make sure that an unreachable-looking code is actually unreachable."
},
{
"code": null,
"e": 26923,
"s": 26862,
"text": "To make sure that assumptions written in comments are right."
},
{
"code": null,
"e": 26998,
"s": 26923,
"text": "if ((x & 1) == 1) {\n\n}\nelse // x must be even\n{\n assert (x % 2 == 0);\n}"
},
{
"code": null,
"e": 27051,
"s": 26998,
"text": "To make sure the default switch case is not reached."
},
{
"code": null,
"e": 27080,
"s": 27051,
"text": "To check the objectβs state."
},
{
"code": null,
"e": 27111,
"s": 27080,
"text": "At the beginning of the method"
},
{
"code": null,
"e": 27136,
"s": 27111,
"text": "After method invocation."
},
{
"code": null,
"e": 27175,
"s": 27136,
"text": "Assertion Vs Normal Exception Handling"
},
{
"code": null,
"e": 27461,
"s": 27175,
"text": "Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time. "
},
{
"code": null,
"e": 27487,
"s": 27461,
"text": "Where to use Assertions "
},
{
"code": null,
"e": 27650,
"s": 27487,
"text": "Arguments to private methods. Private arguments are provided by the developerβs code only and the developer may want to check his/her assumptions about arguments."
},
{
"code": null,
"e": 27669,
"s": 27650,
"text": "Conditional cases."
},
{
"code": null,
"e": 27712,
"s": 27669,
"text": "Conditions at the beginning of any method."
},
{
"code": null,
"e": 27742,
"s": 27712,
"text": "Where not to use Assertions "
},
{
"code": null,
"e": 27798,
"s": 27742,
"text": "Assertions should not be used to replace error messages"
},
{
"code": null,
"e": 27972,
"s": 27798,
"text": "Assertions should not be used to check arguments in the public methods as they may be provided by the user. Error handling should be used to handle errors provided by users."
},
{
"code": null,
"e": 28029,
"s": 27972,
"text": "Assertions should not be used on command line arguments."
},
{
"code": null,
"e": 28038,
"s": 28029,
"text": "Example:"
},
{
"code": null,
"e": 28043,
"s": 28038,
"text": "Java"
},
{
"code": "// Java program to demonstrate assertion in Javapublic class Example { public static void main(String[] args) { int age = 14; assert age <= 18 : \"Cannot Vote\"; System.out.println(\"The voter's age is \" + age); }}",
"e": 28285,
"s": 28043,
"text": null
},
{
"code": null,
"e": 28307,
"s": 28285,
"text": "The voter's age is 14"
},
{
"code": null,
"e": 28480,
"s": 28307,
"text": "This article is contributed by Rahul Aggarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28496,
"s": 28480,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 28501,
"s": 28496,
"text": "Java"
},
{
"code": null,
"e": 28506,
"s": 28501,
"text": "Java"
},
{
"code": null,
"e": 28604,
"s": 28506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28655,
"s": 28604,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28685,
"s": 28655,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28704,
"s": 28685,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28735,
"s": 28704,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28753,
"s": 28735,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28785,
"s": 28753,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28805,
"s": 28785,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28837,
"s": 28805,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28861,
"s": 28837,
"text": "Singleton Class in Java"
}
] |
How to Install Jupyter Notebook on MacOS? - GeeksforGeeks
|
26 Oct, 2021
>
In this article, we will learn how to install Jupyter Notebook in Python on MacOS.
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
Follow the below steps to install the Jupyter Notebook package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Jupyter Notebook using pip3.
pip3 install jupyter
Follow the below steps to install the Jupyter Notebook package on macOS using the setup.py file:
Step 1: Download the latest source package of Jupyter Notebook for python3 from here.
curl https://files.pythonhosted.org/packages/c9/a9/371d0b8fe37dd231cf4b2cff0a9f0f25e98f3a73c3771742444be27f2944/jupyter-1.0.0.tar.gz > jupyter.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf jupyter.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd jupyter-1.0.0
python3 setup.py install
Enter the following command in your terminal to start up Jupyter Notebook and verify if the installation has been done properly:
jupyter notebook
If there is any error while importing the module then is not installed properly.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
How to Install OpenCV for Python on Windows?
Java Tutorial
How to Install FFmpeg on Windows?
Installation of Node.js on Linux
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Install and Run Apache Kafka on Windows?
|
[
{
"code": null,
"e": 26111,
"s": 26083,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 26113,
"s": 26111,
"text": ">"
},
{
"code": null,
"e": 26197,
"s": 26113,
"text": "In this article, we will learn how to install Jupyter Notebook in Python on MacOS. "
},
{
"code": null,
"e": 26513,
"s": 26197,
"text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more."
},
{
"code": null,
"e": 26596,
"s": 26513,
"text": "Follow the below steps to install the Jupyter Notebook package on macOS using pip:"
},
{
"code": null,
"e": 26640,
"s": 26596,
"text": "Step 1: Install the latest Python3 in MacOS"
},
{
"code": null,
"e": 26699,
"s": 26640,
"text": "Step 2: Check if pip3 and python3 are correctly installed."
},
{
"code": null,
"e": 26732,
"s": 26699,
"text": "python3 --version\npip3 --version"
},
{
"code": null,
"e": 26794,
"s": 26732,
"text": "Step 3: Upgrade your pip to avoid errors during installation."
},
{
"code": null,
"e": 26821,
"s": 26794,
"text": "pip3 install --upgrade pip"
},
{
"code": null,
"e": 26897,
"s": 26821,
"text": "Step 4: Enter the following command to install Jupyter Notebook using pip3."
},
{
"code": null,
"e": 26918,
"s": 26897,
"text": "pip3 install jupyter"
},
{
"code": null,
"e": 27015,
"s": 26918,
"text": "Follow the below steps to install the Jupyter Notebook package on macOS using the setup.py file:"
},
{
"code": null,
"e": 27101,
"s": 27015,
"text": "Step 1: Download the latest source package of Jupyter Notebook for python3 from here."
},
{
"code": null,
"e": 27251,
"s": 27101,
"text": "curl https://files.pythonhosted.org/packages/c9/a9/371d0b8fe37dd231cf4b2cff0a9f0f25e98f3a73c3771742444be27f2944/jupyter-1.0.0.tar.gz > jupyter.tar.gz"
},
{
"code": null,
"e": 27319,
"s": 27251,
"text": "Step 2: Extract the downloaded package using the following command."
},
{
"code": null,
"e": 27344,
"s": 27319,
"text": "tar -xzvf jupyter.tar.gz"
},
{
"code": null,
"e": 27429,
"s": 27344,
"text": "Step 3: Go inside the folder and Enter the following command to install the package."
},
{
"code": null,
"e": 27506,
"s": 27429,
"text": "Note: You must have developer tools for XCode MacOS installed in your system"
},
{
"code": null,
"e": 27548,
"s": 27506,
"text": "cd jupyter-1.0.0\npython3 setup.py install"
},
{
"code": null,
"e": 27677,
"s": 27548,
"text": "Enter the following command in your terminal to start up Jupyter Notebook and verify if the installation has been done properly:"
},
{
"code": null,
"e": 27694,
"s": 27677,
"text": "jupyter notebook"
},
{
"code": null,
"e": 27775,
"s": 27694,
"text": "If there is any error while importing the module then is not installed properly."
},
{
"code": null,
"e": 27790,
"s": 27775,
"text": "how-to-install"
},
{
"code": null,
"e": 27797,
"s": 27790,
"text": "Picked"
},
{
"code": null,
"e": 27804,
"s": 27797,
"text": "How To"
},
{
"code": null,
"e": 27823,
"s": 27804,
"text": "Installation Guide"
},
{
"code": null,
"e": 27921,
"s": 27823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27948,
"s": 27921,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 27996,
"s": 27948,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28041,
"s": 27996,
"text": "How to Install OpenCV for Python on Windows?"
},
{
"code": null,
"e": 28055,
"s": 28041,
"text": "Java Tutorial"
},
{
"code": null,
"e": 28089,
"s": 28055,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28122,
"s": 28089,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28167,
"s": 28122,
"text": "How to Install OpenCV for Python on Windows?"
},
{
"code": null,
"e": 28201,
"s": 28167,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28236,
"s": 28201,
"text": "How to Install Pygame on Windows ?"
}
] |
Find postorder traversal of BST from preorder traversal - GeeksforGeeks
|
04 Dec, 2021
Given an array representing preorder traversal of BST, print its postorder traversal.
Examples:
Input : 40 30 35 80 100
Output : 35 30 100 80 40
Input : 40 30 32 35 80 90 100 120
Output : 35 32 30 120 100 90 80 40
Prerequisite: Construct BST from given preorder traversal
Simple Approach: A simple solution is to first construct BST from a given preorder traversal as described in this post. After constructing the tree, perform postorder traversal on it.
Efficient Approach: An efficient approach is to find postorder traversal without constructing the tree. The idea is to traverse the given preorder array and maintain a range in which current element should lie. This is to ensure that the BST property is always satisfied. Initially the range is set to {minval = INT_MIN, maxval = INT_MAX}. In preorder traversal, the first element is always the root, and it will certainly lie in the initial range. So store the first element of the preorder array. In postorder traversal, first left and right subtrees are printed and then root data is printed. So first recursive call for left and right subtrees are performed and then the value of root is printed. For left subtree range is updated to {minval, root->data} and for right subtree range is updated to {root->data, maxval}. If the current preorder array element does not lie in the range specified for it, then it does not belong to a current subtree, return from recursive calls until the correct position of that element is not found.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for finding postorder// traversal of BST from preorder traversal#include <bits/stdc++.h>using namespace std; // Function to find postorder traversal from// preorder traversal.void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex){ // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << " ";} // Function to find postorder traversal.void findPostOrder(int pre[], int n){ // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex);} // Driver codeint main(){ int pre[] = { 40, 30, 35, 80, 100 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0;}
// Java program for finding postorder// traversal of BST from preorder traversal import java.util.*; class Solution { static class INT { int data; INT(int d) { data = d; } } // Function to find postorder traversal from // preorder traversal. static void findPostOrderUtil(int pre[], int n, int minval, int maxval, INT preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex.data == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex.data]; preIndex.data++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); System.out.print(val + " "); } // Function to find postorder traversal. static void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. INT preIndex = new INT(0); findPostOrderUtil(pre, n, Integer.MIN_VALUE, Integer.MAX_VALUE, preIndex); } // Driver code public static void main(String args[]) { int pre[] = { 40, 30, 35, 80, 100 }; int n = pre.length; // Calling function findPostOrder(pre, n); }} // This code is contributed// by Arnab Kundu
"""Python3 program for finding postorder traversal of BST from preorder traversal""" INT_MIN = -2**31INT_MAX = 2**31 # Function to find postorder traversal# from preorder traversal. def findPostOrderUtil(pre, n, minval, maxval, preIndex): # If entire preorder array is traversed # then return as no more element is left # to be added to post order array. if (preIndex[0] == n): return # If array element does not lie in # range specified, then it is not # part of current subtree. if (pre[preIndex[0]] < minval or pre[preIndex[0]] > maxval): return # Store current value, to be printed later, # after printing left and right subtrees. # Increment preIndex to find left and right # subtrees, and pass this updated value to # recursive calls. val = pre[preIndex[0]] preIndex[0] += 1 # All elements with value between minval # and val lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex) # All elements with value between val # and maxval lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex) print(val, end=" ") # Function to find postorder traversal. def findPostOrder(pre, n): # To store index of element to be # traversed next in preorder array. # This is passed by reference to # utility function. preIndex = [0] findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex) # Driver Codeif __name__ == '__main__': pre = [40, 30, 35, 80, 100] n = len(pre) # Calling function findPostOrder(pre, n) # This code is contributed by# SHUBHAMSINGH10
// C# program for finding postorder// traversal of BST from preorder traversalusing System; class GFG { public class INT { public int data; public INT(int d) { data = d; } } // Function to find postorder traversal from // preorder traversal. public static void findPostOrderUtil(int[] pre, int n, int minval, int maxval, INT preIndex) { // If entire preorder array is traversed // then return as no more element is left // to be added to post order array. if (preIndex.data == n) { return; } // If array element does not lie in // range specified, then it is not // part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed // later, after printing left and right // subtrees. Increment preIndex to find // left and right subtrees, and pass this // updated value to recursive calls. int val = pre[preIndex.data]; preIndex.data++; // All elements with value between // minval and val lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between // val and maxval lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); Console.Write(val + " "); } // Function to find postorder traversal. public static void findPostOrder(int[] pre, int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. INT preIndex = new INT(0); findPostOrderUtil(pre, n, int.MinValue, int.MaxValue, preIndex); } // Driver code public static void Main(string[] args) { int[] pre = new int[] { 40, 30, 35, 80, 100 }; int n = pre.Length; // Calling function findPostOrder(pre, n); }} // This code is contributed by Shrikant13
<script>// Javascript program for finding postorder// traversal of BST from preorder traversal class INT{ constructor(d) { this.data=d; }} // Function to find postorder traversal from // preorder traversal.function findPostOrderUtil(pre,n,minval,maxval,preIndex){ // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex.data == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. let val = pre[preIndex.data]; preIndex.data++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); document.write(val + " ");} // Function to find postorder traversal.function findPostOrder(pre,n){ // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. let preIndex = new INT(0); findPostOrderUtil(pre, n, Number.MIN_VALUE, Number.MAX_VALUE, preIndex);} // Driver codelet pre=[40, 30, 35, 80, 100];let n = pre.length;// Calling functionfindPostOrder(pre, n); // This code is contributed by unknown2108</script>
35 30 100 80 40
Time Complexity: O(N), where N is the number of nodes. Auxiliary Space: O(N) (Function call stack size)
andrew1234
shrikanth13
SHUBHAMSINGH10
rohit sehajpal
RohitOberoi
mohit kumar 29
shivanisinghss2110
itsok
unknown2108
BST
PostOrder Traversal
Preorder Traversal
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Construct BST from given preorder traversal | Set 2
Print BST keys in the given range
Find median of BST in O(n) time and O(1) space
Red Black Tree vs AVL Tree
Find the largest BST subtree in a given Binary Tree | Set 1
Binary Search Tree | Set 3 (Iterative Delete)
Largest BST in a Binary Tree | Set 2
Flatten BST to sorted list | Increasing order
Construct all possible BSTs for keys 1 to N
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n04 Dec, 2021"
},
{
"code": null,
"e": 26444,
"s": 26357,
"text": "Given an array representing preorder traversal of BST, print its postorder traversal. "
},
{
"code": null,
"e": 26455,
"s": 26444,
"text": "Examples: "
},
{
"code": null,
"e": 26574,
"s": 26455,
"text": "Input : 40 30 35 80 100\nOutput : 35 30 100 80 40\n\nInput : 40 30 32 35 80 90 100 120\nOutput : 35 32 30 120 100 90 80 40"
},
{
"code": null,
"e": 26632,
"s": 26574,
"text": "Prerequisite: Construct BST from given preorder traversal"
},
{
"code": null,
"e": 26816,
"s": 26632,
"text": "Simple Approach: A simple solution is to first construct BST from a given preorder traversal as described in this post. After constructing the tree, perform postorder traversal on it."
},
{
"code": null,
"e": 27852,
"s": 26816,
"text": "Efficient Approach: An efficient approach is to find postorder traversal without constructing the tree. The idea is to traverse the given preorder array and maintain a range in which current element should lie. This is to ensure that the BST property is always satisfied. Initially the range is set to {minval = INT_MIN, maxval = INT_MAX}. In preorder traversal, the first element is always the root, and it will certainly lie in the initial range. So store the first element of the preorder array. In postorder traversal, first left and right subtrees are printed and then root data is printed. So first recursive call for left and right subtrees are performed and then the value of root is printed. For left subtree range is updated to {minval, root->data} and for right subtree range is updated to {root->data, maxval}. If the current preorder array element does not lie in the range specified for it, then it does not belong to a current subtree, return from recursive calls until the correct position of that element is not found."
},
{
"code": null,
"e": 27904,
"s": 27852,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27908,
"s": 27904,
"text": "C++"
},
{
"code": null,
"e": 27913,
"s": 27908,
"text": "Java"
},
{
"code": null,
"e": 27921,
"s": 27913,
"text": "Python3"
},
{
"code": null,
"e": 27924,
"s": 27921,
"text": "C#"
},
{
"code": null,
"e": 27935,
"s": 27924,
"text": "Javascript"
},
{
"code": "// C++ program for finding postorder// traversal of BST from preorder traversal#include <bits/stdc++.h>using namespace std; // Function to find postorder traversal from// preorder traversal.void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex){ // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << \" \";} // Function to find postorder traversal.void findPostOrder(int pre[], int n){ // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex);} // Driver codeint main(){ int pre[] = { 40, 30, 35, 80, 100 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0;}",
"e": 29604,
"s": 27935,
"text": null
},
{
"code": "// Java program for finding postorder// traversal of BST from preorder traversal import java.util.*; class Solution { static class INT { int data; INT(int d) { data = d; } } // Function to find postorder traversal from // preorder traversal. static void findPostOrderUtil(int pre[], int n, int minval, int maxval, INT preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex.data == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex.data]; preIndex.data++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); System.out.print(val + \" \"); } // Function to find postorder traversal. static void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. INT preIndex = new INT(0); findPostOrderUtil(pre, n, Integer.MIN_VALUE, Integer.MAX_VALUE, preIndex); } // Driver code public static void main(String args[]) { int pre[] = { 40, 30, 35, 80, 100 }; int n = pre.length; // Calling function findPostOrder(pre, n); }} // This code is contributed// by Arnab Kundu",
"e": 31729,
"s": 29604,
"text": null
},
{
"code": "\"\"\"Python3 program for finding postorder traversal of BST from preorder traversal\"\"\" INT_MIN = -2**31INT_MAX = 2**31 # Function to find postorder traversal# from preorder traversal. def findPostOrderUtil(pre, n, minval, maxval, preIndex): # If entire preorder array is traversed # then return as no more element is left # to be added to post order array. if (preIndex[0] == n): return # If array element does not lie in # range specified, then it is not # part of current subtree. if (pre[preIndex[0]] < minval or pre[preIndex[0]] > maxval): return # Store current value, to be printed later, # after printing left and right subtrees. # Increment preIndex to find left and right # subtrees, and pass this updated value to # recursive calls. val = pre[preIndex[0]] preIndex[0] += 1 # All elements with value between minval # and val lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex) # All elements with value between val # and maxval lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex) print(val, end=\" \") # Function to find postorder traversal. def findPostOrder(pre, n): # To store index of element to be # traversed next in preorder array. # This is passed by reference to # utility function. preIndex = [0] findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex) # Driver Codeif __name__ == '__main__': pre = [40, 30, 35, 80, 100] n = len(pre) # Calling function findPostOrder(pre, n) # This code is contributed by# SHUBHAMSINGH10",
"e": 33438,
"s": 31729,
"text": null
},
{
"code": "// C# program for finding postorder// traversal of BST from preorder traversalusing System; class GFG { public class INT { public int data; public INT(int d) { data = d; } } // Function to find postorder traversal from // preorder traversal. public static void findPostOrderUtil(int[] pre, int n, int minval, int maxval, INT preIndex) { // If entire preorder array is traversed // then return as no more element is left // to be added to post order array. if (preIndex.data == n) { return; } // If array element does not lie in // range specified, then it is not // part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed // later, after printing left and right // subtrees. Increment preIndex to find // left and right subtrees, and pass this // updated value to recursive calls. int val = pre[preIndex.data]; preIndex.data++; // All elements with value between // minval and val lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between // val and maxval lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); Console.Write(val + \" \"); } // Function to find postorder traversal. public static void findPostOrder(int[] pre, int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. INT preIndex = new INT(0); findPostOrderUtil(pre, n, int.MinValue, int.MaxValue, preIndex); } // Driver code public static void Main(string[] args) { int[] pre = new int[] { 40, 30, 35, 80, 100 }; int n = pre.Length; // Calling function findPostOrder(pre, n); }} // This code is contributed by Shrikant13",
"e": 35655,
"s": 33438,
"text": null
},
{
"code": "<script>// Javascript program for finding postorder// traversal of BST from preorder traversal class INT{ constructor(d) { this.data=d; }} // Function to find postorder traversal from // preorder traversal.function findPostOrderUtil(pre,n,minval,maxval,preIndex){ // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex.data == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex.data] < minval || pre[preIndex.data] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. let val = pre[preIndex.data]; preIndex.data++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); document.write(val + \" \");} // Function to find postorder traversal.function findPostOrder(pre,n){ // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. let preIndex = new INT(0); findPostOrderUtil(pre, n, Number.MIN_VALUE, Number.MAX_VALUE, preIndex);} // Driver codelet pre=[40, 30, 35, 80, 100];let n = pre.length;// Calling functionfindPostOrder(pre, n); // This code is contributed by unknown2108</script>",
"e": 37512,
"s": 35655,
"text": null
},
{
"code": null,
"e": 37528,
"s": 37512,
"text": "35 30 100 80 40"
},
{
"code": null,
"e": 37633,
"s": 37528,
"text": "Time Complexity: O(N), where N is the number of nodes. Auxiliary Space: O(N) (Function call stack size) "
},
{
"code": null,
"e": 37644,
"s": 37633,
"text": "andrew1234"
},
{
"code": null,
"e": 37656,
"s": 37644,
"text": "shrikanth13"
},
{
"code": null,
"e": 37671,
"s": 37656,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37686,
"s": 37671,
"text": "rohit sehajpal"
},
{
"code": null,
"e": 37698,
"s": 37686,
"text": "RohitOberoi"
},
{
"code": null,
"e": 37713,
"s": 37698,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37732,
"s": 37713,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 37738,
"s": 37732,
"text": "itsok"
},
{
"code": null,
"e": 37750,
"s": 37738,
"text": "unknown2108"
},
{
"code": null,
"e": 37754,
"s": 37750,
"text": "BST"
},
{
"code": null,
"e": 37774,
"s": 37754,
"text": "PostOrder Traversal"
},
{
"code": null,
"e": 37793,
"s": 37774,
"text": "Preorder Traversal"
},
{
"code": null,
"e": 37812,
"s": 37793,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37831,
"s": 37812,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 37929,
"s": 37831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37961,
"s": 37929,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 38013,
"s": 37961,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 38047,
"s": 38013,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 38094,
"s": 38047,
"text": "Find median of BST in O(n) time and O(1) space"
},
{
"code": null,
"e": 38121,
"s": 38094,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 38181,
"s": 38121,
"text": "Find the largest BST subtree in a given Binary Tree | Set 1"
},
{
"code": null,
"e": 38227,
"s": 38181,
"text": "Binary Search Tree | Set 3 (Iterative Delete)"
},
{
"code": null,
"e": 38264,
"s": 38227,
"text": "Largest BST in a Binary Tree | Set 2"
},
{
"code": null,
"e": 38310,
"s": 38264,
"text": "Flatten BST to sorted list | Increasing order"
}
] |
How to Scrape all PDF files in a Website? - GeeksforGeeks
|
21 Dec, 2021
Prerequisites: Implementing Web Scraping in Python with BeautifulSoup
Web Scraping is a method of extracting data from the website and use that data for other uses. There are several libraries and modules for doing web scraping in Python. In this article, weβll learn how to scrape the PDF files from the website with the help of beautifulsoup, which is one of the best web scraping modules in python, and the requests module for the GET requests. Also, for getting more information about the PDF file, we use PyPDF2 module.
Step by Step Code β
Step 1: Import all the important modules and packages.
Python3
# for get the pdf files or urlimport requests # for tree traversal scraping in webpagefrom bs4 import BeautifulSoup # for input and output operationsimport io # For getting information about the pdfsfrom PyPDF2 import PdfFileReader
Step 2: Passing the URL and make an HTML parser with the help of BeautifulSoup.
Python3
# website to scrapurl = "https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/" # get the url from requests get methodread = requests.get(url) # full html contenthtml_content = read.content # Parse the html contentsoup = BeautifulSoup(html_content, "html.parser")
In the above code:
Scraping is done by the https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/ link
requests module is used for making get request
read.content is used to go through all the HTML code. Printing will output the source code of the web page.
soup is having HTML content and used to parse the HTML
Step 3: We need to traverse through the PDFs from the website.
Python3
# created an empty list for putting the pdfslist_of_pdf = set() # accessed the first p tag in the htmll = soup.find('p') # accessed all the anchors tag from given p tagp = l.find_all('a') # iterate through p for getting all the href linksfor link in p: # original html links print("links: ", link.get('href')) print("\n") # converting the extension from .html to .pdf pdf_link = (link.get('href')[:-5]) + ".pdf" # converted to .pdf print("converted pdf links: ", pdf_link) print("\n") # added all the pdf links to set list_of_pdf.add(pdf_link)
Output:
In the above code:
list_of_pdf is an empty set created for adding all the PDF files from the web page. Set is used because it never repeats the same-named elements. And automatically get rid of duplicates.
Iteration is done within all the links converting the .HTML to .pdf. It is done as the PDF name and HTML name has an only difference in the format, the rest all are same.
We use the set because we need to get rid of duplicate names. The list can also be used and instead of add, we append all the PDFs.
Step 4: Create info function with pypdf2 module for getting all the required information of the pdf.
Python3
def info(pdf_path): # used get method to get the pdf file response = requests.get(pdf_path) # response.content generate binary code for # string function with io.BytesIO(response.content) as f: # initialized the pdf pdf = PdfFileReader(f) # all info about pdf information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f""" Information about {pdf_path}: Author: {information.author} Creator: {information.creator} Producer: {information.producer} Subject: {information.subject} Title: {information.title} Number of pages: {number_of_pages} """ print(txt) return information
In the above code:
Info function is responsible for giving all the required scraped output inside of the PDF.
io.BytesIO(response.content) β It is used because response.content is a binary code and the requests library is quite low leveled and generally compiled (not interpreted). So to handle byte, io.BytesIO is used.
There are several pypdfs2 functions to access different data in pdf.
Note: Refer Working with PDF files in Python for detailed information.
Python3
# print all the content of pdf in the consolefor i in list_of_pdf: info(i)
Complete Code:
Python3
import requestsfrom bs4 import BeautifulSoupimport iofrom PyPDF2 import PdfFileReader url = "https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/"read = requests.get(url)html_content = read.contentsoup = BeautifulSoup(html_content, "html.parser") list_of_pdf = set()l = soup.find('p')p = l.find_all('a') for link in (p): pdf_link = (link.get('href')[:-5]) + ".pdf" print(pdf_link) list_of_pdf.add(pdf_link) def info(pdf_path): response = requests.get(pdf_path) with io.BytesIO(response.content) as f: pdf = PdfFileReader(f) information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f""" Information about {pdf_path}: Author: {information.author} Creator: {information.creator} Producer: {information.producer} Subject: {information.subject} Title: {information.title} Number of pages: {number_of_pages} """ print(txt) return information for i in list_of_pdf: info(i)
Output:
simranarora5sos
simmytarika5
Picked
Python BeautifulSoup
Python bs4-Exercises
Python web-scraping-exercises
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 25607,
"s": 25537,
"text": "Prerequisites: Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 26063,
"s": 25607,
"text": "Web Scraping is a method of extracting data from the website and use that data for other uses. There are several libraries and modules for doing web scraping in Python. In this article, weβll learn how to scrape the PDF files from the website with the help of beautifulsoup, which is one of the best web scraping modules in python, and the requests module for the GET requests. Also, for getting more information about the PDF file, we use PyPDF2 module."
},
{
"code": null,
"e": 26083,
"s": 26063,
"text": "Step by Step Code β"
},
{
"code": null,
"e": 26138,
"s": 26083,
"text": "Step 1: Import all the important modules and packages."
},
{
"code": null,
"e": 26146,
"s": 26138,
"text": "Python3"
},
{
"code": "# for get the pdf files or urlimport requests # for tree traversal scraping in webpagefrom bs4 import BeautifulSoup # for input and output operationsimport io # For getting information about the pdfsfrom PyPDF2 import PdfFileReader",
"e": 26378,
"s": 26146,
"text": null
},
{
"code": null,
"e": 26458,
"s": 26378,
"text": "Step 2: Passing the URL and make an HTML parser with the help of BeautifulSoup."
},
{
"code": null,
"e": 26466,
"s": 26458,
"text": "Python3"
},
{
"code": "# website to scrapurl = \"https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/\" # get the url from requests get methodread = requests.get(url) # full html contenthtml_content = read.content # Parse the html contentsoup = BeautifulSoup(html_content, \"html.parser\")",
"e": 26743,
"s": 26466,
"text": null
},
{
"code": null,
"e": 26762,
"s": 26743,
"text": "In the above code:"
},
{
"code": null,
"e": 26858,
"s": 26762,
"text": "Scraping is done by the https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/ link"
},
{
"code": null,
"e": 26905,
"s": 26858,
"text": "requests module is used for making get request"
},
{
"code": null,
"e": 27013,
"s": 26905,
"text": "read.content is used to go through all the HTML code. Printing will output the source code of the web page."
},
{
"code": null,
"e": 27068,
"s": 27013,
"text": "soup is having HTML content and used to parse the HTML"
},
{
"code": null,
"e": 27131,
"s": 27068,
"text": "Step 3: We need to traverse through the PDFs from the website."
},
{
"code": null,
"e": 27139,
"s": 27131,
"text": "Python3"
},
{
"code": "# created an empty list for putting the pdfslist_of_pdf = set() # accessed the first p tag in the htmll = soup.find('p') # accessed all the anchors tag from given p tagp = l.find_all('a') # iterate through p for getting all the href linksfor link in p: # original html links print(\"links: \", link.get('href')) print(\"\\n\") # converting the extension from .html to .pdf pdf_link = (link.get('href')[:-5]) + \".pdf\" # converted to .pdf print(\"converted pdf links: \", pdf_link) print(\"\\n\") # added all the pdf links to set list_of_pdf.add(pdf_link)",
"e": 27733,
"s": 27139,
"text": null
},
{
"code": null,
"e": 27744,
"s": 27736,
"text": "Output:"
},
{
"code": null,
"e": 27763,
"s": 27744,
"text": "In the above code:"
},
{
"code": null,
"e": 27950,
"s": 27763,
"text": "list_of_pdf is an empty set created for adding all the PDF files from the web page. Set is used because it never repeats the same-named elements. And automatically get rid of duplicates."
},
{
"code": null,
"e": 28121,
"s": 27950,
"text": "Iteration is done within all the links converting the .HTML to .pdf. It is done as the PDF name and HTML name has an only difference in the format, the rest all are same."
},
{
"code": null,
"e": 28253,
"s": 28121,
"text": "We use the set because we need to get rid of duplicate names. The list can also be used and instead of add, we append all the PDFs."
},
{
"code": null,
"e": 28355,
"s": 28253,
"text": " Step 4: Create info function with pypdf2 module for getting all the required information of the pdf."
},
{
"code": null,
"e": 28363,
"s": 28355,
"text": "Python3"
},
{
"code": "def info(pdf_path): # used get method to get the pdf file response = requests.get(pdf_path) # response.content generate binary code for # string function with io.BytesIO(response.content) as f: # initialized the pdf pdf = PdfFileReader(f) # all info about pdf information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f\"\"\" Information about {pdf_path}: Author: {information.author} Creator: {information.creator} Producer: {information.producer} Subject: {information.subject} Title: {information.title} Number of pages: {number_of_pages} \"\"\" print(txt) return information",
"e": 29054,
"s": 28363,
"text": null
},
{
"code": null,
"e": 29076,
"s": 29054,
"text": " In the above code: "
},
{
"code": null,
"e": 29167,
"s": 29076,
"text": "Info function is responsible for giving all the required scraped output inside of the PDF."
},
{
"code": null,
"e": 29378,
"s": 29167,
"text": "io.BytesIO(response.content) β It is used because response.content is a binary code and the requests library is quite low leveled and generally compiled (not interpreted). So to handle byte, io.BytesIO is used."
},
{
"code": null,
"e": 29447,
"s": 29378,
"text": "There are several pypdfs2 functions to access different data in pdf."
},
{
"code": null,
"e": 29519,
"s": 29447,
"text": " Note: Refer Working with PDF files in Python for detailed information."
},
{
"code": null,
"e": 29527,
"s": 29519,
"text": "Python3"
},
{
"code": "# print all the content of pdf in the consolefor i in list_of_pdf: info(i)",
"e": 29605,
"s": 29527,
"text": null
},
{
"code": null,
"e": 29620,
"s": 29605,
"text": "Complete Code:"
},
{
"code": null,
"e": 29628,
"s": 29620,
"text": "Python3"
},
{
"code": "import requestsfrom bs4 import BeautifulSoupimport iofrom PyPDF2 import PdfFileReader url = \"https://www.geeksforgeeks.org/how-to-extract-pdf-tables-in-python/\"read = requests.get(url)html_content = read.contentsoup = BeautifulSoup(html_content, \"html.parser\") list_of_pdf = set()l = soup.find('p')p = l.find_all('a') for link in (p): pdf_link = (link.get('href')[:-5]) + \".pdf\" print(pdf_link) list_of_pdf.add(pdf_link) def info(pdf_path): response = requests.get(pdf_path) with io.BytesIO(response.content) as f: pdf = PdfFileReader(f) information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f\"\"\" Information about {pdf_path}: Author: {information.author} Creator: {information.creator} Producer: {information.producer} Subject: {information.subject} Title: {information.title} Number of pages: {number_of_pages} \"\"\" print(txt) return information for i in list_of_pdf: info(i)",
"e": 30610,
"s": 29628,
"text": null
},
{
"code": null,
"e": 30618,
"s": 30610,
"text": "Output:"
},
{
"code": null,
"e": 30634,
"s": 30618,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30647,
"s": 30634,
"text": "simmytarika5"
},
{
"code": null,
"e": 30654,
"s": 30647,
"text": "Picked"
},
{
"code": null,
"e": 30675,
"s": 30654,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 30696,
"s": 30675,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 30726,
"s": 30696,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 30739,
"s": 30726,
"text": "Web-scraping"
},
{
"code": null,
"e": 30746,
"s": 30739,
"text": "Python"
},
{
"code": null,
"e": 30844,
"s": 30746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30876,
"s": 30844,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30918,
"s": 30876,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30960,
"s": 30918,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31016,
"s": 30960,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31043,
"s": 31016,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31074,
"s": 31043,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31113,
"s": 31074,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31142,
"s": 31113,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 31164,
"s": 31142,
"text": "Defaultdict in Python"
}
] |
Running User Interface Thread in Android using Kotlin - GeeksforGeeks
|
23 Sep, 2021
User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.
Realizing UI Thread: For example, a thread action is started, and the developer wants to update the front-end element with respect to the thread elements, runOnUIThread{...} function can be used.Below is an example of the application where UI thread is used.
Sample App in which the text in the TextView is changed every second
Initially, the application will show a Welcome message and as soon as the start button is clicked, it will show 2 messages, βlove gfgβ and βnot gfgβ alternatively at each second.
Approach: Step 1: Add the below code in activity_main.xml. Here, add a TextView and a button to our MainActivity layout.
HTML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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/tv1" android:layout_width="210sp" android:layout_height="100sp" android:layout_centerInParent="true" android:gravity="center" android:textSize="50sp" android:text="Welcome" /> <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:layout_below="@id/tv1" android:layout_centerHorizontal="true" /> </RelativeLayout>
Step 2: Add the below code in MainActivity. Here OnClickListener is added with the button. So it is invoked whenever the user clicks the button. In the listener, an infinite loop is created in the main thread and using the UI thread the text is changed after every second.
Java
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning Layout elements val tv = findViewById<TextView>(R.id.tv1) val btn = findViewById<Button>(R.id.btnStart) val msg1 = "love gfg" val msg2 = "not gfg" // Button onClick action btn.setOnClickListener { // Declaring Main Thread Thread(Runnable { while (true) { // Updating Text View at current // iteration runOnUiThread{ tv.text = msg1 } // Thread sleep for 1 sec Thread.sleep(1000) // Updating Text View at current // iteration runOnUiThread{ tv.text = msg2 } // Thread sleep for 1 sec Thread.sleep(1000) } }).start() } }}
Note: The While loop must be declared only inside the Thread. If a Thread is declared inside a while loop, the program doesnβt work and crashes.
Sample Timer App From the basic concept of the above code, a timer app can be designed. Below is the code for the same:
Approach: Step 1: Add the below code in MainActivity layout. Here a button, edittext, and textview are added. The button is used to start the timer, edittext is used to take the input from the user, and textview is used to display the time left.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <Button android:id="@+id/btnStart" android:layout_width="100sp" android:layout_height="50sp" android:layout_centerInParent="true" android:text="Start" /> <EditText android:id="@+id/et1" android:layout_width="100sp" android:layout_height="100sp" android:layout_centerHorizontal="true" android:layout_above="@id/btnStart" android:textSize="50sp" android:inputType="number" android:gravity="center" android:background="@color/colorPrimary" android:textColor="@color/colorAccent" /> <TextView android:id="@+id/tv1" android:layout_width="100sp" android:layout_height="100sp" android:layout_centerHorizontal="true" android:layout_below="@id/btnStart" android:gravity="center" android:textSize="50sp" android:background="@color/colorPrimaryDark" android:textColor="@color/colorAccent" /> </RelativeLayout>
Step 2: Add the below code in MainActivity class. Here we add the onClickListener with the button. As the button is clicked, runOnUiThread function is used to display the time left.
Java
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning Layout elements val et = findViewById<EditText>(R.id.et1) val btn = findViewById<Button>(R.id.btnStart) val tv = findViewById<TextView>(R.id.tv1) // Button onClick action btn.setOnClickListener{ // Converting Edit Text input to String val stringTime= (et.text).toString() // Converting stringTime to Integer val intTime= Integer.parseInt(stringTime) // Declaring Main Thread Thread(Runnable { // For loop Decrement for (i in intTime downTo 0) { // Updating Text View at // current iteration runOnUiThread{ tv.text = i.toString() } // Thread sleep for 1 sec Thread.sleep(1000) } }).start() } }}
simmytarika5
android
Kotlin Android
Processes & Threads
Kotlin
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
ImageView in Android with Example
How to Build a Weather App in Android?
Android SQLite Database in Kotlin
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
|
[
{
"code": null,
"e": 25763,
"s": 25735,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 26076,
"s": 25763,
"text": "User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread. "
},
{
"code": null,
"e": 26336,
"s": 26076,
"text": "Realizing UI Thread: For example, a thread action is started, and the developer wants to update the front-end element with respect to the thread elements, runOnUIThread{...} function can be used.Below is an example of the application where UI thread is used. "
},
{
"code": null,
"e": 26407,
"s": 26336,
"text": "Sample App in which the text in the TextView is changed every second "
},
{
"code": null,
"e": 26587,
"s": 26407,
"text": "Initially, the application will show a Welcome message and as soon as the start button is clicked, it will show 2 messages, βlove gfgβ and βnot gfgβ alternatively at each second. "
},
{
"code": null,
"e": 26708,
"s": 26587,
"text": "Approach: Step 1: Add the below code in activity_main.xml. Here, add a TextView and a button to our MainActivity layout."
},
{
"code": null,
"e": 26713,
"s": 26708,
"text": "HTML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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/tv1\" android:layout_width=\"210sp\" android:layout_height=\"100sp\" android:layout_centerInParent=\"true\" android:gravity=\"center\" android:textSize=\"50sp\" android:text=\"Welcome\" /> <Button android:id=\"@+id/btnStart\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Start\" android:layout_below=\"@id/tv1\" android:layout_centerHorizontal=\"true\" /> </RelativeLayout>",
"e": 27580,
"s": 26713,
"text": null
},
{
"code": null,
"e": 27854,
"s": 27580,
"text": "Step 2: Add the below code in MainActivity. Here OnClickListener is added with the button. So it is invoked whenever the user clicks the button. In the listener, an infinite loop is created in the main thread and using the UI thread the text is changed after every second. "
},
{
"code": null,
"e": 27859,
"s": 27854,
"text": "Java"
},
{
"code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning Layout elements val tv = findViewById<TextView>(R.id.tv1) val btn = findViewById<Button>(R.id.btnStart) val msg1 = \"love gfg\" val msg2 = \"not gfg\" // Button onClick action btn.setOnClickListener { // Declaring Main Thread Thread(Runnable { while (true) { // Updating Text View at current // iteration runOnUiThread{ tv.text = msg1 } // Thread sleep for 1 sec Thread.sleep(1000) // Updating Text View at current // iteration runOnUiThread{ tv.text = msg2 } // Thread sleep for 1 sec Thread.sleep(1000) } }).start() } }}",
"e": 28897,
"s": 27859,
"text": null
},
{
"code": null,
"e": 29042,
"s": 28897,
"text": "Note: The While loop must be declared only inside the Thread. If a Thread is declared inside a while loop, the program doesnβt work and crashes."
},
{
"code": null,
"e": 29163,
"s": 29042,
"text": "Sample Timer App From the basic concept of the above code, a timer app can be designed. Below is the code for the same: "
},
{
"code": null,
"e": 29410,
"s": 29163,
"text": "Approach: Step 1: Add the below code in MainActivity layout. Here a button, edittext, and textview are added. The button is used to start the timer, edittext is used to take the input from the user, and textview is used to display the time left. "
},
{
"code": null,
"e": 29414,
"s": 29410,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <Button android:id=\"@+id/btnStart\" android:layout_width=\"100sp\" android:layout_height=\"50sp\" android:layout_centerInParent=\"true\" android:text=\"Start\" /> <EditText android:id=\"@+id/et1\" android:layout_width=\"100sp\" android:layout_height=\"100sp\" android:layout_centerHorizontal=\"true\" android:layout_above=\"@id/btnStart\" android:textSize=\"50sp\" android:inputType=\"number\" android:gravity=\"center\" android:background=\"@color/colorPrimary\" android:textColor=\"@color/colorAccent\" /> <TextView android:id=\"@+id/tv1\" android:layout_width=\"100sp\" android:layout_height=\"100sp\" android:layout_centerHorizontal=\"true\" android:layout_below=\"@id/btnStart\" android:gravity=\"center\" android:textSize=\"50sp\" android:background=\"@color/colorPrimaryDark\" android:textColor=\"@color/colorAccent\" /> </RelativeLayout>",
"e": 30745,
"s": 29414,
"text": null
},
{
"code": null,
"e": 30927,
"s": 30745,
"text": "Step 2: Add the below code in MainActivity class. Here we add the onClickListener with the button. As the button is clicked, runOnUiThread function is used to display the time left."
},
{
"code": null,
"e": 30932,
"s": 30927,
"text": "Java"
},
{
"code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Assigning Layout elements val et = findViewById<EditText>(R.id.et1) val btn = findViewById<Button>(R.id.btnStart) val tv = findViewById<TextView>(R.id.tv1) // Button onClick action btn.setOnClickListener{ // Converting Edit Text input to String val stringTime= (et.text).toString() // Converting stringTime to Integer val intTime= Integer.parseInt(stringTime) // Declaring Main Thread Thread(Runnable { // For loop Decrement for (i in intTime downTo 0) { // Updating Text View at // current iteration runOnUiThread{ tv.text = i.toString() } // Thread sleep for 1 sec Thread.sleep(1000) } }).start() } }}",
"e": 32096,
"s": 30932,
"text": null
},
{
"code": null,
"e": 32111,
"s": 32098,
"text": "simmytarika5"
},
{
"code": null,
"e": 32119,
"s": 32111,
"text": "android"
},
{
"code": null,
"e": 32134,
"s": 32119,
"text": "Kotlin Android"
},
{
"code": null,
"e": 32154,
"s": 32134,
"text": "Processes & Threads"
},
{
"code": null,
"e": 32161,
"s": 32154,
"text": "Kotlin"
},
{
"code": null,
"e": 32179,
"s": 32161,
"text": "Operating Systems"
},
{
"code": null,
"e": 32197,
"s": 32179,
"text": "Operating Systems"
},
{
"code": null,
"e": 32295,
"s": 32197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32337,
"s": 32295,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32377,
"s": 32337,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 32411,
"s": 32377,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 32450,
"s": 32411,
"text": "How to Build a Weather App in Android?"
},
{
"code": null,
"e": 32484,
"s": 32450,
"text": "Android SQLite Database in Kotlin"
},
{
"code": null,
"e": 32511,
"s": 32484,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 32550,
"s": 32511,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 32599,
"s": 32550,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 32639,
"s": 32599,
"text": "Program for FCFS CPU Scheduling | Set 1"
}
] |
Word Break Problem using Backtracking - GeeksforGeeks
|
08 Nov, 2021
Given a valid sentence without any spaces between the words and a dictionary of valid English words, find all possible ways to break the sentence into individual dictionary words.
Example
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
and, cream, icecream, man, go, mango}
Input: "ilikesamsungmobile"
Output: i like sam sung mobile
i like samsung mobile
Input: "ilikeicecreamandmango"
Output: i like ice cream and man go
i like ice cream and mango
i like icecream and man go
i like icecream and mango
We have discussed a Dynamic Programming solution in the below post. Dynamic Programming | Set 32 (Word Break Problem)
The Dynamic Programming solution only finds whether it is possible to break a word or not. Here we need to print all possible word breaks.We start scanning the sentence from the left. As we find a valid word, we need to check whether the rest of the sentence can make valid words or not. Because in some situations the first found word from the left side can leave a remaining portion that is not further separable. So, in that case, we should come back and leave the currently found word and keep on searching for the next word. And this process is recursive because to find out whether the right portion is separable or not, we need the same logic. So we will use recursion and backtracking to solve this problem. To keep track of the found words we will use a stack. Whenever the right portion of the string does not make valid words, we pop the top string from the stack and continue finding.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// A recursive program to print all possible// partitions of a given string into dictionary// words#include <iostream>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string &word){ string dictionary[] = {"mobile","samsung","sam","sung", "man","mango", "icecream","and", "go","i","love","ice","cream"}; int n = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < n; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Prototype of wordBreakUtilvoid wordBreakUtil(string str, int size, string result); // Prints all possible word breaks of given stringvoid wordBreak(string str){ // Last argument is prefix wordBreakUtil(str, str.size(), "");} // Result store the current prefix with spaces// between wordsvoid wordBreakUtil(string str, int n, string result){ //Process all prefixes one by one for (int i=1; i<=n; i++) { // Extract substring from 0 to i in prefix string prefix = str.substr(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if (dictionaryContains(prefix)) { // If no more elements are there, print it if (i == n) { // Add this element to previous prefix result += prefix; cout << result << endl; return; } wordBreakUtil(str.substr(i, n-i), n-i, result + prefix + " "); } } } //Driver Codeint main(){ // Function call cout << "First Test:\n"; wordBreak("iloveicecreamandmango"); cout << "\nSecond Test:\n"; wordBreak("ilovesamsungmobile"); return 0;}
// A recursive program to print all possible// partitions of a given string into dictionary// wordsimport java.io.*;import java.util.*; class GFG { // Prints all possible word breaks of given string static void wordBreak(int n, List<String> dict, String s) { String ans=""; wordBreakUtil(n, s, dict, ans); } static void wordBreakUtil(int n, String s, List<String> dict, String ans) { for(int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix String prefix=s.substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.contains(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; System.out.println(ans); return; } wordBreakUtil(n - i, s.substring(i,n), dict, ans+prefix+" "); } } } // main function public static void main(String args[]) { String str1 = "iloveicecreamandmango"; // for first test case String str2 ="ilovesamsungmobile"; // for second test case int n1 = str1.length(); // length of first string int n2 = str2.length(); // length of second string // List of strings in dictionary List <String> dict= Arrays.asList("mobile","samsung","sam","sung", "man","mango", "icecream","and", "go","i","love","ice","cream"); System.out.println("First Test:"); // call to the method wordBreak(n1,dict,str1); System.out.println("\nSecond Test:"); // call to the method wordBreak(n2,dict,str2); }} // This code is contributed by mohitjha727.
# A recursive program to print all possible# partitions of a given string into dictionary# words # A utility function to check whether a word# is present in dictionary or not. An array of# strings is used for dictionary. Using array# of strings for dictionary is definitely not# a good idea. We have used for simplicity of# the programdef dictionaryContains(word): dictionary = {"mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "love", "ice", "cream"} return word in dictionary # Prints all possible word breaks of given stringdef wordBreak(string): # Last argument is prefix wordBreakUtil(string, len(string), "") # Result store the current prefix with spaces# between wordsdef wordBreakUtil(string, n, result): # Process all prefixes one by one for i in range(1, n + 1): # Extract substring from 0 to i in prefix prefix = string[:i] # If dictionary contains this prefix, then # we check for remaining string. Otherwise # we ignore this prefix (there is no else for # this if) and try next if dictionaryContains(prefix): # If no more elements are there, print it if i == n: # Add this element to previous prefix result += prefix print(result) return wordBreakUtil(string[i:], n - i, result+prefix+" ") # Driver Codeif __name__ == "__main__": print("First Test:") wordBreak("iloveicecreamandmango") print("\nSecond Test:") wordBreak("ilovesamsungmobile") # This code is contributed by harshitkap00r
// A recursive program to print all possible// partitions of a given string into dictionary// wordsusing System;using System.Collections.Generic;class GFG { // Prints all possible word breaks of given string static void wordBreak(int n, List<string> dict, string s) { string ans=""; wordBreakUtil(n, s, dict, ans); } static void wordBreakUtil(int n, string s, List<string> dict, string ans) { for(int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix string prefix=s.Substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.Contains(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; Console.WriteLine(ans); return; } wordBreakUtil(n - i, s.Substring(i,n-i), dict, ans+prefix+" "); } } } static void Main() { string str1 = "iloveicecreamandmango"; // for first test case string str2 ="ilovesamsungmobile"; // for second test case int n1 = str1.Length; // length of first string int n2 = str2.Length; // length of second string // List of strings in dictionary List<string> dict= new List<string>(new string[]{"mobile","samsung","sam","sung", "man","mango", "icecream","and", "go","i","love","ice","cream"}); Console.WriteLine("First Test:"); // call to the method wordBreak(n1,dict,str1); Console.WriteLine(); Console.WriteLine("Second Test:"); // call to the method wordBreak(n2,dict,str2); }} // This code is contributed by divyeshrabadiya07.
<script>// A recursive program to print all possible// partitions of a given string into dictionary// words // Prints all possible word breaks of given stringfunction wordBreak(n,dict,s){ let ans=""; wordBreakUtil(n, s, dict, ans);} function wordBreakUtil(n,s,dict,ans){ for(let i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix let prefix=s.substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.includes(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; document.write(ans+"<br>"); return; } wordBreakUtil(n - i, s.substring(i,n), dict, ans+prefix+" "); } }} // main functionlet str1 = "iloveicecreamandmango"; // for first test caselet str2 ="ilovesamsungmobile"; // for second test caselet n1 = str1.length; // length of first stringlet n2 = str2.length; // length of second string // List of strings in dictionarylet dict= ["mobile","samsung","sam","sung", "man","mango", "icecream","and", "go","i","love","ice","cream"]; document.write("First Test:<br>"); // call to the methodwordBreak(n1,dict,str1);document.write("<br>Second Test:<br>"); // call to the methodwordBreak(n2,dict,str2); // This code is contributed by avanitrachhadiya2155</script>
First Test:
i love ice cream and man go
i love ice cream and mango
i love icecream and man go
i love icecream and mango
Second Test:
i love sam sung mobile
i love samsung mobile
Complexities:
Time Complexity: O(2n). Because there are 2n combinations in The Worst Case.
Auxiliary Space: O(n2). Because of the Recursive Stack of wordBreakUtil(...) function in The Worst Case.
Where n is the length of the input string.
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sreejithsankar55
pratikraut0000
harshitkap00r
mohitjha727
pushvind_1
avanitrachhadiya2155
anikakapoor
divyeshrabadiya07
D-E-Shaw
Google
IBM
Backtracking
Recursion
Strings
D-E-Shaw
Google
IBM
Strings
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
The Knight's tour problem | Backtracking-1
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Subset Sum | Backtracking-4
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Print all possible combinations of r elements in a given array of size n
Program for Sum of the digits of a given number
|
[
{
"code": null,
"e": 26575,
"s": 26547,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 26755,
"s": 26575,
"text": "Given a valid sentence without any spaces between the words and a dictionary of valid English words, find all possible ways to break the sentence into individual dictionary words."
},
{
"code": null,
"e": 26764,
"s": 26755,
"text": "Example "
},
{
"code": null,
"e": 27146,
"s": 26764,
"text": "Consider the following dictionary \n{ i, like, sam, sung, samsung, mobile, ice, \n and, cream, icecream, man, go, mango}\n\nInput: \"ilikesamsungmobile\"\nOutput: i like sam sung mobile\n i like samsung mobile\n\nInput: \"ilikeicecreamandmango\"\nOutput: i like ice cream and man go\n i like ice cream and mango\n i like icecream and man go\n i like icecream and mango"
},
{
"code": null,
"e": 27264,
"s": 27146,
"text": "We have discussed a Dynamic Programming solution in the below post. Dynamic Programming | Set 32 (Word Break Problem)"
},
{
"code": null,
"e": 28161,
"s": 27264,
"text": "The Dynamic Programming solution only finds whether it is possible to break a word or not. Here we need to print all possible word breaks.We start scanning the sentence from the left. As we find a valid word, we need to check whether the rest of the sentence can make valid words or not. Because in some situations the first found word from the left side can leave a remaining portion that is not further separable. So, in that case, we should come back and leave the currently found word and keep on searching for the next word. And this process is recursive because to find out whether the right portion is separable or not, we need the same logic. So we will use recursion and backtracking to solve this problem. To keep track of the found words we will use a stack. Whenever the right portion of the string does not make valid words, we pop the top string from the stack and continue finding."
},
{
"code": null,
"e": 28208,
"s": 28161,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 28212,
"s": 28208,
"text": "C++"
},
{
"code": null,
"e": 28217,
"s": 28212,
"text": "Java"
},
{
"code": null,
"e": 28225,
"s": 28217,
"text": "Python3"
},
{
"code": null,
"e": 28228,
"s": 28225,
"text": "C#"
},
{
"code": null,
"e": 28239,
"s": 28228,
"text": "Javascript"
},
{
"code": "// A recursive program to print all possible// partitions of a given string into dictionary// words#include <iostream>using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/int dictionaryContains(string &word){ string dictionary[] = {\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\", \"icecream\",\"and\", \"go\",\"i\",\"love\",\"ice\",\"cream\"}; int n = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < n; i++) if (dictionary[i].compare(word) == 0) return true; return false;} // Prototype of wordBreakUtilvoid wordBreakUtil(string str, int size, string result); // Prints all possible word breaks of given stringvoid wordBreak(string str){ // Last argument is prefix wordBreakUtil(str, str.size(), \"\");} // Result store the current prefix with spaces// between wordsvoid wordBreakUtil(string str, int n, string result){ //Process all prefixes one by one for (int i=1; i<=n; i++) { // Extract substring from 0 to i in prefix string prefix = str.substr(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if (dictionaryContains(prefix)) { // If no more elements are there, print it if (i == n) { // Add this element to previous prefix result += prefix; cout << result << endl; return; } wordBreakUtil(str.substr(i, n-i), n-i, result + prefix + \" \"); } } } //Driver Codeint main(){ // Function call cout << \"First Test:\\n\"; wordBreak(\"iloveicecreamandmango\"); cout << \"\\nSecond Test:\\n\"; wordBreak(\"ilovesamsungmobile\"); return 0;}",
"e": 30330,
"s": 28239,
"text": null
},
{
"code": "// A recursive program to print all possible// partitions of a given string into dictionary// wordsimport java.io.*;import java.util.*; class GFG { // Prints all possible word breaks of given string static void wordBreak(int n, List<String> dict, String s) { String ans=\"\"; wordBreakUtil(n, s, dict, ans); } static void wordBreakUtil(int n, String s, List<String> dict, String ans) { for(int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix String prefix=s.substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.contains(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; System.out.println(ans); return; } wordBreakUtil(n - i, s.substring(i,n), dict, ans+prefix+\" \"); } } } // main function public static void main(String args[]) { String str1 = \"iloveicecreamandmango\"; // for first test case String str2 =\"ilovesamsungmobile\"; // for second test case int n1 = str1.length(); // length of first string int n2 = str2.length(); // length of second string // List of strings in dictionary List <String> dict= Arrays.asList(\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\", \"icecream\",\"and\", \"go\",\"i\",\"love\",\"ice\",\"cream\"); System.out.println(\"First Test:\"); // call to the method wordBreak(n1,dict,str1); System.out.println(\"\\nSecond Test:\"); // call to the method wordBreak(n2,dict,str2); }} // This code is contributed by mohitjha727.",
"e": 32185,
"s": 30330,
"text": null
},
{
"code": "# A recursive program to print all possible# partitions of a given string into dictionary# words # A utility function to check whether a word# is present in dictionary or not. An array of# strings is used for dictionary. Using array# of strings for dictionary is definitely not# a good idea. We have used for simplicity of# the programdef dictionaryContains(word): dictionary = {\"mobile\", \"samsung\", \"sam\", \"sung\", \"man\", \"mango\", \"icecream\", \"and\", \"go\", \"i\", \"love\", \"ice\", \"cream\"} return word in dictionary # Prints all possible word breaks of given stringdef wordBreak(string): # Last argument is prefix wordBreakUtil(string, len(string), \"\") # Result store the current prefix with spaces# between wordsdef wordBreakUtil(string, n, result): # Process all prefixes one by one for i in range(1, n + 1): # Extract substring from 0 to i in prefix prefix = string[:i] # If dictionary contains this prefix, then # we check for remaining string. Otherwise # we ignore this prefix (there is no else for # this if) and try next if dictionaryContains(prefix): # If no more elements are there, print it if i == n: # Add this element to previous prefix result += prefix print(result) return wordBreakUtil(string[i:], n - i, result+prefix+\" \") # Driver Codeif __name__ == \"__main__\": print(\"First Test:\") wordBreak(\"iloveicecreamandmango\") print(\"\\nSecond Test:\") wordBreak(\"ilovesamsungmobile\") # This code is contributed by harshitkap00r",
"e": 33841,
"s": 32185,
"text": null
},
{
"code": "// A recursive program to print all possible// partitions of a given string into dictionary// wordsusing System;using System.Collections.Generic;class GFG { // Prints all possible word breaks of given string static void wordBreak(int n, List<string> dict, string s) { string ans=\"\"; wordBreakUtil(n, s, dict, ans); } static void wordBreakUtil(int n, string s, List<string> dict, string ans) { for(int i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix string prefix=s.Substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.Contains(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; Console.WriteLine(ans); return; } wordBreakUtil(n - i, s.Substring(i,n-i), dict, ans+prefix+\" \"); } } } static void Main() { string str1 = \"iloveicecreamandmango\"; // for first test case string str2 =\"ilovesamsungmobile\"; // for second test case int n1 = str1.Length; // length of first string int n2 = str2.Length; // length of second string // List of strings in dictionary List<string> dict= new List<string>(new string[]{\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\", \"icecream\",\"and\", \"go\",\"i\",\"love\",\"ice\",\"cream\"}); Console.WriteLine(\"First Test:\"); // call to the method wordBreak(n1,dict,str1); Console.WriteLine(); Console.WriteLine(\"Second Test:\"); // call to the method wordBreak(n2,dict,str2); }} // This code is contributed by divyeshrabadiya07.",
"e": 35846,
"s": 33841,
"text": null
},
{
"code": "<script>// A recursive program to print all possible// partitions of a given string into dictionary// words // Prints all possible word breaks of given stringfunction wordBreak(n,dict,s){ let ans=\"\"; wordBreakUtil(n, s, dict, ans);} function wordBreakUtil(n,s,dict,ans){ for(let i = 1; i <= n; i++) { // Extract substring from 0 to i in prefix let prefix=s.substring(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if(dict.includes(prefix)) { // If no more elements are there, print it if(i == n) { // Add this element to previous prefix ans += prefix; document.write(ans+\"<br>\"); return; } wordBreakUtil(n - i, s.substring(i,n), dict, ans+prefix+\" \"); } }} // main functionlet str1 = \"iloveicecreamandmango\"; // for first test caselet str2 =\"ilovesamsungmobile\"; // for second test caselet n1 = str1.length; // length of first stringlet n2 = str2.length; // length of second string // List of strings in dictionarylet dict= [\"mobile\",\"samsung\",\"sam\",\"sung\", \"man\",\"mango\", \"icecream\",\"and\", \"go\",\"i\",\"love\",\"ice\",\"cream\"]; document.write(\"First Test:<br>\"); // call to the methodwordBreak(n1,dict,str1);document.write(\"<br>Second Test:<br>\"); // call to the methodwordBreak(n2,dict,str2); // This code is contributed by avanitrachhadiya2155</script>",
"e": 37463,
"s": 35846,
"text": null
},
{
"code": null,
"e": 37642,
"s": 37463,
"text": "First Test:\ni love ice cream and man go\ni love ice cream and mango\ni love icecream and man go\ni love icecream and mango\n\nSecond Test:\ni love sam sung mobile\ni love samsung mobile"
},
{
"code": null,
"e": 37657,
"s": 37642,
"text": "Complexities: "
},
{
"code": null,
"e": 37734,
"s": 37657,
"text": "Time Complexity: O(2n). Because there are 2n combinations in The Worst Case."
},
{
"code": null,
"e": 37839,
"s": 37734,
"text": "Auxiliary Space: O(n2). Because of the Recursive Stack of wordBreakUtil(...) function in The Worst Case."
},
{
"code": null,
"e": 37882,
"s": 37839,
"text": "Where n is the length of the input string."
},
{
"code": null,
"e": 38309,
"s": 37882,
"text": "This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 38326,
"s": 38309,
"text": "sreejithsankar55"
},
{
"code": null,
"e": 38341,
"s": 38326,
"text": "pratikraut0000"
},
{
"code": null,
"e": 38355,
"s": 38341,
"text": "harshitkap00r"
},
{
"code": null,
"e": 38367,
"s": 38355,
"text": "mohitjha727"
},
{
"code": null,
"e": 38378,
"s": 38367,
"text": "pushvind_1"
},
{
"code": null,
"e": 38399,
"s": 38378,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 38411,
"s": 38399,
"text": "anikakapoor"
},
{
"code": null,
"e": 38429,
"s": 38411,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 38438,
"s": 38429,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 38445,
"s": 38438,
"text": "Google"
},
{
"code": null,
"e": 38449,
"s": 38445,
"text": "IBM"
},
{
"code": null,
"e": 38462,
"s": 38449,
"text": "Backtracking"
},
{
"code": null,
"e": 38472,
"s": 38462,
"text": "Recursion"
},
{
"code": null,
"e": 38480,
"s": 38472,
"text": "Strings"
},
{
"code": null,
"e": 38489,
"s": 38480,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 38496,
"s": 38489,
"text": "Google"
},
{
"code": null,
"e": 38500,
"s": 38496,
"text": "IBM"
},
{
"code": null,
"e": 38508,
"s": 38500,
"text": "Strings"
},
{
"code": null,
"e": 38518,
"s": 38508,
"text": "Recursion"
},
{
"code": null,
"e": 38531,
"s": 38518,
"text": "Backtracking"
},
{
"code": null,
"e": 38629,
"s": 38531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38657,
"s": 38629,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 38700,
"s": 38657,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 38736,
"s": 38700,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 38771,
"s": 38736,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 38799,
"s": 38771,
"text": "Subset Sum | Backtracking-4"
},
{
"code": null,
"e": 38809,
"s": 38799,
"text": "Recursion"
},
{
"code": null,
"e": 38836,
"s": 38809,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 38864,
"s": 38836,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 38937,
"s": 38864,
"text": "Print all possible combinations of r elements in a given array of size n"
}
] |
C++ Program to Count Inversions of size three in a given array - GeeksforGeeks
|
30 Dec, 2021
Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example :
Input: {8, 4, 2, 1}
Output: 4
The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).
Input: {9, 6, 4, 5, 8}
Output: 2
The two inversions are {9, 6, 4} and {9, 6, 5}
We have already discussed inversion count of size two by merge sort, Self Balancing BST and BIT.Simple approach :- Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k.
C++
// A Simple C++ O(n^3) program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns counts of inversions of size threeint getInvCount(int arr[],int n){ int invcount = 0; // Initialize result for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { if (arr[i]>arr[j]) { for (int k=j+1; k<n; k++) { if (arr[j]>arr[k]) invcount++; } } } } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Inversion Count : " << getInvCount(arr, n); return 0;}
Output:
Inversion Count : 4
Time complexity of this approach is : O(n^3)Better Approach : We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result. Below is the implementation of the idea.
C++
// A O(n^2) C++ program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns count of inversions of size 3int getInvCount(int arr[], int n){ int invcount = 0; // Initialize result for (int i=1; i<n-1; i++) { // Count all smaller elements on right of arr[i] int small = 0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // Count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // Update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Inversion Count : " << getInvCount(arr, n); return 0;}
Output :
Inversion Count : 4
Time Complexity of this approach : O(n^2)Binary Indexed Tree Approach : Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.Count inversions of size two Using BITThe idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result. Solution :
To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.
To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
Please refer complete article on Count Inversions of size three in a given array for more details!
Binary Indexed Tree
inversion
Advanced Data Structure
Arrays
C++
C++ Programs
Arrays
Binary Indexed Tree
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Suffix Array | Set 1 (Introduction)
Interval Tree
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 25707,
"s": 25679,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 25898,
"s": 25707,
"text": "Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.Example : "
},
{
"code": null,
"e": 26075,
"s": 25898,
"text": "Input: {8, 4, 2, 1}\nOutput: 4\nThe four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).\n\nInput: {9, 6, 4, 5, 8}\nOutput: 2\nThe two inversions are {9, 6, 4} and {9, 6, 5}"
},
{
"code": null,
"e": 26295,
"s": 26075,
"text": "We have already discussed inversion count of size two by merge sort, Self Balancing BST and BIT.Simple approach :- Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k. "
},
{
"code": null,
"e": 26299,
"s": 26295,
"text": "C++"
},
{
"code": "// A Simple C++ O(n^3) program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns counts of inversions of size threeint getInvCount(int arr[],int n){ int invcount = 0; // Initialize result for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { if (arr[i]>arr[j]) { for (int k=j+1; k<n; k++) { if (arr[j]>arr[k]) invcount++; } } } } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Inversion Count : \" << getInvCount(arr, n); return 0;}",
"e": 27037,
"s": 26299,
"text": null
},
{
"code": null,
"e": 27045,
"s": 27037,
"text": "Output:"
},
{
"code": null,
"e": 27066,
"s": 27045,
"text": "Inversion Count : 4 "
},
{
"code": null,
"e": 27532,
"s": 27066,
"text": "Time complexity of this approach is : O(n^3)Better Approach : We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result. Below is the implementation of the idea. "
},
{
"code": null,
"e": 27536,
"s": 27532,
"text": "C++"
},
{
"code": "// A O(n^2) C++ program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns count of inversions of size 3int getInvCount(int arr[], int n){ int invcount = 0; // Initialize result for (int i=1; i<n-1; i++) { // Count all smaller elements on right of arr[i] int small = 0; for (int j=i+1; j<n; j++) if (arr[i] > arr[j]) small++; // Count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // Update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount;} // Driver program to test above functionint main(){ int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Inversion Count : \" << getInvCount(arr, n); return 0;}",
"e": 28491,
"s": 27536,
"text": null
},
{
"code": null,
"e": 28500,
"s": 28491,
"text": "Output :"
},
{
"code": null,
"e": 28521,
"s": 28500,
"text": "Inversion Count : 4 "
},
{
"code": null,
"e": 28972,
"s": 28521,
"text": "Time Complexity of this approach : O(n^2)Binary Indexed Tree Approach : Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.Count inversions of size two Using BITThe idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result. Solution :"
},
{
"code": null,
"e": 29496,
"s": 28972,
"text": "To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i]."
},
{
"code": null,
"e": 29697,
"s": 29496,
"text": "To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1."
},
{
"code": null,
"e": 30021,
"s": 29697,
"text": "To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i]."
},
{
"code": null,
"e": 30120,
"s": 30021,
"text": "Please refer complete article on Count Inversions of size three in a given array for more details!"
},
{
"code": null,
"e": 30140,
"s": 30120,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 30150,
"s": 30140,
"text": "inversion"
},
{
"code": null,
"e": 30174,
"s": 30150,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 30181,
"s": 30174,
"text": "Arrays"
},
{
"code": null,
"e": 30185,
"s": 30181,
"text": "C++"
},
{
"code": null,
"e": 30198,
"s": 30185,
"text": "C++ Programs"
},
{
"code": null,
"e": 30205,
"s": 30198,
"text": "Arrays"
},
{
"code": null,
"e": 30225,
"s": 30205,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 30229,
"s": 30225,
"text": "CPP"
},
{
"code": null,
"e": 30327,
"s": 30229,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30356,
"s": 30327,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 30398,
"s": 30356,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 30444,
"s": 30398,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 30480,
"s": 30444,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 30494,
"s": 30480,
"text": "Interval Tree"
},
{
"code": null,
"e": 30509,
"s": 30494,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30525,
"s": 30509,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30593,
"s": 30525,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 30639,
"s": 30593,
"text": "Write a program to reverse an array or string"
}
] |
Binary Number System
|
Binary Number System is one the type of Number Representation techniques. It is most popular and used in digital systems. Binary system is used for representing binary quantities which can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: open or close.
In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1. Represented by any device that only 2 operating states or possible conditions. Binary numbers are indicated by the addition of either an 0b prefix or an 2 suffix.
Position of every digit has a weight which is a power of 2. Each position in the Binary system is 2 times more significant than the previous position, that means numeric value of a Binary number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system.
Voltage range between 0V to 0.8V is used for binary logic 0 and voltage range between 2V to 5V is used for binary logic 1. Voltage range between 0.8V to 2V is not used because it may causes error in a digital circuit.
Example-1 β The number 125 is interpreted as
125 = 1x26+1x25+1x24+1x23+1x22+0x21+1x20=1111101
Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB).
Example-2 β The number 90.75 is interpreted as
90.75 = 1x26+0x25+1x24+1x23+0x22+1x21+0x20+1x2-1+1x2-2=1011010.11
Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB).
Example-3 β A decimal number 21 to represent in Binary representation
(21)10 =16+0+4+0+1 = 1x24+0x23+1x22+0x21+1x20 =(10101)2
So, decimal value 21 is equivalent to 10101 in Binary Number System.
The binary number system is very useful in computer technology and computer programming languages also uses binary number system that is helpful in digital encoding. The binary number system can also be used in Boolean algebra.
The main advantage of using binary is that it is a base which is easily represented by electronic devices. The Binary Number System are also ease of use in coding, fewer computations and less computational errors.
The major disadvantage of binary number is difficult to read and write for humans because of large number of binary of a equivalent decimal number.
To get 1βs complement of a binary number, simply invert the given number. For example, 1βs complement of binary number 110010 is 001101.
2βs complement of binary number is 1βs complement of given number plus 1 to the least significant bit (LSB). For example 2βs complement of binary number 10010 is (01101) + 1 = 01110.
|
[
{
"code": null,
"e": 1397,
"s": 1062,
"text": "Binary Number System is one the type of Number Representation techniques. It is most popular and used in digital systems. Binary system is used for representing binary quantities which can be represented by any device that has only two operating states or possible conditions. For example, a switch has only two states: open or close."
},
{
"code": null,
"e": 1650,
"s": 1397,
"text": "In the Binary System, there are only two symbols or possible digit values, i.e., 0 and 1. Represented by any device that only 2 operating states or possible conditions. Binary numbers are indicated by the addition of either an 0b prefix or an 2 suffix."
},
{
"code": null,
"e": 2042,
"s": 1650,
"text": "Position of every digit has a weight which is a power of 2. Each position in the Binary system is 2 times more significant than the previous position, that means numeric value of a Binary number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system."
},
{
"code": null,
"e": 2260,
"s": 2042,
"text": "Voltage range between 0V to 0.8V is used for binary logic 0 and voltage range between 2V to 5V is used for binary logic 1. Voltage range between 0.8V to 2V is not used because it may causes error in a digital circuit."
},
{
"code": null,
"e": 2305,
"s": 2260,
"text": "Example-1 β The number 125 is interpreted as"
},
{
"code": null,
"e": 2354,
"s": 2305,
"text": "125 = 1x26+1x25+1x24+1x23+1x22+0x21+1x20=1111101"
},
{
"code": null,
"e": 2467,
"s": 2354,
"text": "Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB)."
},
{
"code": null,
"e": 2514,
"s": 2467,
"text": "Example-2 β The number 90.75 is interpreted as"
},
{
"code": null,
"e": 2580,
"s": 2514,
"text": "90.75 = 1x26+0x25+1x24+1x23+0x22+1x21+0x20+1x2-1+1x2-2=1011010.11"
},
{
"code": null,
"e": 2693,
"s": 2580,
"text": "Here, right most bit 1 is the least significant bit (LSB) and left most bit 1 is the most significant bit (MSB)."
},
{
"code": null,
"e": 2763,
"s": 2693,
"text": "Example-3 β A decimal number 21 to represent in Binary representation"
},
{
"code": null,
"e": 2888,
"s": 2763,
"text": "(21)10 =16+0+4+0+1 = 1x24+0x23+1x22+0x21+1x20 =(10101)2\nSo, decimal value 21 is equivalent to 10101 in Binary Number System."
},
{
"code": null,
"e": 3116,
"s": 2888,
"text": "The binary number system is very useful in computer technology and computer programming languages also uses binary number system that is helpful in digital encoding. The binary number system can also be used in Boolean algebra."
},
{
"code": null,
"e": 3330,
"s": 3116,
"text": "The main advantage of using binary is that it is a base which is easily represented by electronic devices. The Binary Number System are also ease of use in coding, fewer computations and less computational errors."
},
{
"code": null,
"e": 3478,
"s": 3330,
"text": "The major disadvantage of binary number is difficult to read and write for humans because of large number of binary of a equivalent decimal number."
},
{
"code": null,
"e": 3615,
"s": 3478,
"text": "To get 1βs complement of a binary number, simply invert the given number. For example, 1βs complement of binary number 110010 is 001101."
},
{
"code": null,
"e": 3798,
"s": 3615,
"text": "2βs complement of binary number is 1βs complement of given number plus 1 to the least significant bit (LSB). For example 2βs complement of binary number 10010 is (01101) + 1 = 01110."
}
] |
Android RecyclerView in Kotlin - GeeksforGeeks
|
06 Jun, 2021
In this article, you will know how to implement RecyclerView in Android using Kotlin. Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ability to reuse its views. In RecyclerView when the View goes out of the screen or not visible to the user it wonβt destroy it, it will reuse these views. This feature helps in reducing power consumption and providing more responsiveness to the application. Now letβs see how to implement RecyclerView using Kotlin.
Step 1: Create a New Project
On the Welcome screen of Android Studio, click on Create New Project. If you have a project already opened, Go to File > New > New Project. Then select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field. Select Kotlin from the Language drop-down menu.
Step 2: Add the Dependencies
Go to app < Gradle Scripts < gradle.build(Module: app) and add the following dependencies.
dependencies{
// for adding recyclerview
implementation 'androidx.recyclerview:recyclerview:1.2.0'
// for adding cardview
implementation 'androidx.cardview:cardview:1.0.0'
}
Step 3: Go to activity_main.xml and add the following code
Add RecyclerView to activity_main.xml you can add it from the drag and drop from the design section or you can add it manually by writing some initial characters of RecyclerView then the IDE will give you suggestions for RecyclerView then select RecyclerView it will automatically add it to your layout file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" tools:itemCount="5" tools:listitem="@layout/card_view_design" /> </LinearLayout>
Step 4: Create a New Layout Resource File
Now create a new Layout Resource File which will be used to design our CardView layout. Go to app > res > layout > right-click on layout > New > Layout Resource File and name that file as card_view_design and add the code provided below. In this file, you can design the layout to show it into the RecyclerView.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="50dp" android:layout_margin="10dp" app:cardElevation="6dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dp"> <ImageView android:id="@+id/imageview" android:layout_width="40dp" android:layout_height="40dp" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginLeft="15dp" android:text="Item" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout> </androidx.cardview.widget.CardView>
Step 5: Create a new Kotlin class
Go to app > java > package name > right-click > New > Kotlin class/file and choose Data class from the list. Name that file as ItemsViewModel and then click on OK. This file will hold the information of every item which you want to show in your RecyclerView.
Kotlin
data class ItemsViewModel(val image: Int, val text: String) {}
Step 6: Create Adapter Class
Go to app > java > package name > right-click > New > Kotlin class/file and name that file as CustomAdapter and then click on OK. After this add the code provided below. Comments are added inside the code to understand the code in more detail.
This class contains some important functions to work with the RecyclerView these are as follows:
onCreateViewHolder(): This function sets the views to display the items.
onBindViewHolder(): This function is used to bind the list items to our widgets such as TextView, ImageView, etc.
getItemCount(): It returns the count of items present in the list.
Kotlin
import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerView class CustomAdapter(private val mList: List<ItemsViewModel>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() { // create new views override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // inflates the card_view_design view // that is used to hold list item val view = LayoutInflater.from(parent.context) .inflate(R.layout.card_view_design, parent, false) return ViewHolder(view) } // binds the list items to a view override fun onBindViewHolder(holder: ViewHolder, position: Int) { val ItemsViewModel = mList[position] // sets the image to the imageview from our itemHolder class holder.imageView.setImageResource(ItemsViewModel.image) // sets the text to the textview from our itemHolder class holder.textView.text = ItemsViewModel.text } // return the number of the items in the list override fun getItemCount(): Int { return mList.size } // Holds the views for adding it to image and text class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) { val imageView: ImageView = itemView.findViewById(R.id.imageview) val textView: TextView = itemView.findViewById(R.id.textView) }}
Step 7: Working with the MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // getting the recyclerview by its id val recyclerview = findViewById<RecyclerView>(R.id.recyclerview) // this creates a vertical layout Manager recyclerview.layoutManager = LinearLayoutManager(this) // ArrayList of class ItemsViewModel val data = ArrayList<ItemsViewModel>() // This loop will create 20 Views containing // the image with the count of view for (i in 1..20) { data.add(ItemsViewModel(R.drawable.ic_baseline_folder_24, "Item " + i)) } // This will pass the ArrayList to our Adapter val adapter = CustomAdapter(data) // Setting the Adapter with the recyclerview recyclerview.adapter = adapter }}
Output:
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
CardView in Android With Example
Content Providers in Android with Example
Broadcast Receiver in Android With Example
Android UI Layouts
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 25510,
"s": 25482,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 26124,
"s": 25510,
"text": "In this article, you will know how to implement RecyclerView in Android using Kotlin. Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ability to reuse its views. In RecyclerView when the View goes out of the screen or not visible to the user it wonβt destroy it, it will reuse these views. This feature helps in reducing power consumption and providing more responsiveness to the application. Now letβs see how to implement RecyclerView using Kotlin."
},
{
"code": null,
"e": 26153,
"s": 26124,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26457,
"s": 26153,
"text": "On the Welcome screen of Android Studio, click on Create New Project. If you have a project already opened, Go to File > New > New Project. Then select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field. Select Kotlin from the Language drop-down menu."
},
{
"code": null,
"e": 26486,
"s": 26457,
"text": "Step 2: Add the Dependencies"
},
{
"code": null,
"e": 26577,
"s": 26486,
"text": "Go to app < Gradle Scripts < gradle.build(Module: app) and add the following dependencies."
},
{
"code": null,
"e": 26762,
"s": 26577,
"text": "dependencies{\n // for adding recyclerview\n implementation 'androidx.recyclerview:recyclerview:1.2.0'\n \n // for adding cardview\n implementation 'androidx.cardview:cardview:1.0.0'\n}"
},
{
"code": null,
"e": 26821,
"s": 26762,
"text": "Step 3: Go to activity_main.xml and add the following code"
},
{
"code": null,
"e": 27130,
"s": 26821,
"text": "Add RecyclerView to activity_main.xml you can add it from the drag and drop from the design section or you can add it manually by writing some initial characters of RecyclerView then the IDE will give you suggestions for RecyclerView then select RecyclerView it will automatically add it to your layout file."
},
{
"code": null,
"e": 27134,
"s": 27130,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerview\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:itemCount=\"5\" tools:listitem=\"@layout/card_view_design\" /> </LinearLayout>",
"e": 27719,
"s": 27134,
"text": null
},
{
"code": null,
"e": 27761,
"s": 27719,
"text": "Step 4: Create a New Layout Resource File"
},
{
"code": null,
"e": 28073,
"s": 27761,
"text": "Now create a new Layout Resource File which will be used to design our CardView layout. Go to app > res > layout > right-click on layout > New > Layout Resource File and name that file as card_view_design and add the code provided below. In this file, you can design the layout to show it into the RecyclerView."
},
{
"code": null,
"e": 28077,
"s": 28073,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"50dp\" android:layout_margin=\"10dp\" app:cardElevation=\"6dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:padding=\"5dp\"> <ImageView android:id=\"@+id/imageview\" android:layout_width=\"40dp\" android:layout_height=\"40dp\" /> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginLeft=\"15dp\" android:text=\"Item\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </LinearLayout> </androidx.cardview.widget.CardView>",
"e": 29121,
"s": 28077,
"text": null
},
{
"code": null,
"e": 29155,
"s": 29121,
"text": "Step 5: Create a new Kotlin class"
},
{
"code": null,
"e": 29414,
"s": 29155,
"text": "Go to app > java > package name > right-click > New > Kotlin class/file and choose Data class from the list. Name that file as ItemsViewModel and then click on OK. This file will hold the information of every item which you want to show in your RecyclerView."
},
{
"code": null,
"e": 29421,
"s": 29414,
"text": "Kotlin"
},
{
"code": "data class ItemsViewModel(val image: Int, val text: String) {}",
"e": 29484,
"s": 29421,
"text": null
},
{
"code": null,
"e": 29514,
"s": 29484,
"text": "Step 6: Create Adapter Class "
},
{
"code": null,
"e": 29758,
"s": 29514,
"text": "Go to app > java > package name > right-click > New > Kotlin class/file and name that file as CustomAdapter and then click on OK. After this add the code provided below. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 29855,
"s": 29758,
"text": "This class contains some important functions to work with the RecyclerView these are as follows:"
},
{
"code": null,
"e": 29928,
"s": 29855,
"text": "onCreateViewHolder(): This function sets the views to display the items."
},
{
"code": null,
"e": 30042,
"s": 29928,
"text": "onBindViewHolder(): This function is used to bind the list items to our widgets such as TextView, ImageView, etc."
},
{
"code": null,
"e": 30109,
"s": 30042,
"text": "getItemCount(): It returns the count of items present in the list."
},
{
"code": null,
"e": 30116,
"s": 30109,
"text": "Kotlin"
},
{
"code": "import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.TextViewimport androidx.recyclerview.widget.RecyclerView class CustomAdapter(private val mList: List<ItemsViewModel>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() { // create new views override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // inflates the card_view_design view // that is used to hold list item val view = LayoutInflater.from(parent.context) .inflate(R.layout.card_view_design, parent, false) return ViewHolder(view) } // binds the list items to a view override fun onBindViewHolder(holder: ViewHolder, position: Int) { val ItemsViewModel = mList[position] // sets the image to the imageview from our itemHolder class holder.imageView.setImageResource(ItemsViewModel.image) // sets the text to the textview from our itemHolder class holder.textView.text = ItemsViewModel.text } // return the number of the items in the list override fun getItemCount(): Int { return mList.size } // Holds the views for adding it to image and text class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) { val imageView: ImageView = itemView.findViewById(R.id.imageview) val textView: TextView = itemView.findViewById(R.id.textView) }}",
"e": 31586,
"s": 30116,
"text": null
},
{
"code": null,
"e": 31627,
"s": 31586,
"text": "Step 7: Working with the MainActivity.kt"
},
{
"code": null,
"e": 31813,
"s": 31627,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 31820,
"s": 31813,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // getting the recyclerview by its id val recyclerview = findViewById<RecyclerView>(R.id.recyclerview) // this creates a vertical layout Manager recyclerview.layoutManager = LinearLayoutManager(this) // ArrayList of class ItemsViewModel val data = ArrayList<ItemsViewModel>() // This loop will create 20 Views containing // the image with the count of view for (i in 1..20) { data.add(ItemsViewModel(R.drawable.ic_baseline_folder_24, \"Item \" + i)) } // This will pass the ArrayList to our Adapter val adapter = CustomAdapter(data) // Setting the Adapter with the recyclerview recyclerview.adapter = adapter }}",
"e": 32920,
"s": 31820,
"text": null
},
{
"code": null,
"e": 32928,
"s": 32920,
"text": "Output:"
},
{
"code": null,
"e": 32943,
"s": 32928,
"text": "Kotlin Android"
},
{
"code": null,
"e": 32951,
"s": 32943,
"text": "Android"
},
{
"code": null,
"e": 32958,
"s": 32951,
"text": "Kotlin"
},
{
"code": null,
"e": 32966,
"s": 32958,
"text": "Android"
},
{
"code": null,
"e": 33064,
"s": 32966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33122,
"s": 33064,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 33165,
"s": 33122,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 33203,
"s": 33165,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 33236,
"s": 33203,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 33278,
"s": 33236,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 33321,
"s": 33278,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 33340,
"s": 33321,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 33382,
"s": 33340,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 33424,
"s": 33382,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
Check if binary representations of two numbers are anagram - GeeksforGeeks
|
28 Mar, 2022
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples:
Input : a = 8, b = 4
Output : Yes
Binary representations of both
numbers have same 0s and 1s.
Input : a = 4, b = 5
Output : No
Simple Approach:
Find Binary Representation of βaβ and βbβ using simple decimal to binary representation technique.Check if two binary representations are an anagram
Find Binary Representation of βaβ and βbβ using simple decimal to binary representation technique.
Check if two binary representations are an anagram
C++
Java
Python3
C#
Javascript
// A simple C++ program to check if binary// representations of two numbers are anagram.#include <bits/stdc++.h>#define ull unsigned long long intusing namespace std; const int SIZE = 8 * sizeof(ull); bool bit_anagram_check(ull a, ull b){ // Find reverse binary representation of a // and store it in binary_a[] int i = 0, binary_a[SIZE] = { 0 }; while (a > 0) { binary_a[i] = a % 2; a /= 2; i++; } // Find reverse binary representation of b // and store it in binary_a[] int j = 0, binary_b[SIZE] = { 0 }; while (b > 0) { binary_b[j] = b % 2; b /= 2; j++; } // Sort two binary representations sort(binary_a, binary_a + SIZE); sort(binary_b, binary_b + SIZE); // Compare two sorted binary representations for (int i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return false; return true;} // Driver codeint main(){ ull a = 8, b = 4; cout << bit_anagram_check(a, b) << endl; return 0;}
// A simple Java program to check if binary// representations of two numbers are anagramimport java.io.*;import java.util.*; class GFG{ public static int SIZE = 8; // Function to check if binary representation // of two numbers are anagram static int bit_anagram_check(long a, long b) { // Find reverse binary representation of a // and store it in binary_a[] int i = 0; long[] binary_a = new long[SIZE]; Arrays.fill(binary_a, 0); while (a > 0) { binary_a[i] = a%2; a /= 2; i++; } // Find reverse binary representation of b // and store it in binary_a[] int j = 0; long[] binary_b = new long[SIZE]; Arrays.fill(binary_b, 0); while (b > 0) { binary_b[j] = b%2; b /= 2; j++; } // Sort two binary representations Arrays.sort(binary_a); Arrays.sort(binary_b); // Compare two sorted binary representations for (i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return 0; return 1; } // driver program public static void main (String[] args) { long a = 8, b = 4; System.out.println(bit_anagram_check(a, b)); }} // Contributed by Pramod Kumar
# A simple Python program to check if binary# representations of two numbers are anagram.SIZE = 8def bit_anagram_check(a, b): # Find reverse binary representation of a # and store it in binary_a[] global size i = 0 binary_a = [0] * SIZE while (a > 0): binary_a[i] = a % 2 a //= 2 i += 1 # Find reverse binary representation of b # and store it in binary_a[] j = 0 binary_b = [0] * SIZE while (b > 0): binary_b[j] = b % 2 b //= 2 j += 1 # Sort two binary representations binary_a.sort() binary_b.sort() # Compare two sorted binary representations for i in range(SIZE): if (binary_a[i] != binary_b[i]): return 0 return 1 # Driver codeif __name__ == "__main__": a = 8 b = 4 print(bit_anagram_check(a, b)) # This code is contributed by ukasp.
// A simple C# program to check if// binary representations of two// numbers are anagramusing System; class GFG{public static int SIZE = 8; // Function to check if binary// representation of two numbers// are anagrampublic static int bit_anagram_check(long a, long b){ // Find reverse binary representation // of a and store it in binary_a[] int i = 0; long[] binary_a = new long[SIZE]; Arrays.Fill(binary_a, 0); while (a > 0) { binary_a[i] = a % 2; a /= 2; i++; } // Find reverse binary representation // of b and store it in binary_a[] int j = 0; long[] binary_b = new long[SIZE]; Arrays.Fill(binary_b, 0); while (b > 0) { binary_b[j] = b % 2; b /= 2; j++; } // Sort two binary representations Array.Sort(binary_a); Array.Sort(binary_b); // Compare two sorted binary // representations for (i = 0; i < SIZE; i++) { if (binary_a[i] != binary_b[i]) { return 0; } } return 1;} public static class Arrays{public static T[] CopyOf<T>(T[] original, int newLength){ T[] dest = new T[newLength]; System.Array.Copy(original, dest, newLength); return dest;} public static T[] CopyOfRange<T>(T[] original, int fromIndex, int toIndex){ int length = toIndex - fromIndex; T[] dest = new T[length]; System.Array.Copy(original, fromIndex, dest, 0, length); return dest;} public static void Fill<T>(T[] array, T value){ for (int i = 0; i < array.Length; i++) { array[i] = value; }} public static void Fill<T>(T[] array, int fromIndex, int toIndex, T value){ for (int i = fromIndex; i < toIndex; i++) { array[i] = value; }}} // Driver Codepublic static void Main(string[] args){ long a = 8, b = 4; Console.WriteLine(bit_anagram_check(a, b));}} // This code is contributed by Shrikant13
<script>// A simple Javascript program to check if binary// representations of two numbers are anagram let SIZE = 8; // Function to check if binary representation // of two numbers are anagram function bit_anagram_check(a,b) { // Find reverse binary representation of a // and store it in binary_a[] let i = 0; let binary_a = new Array(SIZE); for(let i=0;i<SIZE;i++) { binary_a[i]=0; } while (a > 0) { binary_a[i] = a%2; a = Math.floor(a/2); i++; } // Find reverse binary representation of b // and store it in binary_a[] let j = 0; let binary_b = new Array(SIZE); for(let i=0;i<SIZE;i++) { binary_b[i]=0; } while (b > 0) { binary_b[j] = b%2; b = Math.floor(b/2); j++; } // Sort two binary representations binary_a.sort(function(a,b){return a-b;}); binary_b.sort(function(a,b){return a-b;}); // Compare two sorted binary representations for (i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return 0; return 1; } // driver program let a = 8, b = 4; document.write(bit_anagram_check(a, b)); //This code is contributed by rag2127 </script>
Output:
1
Note that the above code uses GCC-specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer.Time Complexity: O (1) Auxiliary Space: O (1) No extra space is getting used.This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
Rajput-Ji
ukasp
rag2127
yogeshsakle8
anagram
Bit Magic
Bit Magic
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Josephus problem | Set 1 (A O(n) Solution)
Find the element that appears once
Bits manipulation (Important tactics)
|
[
{
"code": null,
"e": 26277,
"s": 26249,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 26405,
"s": 26277,
"text": "Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples: "
},
{
"code": null,
"e": 26534,
"s": 26405,
"text": "Input : a = 8, b = 4 \nOutput : Yes\nBinary representations of both\nnumbers have same 0s and 1s.\n\nInput : a = 4, b = 5\nOutput : No"
},
{
"code": null,
"e": 26555,
"s": 26536,
"text": "Simple Approach: "
},
{
"code": null,
"e": 26704,
"s": 26555,
"text": "Find Binary Representation of βaβ and βbβ using simple decimal to binary representation technique.Check if two binary representations are an anagram"
},
{
"code": null,
"e": 26803,
"s": 26704,
"text": "Find Binary Representation of βaβ and βbβ using simple decimal to binary representation technique."
},
{
"code": null,
"e": 26854,
"s": 26803,
"text": "Check if two binary representations are an anagram"
},
{
"code": null,
"e": 26860,
"s": 26856,
"text": "C++"
},
{
"code": null,
"e": 26865,
"s": 26860,
"text": "Java"
},
{
"code": null,
"e": 26873,
"s": 26865,
"text": "Python3"
},
{
"code": null,
"e": 26876,
"s": 26873,
"text": "C#"
},
{
"code": null,
"e": 26887,
"s": 26876,
"text": "Javascript"
},
{
"code": "// A simple C++ program to check if binary// representations of two numbers are anagram.#include <bits/stdc++.h>#define ull unsigned long long intusing namespace std; const int SIZE = 8 * sizeof(ull); bool bit_anagram_check(ull a, ull b){ // Find reverse binary representation of a // and store it in binary_a[] int i = 0, binary_a[SIZE] = { 0 }; while (a > 0) { binary_a[i] = a % 2; a /= 2; i++; } // Find reverse binary representation of b // and store it in binary_a[] int j = 0, binary_b[SIZE] = { 0 }; while (b > 0) { binary_b[j] = b % 2; b /= 2; j++; } // Sort two binary representations sort(binary_a, binary_a + SIZE); sort(binary_b, binary_b + SIZE); // Compare two sorted binary representations for (int i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return false; return true;} // Driver codeint main(){ ull a = 8, b = 4; cout << bit_anagram_check(a, b) << endl; return 0;}",
"e": 27900,
"s": 26887,
"text": null
},
{
"code": "// A simple Java program to check if binary// representations of two numbers are anagramimport java.io.*;import java.util.*; class GFG{ public static int SIZE = 8; // Function to check if binary representation // of two numbers are anagram static int bit_anagram_check(long a, long b) { // Find reverse binary representation of a // and store it in binary_a[] int i = 0; long[] binary_a = new long[SIZE]; Arrays.fill(binary_a, 0); while (a > 0) { binary_a[i] = a%2; a /= 2; i++; } // Find reverse binary representation of b // and store it in binary_a[] int j = 0; long[] binary_b = new long[SIZE]; Arrays.fill(binary_b, 0); while (b > 0) { binary_b[j] = b%2; b /= 2; j++; } // Sort two binary representations Arrays.sort(binary_a); Arrays.sort(binary_b); // Compare two sorted binary representations for (i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return 0; return 1; } // driver program public static void main (String[] args) { long a = 8, b = 4; System.out.println(bit_anagram_check(a, b)); }} // Contributed by Pramod Kumar",
"e": 29244,
"s": 27900,
"text": null
},
{
"code": "# A simple Python program to check if binary# representations of two numbers are anagram.SIZE = 8def bit_anagram_check(a, b): # Find reverse binary representation of a # and store it in binary_a[] global size i = 0 binary_a = [0] * SIZE while (a > 0): binary_a[i] = a % 2 a //= 2 i += 1 # Find reverse binary representation of b # and store it in binary_a[] j = 0 binary_b = [0] * SIZE while (b > 0): binary_b[j] = b % 2 b //= 2 j += 1 # Sort two binary representations binary_a.sort() binary_b.sort() # Compare two sorted binary representations for i in range(SIZE): if (binary_a[i] != binary_b[i]): return 0 return 1 # Driver codeif __name__ == \"__main__\": a = 8 b = 4 print(bit_anagram_check(a, b)) # This code is contributed by ukasp.",
"e": 30113,
"s": 29244,
"text": null
},
{
"code": "// A simple C# program to check if// binary representations of two// numbers are anagramusing System; class GFG{public static int SIZE = 8; // Function to check if binary// representation of two numbers// are anagrampublic static int bit_anagram_check(long a, long b){ // Find reverse binary representation // of a and store it in binary_a[] int i = 0; long[] binary_a = new long[SIZE]; Arrays.Fill(binary_a, 0); while (a > 0) { binary_a[i] = a % 2; a /= 2; i++; } // Find reverse binary representation // of b and store it in binary_a[] int j = 0; long[] binary_b = new long[SIZE]; Arrays.Fill(binary_b, 0); while (b > 0) { binary_b[j] = b % 2; b /= 2; j++; } // Sort two binary representations Array.Sort(binary_a); Array.Sort(binary_b); // Compare two sorted binary // representations for (i = 0; i < SIZE; i++) { if (binary_a[i] != binary_b[i]) { return 0; } } return 1;} public static class Arrays{public static T[] CopyOf<T>(T[] original, int newLength){ T[] dest = new T[newLength]; System.Array.Copy(original, dest, newLength); return dest;} public static T[] CopyOfRange<T>(T[] original, int fromIndex, int toIndex){ int length = toIndex - fromIndex; T[] dest = new T[length]; System.Array.Copy(original, fromIndex, dest, 0, length); return dest;} public static void Fill<T>(T[] array, T value){ for (int i = 0; i < array.Length; i++) { array[i] = value; }} public static void Fill<T>(T[] array, int fromIndex, int toIndex, T value){ for (int i = fromIndex; i < toIndex; i++) { array[i] = value; }}} // Driver Codepublic static void Main(string[] args){ long a = 8, b = 4; Console.WriteLine(bit_anagram_check(a, b));}} // This code is contributed by Shrikant13",
"e": 32173,
"s": 30113,
"text": null
},
{
"code": "<script>// A simple Javascript program to check if binary// representations of two numbers are anagram let SIZE = 8; // Function to check if binary representation // of two numbers are anagram function bit_anagram_check(a,b) { // Find reverse binary representation of a // and store it in binary_a[] let i = 0; let binary_a = new Array(SIZE); for(let i=0;i<SIZE;i++) { binary_a[i]=0; } while (a > 0) { binary_a[i] = a%2; a = Math.floor(a/2); i++; } // Find reverse binary representation of b // and store it in binary_a[] let j = 0; let binary_b = new Array(SIZE); for(let i=0;i<SIZE;i++) { binary_b[i]=0; } while (b > 0) { binary_b[j] = b%2; b = Math.floor(b/2); j++; } // Sort two binary representations binary_a.sort(function(a,b){return a-b;}); binary_b.sort(function(a,b){return a-b;}); // Compare two sorted binary representations for (i = 0; i < SIZE; i++) if (binary_a[i] != binary_b[i]) return 0; return 1; } // driver program let a = 8, b = 4; document.write(bit_anagram_check(a, b)); //This code is contributed by rag2127 </script>",
"e": 33578,
"s": 32173,
"text": null
},
{
"code": null,
"e": 33588,
"s": 33578,
"text": "Output: "
},
{
"code": null,
"e": 33590,
"s": 33588,
"text": "1"
},
{
"code": null,
"e": 34228,
"s": 33590,
"text": "Note that the above code uses GCC-specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer.Time Complexity: O (1) Auxiliary Space: O (1) No extra space is getting used.This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 34240,
"s": 34228,
"text": "shrikanth13"
},
{
"code": null,
"e": 34250,
"s": 34240,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34256,
"s": 34250,
"text": "ukasp"
},
{
"code": null,
"e": 34264,
"s": 34256,
"text": "rag2127"
},
{
"code": null,
"e": 34277,
"s": 34264,
"text": "yogeshsakle8"
},
{
"code": null,
"e": 34285,
"s": 34277,
"text": "anagram"
},
{
"code": null,
"e": 34295,
"s": 34285,
"text": "Bit Magic"
},
{
"code": null,
"e": 34305,
"s": 34295,
"text": "Bit Magic"
},
{
"code": null,
"e": 34313,
"s": 34305,
"text": "anagram"
},
{
"code": null,
"e": 34411,
"s": 34313,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34441,
"s": 34411,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 34487,
"s": 34441,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 34527,
"s": 34487,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 34580,
"s": 34527,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 34631,
"s": 34580,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 34682,
"s": 34631,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34698,
"s": 34682,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 34741,
"s": 34698,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 34776,
"s": 34741,
"text": "Find the element that appears once"
}
] |
C++ | A Speed Breaker | Practice | GeeksforGeeks
|
Write a program to display the floating number a with a given precision value b.
Example 1:
Input: a = 4.567, b = 2
Output:
4.57
Explanation: Rounding a to two decimal
places.
Example 2:
Input: a = 8.92, b = 3
Output:
8.920
Explanation: Rounding a to three decimal
places.
Your Task:
You dont need to read input. Complete the function speedBreaker() which takes a and b as input parameters and print the floating number a with a given precision value b.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 β€ b β€ 15
0
n000nautiyal7 months ago
What mistake i was doing, maybe you are also facing the same issue:
After submitting its showing error and the output of my code is: 45.72.2203010.05500051 this long.
This occured due to a problem of not writing endl in this line;
cout<<fixed<<setprecision(b)<<a<<endl;
You may be also writing as:
cout<<fixed<<setprecision(b)<<a;
It needs a new line basically.
0
Gurucharan Rajput
This comment was deleted.
0
Muskan Gupta1 year ago
Muskan Gupta
void speedBreaker(double a, int b){ // code here cout<<fixed<<setprecision(b)<<a; }="" why="" this="" code="" is="" creating="" problem="" during="" submission.="">
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": 307,
"s": 226,
"text": "Write a program to display the floating number a with a given precision value b."
},
{
"code": null,
"e": 318,
"s": 307,
"text": "Example 1:"
},
{
"code": null,
"e": 404,
"s": 318,
"text": "Input: a = 4.567, b = 2\nOutput: \n4.57\nExplanation: Rounding a to two decimal\nplaces.\n"
},
{
"code": null,
"e": 415,
"s": 404,
"text": "Example 2:"
},
{
"code": null,
"e": 503,
"s": 415,
"text": "Input: a = 8.92, b = 3\nOutput: \n8.920\nExplanation: Rounding a to three decimal\nplaces.\n"
},
{
"code": null,
"e": 686,
"s": 503,
"text": "Your Task: \nYou dont need to read input. Complete the function speedBreaker() which takes a and b as input parameters and print the floating number a with a given precision value b."
},
{
"code": null,
"e": 748,
"s": 686,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 772,
"s": 748,
"text": "Constraints:\n1 β€ b β€ 15"
},
{
"code": null,
"e": 774,
"s": 772,
"text": "0"
},
{
"code": null,
"e": 799,
"s": 774,
"text": "n000nautiyal7 months ago"
},
{
"code": null,
"e": 868,
"s": 799,
"text": "What mistake i was doing, maybe you are also facing the same issue: "
},
{
"code": null,
"e": 967,
"s": 868,
"text": "After submitting its showing error and the output of my code is: 45.72.2203010.05500051 this long."
},
{
"code": null,
"e": 1031,
"s": 967,
"text": "This occured due to a problem of not writing endl in this line;"
},
{
"code": null,
"e": 1070,
"s": 1031,
"text": "cout<<fixed<<setprecision(b)<<a<<endl;"
},
{
"code": null,
"e": 1099,
"s": 1070,
"text": "You may be also writing as: "
},
{
"code": null,
"e": 1132,
"s": 1099,
"text": "cout<<fixed<<setprecision(b)<<a;"
},
{
"code": null,
"e": 1163,
"s": 1132,
"text": "It needs a new line basically."
},
{
"code": null,
"e": 1165,
"s": 1163,
"text": "0"
},
{
"code": null,
"e": 1183,
"s": 1165,
"text": "Gurucharan Rajput"
},
{
"code": null,
"e": 1209,
"s": 1183,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1211,
"s": 1209,
"text": "0"
},
{
"code": null,
"e": 1234,
"s": 1211,
"text": "Muskan Gupta1 year ago"
},
{
"code": null,
"e": 1247,
"s": 1234,
"text": "Muskan Gupta"
},
{
"code": null,
"e": 1426,
"s": 1247,
"text": "void speedBreaker(double a, int b){ // code here cout<<fixed<<setprecision(b)<<a; }=\"\" why=\"\" this=\"\" code=\"\" is=\"\" creating=\"\" problem=\"\" during=\"\" submission.=\"\">"
},
{
"code": null,
"e": 1572,
"s": 1426,
"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": 1608,
"s": 1572,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1618,
"s": 1608,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1628,
"s": 1618,
"text": "\nContest\n"
},
{
"code": null,
"e": 1691,
"s": 1628,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1839,
"s": 1691,
"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": 2047,
"s": 1839,
"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": 2153,
"s": 2047,
"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 change the color of an icon using jQuery ? - GeeksforGeeks
|
18 Oct, 2021
In this article, we will see how to change the color of the icon using jQuery. To change the color of the icon, we will use a jquery method.
jQuery css() method this method is used to change the styling of a particular selector. This method is also can be used for changing the color of the icon. First, we will create an icon element using font awesome icon and add some styles on it using CSS property. We have added an HTML button and when the button is clicked, the css() method is called and added some color and background color on the icon element.
Syntax:
$(selector).css(property)
Return value: It will return the value of the property for the selected element.
Example:
HTML
<!DOCTYPE html><html> <head> <title> How to change the color of the icon using jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> .btn { background-color: blue; border: none; color: white; padding: 16px 16px; font-size: 100px; border-radius: 5px; } #append { padding: 5px 15px; } </style> <!-- Script to add div element in the HTML document --> <script> $(document).ready(function () { $("button").click(function () { $(".btn").css({ backgroundColor: "green", color: "yellow" }); }); }); </script> </head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to change the color of the icon using jQuery? </h3> <button class="btn"> <i class="fa fa-home"></i> </button> <br><br> <button id="append"> Change Icon Color </button> </center></body> </html>
Output:
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27064,
"s": 27036,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 27205,
"s": 27064,
"text": "In this article, we will see how to change the color of the icon using jQuery. To change the color of the icon, we will use a jquery method."
},
{
"code": null,
"e": 27620,
"s": 27205,
"text": "jQuery css() method this method is used to change the styling of a particular selector. This method is also can be used for changing the color of the icon. First, we will create an icon element using font awesome icon and add some styles on it using CSS property. We have added an HTML button and when the button is clicked, the css() method is called and added some color and background color on the icon element."
},
{
"code": null,
"e": 27628,
"s": 27620,
"text": "Syntax:"
},
{
"code": null,
"e": 27654,
"s": 27628,
"text": "$(selector).css(property)"
},
{
"code": null,
"e": 27736,
"s": 27654,
"text": "Return value: It will return the value of the property for the selected element. "
},
{
"code": null,
"e": 27745,
"s": 27736,
"text": "Example:"
},
{
"code": null,
"e": 27750,
"s": 27745,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the color of the icon using jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> .btn { background-color: blue; border: none; color: white; padding: 16px 16px; font-size: 100px; border-radius: 5px; } #append { padding: 5px 15px; } </style> <!-- Script to add div element in the HTML document --> <script> $(document).ready(function () { $(\"button\").click(function () { $(\".btn\").css({ backgroundColor: \"green\", color: \"yellow\" }); }); }); </script> </head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to change the color of the icon using jQuery? </h3> <button class=\"btn\"> <i class=\"fa fa-home\"></i> </button> <br><br> <button id=\"append\"> Change Icon Color </button> </center></body> </html>",
"e": 29095,
"s": 27750,
"text": null
},
{
"code": null,
"e": 29103,
"s": 29095,
"text": "Output:"
},
{
"code": null,
"e": 29118,
"s": 29103,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 29135,
"s": 29118,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 29142,
"s": 29135,
"text": "Picked"
},
{
"code": null,
"e": 29149,
"s": 29142,
"text": "JQuery"
},
{
"code": null,
"e": 29166,
"s": 29149,
"text": "Web Technologies"
},
{
"code": null,
"e": 29264,
"s": 29166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29319,
"s": 29264,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 29392,
"s": 29319,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29415,
"s": 29392,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29451,
"s": 29415,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 29508,
"s": 29451,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 29548,
"s": 29508,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29581,
"s": 29548,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29626,
"s": 29581,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29669,
"s": 29626,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
PHP | strstr() Function
|
02 Nov, 2020
The strstr() function is a built-in function in PHP. It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified). This function is case-sensitive.
Syntax :
strstr( $string, $search, $before )
Parameters : This function accepts three parameters as shown in the above syntax out of which the first two parameters must be supplied and the third one is optional. All of these parameters are described below:
$string : It is a mandatory parameter which specifies the string in which we want to perform the search.
$search : It is a mandatory parameter which specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number
$before : It is an optional parameter. It specifies a boolean value whose default is false. If set to true, it returns the part of the $string before the first occurrence of the $search parameter.
Return Value : The function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
Examples:
Input : $string = "Hello world!", $search = "world"
Output : world!
Input : $string = "Geeks for Geeks!", $search = "k"
Output : ks for Geeks!
Below programs illustrate the strstr() function in PHP :
Program 1: In this program, we will display the portion of $string from the first occurrence of $search.
PHP
<?phpecho strstr("Geeks for Geeks!", "k");?>
Output:
ks for Geeks!
Program 2: In this program, we will display the portion of $string before the first occurrence of $search.
PHP
<?phpecho strstr("Geeks for Geeks!", "k", true);?>
Output:
Gee
Program 3: In this program we will pass an integer as $search.
PHP
<?php $string = "Geeks"; echo strstr($string, 101); // 101 is ASCII value of lowercase e?>
Output:
eeks
Reference: http://php.net/manual/en/function.strstr.php
arorakashish0911
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "The strstr() function is a built-in function in PHP. It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified). This function is case-sensitive."
},
{
"code": null,
"e": 320,
"s": 310,
"text": "Syntax : "
},
{
"code": null,
"e": 358,
"s": 320,
"text": "strstr( $string, $search, $before )\n\n"
},
{
"code": null,
"e": 571,
"s": 358,
"text": "Parameters : This function accepts three parameters as shown in the above syntax out of which the first two parameters must be supplied and the third one is optional. All of these parameters are described below: "
},
{
"code": null,
"e": 676,
"s": 571,
"text": "$string : It is a mandatory parameter which specifies the string in which we want to perform the search."
},
{
"code": null,
"e": 859,
"s": 676,
"text": "$search : It is a mandatory parameter which specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number"
},
{
"code": null,
"e": 1056,
"s": 859,
"text": "$before : It is an optional parameter. It specifies a boolean value whose default is false. If set to true, it returns the part of the $string before the first occurrence of the $search parameter."
},
{
"code": null,
"e": 1194,
"s": 1056,
"text": "Return Value : The function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found."
},
{
"code": null,
"e": 1205,
"s": 1194,
"text": "Examples: "
},
{
"code": null,
"e": 1351,
"s": 1205,
"text": "Input : $string = \"Hello world!\", $search = \"world\"\nOutput : world!\n\nInput : $string = \"Geeks for Geeks!\", $search = \"k\"\nOutput : ks for Geeks!\n\n"
},
{
"code": null,
"e": 1408,
"s": 1351,
"text": "Below programs illustrate the strstr() function in PHP :"
},
{
"code": null,
"e": 1515,
"s": 1408,
"text": "Program 1: In this program, we will display the portion of $string from the first occurrence of $search. "
},
{
"code": null,
"e": 1519,
"s": 1515,
"text": "PHP"
},
{
"code": "<?phpecho strstr(\"Geeks for Geeks!\", \"k\");?>",
"e": 1564,
"s": 1519,
"text": null
},
{
"code": null,
"e": 1573,
"s": 1564,
"text": "Output: "
},
{
"code": null,
"e": 1590,
"s": 1573,
"text": "ks for Geeks! \n\n"
},
{
"code": null,
"e": 1698,
"s": 1590,
"text": "Program 2: In this program, we will display the portion of $string before the first occurrence of $search. "
},
{
"code": null,
"e": 1702,
"s": 1698,
"text": "PHP"
},
{
"code": "<?phpecho strstr(\"Geeks for Geeks!\", \"k\", true);?>",
"e": 1753,
"s": 1702,
"text": null
},
{
"code": null,
"e": 1762,
"s": 1753,
"text": "Output: "
},
{
"code": null,
"e": 1768,
"s": 1762,
"text": "Gee\n\n"
},
{
"code": null,
"e": 1832,
"s": 1768,
"text": "Program 3: In this program we will pass an integer as $search. "
},
{
"code": null,
"e": 1836,
"s": 1832,
"text": "PHP"
},
{
"code": "<?php $string = \"Geeks\"; echo strstr($string, 101); // 101 is ASCII value of lowercase e?>",
"e": 1929,
"s": 1836,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1929,
"text": "Output: "
},
{
"code": null,
"e": 1945,
"s": 1938,
"text": "eeks\n\n"
},
{
"code": null,
"e": 2002,
"s": 1945,
"text": "Reference: http://php.net/manual/en/function.strstr.php "
},
{
"code": null,
"e": 2019,
"s": 2002,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2030,
"s": 2019,
"text": "PHP-string"
},
{
"code": null,
"e": 2034,
"s": 2030,
"text": "PHP"
},
{
"code": null,
"e": 2051,
"s": 2034,
"text": "Web Technologies"
},
{
"code": null,
"e": 2055,
"s": 2051,
"text": "PHP"
}
] |
Tailwind CSS Transition Property
|
23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. The transition-property class is used to specify the name of the CSS property for which the transition effect will occur. In CSS, we have done that by using the CSS transition-property.
Transition Property classes:
transition-none: This value is used to specify that no class will get a transition effect.
transition-all: All the class will get a transition effect. This is also the default value for this class.
transition: We can specify the names of CSS properties for which transition effect will be applied. We can also specify multiple properties by separating them with a comma.
transition-colors: This value is used to specify that the color class will get a transition effect.
transition-opacity: This value is used to specify that the opacity class will get a transition effect.
transition-shadow: This value is used to specify that the shadow class will get a transition effect.
transition-transform: This value is used to specify that the transformation into a defined shape.
Syntax:
<element class="transition-{properties}">...</element>
Example:
HTML
<!DOCTYPE html> <html><head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Transition Property Class</b> <div class="bg-green-200 m-8 grid grid-flow-col gap-4 p-5"> <button class="transition duration-500 ease-in-out bg-green-300 hover:bg-green-600 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900"> Hover me </button> <button class="transition-opacity duration-500 ease-in-out bg-green-300 hover:opacity-75 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900"> Hover me </button> <button class="transition-none duration-500 ease-in-out bg-green-300 hover:bg-green-600 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900"> Hover me </button> <button class="transition-colors duration-500 ease-in-out bg-green-300 hover:bg-yellow-600 transform hover:scale-110 rounded-lg p-4 border border-green-900 hover:border-black"> Hover me </button> </div> </body> </html>
Output:
different property class
Tailwind CSS
Tailwind-Transition & Animation
CSS
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": "\n23 Mar, 2022"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. The transition-property class is used to specify the name of the CSS property for which the transition effect will occur. In CSS, we have done that by using the CSS transition-property."
},
{
"code": null,
"e": 347,
"s": 318,
"text": "Transition Property classes:"
},
{
"code": null,
"e": 438,
"s": 347,
"text": "transition-none: This value is used to specify that no class will get a transition effect."
},
{
"code": null,
"e": 545,
"s": 438,
"text": "transition-all: All the class will get a transition effect. This is also the default value for this class."
},
{
"code": null,
"e": 718,
"s": 545,
"text": "transition: We can specify the names of CSS properties for which transition effect will be applied. We can also specify multiple properties by separating them with a comma."
},
{
"code": null,
"e": 818,
"s": 718,
"text": "transition-colors: This value is used to specify that the color class will get a transition effect."
},
{
"code": null,
"e": 921,
"s": 818,
"text": "transition-opacity: This value is used to specify that the opacity class will get a transition effect."
},
{
"code": null,
"e": 1022,
"s": 921,
"text": "transition-shadow: This value is used to specify that the shadow class will get a transition effect."
},
{
"code": null,
"e": 1120,
"s": 1022,
"text": "transition-transform: This value is used to specify that the transformation into a defined shape."
},
{
"code": null,
"e": 1128,
"s": 1120,
"text": "Syntax:"
},
{
"code": null,
"e": 1183,
"s": 1128,
"text": "<element class=\"transition-{properties}\">...</element>"
},
{
"code": null,
"e": 1192,
"s": 1183,
"text": "Example:"
},
{
"code": null,
"e": 1197,
"s": 1192,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html><head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Transition Property Class</b> <div class=\"bg-green-200 m-8 grid grid-flow-col gap-4 p-5\"> <button class=\"transition duration-500 ease-in-out bg-green-300 hover:bg-green-600 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900\"> Hover me </button> <button class=\"transition-opacity duration-500 ease-in-out bg-green-300 hover:opacity-75 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900\"> Hover me </button> <button class=\"transition-none duration-500 ease-in-out bg-green-300 hover:bg-green-600 transform hover:-translate-y-1 hover:scale-110 rounded-lg p-4 border border-green-900\"> Hover me </button> <button class=\"transition-colors duration-500 ease-in-out bg-green-300 hover:bg-yellow-600 transform hover:scale-110 rounded-lg p-4 border border-green-900 hover:border-black\"> Hover me </button> </div> </body> </html> ",
"e": 2758,
"s": 1197,
"text": null
},
{
"code": null,
"e": 2766,
"s": 2758,
"text": "Output:"
},
{
"code": null,
"e": 2804,
"s": 2779,
"text": "different property class"
},
{
"code": null,
"e": 2817,
"s": 2804,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 2849,
"s": 2817,
"text": "Tailwind-Transition & Animation"
},
{
"code": null,
"e": 2853,
"s": 2849,
"text": "CSS"
},
{
"code": null,
"e": 2870,
"s": 2853,
"text": "Web Technologies"
}
] |
How to remove rows based on blanks in a column from a data frame in R?
|
Sometimes data is incorrectly entered into systems and that is the reason we must be careful while doing data cleaning before proceeding to analysis. A data collector or the sampled unit might enter blank to an answer if he or she does not find an appropriate option for the question. This also happens if the questionnaire is not properly designed or blank is filled by mistake. Also, if we have categorical variable then a control category might be filled with blank or we may want to have a blank category to use a new one at later stage. Whatever the reason behind, an analyst faces such type of problems. These blanks are actually inserted by using space key on computers. Therefore, if a data frame has any column with blank values then those rows can be removed by using subsetting with single square brackets.
Consider the below data frame:
Live Demo
> set.seed(24)
> x1<-sample(c(" ",1:5),20,replace=TRUE)
> x2<-rnorm(20,4,1.25)
> df1<-data.frame(x1,x2)
> df1
x1 x2
1 2 3.413674
2 1 3.581267
3 2 5.920315
4 4 4.762493
5 1 4.645420
6 5 3.907114
7 1 3.243554
8 1.862944
9 3 3.664134
10 3.189261
11 3.882362
12 4 3.893074
13 4 4.149414
14 3.854630
15 4 2.820216
16 4 3.957828
17 3 3.268216
18 4 4.766064
19 1 5.896403
20 4.821726
Removing rows with blanks:
Live Demo
> df1[!df1$x1==" ",]
x1 x2
1 2 3.413674
2 1 3.581267
3 2 5.920315
4 4 4.762493
5 1 4.645420
6 5 3.907114
7 1 3.243554
9 3 3.664134
12 4 3.893074
13 4 4.149414
15 4 2.820216
16 4 3.957828
17 3 3.268216
18 4 4.766064
19 1 5.896403
Live Demo
> y1<-sample(c(" ",rpois(5,1)),20,replace=TRUE)
> y2<-rpois(20,5)
> df2<-data.frame(y1,y2)
> df2
y1 y2
1 1 2
2 0 4
3 3
4 10
5 0 6
6 0 5
7 0 7
8 0 3
9 1 1
10 1 6
11 2 7
12 2 5
13 0 5
14 3
15 0 5
16 0 3
17 1 4
18 0 4
19 2 2
20 14
Removing rows with blanks:
> df2[!df2$y1==" ",]
y1 y2
1 1 2
2 0 4
5 0 6
6 0 5
7 0 7
8 0 3
9 1 1
10 1 6
11 2 7
12 2 5
13 0 5
15 0 5
16 0 3
17 1 4
18 0 4
19 2 2
|
[
{
"code": null,
"e": 2005,
"s": 1187,
"text": "Sometimes data is incorrectly entered into systems and that is the reason we must be careful while doing data cleaning before proceeding to analysis. A data collector or the sampled unit might enter blank to an answer if he or she does not find an appropriate option for the question. This also happens if the questionnaire is not properly designed or blank is filled by mistake. Also, if we have categorical variable then a control category might be filled with blank or we may want to have a blank category to use a new one at later stage. Whatever the reason behind, an analyst faces such type of problems. These blanks are actually inserted by using space key on computers. Therefore, if a data frame has any column with blank values then those rows can be removed by using subsetting with single square brackets."
},
{
"code": null,
"e": 2036,
"s": 2005,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 2046,
"s": 2036,
"text": "Live Demo"
},
{
"code": null,
"e": 2156,
"s": 2046,
"text": "> set.seed(24)\n> x1<-sample(c(\" \",1:5),20,replace=TRUE)\n> x2<-rnorm(20,4,1.25)\n> df1<-data.frame(x1,x2)\n> df1"
},
{
"code": null,
"e": 2427,
"s": 2156,
"text": " x1 x2\n1 2 3.413674\n2 1 3.581267\n3 2 5.920315\n4 4 4.762493\n5 1 4.645420\n6 5 3.907114\n7 1 3.243554\n8 1.862944\n9 3 3.664134\n10 3.189261\n11 3.882362\n12 4 3.893074\n13 4 4.149414\n14 3.854630\n15 4 2.820216\n16 4 3.957828\n17 3 3.268216\n18 4 4.766064\n19 1 5.896403\n20 4.821726"
},
{
"code": null,
"e": 2454,
"s": 2427,
"text": "Removing rows with blanks:"
},
{
"code": null,
"e": 2464,
"s": 2454,
"text": "Live Demo"
},
{
"code": null,
"e": 2485,
"s": 2464,
"text": "> df1[!df1$x1==\" \",]"
},
{
"code": null,
"e": 2697,
"s": 2485,
"text": " x1 x2\n1 2 3.413674\n2 1 3.581267\n3 2 5.920315\n4 4 4.762493\n5 1 4.645420\n6 5 3.907114\n7 1 3.243554\n9 3 3.664134\n12 4 3.893074\n13 4 4.149414\n15 4 2.820216\n16 4 3.957828\n17 3 3.268216\n18 4 4.766064\n19 1 5.896403"
},
{
"code": null,
"e": 2707,
"s": 2697,
"text": "Live Demo"
},
{
"code": null,
"e": 2804,
"s": 2707,
"text": "> y1<-sample(c(\" \",rpois(5,1)),20,replace=TRUE)\n> y2<-rpois(20,5)\n> df2<-data.frame(y1,y2)\n> df2"
},
{
"code": null,
"e": 2940,
"s": 2804,
"text": " y1 y2\n1 1 2\n2 0 4\n3 3\n4 10\n5 0 6\n6 0 5\n7 0 7\n8 0 3\n9 1 1\n10 1 6\n11 2 7\n12 2 5\n13 0 5\n14 3\n15 0 5\n16 0 3\n17 1 4\n18 0 4\n19 2 2\n20 14"
},
{
"code": null,
"e": 2967,
"s": 2940,
"text": "Removing rows with blanks:"
},
{
"code": null,
"e": 2988,
"s": 2967,
"text": "> df2[!df2$y1==\" \",]"
},
{
"code": null,
"e": 3100,
"s": 2988,
"text": " y1 y2\n1 1 2\n2 0 4\n5 0 6\n6 0 5\n7 0 7\n8 0 3\n9 1 1\n10 1 6\n11 2 7\n12 2 5\n13 0 5\n15 0 5\n16 0 3\n17 1 4\n18 0 4\n19 2 2"
}
] |
Saving a Networkx graph in GEXF format and visualize using Gephi
|
29 Sep, 2021
Prerequisites: Networkx
NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms and draw networks.
In this article we will discuss how we can save a networkx graph in GEXF format and then visualize it using Gephi.
GEXF stands for Graph Exchange XML Format. Although it has features for supporting visualization of graphs but there are some limitations of visualization methods provided by NetworkX library. Hence, the need of using external tools like Gephi used for graph visualization arises. But we cannot straight away export graphs from python to Gephi we need to convert the graph into a format supported by it. GEXF is one such file format.
Gephi needs to installed first to be used: Gephi
To achieve this we will be employing write_gexf() function which as the name suggests saves a networkx graph into gexf format easily.
Syntax:
networkx.write_gexf( G , path )
Parameter:
G: In this argument NetworkX graph object or simply the graph is sent as parameter.
path: In this argument a valid path for saving the graph is specified.
Approach:
Import module
Create a networkx graph
Save this graph in gexf format
Program:
Python3
# importing the required moduleimport networkx as nx # making a simple graph with 1 node.G = nx.path_graph(10) # saving graph created above in gexf formatnx.write_gexf(G, "geeksforgeeks.gexf")
Output:
A file named geeksforgeeks.gexf will be saved at the specified path, it can be viewed using any text editor which will be shown in XML.
The graph created in the above program will be visualized using Gephi.
Approach
Install Gephi
Import gexf file
After visualization this is what the graph looks like:
sumitgumber28
Python DSA-exercises
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 52,
"s": 28,
"text": "Prerequisites: Networkx"
},
{
"code": null,
"e": 510,
"s": 52,
"text": "NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic networks, analyze network structure, build network models, design new network algorithms and draw networks."
},
{
"code": null,
"e": 626,
"s": 510,
"text": "In this article we will discuss how we can save a networkx graph in GEXF format and then visualize it using Gephi. "
},
{
"code": null,
"e": 1060,
"s": 626,
"text": "GEXF stands for Graph Exchange XML Format. Although it has features for supporting visualization of graphs but there are some limitations of visualization methods provided by NetworkX library. Hence, the need of using external tools like Gephi used for graph visualization arises. But we cannot straight away export graphs from python to Gephi we need to convert the graph into a format supported by it. GEXF is one such file format."
},
{
"code": null,
"e": 1109,
"s": 1060,
"text": "Gephi needs to installed first to be used: Gephi"
},
{
"code": null,
"e": 1244,
"s": 1109,
"text": "To achieve this we will be employing write_gexf() function which as the name suggests saves a networkx graph into gexf format easily. "
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Syntax:"
},
{
"code": null,
"e": 1284,
"s": 1252,
"text": "networkx.write_gexf( G , path )"
},
{
"code": null,
"e": 1295,
"s": 1284,
"text": "Parameter:"
},
{
"code": null,
"e": 1379,
"s": 1295,
"text": "G: In this argument NetworkX graph object or simply the graph is sent as parameter."
},
{
"code": null,
"e": 1450,
"s": 1379,
"text": "path: In this argument a valid path for saving the graph is specified."
},
{
"code": null,
"e": 1460,
"s": 1450,
"text": "Approach:"
},
{
"code": null,
"e": 1474,
"s": 1460,
"text": "Import module"
},
{
"code": null,
"e": 1498,
"s": 1474,
"text": "Create a networkx graph"
},
{
"code": null,
"e": 1529,
"s": 1498,
"text": "Save this graph in gexf format"
},
{
"code": null,
"e": 1538,
"s": 1529,
"text": "Program:"
},
{
"code": null,
"e": 1546,
"s": 1538,
"text": "Python3"
},
{
"code": "# importing the required moduleimport networkx as nx # making a simple graph with 1 node.G = nx.path_graph(10) # saving graph created above in gexf formatnx.write_gexf(G, \"geeksforgeeks.gexf\")",
"e": 1739,
"s": 1546,
"text": null
},
{
"code": null,
"e": 1747,
"s": 1739,
"text": "Output:"
},
{
"code": null,
"e": 1883,
"s": 1747,
"text": "A file named geeksforgeeks.gexf will be saved at the specified path, it can be viewed using any text editor which will be shown in XML."
},
{
"code": null,
"e": 1954,
"s": 1883,
"text": "The graph created in the above program will be visualized using Gephi."
},
{
"code": null,
"e": 1963,
"s": 1954,
"text": "Approach"
},
{
"code": null,
"e": 1977,
"s": 1963,
"text": "Install Gephi"
},
{
"code": null,
"e": 1994,
"s": 1977,
"text": "Import gexf file"
},
{
"code": null,
"e": 2049,
"s": 1994,
"text": "After visualization this is what the graph looks like:"
},
{
"code": null,
"e": 2063,
"s": 2049,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2084,
"s": 2063,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 2090,
"s": 2084,
"text": "Graph"
},
{
"code": null,
"e": 2097,
"s": 2090,
"text": "Python"
},
{
"code": null,
"e": 2103,
"s": 2097,
"text": "Graph"
}
] |
Lex program to check if a Date is valid or not
|
03 May, 2019
Problem: Write a Lex program to check if a date is valid or not.
Explanation:Flex (Fast lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Note: Format of Date is DD/MM/YYYY.
Examples:
Input: 02/05/2019
Output: It is a valid date
Input: 05/20/2019
Output: It is not a valid date
Implementation:
/* Lex program to check if a date is valid or not */ %{ /* Definition section */ #include<stdio.h> int i=0, yr=0, valid=0;%} /* Rule Section */%%([0-2][0-9]|[3][0-1])\/((0(1|3|5|7|8))|(10|12)) \/([1-2][0-9][0-9][-0-9]) {valid=1;} ([0-2][0-9]|30)\/((0(4|6|9))|11) \/([1-2][0-9][0-9][0-9]) {valid=1;} ([0-1][0-9]|2[0-8])\/02 \/([1-2][0-9][0-9][0-9]) {valid=1;} 29\/02\/([1-2][0-9][0-9][0-9]) { while(yytext[i]!='/')i++; i++; while(yytext[i]!='/')i++;i++; while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0'); if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;} %% // driver code main(){ yyin=fopen("vpn.txt", "r"); yylex(); if(valid==1) printf("It is a valid date\n"); else printf("It is not a valid date\n");} int yywrap(){ return 1;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 May, 2019"
},
{
"code": null,
"e": 93,
"s": 28,
"text": "Problem: Write a Lex program to check if a date is valid or not."
},
{
"code": null,
"e": 478,
"s": 93,
"text": "Explanation:Flex (Fast lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section."
},
{
"code": null,
"e": 514,
"s": 478,
"text": "Note: Format of Date is DD/MM/YYYY."
},
{
"code": null,
"e": 524,
"s": 514,
"text": "Examples:"
},
{
"code": null,
"e": 620,
"s": 524,
"text": "Input: 02/05/2019\nOutput: It is a valid date\n\nInput: 05/20/2019\nOutput: It is not a valid date "
},
{
"code": null,
"e": 636,
"s": 620,
"text": "Implementation:"
},
{
"code": "/* Lex program to check if a date is valid or not */ %{ /* Definition section */ #include<stdio.h> int i=0, yr=0, valid=0;%} /* Rule Section */%%([0-2][0-9]|[3][0-1])\\/((0(1|3|5|7|8))|(10|12)) \\/([1-2][0-9][0-9][-0-9]) {valid=1;} ([0-2][0-9]|30)\\/((0(4|6|9))|11) \\/([1-2][0-9][0-9][0-9]) {valid=1;} ([0-1][0-9]|2[0-8])\\/02 \\/([1-2][0-9][0-9][0-9]) {valid=1;} 29\\/02\\/([1-2][0-9][0-9][0-9]) { while(yytext[i]!='/')i++; i++; while(yytext[i]!='/')i++;i++; while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0'); if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;} %% // driver code main(){ yyin=fopen(\"vpn.txt\", \"r\"); yylex(); if(valid==1) printf(\"It is a valid date\\n\"); else printf(\"It is not a valid date\\n\");} int yywrap(){ return 1;}",
"e": 1425,
"s": 636,
"text": null
},
{
"code": null,
"e": 1433,
"s": 1425,
"text": "Output:"
},
{
"code": null,
"e": 1445,
"s": 1433,
"text": "Lex program"
},
{
"code": null,
"e": 1461,
"s": 1445,
"text": "Compiler Design"
}
] |
Express.js router.param() function
|
16 Jul, 2020
The parameters of router.param() are name and a function. Where name is the actual name of parameter and function is the callback function. Basically router.param() function triggers the callback function whenever user routes to the parameter. This callback function will be called for only single time in request response cycle, even if user routes to the parameter multiple times.
Syntax:
router.param(name, function)
Parameters of callback function are:
req β the request objectres β the response objectnext β the next middleware functionid β the value of name parameter
req β the request object
res β the response object
next β the next middleware function
id β the value of name parameter
First you need to install express node module into your node js application.
Installations of express js is as follows:
npm init
npm install express
Create a file names app.js and paste the following code in the file.
//const express = require("express");const app = express(); //import router module from route.js fileconst userRoutes = require("./route"); app.use("/", userRoutes); //PORTconst port = process.env.PORT || 8000; //Starting a serverapp.listen(port, () => { console.log(`app is running at ${port}`);});
We have to create another file named route.js in the same directory
Code for route.js file
const express = require("express");const router = express.Router(); router.param("userId", (req, res, next, id) => { console.log("This function will be called first"); next();}); router.get("/user/:userId", (req, res) => { console.log("Then this function will be called"); res.end();});// Export router module.exports = router;
Start the server by entering the following command
node app.js
Enter the following address into the browser
http://localhost:8000/user/343
You will see the following output in your terminal
Express.js
JavaScript
Node.js
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": "\n16 Jul, 2020"
},
{
"code": null,
"e": 411,
"s": 28,
"text": "The parameters of router.param() are name and a function. Where name is the actual name of parameter and function is the callback function. Basically router.param() function triggers the callback function whenever user routes to the parameter. This callback function will be called for only single time in request response cycle, even if user routes to the parameter multiple times."
},
{
"code": null,
"e": 419,
"s": 411,
"text": "Syntax:"
},
{
"code": null,
"e": 448,
"s": 419,
"text": "router.param(name, function)"
},
{
"code": null,
"e": 486,
"s": 448,
"text": "Parameters of callback function are: "
},
{
"code": null,
"e": 603,
"s": 486,
"text": "req β the request objectres β the response objectnext β the next middleware functionid β the value of name parameter"
},
{
"code": null,
"e": 628,
"s": 603,
"text": "req β the request object"
},
{
"code": null,
"e": 654,
"s": 628,
"text": "res β the response object"
},
{
"code": null,
"e": 690,
"s": 654,
"text": "next β the next middleware function"
},
{
"code": null,
"e": 723,
"s": 690,
"text": "id β the value of name parameter"
},
{
"code": null,
"e": 800,
"s": 723,
"text": "First you need to install express node module into your node js application."
},
{
"code": null,
"e": 843,
"s": 800,
"text": "Installations of express js is as follows:"
},
{
"code": null,
"e": 874,
"s": 843,
"text": "npm init \nnpm install express "
},
{
"code": null,
"e": 943,
"s": 874,
"text": "Create a file names app.js and paste the following code in the file."
},
{
"code": "//const express = require(\"express\");const app = express(); //import router module from route.js fileconst userRoutes = require(\"./route\"); app.use(\"/\", userRoutes); //PORTconst port = process.env.PORT || 8000; //Starting a serverapp.listen(port, () => { console.log(`app is running at ${port}`);});",
"e": 1248,
"s": 943,
"text": null
},
{
"code": null,
"e": 1316,
"s": 1248,
"text": "We have to create another file named route.js in the same directory"
},
{
"code": null,
"e": 1339,
"s": 1316,
"text": "Code for route.js file"
},
{
"code": "const express = require(\"express\");const router = express.Router(); router.param(\"userId\", (req, res, next, id) => { console.log(\"This function will be called first\"); next();}); router.get(\"/user/:userId\", (req, res) => { console.log(\"Then this function will be called\"); res.end();});// Export router module.exports = router;",
"e": 1681,
"s": 1339,
"text": null
},
{
"code": null,
"e": 1732,
"s": 1681,
"text": "Start the server by entering the following command"
},
{
"code": null,
"e": 1744,
"s": 1732,
"text": "node app.js"
},
{
"code": null,
"e": 1789,
"s": 1744,
"text": "Enter the following address into the browser"
},
{
"code": null,
"e": 1820,
"s": 1789,
"text": "http://localhost:8000/user/343"
},
{
"code": null,
"e": 1871,
"s": 1820,
"text": "You will see the following output in your terminal"
},
{
"code": null,
"e": 1882,
"s": 1871,
"text": "Express.js"
},
{
"code": null,
"e": 1893,
"s": 1882,
"text": "JavaScript"
},
{
"code": null,
"e": 1901,
"s": 1893,
"text": "Node.js"
},
{
"code": null,
"e": 1918,
"s": 1901,
"text": "Web Technologies"
}
] |
unordered_set insert() function in C++ STL
|
23 Jun, 2022
The unordered_set::insert() is a built-in function in C++ STL which is used to insert a new {element} in the unordered_set container. Each element is inserted only if it is not already present in the container (elements in an unordered_set have unique values). The insertion is done automatically at the position according to the containerβs criterion (since it uses different hashing functions). This effectively increases the container size by the number of elements inserted.Syntax:
unordered_set_name.insert (Value)
or,
unordered_set_name.insert (InputIterator first, InputIterator last)
Parameters:
Value: It specifies the value which is to be inserted in the container.
first, last: Iterators specifying a range of elements. Copies of the elements in the range [first, last) are inserted in the unordered_set container. Keep in mind that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
Return Value: The function returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed. Below are programs that illustrate the above function:Time Complexity: insert() method takes O(1).
Program 1:
CPP
#include<iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<string> mySet = { "first", "third" }; string myString = "tenth"; // inserts key in set mySet.insert(myString); cout << "My set contains:" << endl; for (const string& x : mySet) { cout << x << " "; } cout << endl; return 0;}
My set contains:
tenth first third
Program 2:
CPP
// C++ program to illustrate// unordered_set::insert() #include <array>#include <iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<std::string> mySet = { "first", "third", "second" }; array<std::string, 2> myArray = { "tenth", "seventh" }; string myString = "ninth"; mySet.insert(myString); // array elements range insertion in set mySet.insert(myArray.begin(), myArray.end()); // initializer list insertion mySet.insert({ "fourth", "sixth" }); cout << "myset contains:" << endl; for (const string& x : mySet) { cout << x << " "; } cout << endl; return 0;}
myset contains:
sixth fourth seventh first tenth second third ninth
Program 3:
C++
// C++ program to illustrate// unordered_set::insert() return values#include <iostream>#include <bits/stdc++.h>using namespace std; //function to display the elements of the unordered setvoid display_elements(unordered_set<int> &u_set){ cout<<"the elements int the unordered set are: "; for(auto it:u_set) { cout<<it <<" "; } cout<<endl;} int main() { unordered_set<int> u_set; cout<<"u_set.insert(1).second: "<<u_set.insert(1).second<<endl; //on successful insertion it's true else false. cout<<"*(u_set.insert(1).first): "<<*(u_set.insert(1).first)<<endl; //first is the iterator to the inseted element, if the element not present in the u_set, //if the element already in the u_set, then it points to that element cout<<"u_set.insert(1).second: "<<u_set.insert(1).second<<endl; cout<<"*(u_set.insert(1).first): "<<*(u_set.insert(1).first)<<endl; cout<<"u_set.insert(2).second: "<<u_set.insert(2).second<<endl; //on successful insertion it's true else false. cout<<"*(u_set.insert(2).first): "<<*(u_set.insert(2).first)<<endl; display_elements(u_set); return 0;}
u_set.insert(1).second: 1
*(u_set.insert(1).first): 1
u_set.insert(1).second: 0
*(u_set.insert(1).first): 1
u_set.insert(2).second: 1
*(u_set.insert(2).first): 2
the elements int the unordered set are: 2 1
AkshitaSaraf
hguru001
singghakshay
divyanshmishra101010
CPP-Functions
cpp-unordered_set
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Templates in C++ with Examples
Inheritance in C++
Operator Overloading in C++
Polymorphism in C++
vector erase() and clear() in C++
Socket Programming in C/C++
C++ Classes and Objects
Object Oriented Programming in C++
2D Vector In C++ With User Defined Size
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 541,
"s": 54,
"text": "The unordered_set::insert() is a built-in function in C++ STL which is used to insert a new {element} in the unordered_set container. Each element is inserted only if it is not already present in the container (elements in an unordered_set have unique values). The insertion is done automatically at the position according to the containerβs criterion (since it uses different hashing functions). This effectively increases the container size by the number of elements inserted.Syntax: "
},
{
"code": null,
"e": 649,
"s": 541,
"text": "unordered_set_name.insert (Value)\n\nor,\n\nunordered_set_name.insert (InputIterator first, InputIterator last)"
},
{
"code": null,
"e": 662,
"s": 649,
"text": "Parameters: "
},
{
"code": null,
"e": 734,
"s": 662,
"text": "Value: It specifies the value which is to be inserted in the container."
},
{
"code": null,
"e": 1034,
"s": 734,
"text": "first, last: Iterators specifying a range of elements. Copies of the elements in the range [first, last) are inserted in the unordered_set container. Keep in mind that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last."
},
{
"code": null,
"e": 1451,
"s": 1034,
"text": "Return Value: The function returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed. Below are programs that illustrate the above function:Time Complexity: insert() method takes O(1)."
},
{
"code": null,
"e": 1463,
"s": 1451,
"text": "Program 1: "
},
{
"code": null,
"e": 1467,
"s": 1463,
"text": "CPP"
},
{
"code": "#include<iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<string> mySet = { \"first\", \"third\" }; string myString = \"tenth\"; // inserts key in set mySet.insert(myString); cout << \"My set contains:\" << endl; for (const string& x : mySet) { cout << x << \" \"; } cout << endl; return 0;}",
"e": 1855,
"s": 1467,
"text": null
},
{
"code": null,
"e": 1891,
"s": 1855,
"text": "My set contains:\ntenth first third "
},
{
"code": null,
"e": 1903,
"s": 1891,
"text": "Program 2: "
},
{
"code": null,
"e": 1907,
"s": 1903,
"text": "CPP"
},
{
"code": "// C++ program to illustrate// unordered_set::insert() #include <array>#include <iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<std::string> mySet = { \"first\", \"third\", \"second\" }; array<std::string, 2> myArray = { \"tenth\", \"seventh\" }; string myString = \"ninth\"; mySet.insert(myString); // array elements range insertion in set mySet.insert(myArray.begin(), myArray.end()); // initializer list insertion mySet.insert({ \"fourth\", \"sixth\" }); cout << \"myset contains:\" << endl; for (const string& x : mySet) { cout << x << \" \"; } cout << endl; return 0;}",
"e": 2650,
"s": 1907,
"text": null
},
{
"code": null,
"e": 2719,
"s": 2650,
"text": "myset contains:\nsixth fourth seventh first tenth second third ninth "
},
{
"code": null,
"e": 2730,
"s": 2719,
"text": "Program 3:"
},
{
"code": null,
"e": 2734,
"s": 2730,
"text": "C++"
},
{
"code": "// C++ program to illustrate// unordered_set::insert() return values#include <iostream>#include <bits/stdc++.h>using namespace std; //function to display the elements of the unordered setvoid display_elements(unordered_set<int> &u_set){ cout<<\"the elements int the unordered set are: \"; for(auto it:u_set) { cout<<it <<\" \"; } cout<<endl;} int main() { unordered_set<int> u_set; cout<<\"u_set.insert(1).second: \"<<u_set.insert(1).second<<endl; //on successful insertion it's true else false. cout<<\"*(u_set.insert(1).first): \"<<*(u_set.insert(1).first)<<endl; //first is the iterator to the inseted element, if the element not present in the u_set, //if the element already in the u_set, then it points to that element cout<<\"u_set.insert(1).second: \"<<u_set.insert(1).second<<endl; cout<<\"*(u_set.insert(1).first): \"<<*(u_set.insert(1).first)<<endl; cout<<\"u_set.insert(2).second: \"<<u_set.insert(2).second<<endl; //on successful insertion it's true else false. cout<<\"*(u_set.insert(2).first): \"<<*(u_set.insert(2).first)<<endl; display_elements(u_set); return 0;}",
"e": 3867,
"s": 2734,
"text": null
},
{
"code": null,
"e": 4074,
"s": 3867,
"text": "u_set.insert(1).second: 1\n*(u_set.insert(1).first): 1\nu_set.insert(1).second: 0\n*(u_set.insert(1).first): 1\nu_set.insert(2).second: 1\n*(u_set.insert(2).first): 2\nthe elements int the unordered set are: 2 1 "
},
{
"code": null,
"e": 4089,
"s": 4076,
"text": "AkshitaSaraf"
},
{
"code": null,
"e": 4098,
"s": 4089,
"text": "hguru001"
},
{
"code": null,
"e": 4111,
"s": 4098,
"text": "singghakshay"
},
{
"code": null,
"e": 4132,
"s": 4111,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 4146,
"s": 4132,
"text": "CPP-Functions"
},
{
"code": null,
"e": 4164,
"s": 4146,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 4171,
"s": 4164,
"text": "Picked"
},
{
"code": null,
"e": 4175,
"s": 4171,
"text": "C++"
},
{
"code": null,
"e": 4179,
"s": 4175,
"text": "CPP"
},
{
"code": null,
"e": 4277,
"s": 4179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4304,
"s": 4277,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 4335,
"s": 4304,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 4354,
"s": 4335,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 4382,
"s": 4354,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 4402,
"s": 4382,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 4436,
"s": 4402,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4464,
"s": 4436,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 4488,
"s": 4464,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 4523,
"s": 4488,
"text": "Object Oriented Programming in C++"
}
] |
Vector set() Method in Java
|
14 Aug, 2018
The Java.util.Vector.set() method is used to replace any particular element in the vector, created using the Vector class, with another element.
Syntax:
Vector.set(int index, Object element)
Parameters: This function accepts two mandatory parameters as shown in the above syntax and described below.
index: This is of integer type and refers to the position of the element that is to be replaced from the vector.
element: It is the new element by which the existing element will be replaced and is of the same object type as the vector.
Return Value: The method returns the previous value from the vector that is replaced with the new value.
Below programs illustrate the Java.util.Vector.set() method:
Program 1:
// Java code to illustrate set()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(); // Use add() method to add elements in the vector vec_tor.add("Geeks"); vec_tor.add("for"); vec_tor.add("Geeks"); vec_tor.add("10"); vec_tor.add("20"); // Displaying the Vector System.out.println("Vector: " + vec_tor); // Using set() method to replace Geeks with GFG System.out.println("The Object that is replaced is: " + vec_tor.set(2, "GFG")); // Using set() method to replace 20 with 50 System.out.println("The Object that is replaced is: " + vec_tor.set(4, "50")); // Displaying the modified vector System.out.println("The new Vector is:" + vec_tor); }}
Vector: [Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new Vector is:[Geeks, for, GFG, 10, 50]
Program 2:
// Java code to illustrate set()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements in the vector vec_tor.add(12); vec_tor.add(23); vec_tor.add(22); vec_tor.add(10); vec_tor.add(20); // Displaying the Vector System.out.println("Vector: " + vec_tor); // Using set() method to replace 12 with 21 System.out.println("The Object that is replaced is: " + vec_tor.set(0, 21)); // Using set() method to replace 20 with 50 System.out.println("The Object that is replaced is: " + vec_tor.set(4, 50)); // Displaying the modified vector System.out.println("The new Vector is:" + vec_tor); }}
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Aug, 2018"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "The Java.util.Vector.set() method is used to replace any particular element in the vector, created using the Vector class, with another element."
},
{
"code": null,
"e": 181,
"s": 173,
"text": "Syntax:"
},
{
"code": null,
"e": 219,
"s": 181,
"text": "Vector.set(int index, Object element)"
},
{
"code": null,
"e": 328,
"s": 219,
"text": "Parameters: This function accepts two mandatory parameters as shown in the above syntax and described below."
},
{
"code": null,
"e": 441,
"s": 328,
"text": "index: This is of integer type and refers to the position of the element that is to be replaced from the vector."
},
{
"code": null,
"e": 565,
"s": 441,
"text": "element: It is the new element by which the existing element will be replaced and is of the same object type as the vector."
},
{
"code": null,
"e": 670,
"s": 565,
"text": "Return Value: The method returns the previous value from the vector that is replaced with the new value."
},
{
"code": null,
"e": 731,
"s": 670,
"text": "Below programs illustrate the Java.util.Vector.set() method:"
},
{
"code": null,
"e": 742,
"s": 731,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate set()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<String> vec_tor = new Vector<String>(); // Use add() method to add elements in the vector vec_tor.add(\"Geeks\"); vec_tor.add(\"for\"); vec_tor.add(\"Geeks\"); vec_tor.add(\"10\"); vec_tor.add(\"20\"); // Displaying the Vector System.out.println(\"Vector: \" + vec_tor); // Using set() method to replace Geeks with GFG System.out.println(\"The Object that is replaced is: \" + vec_tor.set(2, \"GFG\")); // Using set() method to replace 20 with 50 System.out.println(\"The Object that is replaced is: \" + vec_tor.set(4, \"50\")); // Displaying the modified vector System.out.println(\"The new Vector is:\" + vec_tor); }}",
"e": 1679,
"s": 742,
"text": null
},
{
"code": null,
"e": 1833,
"s": 1679,
"text": "Vector: [Geeks, for, Geeks, 10, 20]\nThe Object that is replaced is: Geeks\nThe Object that is replaced is: 20\nThe new Vector is:[Geeks, for, GFG, 10, 50]\n"
},
{
"code": null,
"e": 1844,
"s": 1833,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate set()import java.util.*; public class VectorDemo { public static void main(String args[]) { // Creating an empty Vector Vector<Integer> vec_tor = new Vector<Integer>(); // Use add() method to add elements in the vector vec_tor.add(12); vec_tor.add(23); vec_tor.add(22); vec_tor.add(10); vec_tor.add(20); // Displaying the Vector System.out.println(\"Vector: \" + vec_tor); // Using set() method to replace 12 with 21 System.out.println(\"The Object that is replaced is: \" + vec_tor.set(0, 21)); // Using set() method to replace 20 with 50 System.out.println(\"The Object that is replaced is: \" + vec_tor.set(4, 50)); // Displaying the modified vector System.out.println(\"The new Vector is:\" + vec_tor); }}",
"e": 2757,
"s": 1844,
"text": null
},
{
"code": null,
"e": 2896,
"s": 2757,
"text": "Vector: [12, 23, 22, 10, 20]\nThe Object that is replaced is: 12\nThe Object that is replaced is: 20\nThe new Vector is:[21, 23, 22, 10, 50]\n"
},
{
"code": null,
"e": 2916,
"s": 2896,
"text": "Java - util package"
},
{
"code": null,
"e": 2933,
"s": 2916,
"text": "Java-Collections"
},
{
"code": null,
"e": 2948,
"s": 2933,
"text": "Java-Functions"
},
{
"code": null,
"e": 2960,
"s": 2948,
"text": "Java-Vector"
},
{
"code": null,
"e": 2965,
"s": 2960,
"text": "Java"
},
{
"code": null,
"e": 2970,
"s": 2965,
"text": "Java"
},
{
"code": null,
"e": 2987,
"s": 2970,
"text": "Java-Collections"
}
] |
main and init function in Golang
|
05 Sep, 2019
The Go language reserve two functions for special purpose and the functions are main() and init() function.
In Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a special type of function and it is the entry point of the executable programs. It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function.
Example:
// Go program to illustrate the// concept of main() function // Declaration of the main packagepackage main // Importing packagesimport ( "fmt" "sort" "strings" "time") // Main functionfunc main() { // Sorting the given slice s := []int{345, 78, 123, 10, 76, 2, 567, 5} sort.Ints(s) fmt.Println("Sorted slice: ", s) // Finding the index fmt.Println("Index value: ", strings.Index("GeeksforGeeks", "ks")) // Finding the time fmt.Println("Time: ", time.Now().Unix()) }
Output:
Sorted slice: [2 5 10 76 78 123 345 567]
Index value: 3
Time: 1257894000
init() function is just like the main function, does not take any argument nor return anything. This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, so you cannot reference it from anywhere and you are allowed to create multiple init() function in the same program and they execute in the order they are created. You are allowed to create init() function anywhere in the program and they are called in lexical file name order (Alphabetical Order). And allowed to put statements if the init() function, but always remember to init() function is executed before the main() function call, so it does not depend to main() function. The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context.
Example:
// Go program to illustrate the// concept of init() function // Declaration of the main packagepackage main // Importing packageimport "fmt" // Multiple init() functionfunc init() { fmt.Println("Welcome to init() function")} func init() { fmt.Println("Hello! init() function")} // Main functionfunc main() { fmt.Println("Welcome to main() function")}
Output:
Welcome to init() function
Hello! init() function
Welcome to main() function
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "The Go language reserve two functions for special purpose and the functions are main() and init() function."
},
{
"code": null,
"e": 617,
"s": 136,
"text": "In Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a special type of function and it is the entry point of the executable programs. It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function."
},
{
"code": null,
"e": 626,
"s": 617,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of main() function // Declaration of the main packagepackage main // Importing packagesimport ( \"fmt\" \"sort\" \"strings\" \"time\") // Main functionfunc main() { // Sorting the given slice s := []int{345, 78, 123, 10, 76, 2, 567, 5} sort.Ints(s) fmt.Println(\"Sorted slice: \", s) // Finding the index fmt.Println(\"Index value: \", strings.Index(\"GeeksforGeeks\", \"ks\")) // Finding the time fmt.Println(\"Time: \", time.Now().Unix()) }",
"e": 1139,
"s": 626,
"text": null
},
{
"code": null,
"e": 1147,
"s": 1139,
"text": "Output:"
},
{
"code": null,
"e": 1224,
"s": 1147,
"text": "Sorted slice: [2 5 10 76 78 123 345 567]\nIndex value: 3\nTime: 1257894000\n"
},
{
"code": null,
"e": 2068,
"s": 1224,
"text": "init() function is just like the main function, does not take any argument nor return anything. This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, so you cannot reference it from anywhere and you are allowed to create multiple init() function in the same program and they execute in the order they are created. You are allowed to create init() function anywhere in the program and they are called in lexical file name order (Alphabetical Order). And allowed to put statements if the init() function, but always remember to init() function is executed before the main() function call, so it does not depend to main() function. The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context."
},
{
"code": null,
"e": 2077,
"s": 2068,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of init() function // Declaration of the main packagepackage main // Importing packageimport \"fmt\" // Multiple init() functionfunc init() { fmt.Println(\"Welcome to init() function\")} func init() { fmt.Println(\"Hello! init() function\")} // Main functionfunc main() { fmt.Println(\"Welcome to main() function\")}",
"e": 2442,
"s": 2077,
"text": null
},
{
"code": null,
"e": 2450,
"s": 2442,
"text": "Output:"
},
{
"code": null,
"e": 2528,
"s": 2450,
"text": "Welcome to init() function\nHello! init() function\nWelcome to main() function\n"
},
{
"code": null,
"e": 2535,
"s": 2528,
"text": "Golang"
},
{
"code": null,
"e": 2547,
"s": 2535,
"text": "Go Language"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.