title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Count Number of Occurrences of Certain Character in String in R - GeeksforGeeks
|
16 May, 2021
In this article, we will discuss how to count the number of occurrences of a certain character in String in R Programming Language.
The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines.
install.packages("stringr")
The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching to the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned.
Syntax: str_count(str, pattern = “”)
Parameters :
str – The string to count the occurrences of
pattern – the pattern to match to
Example 1:
R
library(stringr)
# declaring string
str1 = "$geeks%for!geeks%"
# declaring character to find
ch1 = "a"
print("Count for character a")
str_count(str1,ch1)
ch2 = "%"
print("Count for character %")
str_count(str1,ch2)
Output
[1] "Count for character a"
[1] 0
[1] "Count for character %"
[1] 2
Example 2:
R
library(stringr)
# declaring string
str = c("$geeks%for!geeks%","cs^e%portal",
"le%..e3oten","joinnow3")
print ("Original vector")
print (str)
# declaring character to find
ch2 = "%"
print("Count for character %")
str_count(str,ch2)
Output
[1] "Original vector"
[1] "$geeks%for!geeks%" "cs^e%portal" "le%..e3oten" "joinnow3"
[1] "Count for character %"
[1] 2 1 1 0
This approach uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case.
Syntax:
gregexpr(pattern, text)
This is followed by the application of the regmatches() method in R which is used to extract and then replace the list of matched substrings returned by gregexpr() method. The first argument is the original vector and the second argument is the object returned as a result of the previous method. The lengths() method is then applied in order to return the individual lengths of all the elements of the argument vector.
Syntax:
lengths(x)
Example 1:
R
# declaring string
str1 = "$geeks%for!geeks%"
# declaring character to find
ch1 = "a"
print("Count for character a")
lengths(regmatches(str1, gregexpr(ch1, str1)))
ch2 = "%"
print("Count for character %")
lengths(regmatches(str1, gregexpr(ch2, str1)))
Output
[1] "Count for character a"
[1] 0
[1] "Count for character %"
[1] 2
Example 2:
R
# declaring string
str = c("$geeks%for!geeks%","cs^e%portal","le%..e3oten","joinnow3")
print ("Original vector")
print (str)
# declaring character to find
ch2 = "%"
print("Count for character %")
lengths(regmatches(str, gregexpr(ch2, str)))
Output
[1] "Original vector"
[1] "$geeks%for!geeks%" "cs^e%portal" "le%..e3oten" "joinnow3"
[1] "Count for character %"
[1] 2 1 1 0
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Visualization in R
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Logistic Regression in R Programming
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to filter R DataFrame by values in a column?
Merge DataFrames by Column Names in R
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 24385,
"s": 24354,
"text": " \n16 May, 2021\n"
},
{
"code": null,
"e": 24517,
"s": 24385,
"text": "In this article, we will discuss how to count the number of occurrences of a certain character in String in R Programming Language."
},
{
"code": null,
"e": 24677,
"s": 24517,
"text": "The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access its methods and routines. "
},
{
"code": null,
"e": 24705,
"s": 24677,
"text": "install.packages(\"stringr\")"
},
{
"code": null,
"e": 25297,
"s": 24705,
"text": "The stringr package provides a str_count() method which is used to count the number of occurrences of a certain pattern specified as an argument to the function. The pattern may be a single character or a group of characters. Any instances matching to the expression result in the increment of the count. This method can also be invoked over a vector of strings, and an individual count vector is returned containing individual counts of the number of pattern matches found. However, this method is only considered approximate of regex matching. In case, no matches are found 0 is returned. "
},
{
"code": null,
"e": 25334,
"s": 25297,
"text": "Syntax: str_count(str, pattern = “”)"
},
{
"code": null,
"e": 25348,
"s": 25334,
"text": "Parameters : "
},
{
"code": null,
"e": 25393,
"s": 25348,
"text": "str – The string to count the occurrences of"
},
{
"code": null,
"e": 25427,
"s": 25393,
"text": "pattern – the pattern to match to"
},
{
"code": null,
"e": 25438,
"s": 25427,
"text": "Example 1:"
},
{
"code": null,
"e": 25440,
"s": 25438,
"text": "R"
},
{
"code": "\n\n\n\n\n\n\nlibrary(stringr) \n \n# declaring string \nstr1 = \"$geeks%for!geeks%\"\n \n# declaring character to find \nch1 = \"a\"\nprint(\"Count for character a\") \nstr_count(str1,ch1) \n \nch2 = \"%\"\nprint(\"Count for character %\") \nstr_count(str1,ch2) \n\n\n\n\n\n",
"e": 25694,
"s": 25450,
"text": null
},
{
"code": null,
"e": 25701,
"s": 25694,
"text": "Output"
},
{
"code": null,
"e": 25772,
"s": 25701,
"text": "[1] \"Count for character a\" \n[1] 0 \n[1] \"Count for character %\" \n[1] 2"
},
{
"code": null,
"e": 25783,
"s": 25772,
"text": "Example 2:"
},
{
"code": null,
"e": 25785,
"s": 25783,
"text": "R"
},
{
"code": "\n\n\n\n\n\n\nlibrary(stringr) \n \n# declaring string \nstr = c(\"$geeks%for!geeks%\",\"cs^e%portal\", \n \"le%..e3oten\",\"joinnow3\") \nprint (\"Original vector\") \nprint (str) \n \n# declaring character to find \nch2 = \"%\"\nprint(\"Count for character %\") \nstr_count(str,ch2) \n\n\n\n\n\n",
"e": 26064,
"s": 25795,
"text": null
},
{
"code": null,
"e": 26071,
"s": 26064,
"text": "Output"
},
{
"code": null,
"e": 26196,
"s": 26071,
"text": "[1] \"Original vector\"\n[1] \"$geeks%for!geeks%\" \"cs^e%portal\" \"le%..e3oten\" \"joinnow3\"\n[1] \"Count for character %\"\n[1] 2 1 1 0"
},
{
"code": null,
"e": 26509,
"s": 26196,
"text": "This approach uses a variety of methods available in base R to compute the number of occurrences of a specific character in R. The gregexpr() method is used to return a list of sublists that match a specific pattern of the argument list of the function. The pattern matching used is case-sensitive in this case. "
},
{
"code": null,
"e": 26517,
"s": 26509,
"text": "Syntax:"
},
{
"code": null,
"e": 26541,
"s": 26517,
"text": "gregexpr(pattern, text)"
},
{
"code": null,
"e": 26962,
"s": 26541,
"text": "This is followed by the application of the regmatches() method in R which is used to extract and then replace the list of matched substrings returned by gregexpr() method. The first argument is the original vector and the second argument is the object returned as a result of the previous method. The lengths() method is then applied in order to return the individual lengths of all the elements of the argument vector. "
},
{
"code": null,
"e": 26970,
"s": 26962,
"text": "Syntax:"
},
{
"code": null,
"e": 26981,
"s": 26970,
"text": "lengths(x)"
},
{
"code": null,
"e": 26992,
"s": 26981,
"text": "Example 1:"
},
{
"code": null,
"e": 26994,
"s": 26992,
"text": "R"
},
{
"code": "\n\n\n\n\n\n\n# declaring string \nstr1 = \"$geeks%for!geeks%\"\n \n# declaring character to find \nch1 = \"a\"\nprint(\"Count for character a\") \nlengths(regmatches(str1, gregexpr(ch1, str1))) \n \nch2 = \"%\"\nprint(\"Count for character %\") \nlengths(regmatches(str1, gregexpr(ch2, str1))) \n\n\n\n\n\n",
"e": 27281,
"s": 27004,
"text": null
},
{
"code": null,
"e": 27288,
"s": 27281,
"text": "Output"
},
{
"code": null,
"e": 27356,
"s": 27288,
"text": "[1] \"Count for character a\"\n[1] 0\n[1] \"Count for character %\"\n[1] 2"
},
{
"code": null,
"e": 27367,
"s": 27356,
"text": "Example 2:"
},
{
"code": null,
"e": 27369,
"s": 27367,
"text": "R"
},
{
"code": "\n\n\n\n\n\n\n# declaring string \nstr = c(\"$geeks%for!geeks%\",\"cs^e%portal\",\"le%..e3oten\",\"joinnow3\") \nprint (\"Original vector\") \nprint (str) \n \n# declaring character to find \nch2 = \"%\"\nprint(\"Count for character %\") \nlengths(regmatches(str, gregexpr(ch2, str))) \n\n\n\n\n\n",
"e": 27643,
"s": 27379,
"text": null
},
{
"code": null,
"e": 27650,
"s": 27643,
"text": "Output"
},
{
"code": null,
"e": 27775,
"s": 27650,
"text": "[1] \"Original vector\"\n[1] \"$geeks%for!geeks%\" \"cs^e%portal\" \"le%..e3oten\" \"joinnow3\"\n[1] \"Count for character %\"\n[1] 2 1 1 0"
},
{
"code": null,
"e": 27784,
"s": 27775,
"text": "\nPicked\n"
},
{
"code": null,
"e": 27804,
"s": 27784,
"text": "\nR String-Programs\n"
},
{
"code": null,
"e": 27816,
"s": 27804,
"text": "\nR-strings\n"
},
{
"code": null,
"e": 27829,
"s": 27816,
"text": "\nR Language\n"
},
{
"code": null,
"e": 27842,
"s": 27829,
"text": "\nR Programs\n"
},
{
"code": null,
"e": 28047,
"s": 27842,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 28071,
"s": 28047,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 28107,
"s": 28071,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 28159,
"s": 28107,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28191,
"s": 28159,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 28228,
"s": 28191,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 28272,
"s": 28228,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 28321,
"s": 28272,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 28370,
"s": 28321,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28408,
"s": 28370,
"text": "Merge DataFrames by Column Names in R"
}
] |
Enumerate through a Vector using Java Enumeration - GeeksforGeeks
|
07 Jan, 2021
In the Java Enumeration class, all the listed constants are public, static, and final by default. Now after creating a Vector if we want to enumerate through the Vector then at first, we must get an Enumeration of the Vector’s element, and to do, so we use the elements() method. This method is a member function of java.util.Vector<E> class. The elements() method returns a reference to an object which implements java.util.Enumeration class and therefore we are able to use the hasMoreElements() and nextElement() method which helps us to enumerate through a Vector.
Declaration
public Enumeration<Object> elements()
Syntax:
Enumeration enu = Vector.elements()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the values of the Vector.
Method
Returns
Example 1:
Java
// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // String type elements Vector<String> vector = new Vector<>(); // Adding values to the Vector vector.add("Keep"); vector.add("Calm"); vector.add("and"); vector.add("learn"); vector.add("from"); vector.add("GFG"); // Displaying the values of the vector System.out.println("The elements of the Vector is : " + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and // printing each enumeration constant. System.out.println( "The output after Enumerating through the Vector : "); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}
The elements of the Vector is : [Keep, Calm, and, learn, from, GFG]
The output after Enumerating through the Vector :
Keep
Calm
and
learn
from
GFG
Example 2:
Java
// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // double type elements Vector<Double> vector = new Vector<>(); // Adding values to the Vector vector.add(1.2636); vector.add(23.0258); vector.add(266.1125); vector.add(2548.0125); vector.add(2154.02415); vector.add(856.012); // Displaying the values of the vector System.out.println("The elements of the Vector is : " + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and printing // each enumeration constant. System.out.println( "The output after Enumerating through the Vector : "); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}
The elements of the Vector is : [1.2636, 23.0258, 266.1125, 2548.0125, 2154.02415, 856.012]
The output after Enumerating through the Vector :
1.2636
23.0258
266.1125
2548.0125
2154.02415
856.012
Example 3:
Java
// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // elements of different data types Vector<Object> vector = new Vector<>(); // Adding values to the Vector vector.add("Let's"); vector.add("Contribute"); vector.add("to"); vector.add('G'); vector.add('F'); vector.add('G'); vector.add(3); vector.add(12.054574); // Displaying the values of the vector System.out.println("The elements of the Vector is : " + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and printing // each enumeration constant. System.out.println( "The output after Enumerating through the Vector : "); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}
The elements of the Vector is : [Let's, Contribute, to, G, F, G, 3, 12.054574]
The output after Enumerating through the Vector :
Let's
Contribute
to
G
F
G
3
12.054574
Java-Enumeration
Java-Vector
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 24517,
"s": 23948,
"text": "In the Java Enumeration class, all the listed constants are public, static, and final by default. Now after creating a Vector if we want to enumerate through the Vector then at first, we must get an Enumeration of the Vector’s element, and to do, so we use the elements() method. This method is a member function of java.util.Vector<E> class. The elements() method returns a reference to an object which implements java.util.Enumeration class and therefore we are able to use the hasMoreElements() and nextElement() method which helps us to enumerate through a Vector."
},
{
"code": null,
"e": 24529,
"s": 24517,
"text": "Declaration"
},
{
"code": null,
"e": 24567,
"s": 24529,
"text": "public Enumeration<Object> elements()"
},
{
"code": null,
"e": 24575,
"s": 24567,
"text": "Syntax:"
},
{
"code": null,
"e": 24611,
"s": 24575,
"text": "Enumeration enu = Vector.elements()"
},
{
"code": null,
"e": 24664,
"s": 24611,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 24741,
"s": 24664,
"text": "Return value: The method returns an enumeration of the values of the Vector."
},
{
"code": null,
"e": 24748,
"s": 24741,
"text": "Method"
},
{
"code": null,
"e": 24757,
"s": 24748,
"text": "Returns "
},
{
"code": null,
"e": 24768,
"s": 24757,
"text": "Example 1:"
},
{
"code": null,
"e": 24773,
"s": 24768,
"text": "Java"
},
{
"code": "// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // String type elements Vector<String> vector = new Vector<>(); // Adding values to the Vector vector.add(\"Keep\"); vector.add(\"Calm\"); vector.add(\"and\"); vector.add(\"learn\"); vector.add(\"from\"); vector.add(\"GFG\"); // Displaying the values of the vector System.out.println(\"The elements of the Vector is : \" + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and // printing each enumeration constant. System.out.println( \"The output after Enumerating through the Vector : \"); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}",
"e": 25845,
"s": 24773,
"text": null
},
{
"code": null,
"e": 25993,
"s": 25845,
"text": "The elements of the Vector is : [Keep, Calm, and, learn, from, GFG]\nThe output after Enumerating through the Vector : \nKeep\nCalm\nand\nlearn\nfrom\nGFG"
},
{
"code": null,
"e": 26004,
"s": 25993,
"text": "Example 2:"
},
{
"code": null,
"e": 26009,
"s": 26004,
"text": "Java"
},
{
"code": "// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // double type elements Vector<Double> vector = new Vector<>(); // Adding values to the Vector vector.add(1.2636); vector.add(23.0258); vector.add(266.1125); vector.add(2548.0125); vector.add(2154.02415); vector.add(856.012); // Displaying the values of the vector System.out.println(\"The elements of the Vector is : \" + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and printing // each enumeration constant. System.out.println( \"The output after Enumerating through the Vector : \"); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}",
"e": 27094,
"s": 26009,
"text": null
},
{
"code": null,
"e": 27290,
"s": 27094,
"text": "The elements of the Vector is : [1.2636, 23.0258, 266.1125, 2548.0125, 2154.02415, 856.012]\nThe output after Enumerating through the Vector : \n1.2636\n23.0258\n266.1125\n2548.0125\n2154.02415\n856.012"
},
{
"code": null,
"e": 27301,
"s": 27290,
"text": "Example 3:"
},
{
"code": null,
"e": 27306,
"s": 27301,
"text": "Java"
},
{
"code": "// Java program to Enumerate through a Vector import java.util.Enumeration;import java.util.Vector; class GFG { public static void main(String[] args) { // Creating an object of Vector which contains // elements of different data types Vector<Object> vector = new Vector<>(); // Adding values to the Vector vector.add(\"Let's\"); vector.add(\"Contribute\"); vector.add(\"to\"); vector.add('G'); vector.add('F'); vector.add('G'); vector.add(3); vector.add(12.054574); // Displaying the values of the vector System.out.println(\"The elements of the Vector is : \" + vector); // Creating the Enumeration of the Vector elements. Enumeration enumeration = vector.elements(); // Now Enumerating through the Vector and printing // each enumeration constant. System.out.println( \"The output after Enumerating through the Vector : \"); while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement()); } }}",
"e": 28432,
"s": 27306,
"text": null
},
{
"code": null,
"e": 28600,
"s": 28432,
"text": "The elements of the Vector is : [Let's, Contribute, to, G, F, G, 3, 12.054574]\nThe output after Enumerating through the Vector : \nLet's\nContribute\nto\nG\nF\nG\n3\n12.054574"
},
{
"code": null,
"e": 28617,
"s": 28600,
"text": "Java-Enumeration"
},
{
"code": null,
"e": 28629,
"s": 28617,
"text": "Java-Vector"
},
{
"code": null,
"e": 28636,
"s": 28629,
"text": "Picked"
},
{
"code": null,
"e": 28660,
"s": 28636,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28665,
"s": 28660,
"text": "Java"
},
{
"code": null,
"e": 28679,
"s": 28665,
"text": "Java Programs"
},
{
"code": null,
"e": 28698,
"s": 28679,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28703,
"s": 28698,
"text": "Java"
},
{
"code": null,
"e": 28801,
"s": 28703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28816,
"s": 28801,
"text": "Stream In Java"
},
{
"code": null,
"e": 28862,
"s": 28816,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28883,
"s": 28862,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28902,
"s": 28883,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28932,
"s": 28902,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28976,
"s": 28932,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 29002,
"s": 28976,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29036,
"s": 29002,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29083,
"s": 29036,
"text": "Implementing a Linked List in Java using Class"
}
] |
Java - The HashMap Class
|
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.
Following is the list of constructors supported by the HashMap class.
HashMap( )
This constructor constructs a default HashMap.
HashMap(Map m)
This constructor initializes the hash map by using the elements of the given Map object m.
HashMap(int capacity)
This constructor initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float fillRatio)
This constructor initializes both the capacity and fill ratio of the hash map by using its arguments.
Apart from the methods inherited from its parent classes, HashMap defines the following methods −
void clear()
Removes all mappings from this map.
Object clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
Set entrySet()
Returns a collection view of the mappings contained in this map.
Object get(Object key)
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set keySet()
Returns a set view of the keys contained in this map.
Object put(Object key, Object value)
Associates the specified value with the specified key in this map.
putAll(Map m)
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
Object remove(Object key)
Removes the mapping for this key from this map if present.
int size()
Returns the number of key-value mappings in this map.
Collection values()
Returns a collection view of the values contained in this map.
The following program illustrates several of the methods supported by this collection −
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)hm.get("Zara")).doubleValue();
hm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + hm.get("Zara"));
}
}
This will produce the following result −
Daisy: 99.22
Ayan: 1378.0
Zara: 3434.34
Qadir: -19.08
Mahnaz: 123.22
Zara's new balance: 4434.34
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2563,
"s": 2377,
"text": "The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets."
},
{
"code": null,
"e": 2633,
"s": 2563,
"text": "Following is the list of constructors supported by the HashMap class."
},
{
"code": null,
"e": 2644,
"s": 2633,
"text": "HashMap( )"
},
{
"code": null,
"e": 2691,
"s": 2644,
"text": "This constructor constructs a default HashMap."
},
{
"code": null,
"e": 2706,
"s": 2691,
"text": "HashMap(Map m)"
},
{
"code": null,
"e": 2797,
"s": 2706,
"text": "This constructor initializes the hash map by using the elements of the given Map object m."
},
{
"code": null,
"e": 2819,
"s": 2797,
"text": "HashMap(int capacity)"
},
{
"code": null,
"e": 2915,
"s": 2819,
"text": "This constructor initializes the capacity of the hash map to the given integer value, capacity."
},
{
"code": null,
"e": 2954,
"s": 2915,
"text": "HashMap(int capacity, float fillRatio)"
},
{
"code": null,
"e": 3056,
"s": 2954,
"text": "This constructor initializes both the capacity and fill ratio of the hash map by using its arguments."
},
{
"code": null,
"e": 3154,
"s": 3056,
"text": "Apart from the methods inherited from its parent classes, HashMap defines the following methods −"
},
{
"code": null,
"e": 3167,
"s": 3154,
"text": "void clear()"
},
{
"code": null,
"e": 3203,
"s": 3167,
"text": "Removes all mappings from this map."
},
{
"code": null,
"e": 3218,
"s": 3203,
"text": "Object clone()"
},
{
"code": null,
"e": 3314,
"s": 3218,
"text": "Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned."
},
{
"code": null,
"e": 3346,
"s": 3314,
"text": "boolean containsKey(Object key)"
},
{
"code": null,
"e": 3413,
"s": 3346,
"text": "Returns true if this map contains a mapping for the specified key."
},
{
"code": null,
"e": 3449,
"s": 3413,
"text": "boolean containsValue(Object value)"
},
{
"code": null,
"e": 3520,
"s": 3449,
"text": "Returns true if this map maps one or more keys to the specified value."
},
{
"code": null,
"e": 3535,
"s": 3520,
"text": "Set entrySet()"
},
{
"code": null,
"e": 3600,
"s": 3535,
"text": "Returns a collection view of the mappings contained in this map."
},
{
"code": null,
"e": 3623,
"s": 3600,
"text": "Object get(Object key)"
},
{
"code": null,
"e": 3758,
"s": 3623,
"text": "Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key."
},
{
"code": null,
"e": 3776,
"s": 3758,
"text": "boolean isEmpty()"
},
{
"code": null,
"e": 3833,
"s": 3776,
"text": "Returns true if this map contains no key-value mappings."
},
{
"code": null,
"e": 3846,
"s": 3833,
"text": "Set keySet()"
},
{
"code": null,
"e": 3901,
"s": 3846,
"text": " Returns a set view of the keys contained in this map."
},
{
"code": null,
"e": 3938,
"s": 3901,
"text": "Object put(Object key, Object value)"
},
{
"code": null,
"e": 4005,
"s": 3938,
"text": "Associates the specified value with the specified key in this map."
},
{
"code": null,
"e": 4019,
"s": 4005,
"text": "putAll(Map m)"
},
{
"code": null,
"e": 4193,
"s": 4019,
"text": "Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map."
},
{
"code": null,
"e": 4219,
"s": 4193,
"text": "Object remove(Object key)"
},
{
"code": null,
"e": 4278,
"s": 4219,
"text": "Removes the mapping for this key from this map if present."
},
{
"code": null,
"e": 4290,
"s": 4278,
"text": "int \tsize()"
},
{
"code": null,
"e": 4344,
"s": 4290,
"text": "Returns the number of key-value mappings in this map."
},
{
"code": null,
"e": 4364,
"s": 4344,
"text": "Collection values()"
},
{
"code": null,
"e": 4427,
"s": 4364,
"text": "Returns a collection view of the values contained in this map."
},
{
"code": null,
"e": 4515,
"s": 4427,
"text": "The following program illustrates several of the methods supported by this collection −"
},
{
"code": null,
"e": 5534,
"s": 4515,
"text": "import java.util.*;\npublic class HashMapDemo {\n\n public static void main(String args[]) {\n \n // Create a hash map\n HashMap hm = new HashMap();\n \n // Put elements to the map\n hm.put(\"Zara\", new Double(3434.34));\n hm.put(\"Mahnaz\", new Double(123.22));\n hm.put(\"Ayan\", new Double(1378.00));\n hm.put(\"Daisy\", new Double(99.22));\n hm.put(\"Qadir\", new Double(-19.08));\n \n // Get a set of the entries\n Set set = hm.entrySet();\n \n // Get an iterator\n Iterator i = set.iterator();\n \n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n \n // Deposit 1000 into Zara's account\n double balance = ((Double)hm.get(\"Zara\")).doubleValue();\n hm.put(\"Zara\", new Double(balance + 1000));\n System.out.println(\"Zara's new balance: \" + hm.get(\"Zara\"));\n }\n}"
},
{
"code": null,
"e": 5575,
"s": 5534,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5674,
"s": 5575,
"text": "Daisy: 99.22\nAyan: 1378.0\nZara: 3434.34\nQadir: -19.08\nMahnaz: 123.22\n\nZara's new balance: 4434.34\n"
},
{
"code": null,
"e": 5707,
"s": 5674,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5723,
"s": 5707,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5756,
"s": 5723,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5772,
"s": 5756,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5807,
"s": 5772,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5821,
"s": 5807,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5855,
"s": 5821,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5869,
"s": 5855,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5906,
"s": 5869,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5921,
"s": 5906,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5954,
"s": 5921,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5973,
"s": 5954,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5980,
"s": 5973,
"text": " Print"
},
{
"code": null,
"e": 5991,
"s": 5980,
"text": " Add Notes"
}
] |
How to change display mode with Java Swings
|
To change display mode with Java Swings, use the setDisplayMode() method. Here, we have set the Display mode as:
new DisplayMode(800, 600, 32, 60));
Now, when you will run the program, the frame would be visible in a different resolution than the actual set resolution of your system.
The following is an example to change display mode with Java Swings:
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDevice graphics = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice();
graphics.setFullScreenWindow(frame);
graphics.setDisplayMode(new DisplayMode(800, 600, 32, 60));
frame.setVisible(true);
}
}
The output is as follows displaying a new display mode. Current mode of the system is 1366x768 and we have set 800x600 for the frame:
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To change display mode with Java Swings, use the setDisplayMode() method. Here, we have set the Display mode as:"
},
{
"code": null,
"e": 1211,
"s": 1175,
"text": "new DisplayMode(800, 600, 32, 60));"
},
{
"code": null,
"e": 1347,
"s": 1211,
"text": "Now, when you will run the program, the frame would be visible in a different resolution than the actual set resolution of your system."
},
{
"code": null,
"e": 1416,
"s": 1347,
"text": "The following is an example to change display mode with Java Swings:"
},
{
"code": null,
"e": 2000,
"s": 1416,
"text": "import java.awt.DisplayMode;\nimport java.awt.GraphicsDevice;\nimport java.awt.GraphicsEnvironment;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setSize(800, 600);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n GraphicsDevice graphics = GraphicsEnvironment.getLocalGraphicsEnvironment()\n .getDefaultScreenDevice();\n graphics.setFullScreenWindow(frame);\n graphics.setDisplayMode(new DisplayMode(800, 600, 32, 60));\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2134,
"s": 2000,
"text": "The output is as follows displaying a new display mode. Current mode of the system is 1366x768 and we have set 800x600 for the frame:"
}
] |
\vphantom - Tex Command
|
\vphantom - vertical phantom.
{ \vphantom #1 }
The box created by \vphantom has the height and depth of its argument, but its width is zero (so it doesn't contribute to any horizontal spacing issues). In other words, \hphantom creates vertical space equal to that produced by its argument, but doesn't create any horizontal space.
\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c
(abc)(ab?c)
\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c
(abc)(ab?c)
\binom{\frac ab}c \binom{\vphantom{\frac ab}?}c
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": 8016,
"s": 7986,
"text": "\\vphantom - vertical phantom."
},
{
"code": null,
"e": 8033,
"s": 8016,
"text": "{ \\vphantom #1 }"
},
{
"code": null,
"e": 8318,
"s": 8033,
"text": "The box created by \\vphantom has the height and depth of its argument, but its width is zero (so it doesn't contribute to any horizontal spacing issues). In other words, \\hphantom creates vertical space equal to that produced by its argument, but doesn't create any horizontal space."
},
{
"code": null,
"e": 8383,
"s": 8318,
"text": "\n\\binom{\\frac ab}c \\binom{\\vphantom{\\frac ab}?}c\n\n(abc)(ab?c)\n\n\n"
},
{
"code": null,
"e": 8446,
"s": 8383,
"text": "\\binom{\\frac ab}c \\binom{\\vphantom{\\frac ab}?}c\n\n(abc)(ab?c)\n\n"
},
{
"code": null,
"e": 8494,
"s": 8446,
"text": "\\binom{\\frac ab}c \\binom{\\vphantom{\\frac ab}?}c"
},
{
"code": null,
"e": 8526,
"s": 8494,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8539,
"s": 8526,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8572,
"s": 8539,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8585,
"s": 8572,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8617,
"s": 8585,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8653,
"s": 8617,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8688,
"s": 8653,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8705,
"s": 8688,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8738,
"s": 8705,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8752,
"s": 8738,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8784,
"s": 8752,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8799,
"s": 8784,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8806,
"s": 8799,
"text": " Print"
},
{
"code": null,
"e": 8817,
"s": 8806,
"text": " Add Notes"
}
] |
iOS - Table View
|
It is used for displaying a vertically scrollable view which consists of a number of cells (generally reusable cells). It has special features like headers, footers, rows, and section.
delegate
dataSource
rowHeight
sectionFooterHeight
sectionHeaderHeight
separatorColor
tableHeaderView
tableFooterView
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
forIndexPath:(NSIndexPath *)indexPath
- (void)reloadData
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation
- (NSArray *)visibleCells
Step 1 − Let's add a tableview in ViewController.xib as shown below.
Step 2 − Set delegate and dataSource to file owner for tableview by right-clicking and selecting datasource and delegate. Setting dataSource is shown below.
Step 3 − Create an IBOutlet for tableView and name it as myTableView. It is shown in the following images.
Step 4 − Then add an NSMutableArray for holding the data to be displayed in the table view.
Step 5 − Our ViewController should adopt the UITableViewDataSource and UITableViewDelegate protocols. The ViewController.h should look as shown below.
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDataSource,
UITableViewDelegate> {
IBOutlet UITableView *myTableView;
NSMutableArray *myData;
}
@end
Step 6 − We should implement the required tableview delegate and dataSource methods. The updated ViewController.m is as follows −
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// table view data is being set here
myData = [[NSMutableArray alloc]initWithObjects:
@"Data 1 in array",@"Data 2 in array",@"Data 3 in array",
@"Data 4 in array",@"Data 5 in array",@"Data 5 in array",
@"Data 6 in array",@"Data 7 in array",@"Data 8 in array",
@"Data 9 in array", nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table View Data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
return [myData count]/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
NSString *stringForCell;
if (indexPath.section == 0) {
stringForCell= [myData objectAtIndex:indexPath.row];
} else if (indexPath.section == 1) {
stringForCell= [myData objectAtIndex:indexPath.row+ [myData count]/2];
}
[cell.textLabel setText:stringForCell];
return cell;
}
// Default is 1 if not implemented
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section {
NSString *headerTitle;
if (section==0) {
headerTitle = @"Section 1 Header";
} else {
headerTitle = @"Section 2 Header";
}
return headerTitle;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:
(NSInteger)section {
NSString *footerTitle;
if (section==0) {
footerTitle = @"Section 1 Footer";
} else {
footerTitle = @"Section 2 Footer";
}
return footerTitle;
}
#pragma mark - TableView delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Section:%d Row:%d selected and its data is %@",
indexPath.section,indexPath.row,cell.textLabel.text);
}
@end
Step 7 − When we run the application we'll get the following output −
23 Lectures
1.5 hours
Ashish Sharma
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
69 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2276,
"s": 2091,
"text": "It is used for displaying a vertically scrollable view which consists of a number of cells (generally reusable cells). It has special features like headers, footers, rows, and section."
},
{
"code": null,
"e": 2285,
"s": 2276,
"text": "delegate"
},
{
"code": null,
"e": 2296,
"s": 2285,
"text": "dataSource"
},
{
"code": null,
"e": 2306,
"s": 2296,
"text": "rowHeight"
},
{
"code": null,
"e": 2326,
"s": 2306,
"text": "sectionFooterHeight"
},
{
"code": null,
"e": 2346,
"s": 2326,
"text": "sectionHeaderHeight"
},
{
"code": null,
"e": 2361,
"s": 2346,
"text": "separatorColor"
},
{
"code": null,
"e": 2377,
"s": 2361,
"text": "tableHeaderView"
},
{
"code": null,
"e": 2393,
"s": 2377,
"text": "tableFooterView"
},
{
"code": null,
"e": 2880,
"s": 2393,
"text": "- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath\n- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths\nwithRowAnimation:(UITableViewRowAnimation)animation\n- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier\n- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier\nforIndexPath:(NSIndexPath *)indexPath\n- (void)reloadData\n- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths\nwithRowAnimation:(UITableViewRowAnimation)animation\n- (NSArray *)visibleCells"
},
{
"code": null,
"e": 2949,
"s": 2880,
"text": "Step 1 − Let's add a tableview in ViewController.xib as shown below."
},
{
"code": null,
"e": 3106,
"s": 2949,
"text": "Step 2 − Set delegate and dataSource to file owner for tableview by right-clicking and selecting datasource and delegate. Setting dataSource is shown below."
},
{
"code": null,
"e": 3213,
"s": 3106,
"text": "Step 3 − Create an IBOutlet for tableView and name it as myTableView. It is shown in the following images."
},
{
"code": null,
"e": 3306,
"s": 3213,
"text": "Step 4 − Then add an NSMutableArray for holding the data to be displayed in the table view. "
},
{
"code": null,
"e": 3457,
"s": 3306,
"text": "Step 5 − Our ViewController should adopt the UITableViewDataSource and UITableViewDelegate protocols. The ViewController.h should look as shown below."
},
{
"code": null,
"e": 3648,
"s": 3457,
"text": "#import <UIKit/UIKit.h>\n\n@interface ViewController : UIViewController<UITableViewDataSource,\n UITableViewDelegate> {\n IBOutlet UITableView *myTableView;\n NSMutableArray *myData;\n}\n@end"
},
{
"code": null,
"e": 3778,
"s": 3648,
"text": "Step 6 − We should implement the required tableview delegate and dataSource methods. The updated ViewController.m is as follows −"
},
{
"code": null,
"e": 6372,
"s": 3778,
"text": "#import \"ViewController.h\"\n\n@interface ViewController ()\n\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n // table view data is being set here\t\n myData = [[NSMutableArray alloc]initWithObjects:\n @\"Data 1 in array\",@\"Data 2 in array\",@\"Data 3 in array\",\n @\"Data 4 in array\",@\"Data 5 in array\",@\"Data 5 in array\",\n @\"Data 6 in array\",@\"Data 7 in array\",@\"Data 8 in array\",\n @\"Data 9 in array\", nil];\n // Do any additional setup after loading the view, typically from a nib.\n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n\n#pragma mark - Table View Data source \n- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:\n (NSInteger)section {\n return [myData count]/2;\n}\n\n- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:\n (NSIndexPath *)indexPath {\n static NSString *cellIdentifier = @\"cellID\";\n \n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:\n cellIdentifier];\n \n if (cell == nil) {\n cell = [[UITableViewCell alloc]initWithStyle:\n UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];\n }\n \n NSString *stringForCell;\n \n if (indexPath.section == 0) {\n stringForCell= [myData objectAtIndex:indexPath.row];\n } else if (indexPath.section == 1) {\n stringForCell= [myData objectAtIndex:indexPath.row+ [myData count]/2];\n }\n [cell.textLabel setText:stringForCell];\n return cell;\n}\n\n// Default is 1 if not implemented\n- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {\n return 2;\n}\n\n- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:\n (NSInteger)section {\n NSString *headerTitle;\n \n if (section==0) {\n headerTitle = @\"Section 1 Header\";\n } else {\n headerTitle = @\"Section 2 Header\";\n }\n return headerTitle;\n}\n\n- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:\n (NSInteger)section {\n NSString *footerTitle;\n \n if (section==0) {\n footerTitle = @\"Section 1 Footer\";\n } else {\n footerTitle = @\"Section 2 Footer\";\n }\n return footerTitle;\n}\n\n#pragma mark - TableView delegate\n\n-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:\n (NSIndexPath *)indexPath {\n [tableView deselectRowAtIndexPath:indexPath animated:YES];\n UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];\n NSLog(@\"Section:%d Row:%d selected and its data is %@\",\n indexPath.section,indexPath.row,cell.textLabel.text);\n}\n@end"
},
{
"code": null,
"e": 6442,
"s": 6372,
"text": "Step 7 − When we run the application we'll get the following output −"
},
{
"code": null,
"e": 6477,
"s": 6442,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6492,
"s": 6477,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 6524,
"s": 6492,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6541,
"s": 6524,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6576,
"s": 6541,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6593,
"s": 6576,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6628,
"s": 6593,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6645,
"s": 6628,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6678,
"s": 6645,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6695,
"s": 6678,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6728,
"s": 6695,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6745,
"s": 6728,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6752,
"s": 6745,
"text": " Print"
},
{
"code": null,
"e": 6763,
"s": 6752,
"text": " Add Notes"
}
] |
How to add command line arguments in Python?
|
Python has a very powerful argparse module which provides functions for parsing command line arguments. If we want to get the user input from the OS command line without a lot of interaction or code a program that accepts parameters from the command line e.g. Provide a URL to parse or accepts the file to upload to a S3 bucket then argparse can be used with minimal effort.
Define the arguments that your code is going to accept.
Define the arguments that your code is going to accept.
Call the argument parser to return the results object.
Call the argument parser to return the results object.
Use the arguments.
Use the arguments.
In short, the structure of argument parser looks some thing like below.
def main( parameters):
<< Logic here >>
if __name__ == '__main__':
<< 1. Define argument parser >>
<< 2. Parse the arguements >>
<< 3. Validation >>
<< 4. call main (parameters) >>
The main function knows what the entry point of our code is. The __name__ == '__main__' section is executed only if the code is called directly.
Create a program which will accept only one argument - tennis players as string.
Create a program which will accept only one argument - tennis players as string.
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.
2. type - The actual Python data type
- (note the lack of quotes around str)
3. help - A brief description of the parameter for the usage
"""
parser = argparse.ArgumentParser(
description='Example for Two positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Adding our first argument player name of type string
parser.add_argument('player',
metavar='player',
type=str,
help='Tennis Player')
return parser.parse_args()
# define main
def main(player):
print(f" *** The {player} had won 20 grandslam titles.")
if __name__ == '__main__':
args = get_args()
main(args.player)
a) Now when you execute this program from the command line without passing any parameters i.e. If given nothing, it will print a brief usage statement about the proper way to invoke the program.
In [3]: run <>.ipynb
usage: ipython [-h] player
ipython: error: the following arguments are required: player
An exception has occurred, use %tb to see the full traceback.
b) If we provide more than one argument, it complains again.The program complains about getting a second argument that has not been defined.
c) Only when we give the program exactly one argument will it run
2.
Create a program which will accept only two arguments - tennis players as string and grand slamt titles won by the player as integer.
import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.
2. type - The actual Python data type
- (note the lack of quotes around str)
3. help - A brief description of the parameter for the usage
"""
parser = argparse.ArgumentParser(
description='Example for Two positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Adding our first argument player name of type string
parser.add_argument('player',
metavar='player',
type=str,
help='Tennis Player')
# Adding our second argument player titles of type integer/number.
parser.add_argument('titles',
metavar='titles',
type=int,
help='Tennis Player Grandslam Titles')
return parser.parse_args()
# define main
def main(player, titles):
print(f" *** The {player} had won {titles} grandslam titles.")
if __name__ == '__main__':
args = get_args()
main(args.player, args.titles)
Now open your terminal and execute the program. If the arguments are not passed, the script throw back error with clear message.
<<< python test.py
usage: test.py [-h] player titles
test.py: error: the following arguments are required: player, titles
<<< python test.py federer 20
*** The federer had won 20 grandslam titles.
|
[
{
"code": null,
"e": 1437,
"s": 1062,
"text": "Python has a very powerful argparse module which provides functions for parsing command line arguments. If we want to get the user input from the OS command line without a lot of interaction or code a program that accepts parameters from the command line e.g. Provide a URL to parse or accepts the file to upload to a S3 bucket then argparse can be used with minimal effort."
},
{
"code": null,
"e": 1493,
"s": 1437,
"text": "Define the arguments that your code is going to accept."
},
{
"code": null,
"e": 1549,
"s": 1493,
"text": "Define the arguments that your code is going to accept."
},
{
"code": null,
"e": 1604,
"s": 1549,
"text": "Call the argument parser to return the results object."
},
{
"code": null,
"e": 1659,
"s": 1604,
"text": "Call the argument parser to return the results object."
},
{
"code": null,
"e": 1678,
"s": 1659,
"text": "Use the arguments."
},
{
"code": null,
"e": 1697,
"s": 1678,
"text": "Use the arguments."
},
{
"code": null,
"e": 1769,
"s": 1697,
"text": "In short, the structure of argument parser looks some thing like below."
},
{
"code": null,
"e": 1951,
"s": 1769,
"text": "def main( parameters):\n<< Logic here >>\n\nif __name__ == '__main__':\n<< 1. Define argument parser >>\n<< 2. Parse the arguements >>\n<< 3. Validation >>\n<< 4. call main (parameters) >>"
},
{
"code": null,
"e": 2096,
"s": 1951,
"text": "The main function knows what the entry point of our code is. The __name__ == '__main__' section is executed only if the code is called directly."
},
{
"code": null,
"e": 2177,
"s": 2096,
"text": "Create a program which will accept only one argument - tennis players as string."
},
{
"code": null,
"e": 2258,
"s": 2177,
"text": "Create a program which will accept only one argument - tennis players as string."
},
{
"code": null,
"e": 3056,
"s": 2258,
"text": "import argparse\n\ndef get_args():\n\"\"\" Function : get_args\nparameters used in .add_argument\n1. metavar - Provide a hint to the user about the data type.\n- By default, all arguments are strings.\n\n2. type - The actual Python data type\n- (note the lack of quotes around str)\n\n3. help - A brief description of the parameter for the usage\n\n\"\"\"\n\nparser = argparse.ArgumentParser(\ndescription='Example for Two positional arguments',\nformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Adding our first argument player name of type string\nparser.add_argument('player',\nmetavar='player',\ntype=str,\nhelp='Tennis Player')\n\nreturn parser.parse_args()\n\n# define main\ndef main(player):\nprint(f\" *** The {player} had won 20 grandslam titles.\")\n\nif __name__ == '__main__':\nargs = get_args()\nmain(args.player)"
},
{
"code": null,
"e": 3251,
"s": 3056,
"text": "a) Now when you execute this program from the command line without passing any parameters i.e. If given nothing, it will print a brief usage statement about the proper way to invoke the program."
},
{
"code": null,
"e": 3422,
"s": 3251,
"text": "In [3]: run <>.ipynb\nusage: ipython [-h] player\nipython: error: the following arguments are required: player\nAn exception has occurred, use %tb to see the full traceback."
},
{
"code": null,
"e": 3563,
"s": 3422,
"text": "b) If we provide more than one argument, it complains again.The program complains about getting a second argument that has not been defined."
},
{
"code": null,
"e": 3629,
"s": 3563,
"text": "c) Only when we give the program exactly one argument will it run"
},
{
"code": null,
"e": 3766,
"s": 3629,
"text": "2.\nCreate a program which will accept only two arguments - tennis players as string and grand slamt titles won by the player as integer."
},
{
"code": null,
"e": 4758,
"s": 3766,
"text": "import argparse\n\ndef get_args():\n\"\"\" Function : get_args\nparameters used in .add_argument\n1. metavar - Provide a hint to the user about the data type.\n- By default, all arguments are strings.\n\n2. type - The actual Python data type\n- (note the lack of quotes around str)\n\n3. help - A brief description of the parameter for the usage\n\n\"\"\"\n\nparser = argparse.ArgumentParser(\ndescription='Example for Two positional arguments',\nformatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n# Adding our first argument player name of type string\nparser.add_argument('player',\nmetavar='player',\ntype=str,\nhelp='Tennis Player')\n\n# Adding our second argument player titles of type integer/number.\nparser.add_argument('titles',\nmetavar='titles',\ntype=int,\nhelp='Tennis Player Grandslam Titles')\n\nreturn parser.parse_args()\n\n# define main\ndef main(player, titles):\nprint(f\" *** The {player} had won {titles} grandslam titles.\")\n\nif __name__ == '__main__':\nargs = get_args()\nmain(args.player, args.titles)\n\n"
},
{
"code": null,
"e": 4887,
"s": 4758,
"text": "Now open your terminal and execute the program. If the arguments are not passed, the script throw back error with clear message."
},
{
"code": null,
"e": 5085,
"s": 4887,
"text": "<<< python test.py\nusage: test.py [-h] player titles\ntest.py: error: the following arguments are required: player, titles\n\n<<< python test.py federer 20\n*** The federer had won 20 grandslam titles."
}
] |
C++ List Library - sort() Function
|
The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison.
Following is the declaration for std::list::sort() function form std::list header.
void sort();
None
None
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::list::sort() function.
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l = {1, 4, 2, 5, 3};
cout << "Contents of list before sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
l.sort();
cout << "Contents of list after sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Contents of list before sort operation
1
4
2
5
3
Contents of list after sort operation
1
2
3
4
5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2765,
"s": 2603,
"text": "The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison."
},
{
"code": null,
"e": 2848,
"s": 2765,
"text": "Following is the declaration for std::list::sort() function form std::list header."
},
{
"code": null,
"e": 2862,
"s": 2848,
"text": "void sort();\n"
},
{
"code": null,
"e": 2867,
"s": 2862,
"text": "None"
},
{
"code": null,
"e": 2872,
"s": 2867,
"text": "None"
},
{
"code": null,
"e": 2917,
"s": 2872,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 2934,
"s": 2917,
"text": "Linear i.e. O(n)"
},
{
"code": null,
"e": 3003,
"s": 2934,
"text": "The following example shows the usage of std::list::sort() function."
},
{
"code": null,
"e": 3422,
"s": 3003,
"text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l = {1, 4, 2, 5, 3};\n\n cout << \"Contents of list before sort operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n l.sort();\n\n cout << \"Contents of list after sort operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3505,
"s": 3422,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3603,
"s": 3505,
"text": "Contents of list before sort operation\n1\n4\n2\n5\n3\nContents of list after sort operation\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3610,
"s": 3603,
"text": " Print"
},
{
"code": null,
"e": 3621,
"s": 3610,
"text": " Add Notes"
}
] |
How to create file of particular size in Python?
|
To create a file of a particular size, just seek to the byte number(size) you want to create the file of and write a byte there.
with open('my_file', 'wb') as f:
f.seek(1024 * 1024 * 1024) # One GB
f.write('0')
This creates a sparse file by not actually taking up all that space. To create a full file, you should write the whole file:
with open('my_file', 'wb') as f:
num_chars = 1024 * 1024 * 1024
f.write('0' * num_chars)
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "To create a file of a particular size, just seek to the byte number(size) you want to create the file of and write a byte there."
},
{
"code": null,
"e": 1281,
"s": 1191,
"text": "with open('my_file', 'wb') as f:\n f.seek(1024 * 1024 * 1024) # One GB\n f.write('0')"
},
{
"code": null,
"e": 1406,
"s": 1281,
"text": "This creates a sparse file by not actually taking up all that space. To create a full file, you should write the whole file:"
},
{
"code": null,
"e": 1503,
"s": 1406,
"text": "with open('my_file', 'wb') as f:\n num_chars = 1024 * 1024 * 1024\n f.write('0' * num_chars)"
}
] |
Build a Machine Learning Model to a Practical Use-Case From Scratch | by Yasas Sandeepa | Towards Data Science
|
Machine Learning is an enormous area. It is empowering technology for allowing us to develop software solutions much faster than before and currently the state-of-the-art solution for a wide range of problems. We can apply it to almost every domain. In this article, we are going to study in-depth how the process for developing a machine learning model to a practical use case.
In the article, we will be discussing :
Problem Definition and Data gathering
Data Preprocessing
Data Transformation
Feature Encoding
Scaling and Standardization
Feature Engineering
Dimension reduction with Principal Component Analysis
Regression
Accuracy measures and Evaluation techniques
Assumption:- I believe you have prior knowledge in python programming as well as basic libraries related to machine learning.
Use-Case:- Is there a relationship between humidity and temperature? What about between humidity and apparent temperature? Can you predict the apparent temperature given the humidity?
As the first thing, we have to understand the problem, the environment that problem lies in, and gather the domain knowledge regarding the scenario.
The problem mainly asks to predict the apparent temperature given the humidity. What is this apparent temperature?
Apparent temperature is the temperature equivalent perceived by humans, caused by the combined effects of air temperature, relative humidity and wind speed. -Wikipedia
This reveals one important factor. Not only humidity, but air temperature and wind speed are also affecting the apparent temperature. So for a given scenario, we need to find out what are the direct as well as indirect(hidden) facts that going to affect our problem.
A good example of this is the banking sector. Imagine you need to identify a customer whether he is eligible to receive a loan or not. (performer or non-performer) You cannot just predict it by only looking at the previous bank transactions. You need to analyze, what is the domain he working on, if he is a cooperate customer what are the other industries that producing profit to him (Although he fails in one domain, he may rise in another domain), whether he has any political supports, such as a broad area (indirect) you may need to cover in order to provide a good prediction. So keeping that in mind, let’s go to our problem.
Then we need a data set to tackle this problem. Kaggle website provides a massive collection of data resources for anyone and we easily can find a data set from there. Most importantly, on Kaggle you can learn from others in a variety of problem contexts. I will be using the Kaggle — Weather History Data set to analyze this problem.
www.kaggle.com
Note: All the coding was done in a Google Colab python notebook and you can find it under the resources section.
As a data scientist, you need to have a clear idea of your data set and the complexity of data. Let’s first visualize the data, just to get some insight.
The below code snippet will load the weather data CSV file into a pandas data frame and display the first 5 rows.
weatherDataframe = pd.read_csv(‘weatherHistory.csv’);weatherDataframe.head();
You can analyze the data set furthermore by weatherDataframe.info() method and then you will see there are 96453 entries with 12 columns.
We can identify our target column as the apparent temperature and the rest of the columns as the features.
Preprocessing is the most important part of machine learning. The success of our model highly depends on the quality of the data fed into the machine learning model. Real-world data is usually dirty. It contains duplicates missing values outliers, irrelevant features, non-standardized data..etc. So we need to clean the data set in a proper way. Let’s see step by step, how we going to achieve it.
First, we need to find any unique fields in the data set. If found any, we should drop them because they are not useful when recognizing patterns. If a data set contains columns with very few unique values, that will provide a good basis for data cleaning. Also, if the columns have so many unique values, such as ID number, email (unique for every data point), we should remove them.
# summarize the number of unique values in each columnprint(weatherDataframe.nunique())
As you can see in the results, the Loud cover column only has a single value (0). So we can drop that column entirely. Also, we need to analyze what are the unique values row-wise. To analyze that, we can calculate the number of unique values for each variable as a percentage of the total number of rows in the data set. This is a custom function made for that.
Formatted date giving 100% unique ratio to the total data frame. So we can drop that column. Also by looking at the data set we can conclude that the Daily summary and Summary columns have a great similarity. So we can remove one of them. So I’ll keep the Summary.
The next thing that, there may be duplicate rows. So we need to identify rows that contain duplicate data and delete them.
There is one important thing to remember. When we removing rows, this will cause the indexes are to be different. As an example, if you remove row 18 from the data frame, now the indexes will be ..16,17,19,20.. like this. This will ultimately create a difference between the actual row count and the last index. In order to avoid this, we need to reset indexes. Then it will correct the order.
There can be a number of missing values in the data set. Mainly, there are two things that we can do for missing values, it’s either drop or do imputation to replace them. Imputation is replacing missing values with mean or median values. But the problem with this imputation is, it can lead to causing a bias in the data set. So it is advised to manipulate the imputation carefully.
If the number of cases of missing values is extremely small, the best option is to drop them. (If the number of the cases is less than 5% of the sample, you are safer to drop them)
# Check for any missing valuesweatherDataframe.isnull().values.any()# This gives - True#Getting the summary of what are missing value columnsweatherDataframe.isnull().sum()
As you can see, there are 517 missing values in the Precip type column. So, let’s examine the overall probability to find whether we can drop those columns.
weatherDataframe['Precip Type'].isna().sum()/(len(weatherDataframe))*100
This returns the result as 0.536 and it’s a very low percentage compared to the total data set. So we can drop them. It will ensure no bias or variance is added or removed, and ultimately results in a robust and accurate model.
# make copy to avoid changing original datanew_weatherDf = weatherDataframe.copy()# removing missing valuesnew_weatherDf=new_weatherDf.dropna(axis=0)# Resetting Indexesnew_weatherDf=new_weatherDf.reset_index(drop=True)
An outlier is a data point (or can be a small number of data points) that is significantly stay away from the mainstream.
But if you are seeing many points are staying away from the mainstream, they are not considered as outliers and they could be some kind of cluster pattern or something related to an anomaly. In such cases, we need to treat them separately.
There are numerous methods to discover outliers.
Box Plots —glancing at the variability outside the upper and lower quartiles
Scatter Plots — using Cartesian coordinates of two data columns
Z- Score — using a mathematical function
I’ll use the Box Plot method for detecting them visually.
You can see there are some outliers exists in the data set. So we should examine them one by one to treat them separately. The best option is to remove them. You can apply mean and median values considering the data distribution. But there is a high risk of making the data set bias. So if you want to do that, handle it very precisely.
I’ll demonstrate removing outliers in one column. You can see the rest of the things in my python notebook. As you have seen in the plot, there is an outlier in the pressure column. It’s a pressure and it would not become zero under normal conditions. This may due to an error in data entry or a problem with the collected equipment. So we should remove them.
There is one thing we need to keep in mind before doing transformations. That is data Leakage. We need to keep a test data set in order to estimate our model. But if we do the below transformation steps to all the data in the data set and then split it out (as training and testing set), we have committed the sin of data leakage.
Don’t forget that testing data points represent real-world data. So the model should not see that data. If so, the consequence will be over-fitting your training data and having an overly optimistic evaluation of your model’s performance on unseen data.
In order to avoid that, we should split our data set into train and test sets now and do the transformation steps. This will ensure no peeking ahead. Otherwise, information from the test set will “leak” into your training data.
First, we need to define our features and the target (what we going to predict.) The use case tells us to predict the Apparent Temperature. So it will be our target. The rest of the columns we can take as features.
features_df= new_weatherDf.drop('Apparent Temperature (C)', 1)target = pd.DataFrame(new_weatherDf['Apparent Temperature (C)'], columns=["Apparent Temperature (C)"])
Now we can split them out as training and test tests to 80% — 20% ratio. random_state ensures that the splits that you generate are reproducible. It always splits in the same random order and will not change for every run.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(features_df, target, test_size = 0.2, random_state = 101)
Also, keep in mind to reset the indexes as it may lead to confusion in the latter parts.
X_train=X_train.reset_index(drop=True)X_test=X_test.reset_index(drop=True)y_train=y_train.reset_index(drop=True)y_test=y_test.reset_index(drop=True)
Okay. We are all set for transformations!
The data that you have cleaned previously, may not be in the right format or right scale and it will be difficult to understand for the model. Therefore we need to do data transformations.
Skewness is the asymmetry in a set of data that deviates from a normal distribution. It also can define as a distortion of the symmetrical bell curve. If the curve is shifted to the left (tail in the right), it is right-skewed and if the curve shifted to the right (tail in the left), it is left-skewed. We should apply proper transformations in order to bring it to a symmetrical shape. This will lead to increase the accuracy of our model.
As per the image shown above, we need to apply Log-transformation to the right-skewed data and Exponential-transformation to the left-skewed data in order to bring the data set to symmetrical.
But how we detect the skewness? For that, we have Q-Q plots (quantile-quantile plots) and histograms. Let’s analyze with our dataset.
import scipy.stats as stats# Temperature (C). - Trainingstats.probplot(X_train["Temperature (C)"], dist="norm", plot=plt);plt.show();X_train["Temperature (C)"].hist();
As you can see in the Q-Q plot, most of the data lie in the red line. Also, the histogram is not showing any skewness and it’s symmetric. So we don’t need to transform this column.
If you analyze the Humidity column, you will notice a left-skewed distribution in there. So we need to apply Exponential transformation to make it symmetrical.
# create columns variables to hold the columns that need transformationcolumns = ['Humidity']# create the function transformer object with exponential transformationexp_transformer = FunctionTransformer(lambda x:x**3, validate=True)# apply the transformation data_new = exp_transformer.transform(X_train[columns])df_new = pd.DataFrame(data_new, columns=columns)# replace new values with previous data frameX_train.Humidity=df_new['Humidity']
Now you will see a nice symmetric distribution. So likewise we can do the transformation to all the necessary columns. I’ll show one another important transformation. All the transformations are explained in my python notebook. Refer it for more clarifications.
If you analyze the wind speed column, you would see a right-skewed distribution. To bring it symmetrical we need to apply log transformation. But here is a special case that there are 0 value data points can see in the column. If we apply log transformation, that 0 value data points will be replaced with minus infinity. To avoid that, we can apply log(x+1) transformation.
# create columns variables to hold the columns that need transformationcolumns = ['Wind Speed (km/h)']# create the function transformer object with logarithm transformationlogarithm_transformer = FunctionTransformer(np.log1p, validate=True)# apply the transformation data_new = logarithm_transformer.transform(X_train[columns])df_new = pd.DataFrame(data_new, columns=columns)# replace new values with previous data frameX_train['Wind Speed (km/h)']=df_new['Wind Speed (km/h)']
There are categorical (text) and numeric data in our dataset. But most of the models only accept numeric data. So we need to convert those categorical data, or text data columns into numbers. To do this, we can use two encoders.
Label EncoderOne Hot Encoder (OHE)
Label Encoder
One Hot Encoder (OHE)
Note — Some algorithms can work with categorical data directly like Decision Trees. But most of them cannot operate on label data directly.
Label Encoder encodes the classes with a value between 0 and n-1 where n is the number of distinct classes(labels). If a class replicates, it will assign the same value as assigned earlier.
Let’s take a simple example for clarifying things. There is a column with having different countries. If we apply a label encoder to that, it will provide the below output.
It will assign a unique value from 0 to n classes. As you can see here, label encoding uses alphabetical ordering. Hence, Brazil has been encoded with 0, India with 1, and Italy with 2. If the same class appears in a different row, it will assign the same value as assigned earlier.
But the problem in the label encoding is, it can lead to find relationships between the encoded values. As an example, if the countries have marked 1,2,3,4.. categories, the model can create a pattern like the label 2 country is more powerful than the label 1 country and label 3 country is more powerful than the both 1 and 2 like that. But actually, there is no relation, of any kind, between the countries.
So by label encoding, it will confuse the model into thinking that a column has data with some kind of order or hierarchy. To overcome this problem, we use One hot encoding.
One Hot Encoding takes a column that has categorical data and then splits the column into multiple columns. The classes are replaced by binaries (1s and 0s), depending on which column has a particular class.
Look at the below example. First, it will create separate columns for every class, and then it will assign a binary value of 1 for the presented class and 0 for others as row-wise. E.g: The first row represents Sri Lanka. So value 1 only applied for the Sri Lankan column and the rest of the columns in the first row will get a value of 0.
This will not generate a pattern among classes because the result is binary rather than ordinal and that everything sits in an orthogonal vector space. But it can lead to a massive number of columns and ultimately lead to a curse of dimensionality. But if we apply a Dimensional reduction technique like PCA, it will resolve the problem. Also, It’s advised to use the OHE over Label Encoder.
In our data set, now we have 2 categorical columns, Precip Type and Summary. So we can apply encoding to both columns.
We are dealing with a training and a testing set. So we need to keep in mind one important thing. When you are training a model, you will use the training data set. For a trained model, we need to input the same scale of data we used in training. So how do we get that previous scale? Here comes the interesting part. To carter that issue, there are two methods in most libraries. That is fit() and transform()
You need to first apply fit() method on your training data set to only calculate the scale and keep it internally as an object. Then you can call transform() method to apply the transformation for both training and testing datasets. That will ensure the data is transformed on the same scale.
I applied one-hot encoding for the summary column. For the precip type column, we can apply categorical coding (similar to label encoding) as there are only two classes.
X_train['Precip Type']=X_train['Precip Type'].astype('category')X_train['Precip Type']=X_train['Precip Type'].cat.codes
Our final training data frame will look as follows.
We use Standardization to center the data (make it have zero mean and unit standard deviation). What actually doing by this is, data will subtract by the mean and then divide the result by the standard deviation. ( x′=(x−μ)/σ )
As we did previously, we need to apply standardization for both training and testing data. I hope you have remembered the important fact that I mentioned in the feature encoding section.
You have to use the exact same two parameters μ and σ (values) that you used for centering the training set.
So in sklearn’s StandardScaler provides two methods to achieve this. Hence, every sklearn’s transform’s fit() just calculates the parameters (e.g. μ and σ in this case) and saves them as an internal object's state. Afterward, you can call its transform() method to apply the transformation to any particular set of data.
Another very important thing is that we don’t do any kind of standardization to previously encoded categorical variables. So keep them aside before applying the standardization.
to_standardize_train = X_train[['Temperature (C)', 'Humidity','Wind Speed (km/h)','Visibility (km)','Pressure (millibars)']].copy()
Note: I purposefully left the Wind Bearing column as it shows a large variation in data points. (0–360 degrees) I will be discretizing that column as the next step after standardization.
Before we do the standardization, we can examine how the histograms look like to understand the x scales.
As you can see, they are in different x scales. Now let’s do the standardization.
# create the scaler objectscaler = StandardScaler()# Same as previous - we only fit the training data to scalerscaler.fit(to_standardize_train)train_scaled = scaler.transform(to_standardize_train)test_scaled = scaler.transform(to_standardize_test)standardized_df_train = pd.DataFrame(train_scaled, columns = to_standardize_train.columns)standardized_df_test = pd.DataFrame(test_scaled, columns = to_standardize_test.columns)
Now you can see all the x axes have come to a standard scaler. You can apply the standardization for the target variable as well.
From Data Discretization, we can transform continuous values into the discrete form. This process can be used to reduce the large range of a data set into a small range that can smooth out the relationships between observations.
As an example, if we take age, it can be varied probably up to 1 to 100 years. It is a large range of data and the gaps between data points will also be large. To reduce that we can discretize that column by dividing it into meaningful categories or groups as follows :Under 12 (kids), between 12–18 (teens), between 18–55 (adults), and over 55 (old)
Therefore, discretization helps make the data easier to understand to the model. There are various methods to do the discretization. (Decision trees, Equal width, Equal-Frequency..etc) Here I am using the K-means discretization.
In the data set, we have a feature called Wind Bearing. If you remember, I kept that column aside previously because of this reason. It provides 0–360 degrees coverage about the wind direction. It’s a large range. We can discretize this into eight bins representing the actual wind directions. (North, North-East..etc)
The n_bins argument controls the number of bins that will be created. We can see the output using histograms.
So all the preprocessing and transformation steps are completed. Now we need to further improve it using feature engineering.
Actually we have already done some feature engineering processes in transformations. But here comes the big part. Here we have to manually decide what are the relations between the features and how to select the optimal feature set for training the model. We need to find the most significant features as irrelevant or partially relevant features can negatively impact our model performance.
If we take a practical example like the banking industry, there will be millions of features that need to be analyzed, and also the data points will be immense. Imagine how complex will be the data and how difficult be the data handling. It will lead data analysis tasks to become significantly harder as the dimensionality of the data increases. This phenomenon is called as the curse of dimensionality.
Also, it can lead to another problem that it may cause machine learning models to massively overfit and makes the model too complex. The model will be unable to generalize well on unseen data. Higher dimensions lead to high computation/training time as well as difficulty in visualizing. So it is essential to do a dimensional reduction.
Before doing the dimension reduction, we should keep in mind mainly 2 things.1. Original data should be able to approximately reconstructed.2. Distance between data points should be preserved.
We can use the Correlation Matrix with Heatmap to easily identify significant features. It shows how the features are related to each other or the target variable.
Correlation can be proportional or inversely proportional. When it is inversely proportional, it displays with a (-) sign. Let’s plot the Heatmap to identify which features are most related to our target variable and what are the features with high correlations.
correlation_mat = features_df.iloc[:,:6].corr()plt.figure(figsize=(10,8))sns.heatmap(correlation_mat, annot = True, cmap="RdYlGn")plt.title("Correlation matrix for features")plt.show()
As you can see in the heat-map, there are high correlations between:* temperature and humidity* temperature and visibility* humidity and visibility
Any 2 features (independent variables) are considered to be redundant if they are highly correlated. Normally it is recommended to remove such features as it will stabilize the model. But we cannot conclude that these features will not be worth enough. It should decide after training the model. Also dropping a variable is highly subjective and should always be done keeping the domain in mind.
Look at the last column. Apparent Temperature is highly correlated with Humidity followed by Visibility and Pressure. So we can state that they are the most significant features. We should keep these variables as that will cause the model to perform well.
Here we get some kind of contradiction. From figure 1 we identified some features that are highly correlated and they need to be removed as well as figure 2 implies the same set of features are highly correlated with the target variable and we should keep them. So we need to perform several experiments with the model before coming to a conclusion. But don’t worry! We can apply a way better method called PCA to reduce the dimensions.
PCA is a powerful dimensionality reduction algorithm that identifies patterns in the dataset, based on the correlations between the features. By looking at the variance_ratio explained by the PCA object, we can decide how many features (components) can be reduced without affecting the actual data.
PCA actually does is, it projects the data into dimensions in eigenvector space. Then it will identify the most important dimensions that preserve the actual information. Other dimensions will be dropped. So the important part here is, it does not remove the entire feature column but takes the most of information from it and projecting to other dimensions. Finally, it will come as an entirely new set of dimensions (columns).
If you are interested to know PCA in a detailed manner, I recommend a very good article written by Matt Brems and published in towardsdatascience.com
towardsdatascience.com
We will dig deeper into this technique in future articles. So let’s apply PCA to our dataset.
from sklearn.decomposition import PCApca = PCA()pca.fit(X_train)
First, we have to identify the number of dimensions that we can reduce up to. For that, we analyze the explained_variance_ratio_ in the PCA object that we fitted earlier.
pca.explained_variance_ratio_
Here we have a sorted array (vector) of the variance explained by each dimension. We have to keep the high variance dimensions and remove the rest of the dimensions. If the sum of high variance dimensions (n_components) is over 95%, it will be a good number.
By analyzing the vector, we can identify first 7 dimensions are preserving over 95% of the information in the data set. So from that we able to reduce the 33 dimensions into 7 dimensions with a loss of only 5% of the information.
Now we can apply PCA again by adding the no of components (dimensions) that needed to be remain.
pca = PCA(n_components=7)pca.fit(X_train)X_train_pca = pca.transform(X_train)X_test_pca = pca.transform(X_test)
All set! Let’s do the modeling to understand how well it performs on our dataset keeping those core concepts in mind.
Quick reminder- You can compare the model with or without PCA and check the accuracy values. If the accuracy in PCA is less than the original one, you can try out increasing the n_components one by one.
Before you apply any model, you need to understand the domain properly, the complexity of the domain, and whether the given dataset represents the actual complexity of your problem. Also if the problem is related to a business domain, you need to understand the business process, principles, and theories to some extent.
When modeling, there are numerous models available to use according to your problem. I’m using Multiple Linear Regression model as we need to predict a one response variable (target) given multiple explanatory variables (features). This model basically doing is fitting a linear equation to observed data. That line should give a minimum deviation to the original points.
Formally, the model for multiple linear regression, given n observations:
Let’s apply the model to our dataset.
from sklearn import linear_modellm = linear_model.LinearRegression()model2 = lm.fit(X_train_pca,y_train)
For the prediction, we already have prepared a test dataset. If you want to predict for entire new data, you need to apply all the preprocessing and transformation steps (transformation should be done according to previously fitted values) as well as the PCA in order to get the correct prediction.
predictions = lm2.predict(X_test_pca)y_hat_pca = pd.DataFrame(predictions, columns=["Predicted Temparature"])
You can see, our model predicts well for unseen data. Further, this can be visualized in a plot.
import matplotlib.pyplot as pltplt.figure(figsize=(20, 10))# Limiting the data set to 100 rows for more clearanceplt.plot(y_hat_pca[:100], label = "Pred")plt.plot(y_test[:100], label = "Actual")plt.title('Comparison of Prediction vs Actual - With PCA')plt.legend()plt.show()
As we discussed earlier, linear regression tries to fit a line that gives a minimum deviation to the original points. So there is an error between the actual and the predicted. By measuring this error (loss), we can check the accuracy of our model.
We measure this using loss functions. When the loss is minimal, we can decide that the model has very good accuracy. There are several loss functions available:
MSE — Mean Square Error
MAE — Mean Absolute Error
RMSE — Root Mean Square Error
When recording the efficiency of the model as an output, it’s recommended to use the RMSE over MSE as MSE is widely used for removing the error in the training stage. (better for model optimization.) MAE is not recommended for testing the accuracy as it does not gives us an idea of the direction of the error is.
Rather than these, there are various evaluation techniques as F1-Score, Area Under Curve, Confusion Matrix...etc to measure the accuracy of models. You can search more about these things to improve your knowledge. I intend to write a separate article on that as well.
Okay. Let’s cheak the MSE and RMSE for our model.
We use the R-squared value to evaluate the overall fit in the linear model. It’s between 0 and 1. Higher the values, the better the performance. Because it means that more variance is explained by the model.
#Percentage of explained variance of the predictionsscore_pca=lm2.score(X_test_pca,y_test)score_pca#This has given - 0.9902083367554705
Those are actually pretty good values. But before coming to a conclusion, let’s analyze the weight factors as well.
#W parameters of the modelprint(lm2.coef_)
The weights also can be used to evaluate the model. If the weights are giving higher values, that indicates your model is overfitted. If so, you need to revisit your preprocessing and transformation steps to analyze whether you have done something wrong.
Also, another thing that can cause overfitting is the model complexity. If you apply a polynomial or higher regression to a simple dataset, it may get overfitted. So you can try to simpler the model. Also, you can further study how to do weight regularizations. In our scenario, the weight factors are pretty much smaller and not overfitted.
You can further do K-fold cross-validation to get an overall accuracy score. I have done it in my notebook. You can refer that as well for additional testings.
So now we can conclude that our model has achieved over 99% of accuracy.
Complete Co-lab notebook. (With preloaded data set)
colab.research.google.com
Kaggle — Weather History Dataset
www.kaggle.com
We have covered a lot of important concepts through this article. I hope now you have a clear idea about how to train and test a model from scratch with understanding the core concepts.
Data Science is a very wide field and it is impossible to know everything! But there are tons of articles available to explore this amazing world. So learn the fundamental concepts well and use them to solve real problems alongside improving the knowledge.
I would like to extend special thanks to Dr. Subha Fernando (Senior Lecturer at University of Moratuwa) for inspiring me to write this article.
Thank you very much for sticking with me until the end! Hope this article helps you out with your journey in learning about ML. If there anything you need to clarify or mention, please drop by the comments.
Happy Learning! ❤️
|
[
{
"code": null,
"e": 551,
"s": 172,
"text": "Machine Learning is an enormous area. It is empowering technology for allowing us to develop software solutions much faster than before and currently the state-of-the-art solution for a wide range of problems. We can apply it to almost every domain. In this article, we are going to study in-depth how the process for developing a machine learning model to a practical use case."
},
{
"code": null,
"e": 591,
"s": 551,
"text": "In the article, we will be discussing :"
},
{
"code": null,
"e": 629,
"s": 591,
"text": "Problem Definition and Data gathering"
},
{
"code": null,
"e": 648,
"s": 629,
"text": "Data Preprocessing"
},
{
"code": null,
"e": 668,
"s": 648,
"text": "Data Transformation"
},
{
"code": null,
"e": 685,
"s": 668,
"text": "Feature Encoding"
},
{
"code": null,
"e": 713,
"s": 685,
"text": "Scaling and Standardization"
},
{
"code": null,
"e": 733,
"s": 713,
"text": "Feature Engineering"
},
{
"code": null,
"e": 787,
"s": 733,
"text": "Dimension reduction with Principal Component Analysis"
},
{
"code": null,
"e": 798,
"s": 787,
"text": "Regression"
},
{
"code": null,
"e": 842,
"s": 798,
"text": "Accuracy measures and Evaluation techniques"
},
{
"code": null,
"e": 968,
"s": 842,
"text": "Assumption:- I believe you have prior knowledge in python programming as well as basic libraries related to machine learning."
},
{
"code": null,
"e": 1152,
"s": 968,
"text": "Use-Case:- Is there a relationship between humidity and temperature? What about between humidity and apparent temperature? Can you predict the apparent temperature given the humidity?"
},
{
"code": null,
"e": 1301,
"s": 1152,
"text": "As the first thing, we have to understand the problem, the environment that problem lies in, and gather the domain knowledge regarding the scenario."
},
{
"code": null,
"e": 1416,
"s": 1301,
"text": "The problem mainly asks to predict the apparent temperature given the humidity. What is this apparent temperature?"
},
{
"code": null,
"e": 1584,
"s": 1416,
"text": "Apparent temperature is the temperature equivalent perceived by humans, caused by the combined effects of air temperature, relative humidity and wind speed. -Wikipedia"
},
{
"code": null,
"e": 1851,
"s": 1584,
"text": "This reveals one important factor. Not only humidity, but air temperature and wind speed are also affecting the apparent temperature. So for a given scenario, we need to find out what are the direct as well as indirect(hidden) facts that going to affect our problem."
},
{
"code": null,
"e": 2485,
"s": 1851,
"text": "A good example of this is the banking sector. Imagine you need to identify a customer whether he is eligible to receive a loan or not. (performer or non-performer) You cannot just predict it by only looking at the previous bank transactions. You need to analyze, what is the domain he working on, if he is a cooperate customer what are the other industries that producing profit to him (Although he fails in one domain, he may rise in another domain), whether he has any political supports, such as a broad area (indirect) you may need to cover in order to provide a good prediction. So keeping that in mind, let’s go to our problem."
},
{
"code": null,
"e": 2820,
"s": 2485,
"text": "Then we need a data set to tackle this problem. Kaggle website provides a massive collection of data resources for anyone and we easily can find a data set from there. Most importantly, on Kaggle you can learn from others in a variety of problem contexts. I will be using the Kaggle — Weather History Data set to analyze this problem."
},
{
"code": null,
"e": 2835,
"s": 2820,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 2948,
"s": 2835,
"text": "Note: All the coding was done in a Google Colab python notebook and you can find it under the resources section."
},
{
"code": null,
"e": 3102,
"s": 2948,
"text": "As a data scientist, you need to have a clear idea of your data set and the complexity of data. Let’s first visualize the data, just to get some insight."
},
{
"code": null,
"e": 3216,
"s": 3102,
"text": "The below code snippet will load the weather data CSV file into a pandas data frame and display the first 5 rows."
},
{
"code": null,
"e": 3294,
"s": 3216,
"text": "weatherDataframe = pd.read_csv(‘weatherHistory.csv’);weatherDataframe.head();"
},
{
"code": null,
"e": 3432,
"s": 3294,
"text": "You can analyze the data set furthermore by weatherDataframe.info() method and then you will see there are 96453 entries with 12 columns."
},
{
"code": null,
"e": 3539,
"s": 3432,
"text": "We can identify our target column as the apparent temperature and the rest of the columns as the features."
},
{
"code": null,
"e": 3938,
"s": 3539,
"text": "Preprocessing is the most important part of machine learning. The success of our model highly depends on the quality of the data fed into the machine learning model. Real-world data is usually dirty. It contains duplicates missing values outliers, irrelevant features, non-standardized data..etc. So we need to clean the data set in a proper way. Let’s see step by step, how we going to achieve it."
},
{
"code": null,
"e": 4323,
"s": 3938,
"text": "First, we need to find any unique fields in the data set. If found any, we should drop them because they are not useful when recognizing patterns. If a data set contains columns with very few unique values, that will provide a good basis for data cleaning. Also, if the columns have so many unique values, such as ID number, email (unique for every data point), we should remove them."
},
{
"code": null,
"e": 4411,
"s": 4323,
"text": "# summarize the number of unique values in each columnprint(weatherDataframe.nunique())"
},
{
"code": null,
"e": 4774,
"s": 4411,
"text": "As you can see in the results, the Loud cover column only has a single value (0). So we can drop that column entirely. Also, we need to analyze what are the unique values row-wise. To analyze that, we can calculate the number of unique values for each variable as a percentage of the total number of rows in the data set. This is a custom function made for that."
},
{
"code": null,
"e": 5039,
"s": 4774,
"text": "Formatted date giving 100% unique ratio to the total data frame. So we can drop that column. Also by looking at the data set we can conclude that the Daily summary and Summary columns have a great similarity. So we can remove one of them. So I’ll keep the Summary."
},
{
"code": null,
"e": 5162,
"s": 5039,
"text": "The next thing that, there may be duplicate rows. So we need to identify rows that contain duplicate data and delete them."
},
{
"code": null,
"e": 5556,
"s": 5162,
"text": "There is one important thing to remember. When we removing rows, this will cause the indexes are to be different. As an example, if you remove row 18 from the data frame, now the indexes will be ..16,17,19,20.. like this. This will ultimately create a difference between the actual row count and the last index. In order to avoid this, we need to reset indexes. Then it will correct the order."
},
{
"code": null,
"e": 5940,
"s": 5556,
"text": "There can be a number of missing values in the data set. Mainly, there are two things that we can do for missing values, it’s either drop or do imputation to replace them. Imputation is replacing missing values with mean or median values. But the problem with this imputation is, it can lead to causing a bias in the data set. So it is advised to manipulate the imputation carefully."
},
{
"code": null,
"e": 6121,
"s": 5940,
"text": "If the number of cases of missing values is extremely small, the best option is to drop them. (If the number of the cases is less than 5% of the sample, you are safer to drop them)"
},
{
"code": null,
"e": 6294,
"s": 6121,
"text": "# Check for any missing valuesweatherDataframe.isnull().values.any()# This gives - True#Getting the summary of what are missing value columnsweatherDataframe.isnull().sum()"
},
{
"code": null,
"e": 6451,
"s": 6294,
"text": "As you can see, there are 517 missing values in the Precip type column. So, let’s examine the overall probability to find whether we can drop those columns."
},
{
"code": null,
"e": 6524,
"s": 6451,
"text": "weatherDataframe['Precip Type'].isna().sum()/(len(weatherDataframe))*100"
},
{
"code": null,
"e": 6752,
"s": 6524,
"text": "This returns the result as 0.536 and it’s a very low percentage compared to the total data set. So we can drop them. It will ensure no bias or variance is added or removed, and ultimately results in a robust and accurate model."
},
{
"code": null,
"e": 6971,
"s": 6752,
"text": "# make copy to avoid changing original datanew_weatherDf = weatherDataframe.copy()# removing missing valuesnew_weatherDf=new_weatherDf.dropna(axis=0)# Resetting Indexesnew_weatherDf=new_weatherDf.reset_index(drop=True)"
},
{
"code": null,
"e": 7093,
"s": 6971,
"text": "An outlier is a data point (or can be a small number of data points) that is significantly stay away from the mainstream."
},
{
"code": null,
"e": 7333,
"s": 7093,
"text": "But if you are seeing many points are staying away from the mainstream, they are not considered as outliers and they could be some kind of cluster pattern or something related to an anomaly. In such cases, we need to treat them separately."
},
{
"code": null,
"e": 7382,
"s": 7333,
"text": "There are numerous methods to discover outliers."
},
{
"code": null,
"e": 7459,
"s": 7382,
"text": "Box Plots —glancing at the variability outside the upper and lower quartiles"
},
{
"code": null,
"e": 7523,
"s": 7459,
"text": "Scatter Plots — using Cartesian coordinates of two data columns"
},
{
"code": null,
"e": 7564,
"s": 7523,
"text": "Z- Score — using a mathematical function"
},
{
"code": null,
"e": 7622,
"s": 7564,
"text": "I’ll use the Box Plot method for detecting them visually."
},
{
"code": null,
"e": 7959,
"s": 7622,
"text": "You can see there are some outliers exists in the data set. So we should examine them one by one to treat them separately. The best option is to remove them. You can apply mean and median values considering the data distribution. But there is a high risk of making the data set bias. So if you want to do that, handle it very precisely."
},
{
"code": null,
"e": 8319,
"s": 7959,
"text": "I’ll demonstrate removing outliers in one column. You can see the rest of the things in my python notebook. As you have seen in the plot, there is an outlier in the pressure column. It’s a pressure and it would not become zero under normal conditions. This may due to an error in data entry or a problem with the collected equipment. So we should remove them."
},
{
"code": null,
"e": 8650,
"s": 8319,
"text": "There is one thing we need to keep in mind before doing transformations. That is data Leakage. We need to keep a test data set in order to estimate our model. But if we do the below transformation steps to all the data in the data set and then split it out (as training and testing set), we have committed the sin of data leakage."
},
{
"code": null,
"e": 8904,
"s": 8650,
"text": "Don’t forget that testing data points represent real-world data. So the model should not see that data. If so, the consequence will be over-fitting your training data and having an overly optimistic evaluation of your model’s performance on unseen data."
},
{
"code": null,
"e": 9132,
"s": 8904,
"text": "In order to avoid that, we should split our data set into train and test sets now and do the transformation steps. This will ensure no peeking ahead. Otherwise, information from the test set will “leak” into your training data."
},
{
"code": null,
"e": 9347,
"s": 9132,
"text": "First, we need to define our features and the target (what we going to predict.) The use case tells us to predict the Apparent Temperature. So it will be our target. The rest of the columns we can take as features."
},
{
"code": null,
"e": 9512,
"s": 9347,
"text": "features_df= new_weatherDf.drop('Apparent Temperature (C)', 1)target = pd.DataFrame(new_weatherDf['Apparent Temperature (C)'], columns=[\"Apparent Temperature (C)\"])"
},
{
"code": null,
"e": 9735,
"s": 9512,
"text": "Now we can split them out as training and test tests to 80% — 20% ratio. random_state ensures that the splits that you generate are reproducible. It always splits in the same random order and will not change for every run."
},
{
"code": null,
"e": 9897,
"s": 9735,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(features_df, target, test_size = 0.2, random_state = 101)"
},
{
"code": null,
"e": 9986,
"s": 9897,
"text": "Also, keep in mind to reset the indexes as it may lead to confusion in the latter parts."
},
{
"code": null,
"e": 10135,
"s": 9986,
"text": "X_train=X_train.reset_index(drop=True)X_test=X_test.reset_index(drop=True)y_train=y_train.reset_index(drop=True)y_test=y_test.reset_index(drop=True)"
},
{
"code": null,
"e": 10177,
"s": 10135,
"text": "Okay. We are all set for transformations!"
},
{
"code": null,
"e": 10366,
"s": 10177,
"text": "The data that you have cleaned previously, may not be in the right format or right scale and it will be difficult to understand for the model. Therefore we need to do data transformations."
},
{
"code": null,
"e": 10808,
"s": 10366,
"text": "Skewness is the asymmetry in a set of data that deviates from a normal distribution. It also can define as a distortion of the symmetrical bell curve. If the curve is shifted to the left (tail in the right), it is right-skewed and if the curve shifted to the right (tail in the left), it is left-skewed. We should apply proper transformations in order to bring it to a symmetrical shape. This will lead to increase the accuracy of our model."
},
{
"code": null,
"e": 11001,
"s": 10808,
"text": "As per the image shown above, we need to apply Log-transformation to the right-skewed data and Exponential-transformation to the left-skewed data in order to bring the data set to symmetrical."
},
{
"code": null,
"e": 11135,
"s": 11001,
"text": "But how we detect the skewness? For that, we have Q-Q plots (quantile-quantile plots) and histograms. Let’s analyze with our dataset."
},
{
"code": null,
"e": 11303,
"s": 11135,
"text": "import scipy.stats as stats# Temperature (C). - Trainingstats.probplot(X_train[\"Temperature (C)\"], dist=\"norm\", plot=plt);plt.show();X_train[\"Temperature (C)\"].hist();"
},
{
"code": null,
"e": 11484,
"s": 11303,
"text": "As you can see in the Q-Q plot, most of the data lie in the red line. Also, the histogram is not showing any skewness and it’s symmetric. So we don’t need to transform this column."
},
{
"code": null,
"e": 11644,
"s": 11484,
"text": "If you analyze the Humidity column, you will notice a left-skewed distribution in there. So we need to apply Exponential transformation to make it symmetrical."
},
{
"code": null,
"e": 12086,
"s": 11644,
"text": "# create columns variables to hold the columns that need transformationcolumns = ['Humidity']# create the function transformer object with exponential transformationexp_transformer = FunctionTransformer(lambda x:x**3, validate=True)# apply the transformation data_new = exp_transformer.transform(X_train[columns])df_new = pd.DataFrame(data_new, columns=columns)# replace new values with previous data frameX_train.Humidity=df_new['Humidity']"
},
{
"code": null,
"e": 12348,
"s": 12086,
"text": "Now you will see a nice symmetric distribution. So likewise we can do the transformation to all the necessary columns. I’ll show one another important transformation. All the transformations are explained in my python notebook. Refer it for more clarifications."
},
{
"code": null,
"e": 12723,
"s": 12348,
"text": "If you analyze the wind speed column, you would see a right-skewed distribution. To bring it symmetrical we need to apply log transformation. But here is a special case that there are 0 value data points can see in the column. If we apply log transformation, that 0 value data points will be replaced with minus infinity. To avoid that, we can apply log(x+1) transformation."
},
{
"code": null,
"e": 13200,
"s": 12723,
"text": "# create columns variables to hold the columns that need transformationcolumns = ['Wind Speed (km/h)']# create the function transformer object with logarithm transformationlogarithm_transformer = FunctionTransformer(np.log1p, validate=True)# apply the transformation data_new = logarithm_transformer.transform(X_train[columns])df_new = pd.DataFrame(data_new, columns=columns)# replace new values with previous data frameX_train['Wind Speed (km/h)']=df_new['Wind Speed (km/h)']"
},
{
"code": null,
"e": 13429,
"s": 13200,
"text": "There are categorical (text) and numeric data in our dataset. But most of the models only accept numeric data. So we need to convert those categorical data, or text data columns into numbers. To do this, we can use two encoders."
},
{
"code": null,
"e": 13464,
"s": 13429,
"text": "Label EncoderOne Hot Encoder (OHE)"
},
{
"code": null,
"e": 13478,
"s": 13464,
"text": "Label Encoder"
},
{
"code": null,
"e": 13500,
"s": 13478,
"text": "One Hot Encoder (OHE)"
},
{
"code": null,
"e": 13640,
"s": 13500,
"text": "Note — Some algorithms can work with categorical data directly like Decision Trees. But most of them cannot operate on label data directly."
},
{
"code": null,
"e": 13830,
"s": 13640,
"text": "Label Encoder encodes the classes with a value between 0 and n-1 where n is the number of distinct classes(labels). If a class replicates, it will assign the same value as assigned earlier."
},
{
"code": null,
"e": 14003,
"s": 13830,
"text": "Let’s take a simple example for clarifying things. There is a column with having different countries. If we apply a label encoder to that, it will provide the below output."
},
{
"code": null,
"e": 14286,
"s": 14003,
"text": "It will assign a unique value from 0 to n classes. As you can see here, label encoding uses alphabetical ordering. Hence, Brazil has been encoded with 0, India with 1, and Italy with 2. If the same class appears in a different row, it will assign the same value as assigned earlier."
},
{
"code": null,
"e": 14696,
"s": 14286,
"text": "But the problem in the label encoding is, it can lead to find relationships between the encoded values. As an example, if the countries have marked 1,2,3,4.. categories, the model can create a pattern like the label 2 country is more powerful than the label 1 country and label 3 country is more powerful than the both 1 and 2 like that. But actually, there is no relation, of any kind, between the countries."
},
{
"code": null,
"e": 14870,
"s": 14696,
"text": "So by label encoding, it will confuse the model into thinking that a column has data with some kind of order or hierarchy. To overcome this problem, we use One hot encoding."
},
{
"code": null,
"e": 15078,
"s": 14870,
"text": "One Hot Encoding takes a column that has categorical data and then splits the column into multiple columns. The classes are replaced by binaries (1s and 0s), depending on which column has a particular class."
},
{
"code": null,
"e": 15418,
"s": 15078,
"text": "Look at the below example. First, it will create separate columns for every class, and then it will assign a binary value of 1 for the presented class and 0 for others as row-wise. E.g: The first row represents Sri Lanka. So value 1 only applied for the Sri Lankan column and the rest of the columns in the first row will get a value of 0."
},
{
"code": null,
"e": 15810,
"s": 15418,
"text": "This will not generate a pattern among classes because the result is binary rather than ordinal and that everything sits in an orthogonal vector space. But it can lead to a massive number of columns and ultimately lead to a curse of dimensionality. But if we apply a Dimensional reduction technique like PCA, it will resolve the problem. Also, It’s advised to use the OHE over Label Encoder."
},
{
"code": null,
"e": 15929,
"s": 15810,
"text": "In our data set, now we have 2 categorical columns, Precip Type and Summary. So we can apply encoding to both columns."
},
{
"code": null,
"e": 16340,
"s": 15929,
"text": "We are dealing with a training and a testing set. So we need to keep in mind one important thing. When you are training a model, you will use the training data set. For a trained model, we need to input the same scale of data we used in training. So how do we get that previous scale? Here comes the interesting part. To carter that issue, there are two methods in most libraries. That is fit() and transform()"
},
{
"code": null,
"e": 16633,
"s": 16340,
"text": "You need to first apply fit() method on your training data set to only calculate the scale and keep it internally as an object. Then you can call transform() method to apply the transformation for both training and testing datasets. That will ensure the data is transformed on the same scale."
},
{
"code": null,
"e": 16803,
"s": 16633,
"text": "I applied one-hot encoding for the summary column. For the precip type column, we can apply categorical coding (similar to label encoding) as there are only two classes."
},
{
"code": null,
"e": 16923,
"s": 16803,
"text": "X_train['Precip Type']=X_train['Precip Type'].astype('category')X_train['Precip Type']=X_train['Precip Type'].cat.codes"
},
{
"code": null,
"e": 16975,
"s": 16923,
"text": "Our final training data frame will look as follows."
},
{
"code": null,
"e": 17203,
"s": 16975,
"text": "We use Standardization to center the data (make it have zero mean and unit standard deviation). What actually doing by this is, data will subtract by the mean and then divide the result by the standard deviation. ( x′=(x−μ)/σ )"
},
{
"code": null,
"e": 17390,
"s": 17203,
"text": "As we did previously, we need to apply standardization for both training and testing data. I hope you have remembered the important fact that I mentioned in the feature encoding section."
},
{
"code": null,
"e": 17499,
"s": 17390,
"text": "You have to use the exact same two parameters μ and σ (values) that you used for centering the training set."
},
{
"code": null,
"e": 17820,
"s": 17499,
"text": "So in sklearn’s StandardScaler provides two methods to achieve this. Hence, every sklearn’s transform’s fit() just calculates the parameters (e.g. μ and σ in this case) and saves them as an internal object's state. Afterward, you can call its transform() method to apply the transformation to any particular set of data."
},
{
"code": null,
"e": 17998,
"s": 17820,
"text": "Another very important thing is that we don’t do any kind of standardization to previously encoded categorical variables. So keep them aside before applying the standardization."
},
{
"code": null,
"e": 18130,
"s": 17998,
"text": "to_standardize_train = X_train[['Temperature (C)', 'Humidity','Wind Speed (km/h)','Visibility (km)','Pressure (millibars)']].copy()"
},
{
"code": null,
"e": 18317,
"s": 18130,
"text": "Note: I purposefully left the Wind Bearing column as it shows a large variation in data points. (0–360 degrees) I will be discretizing that column as the next step after standardization."
},
{
"code": null,
"e": 18423,
"s": 18317,
"text": "Before we do the standardization, we can examine how the histograms look like to understand the x scales."
},
{
"code": null,
"e": 18505,
"s": 18423,
"text": "As you can see, they are in different x scales. Now let’s do the standardization."
},
{
"code": null,
"e": 18931,
"s": 18505,
"text": "# create the scaler objectscaler = StandardScaler()# Same as previous - we only fit the training data to scalerscaler.fit(to_standardize_train)train_scaled = scaler.transform(to_standardize_train)test_scaled = scaler.transform(to_standardize_test)standardized_df_train = pd.DataFrame(train_scaled, columns = to_standardize_train.columns)standardized_df_test = pd.DataFrame(test_scaled, columns = to_standardize_test.columns)"
},
{
"code": null,
"e": 19061,
"s": 18931,
"text": "Now you can see all the x axes have come to a standard scaler. You can apply the standardization for the target variable as well."
},
{
"code": null,
"e": 19290,
"s": 19061,
"text": "From Data Discretization, we can transform continuous values into the discrete form. This process can be used to reduce the large range of a data set into a small range that can smooth out the relationships between observations."
},
{
"code": null,
"e": 19641,
"s": 19290,
"text": "As an example, if we take age, it can be varied probably up to 1 to 100 years. It is a large range of data and the gaps between data points will also be large. To reduce that we can discretize that column by dividing it into meaningful categories or groups as follows :Under 12 (kids), between 12–18 (teens), between 18–55 (adults), and over 55 (old)"
},
{
"code": null,
"e": 19870,
"s": 19641,
"text": "Therefore, discretization helps make the data easier to understand to the model. There are various methods to do the discretization. (Decision trees, Equal width, Equal-Frequency..etc) Here I am using the K-means discretization."
},
{
"code": null,
"e": 20189,
"s": 19870,
"text": "In the data set, we have a feature called Wind Bearing. If you remember, I kept that column aside previously because of this reason. It provides 0–360 degrees coverage about the wind direction. It’s a large range. We can discretize this into eight bins representing the actual wind directions. (North, North-East..etc)"
},
{
"code": null,
"e": 20299,
"s": 20189,
"text": "The n_bins argument controls the number of bins that will be created. We can see the output using histograms."
},
{
"code": null,
"e": 20425,
"s": 20299,
"text": "So all the preprocessing and transformation steps are completed. Now we need to further improve it using feature engineering."
},
{
"code": null,
"e": 20817,
"s": 20425,
"text": "Actually we have already done some feature engineering processes in transformations. But here comes the big part. Here we have to manually decide what are the relations between the features and how to select the optimal feature set for training the model. We need to find the most significant features as irrelevant or partially relevant features can negatively impact our model performance."
},
{
"code": null,
"e": 21222,
"s": 20817,
"text": "If we take a practical example like the banking industry, there will be millions of features that need to be analyzed, and also the data points will be immense. Imagine how complex will be the data and how difficult be the data handling. It will lead data analysis tasks to become significantly harder as the dimensionality of the data increases. This phenomenon is called as the curse of dimensionality."
},
{
"code": null,
"e": 21560,
"s": 21222,
"text": "Also, it can lead to another problem that it may cause machine learning models to massively overfit and makes the model too complex. The model will be unable to generalize well on unseen data. Higher dimensions lead to high computation/training time as well as difficulty in visualizing. So it is essential to do a dimensional reduction."
},
{
"code": null,
"e": 21753,
"s": 21560,
"text": "Before doing the dimension reduction, we should keep in mind mainly 2 things.1. Original data should be able to approximately reconstructed.2. Distance between data points should be preserved."
},
{
"code": null,
"e": 21917,
"s": 21753,
"text": "We can use the Correlation Matrix with Heatmap to easily identify significant features. It shows how the features are related to each other or the target variable."
},
{
"code": null,
"e": 22180,
"s": 21917,
"text": "Correlation can be proportional or inversely proportional. When it is inversely proportional, it displays with a (-) sign. Let’s plot the Heatmap to identify which features are most related to our target variable and what are the features with high correlations."
},
{
"code": null,
"e": 22365,
"s": 22180,
"text": "correlation_mat = features_df.iloc[:,:6].corr()plt.figure(figsize=(10,8))sns.heatmap(correlation_mat, annot = True, cmap=\"RdYlGn\")plt.title(\"Correlation matrix for features\")plt.show()"
},
{
"code": null,
"e": 22513,
"s": 22365,
"text": "As you can see in the heat-map, there are high correlations between:* temperature and humidity* temperature and visibility* humidity and visibility"
},
{
"code": null,
"e": 22909,
"s": 22513,
"text": "Any 2 features (independent variables) are considered to be redundant if they are highly correlated. Normally it is recommended to remove such features as it will stabilize the model. But we cannot conclude that these features will not be worth enough. It should decide after training the model. Also dropping a variable is highly subjective and should always be done keeping the domain in mind."
},
{
"code": null,
"e": 23165,
"s": 22909,
"text": "Look at the last column. Apparent Temperature is highly correlated with Humidity followed by Visibility and Pressure. So we can state that they are the most significant features. We should keep these variables as that will cause the model to perform well."
},
{
"code": null,
"e": 23602,
"s": 23165,
"text": "Here we get some kind of contradiction. From figure 1 we identified some features that are highly correlated and they need to be removed as well as figure 2 implies the same set of features are highly correlated with the target variable and we should keep them. So we need to perform several experiments with the model before coming to a conclusion. But don’t worry! We can apply a way better method called PCA to reduce the dimensions."
},
{
"code": null,
"e": 23901,
"s": 23602,
"text": "PCA is a powerful dimensionality reduction algorithm that identifies patterns in the dataset, based on the correlations between the features. By looking at the variance_ratio explained by the PCA object, we can decide how many features (components) can be reduced without affecting the actual data."
},
{
"code": null,
"e": 24330,
"s": 23901,
"text": "PCA actually does is, it projects the data into dimensions in eigenvector space. Then it will identify the most important dimensions that preserve the actual information. Other dimensions will be dropped. So the important part here is, it does not remove the entire feature column but takes the most of information from it and projecting to other dimensions. Finally, it will come as an entirely new set of dimensions (columns)."
},
{
"code": null,
"e": 24480,
"s": 24330,
"text": "If you are interested to know PCA in a detailed manner, I recommend a very good article written by Matt Brems and published in towardsdatascience.com"
},
{
"code": null,
"e": 24503,
"s": 24480,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 24597,
"s": 24503,
"text": "We will dig deeper into this technique in future articles. So let’s apply PCA to our dataset."
},
{
"code": null,
"e": 24662,
"s": 24597,
"text": "from sklearn.decomposition import PCApca = PCA()pca.fit(X_train)"
},
{
"code": null,
"e": 24833,
"s": 24662,
"text": "First, we have to identify the number of dimensions that we can reduce up to. For that, we analyze the explained_variance_ratio_ in the PCA object that we fitted earlier."
},
{
"code": null,
"e": 24863,
"s": 24833,
"text": "pca.explained_variance_ratio_"
},
{
"code": null,
"e": 25122,
"s": 24863,
"text": "Here we have a sorted array (vector) of the variance explained by each dimension. We have to keep the high variance dimensions and remove the rest of the dimensions. If the sum of high variance dimensions (n_components) is over 95%, it will be a good number."
},
{
"code": null,
"e": 25352,
"s": 25122,
"text": "By analyzing the vector, we can identify first 7 dimensions are preserving over 95% of the information in the data set. So from that we able to reduce the 33 dimensions into 7 dimensions with a loss of only 5% of the information."
},
{
"code": null,
"e": 25449,
"s": 25352,
"text": "Now we can apply PCA again by adding the no of components (dimensions) that needed to be remain."
},
{
"code": null,
"e": 25561,
"s": 25449,
"text": "pca = PCA(n_components=7)pca.fit(X_train)X_train_pca = pca.transform(X_train)X_test_pca = pca.transform(X_test)"
},
{
"code": null,
"e": 25679,
"s": 25561,
"text": "All set! Let’s do the modeling to understand how well it performs on our dataset keeping those core concepts in mind."
},
{
"code": null,
"e": 25882,
"s": 25679,
"text": "Quick reminder- You can compare the model with or without PCA and check the accuracy values. If the accuracy in PCA is less than the original one, you can try out increasing the n_components one by one."
},
{
"code": null,
"e": 26203,
"s": 25882,
"text": "Before you apply any model, you need to understand the domain properly, the complexity of the domain, and whether the given dataset represents the actual complexity of your problem. Also if the problem is related to a business domain, you need to understand the business process, principles, and theories to some extent."
},
{
"code": null,
"e": 26575,
"s": 26203,
"text": "When modeling, there are numerous models available to use according to your problem. I’m using Multiple Linear Regression model as we need to predict a one response variable (target) given multiple explanatory variables (features). This model basically doing is fitting a linear equation to observed data. That line should give a minimum deviation to the original points."
},
{
"code": null,
"e": 26649,
"s": 26575,
"text": "Formally, the model for multiple linear regression, given n observations:"
},
{
"code": null,
"e": 26687,
"s": 26649,
"text": "Let’s apply the model to our dataset."
},
{
"code": null,
"e": 26792,
"s": 26687,
"text": "from sklearn import linear_modellm = linear_model.LinearRegression()model2 = lm.fit(X_train_pca,y_train)"
},
{
"code": null,
"e": 27091,
"s": 26792,
"text": "For the prediction, we already have prepared a test dataset. If you want to predict for entire new data, you need to apply all the preprocessing and transformation steps (transformation should be done according to previously fitted values) as well as the PCA in order to get the correct prediction."
},
{
"code": null,
"e": 27201,
"s": 27091,
"text": "predictions = lm2.predict(X_test_pca)y_hat_pca = pd.DataFrame(predictions, columns=[\"Predicted Temparature\"])"
},
{
"code": null,
"e": 27298,
"s": 27201,
"text": "You can see, our model predicts well for unseen data. Further, this can be visualized in a plot."
},
{
"code": null,
"e": 27573,
"s": 27298,
"text": "import matplotlib.pyplot as pltplt.figure(figsize=(20, 10))# Limiting the data set to 100 rows for more clearanceplt.plot(y_hat_pca[:100], label = \"Pred\")plt.plot(y_test[:100], label = \"Actual\")plt.title('Comparison of Prediction vs Actual - With PCA')plt.legend()plt.show()"
},
{
"code": null,
"e": 27822,
"s": 27573,
"text": "As we discussed earlier, linear regression tries to fit a line that gives a minimum deviation to the original points. So there is an error between the actual and the predicted. By measuring this error (loss), we can check the accuracy of our model."
},
{
"code": null,
"e": 27983,
"s": 27822,
"text": "We measure this using loss functions. When the loss is minimal, we can decide that the model has very good accuracy. There are several loss functions available:"
},
{
"code": null,
"e": 28007,
"s": 27983,
"text": "MSE — Mean Square Error"
},
{
"code": null,
"e": 28033,
"s": 28007,
"text": "MAE — Mean Absolute Error"
},
{
"code": null,
"e": 28063,
"s": 28033,
"text": "RMSE — Root Mean Square Error"
},
{
"code": null,
"e": 28377,
"s": 28063,
"text": "When recording the efficiency of the model as an output, it’s recommended to use the RMSE over MSE as MSE is widely used for removing the error in the training stage. (better for model optimization.) MAE is not recommended for testing the accuracy as it does not gives us an idea of the direction of the error is."
},
{
"code": null,
"e": 28645,
"s": 28377,
"text": "Rather than these, there are various evaluation techniques as F1-Score, Area Under Curve, Confusion Matrix...etc to measure the accuracy of models. You can search more about these things to improve your knowledge. I intend to write a separate article on that as well."
},
{
"code": null,
"e": 28695,
"s": 28645,
"text": "Okay. Let’s cheak the MSE and RMSE for our model."
},
{
"code": null,
"e": 28903,
"s": 28695,
"text": "We use the R-squared value to evaluate the overall fit in the linear model. It’s between 0 and 1. Higher the values, the better the performance. Because it means that more variance is explained by the model."
},
{
"code": null,
"e": 29039,
"s": 28903,
"text": "#Percentage of explained variance of the predictionsscore_pca=lm2.score(X_test_pca,y_test)score_pca#This has given - 0.9902083367554705"
},
{
"code": null,
"e": 29155,
"s": 29039,
"text": "Those are actually pretty good values. But before coming to a conclusion, let’s analyze the weight factors as well."
},
{
"code": null,
"e": 29198,
"s": 29155,
"text": "#W parameters of the modelprint(lm2.coef_)"
},
{
"code": null,
"e": 29453,
"s": 29198,
"text": "The weights also can be used to evaluate the model. If the weights are giving higher values, that indicates your model is overfitted. If so, you need to revisit your preprocessing and transformation steps to analyze whether you have done something wrong."
},
{
"code": null,
"e": 29795,
"s": 29453,
"text": "Also, another thing that can cause overfitting is the model complexity. If you apply a polynomial or higher regression to a simple dataset, it may get overfitted. So you can try to simpler the model. Also, you can further study how to do weight regularizations. In our scenario, the weight factors are pretty much smaller and not overfitted."
},
{
"code": null,
"e": 29955,
"s": 29795,
"text": "You can further do K-fold cross-validation to get an overall accuracy score. I have done it in my notebook. You can refer that as well for additional testings."
},
{
"code": null,
"e": 30028,
"s": 29955,
"text": "So now we can conclude that our model has achieved over 99% of accuracy."
},
{
"code": null,
"e": 30080,
"s": 30028,
"text": "Complete Co-lab notebook. (With preloaded data set)"
},
{
"code": null,
"e": 30106,
"s": 30080,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 30139,
"s": 30106,
"text": "Kaggle — Weather History Dataset"
},
{
"code": null,
"e": 30154,
"s": 30139,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 30340,
"s": 30154,
"text": "We have covered a lot of important concepts through this article. I hope now you have a clear idea about how to train and test a model from scratch with understanding the core concepts."
},
{
"code": null,
"e": 30597,
"s": 30340,
"text": "Data Science is a very wide field and it is impossible to know everything! But there are tons of articles available to explore this amazing world. So learn the fundamental concepts well and use them to solve real problems alongside improving the knowledge."
},
{
"code": null,
"e": 30741,
"s": 30597,
"text": "I would like to extend special thanks to Dr. Subha Fernando (Senior Lecturer at University of Moratuwa) for inspiring me to write this article."
},
{
"code": null,
"e": 30948,
"s": 30741,
"text": "Thank you very much for sticking with me until the end! Hope this article helps you out with your journey in learning about ML. If there anything you need to clarify or mention, please drop by the comments."
}
] |
Use Pre-trained Word Embedding to detect real disaster tweets | by Zeineb Ghrib | Towards Data Science
|
In this post we will go through the overall text classification pipeline, and especially the data pre-processing steps, we will be using a Glove pre-trained word embedding. Textual features processing is a little bit more tricky than linear or categorical features. In fact, machine learning algorithms are more about scalars and vectors rather than characters or words. So we have to convert the text input into scalars, and the keystone 🗝 element consists in how to find out the best representation of the input words. This is the main idea behind Natural Language Processing
We will use a dataset from a Kaggle competition called Real or Not? NLP with Disaster Tweets. The task consists in predicting whether or not a given tweet is about a real disaster. To address this text classification task we will use word embedding transformation followed by a recurrent deep learning model. Other less sophisticated solutions, but still efficient, are also possible such as combining tf-idf encoding and a naive Bayes classifier (check out my last post).
Also I will include some handy Python code that can be reproduced in other NLP tasks. The overall source code is accessible in this kaggle notebook.
Models such as LSTM or CNN are more efficient to capture the words order and the semantic relationship between them, which usually is critical to the text’s meaning : a sample from our dataset that is labelled as a real disaster:
'#RockyFire Update => California Hwy. 20 closed in both directions due to Lake County fire - #CAfire #wildfires'
It is obvious that the words order was important in the example above.
In the other hand, we need to convert input text to a machine readable format. It exists many technics such as
one-hot encoding: each sequence text input is represented in d- dimensional space where d is size of the dataset vocabulary. Each term would get 1 if it is present in the document 0 otherwise. with a large corpus, the vocabulary would be about tens of thousands of tokens, making the one-hot vectors very sparse and inefficient.
TF-IDF encoding: words are mapped to numerics generated using tf-idf metric. The platform has integrated fast algorithms making it possible to keep all uni-grams and bi-grams tf-idf encoding without having to apply dimension reducing
Word embedding transformation : words are projected to a dense vector space, where semantic distance between words are preserved: (see Figure below):
What is pre-trained Word Embeddings?
An embedding is a dense vector that represents a word (or a symbol). By default, the embedding vectors are randomly initialized, then will gradually be improved during the training phase, with the gradient descent algorithm at each back-propagation step, so that similar words or words in the same lexical field or with common stem ... will end up close in terms of distance in the new vector space; (see figure below):
Pre-trained word embedding is an example of Transfer Learning. The main idea behind it is to use public embeddings that are already trained on large datasets. Specifically, instead of initializing our neural network weights randomly, we will set these pre trained embeddings as initialization weights. This trick helps to accelerate training and boost the performance of NLP models.
Before all, let’s import the required libraries and tools that will help us perform the NLP processing and the
import pandas as pdimport numpy as npfrom nltk.corpus import stopwordsfrom nltk.util import ngramsfrom sklearn.feature_extraction.text import CountVectorizerfrom collections import defaultdictfrom collections import Counterstop=set(stopwords.words('english'))import refrom nltk.tokenize import word_tokenizeimport gensimimport stringfrom keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequencesfrom tqdm import tqdmfrom keras.models import Sequentialfrom keras.layers import Embedding,LSTM,Dense,SpatialDropout1Dfrom keras.initializers import Constantfrom sklearn.model_selection import train_test_splitfrom keras.optimizers import Adam
Regardless of the EDA step that can bring out the uncleaned elements and help us to customize the cleaning code, we can apply some basic data cleaning that are recurrent in tweeters such as removing punctuation, html tags urls and emojis, spelling correction,..
Below a python code that can be be reproduced in other similar use cases 😉
Then we will split the datset into:
a training dataset (80% of the training dataset)
a validation dataset : the remaining 20% of the training dataset that will be used to validate model performences at each epoch
the test dataset (optional here) : it is provided by kaggle to make prediction subission
train = df[~df['target'].isna()]X_train, X_val, y_train, y_val = train_test_split(train, train['target'], test_size=0.2, random_state=42)
As mentioned before, machine learning algorithms take numbers as inputs, not text, which means that we need to convert the texts into numerical vectors.We proceed as follows:
It consists in dividing the texts into words or smaller sub-texts, allowing us to determine the “vocabulary” of the dataset (set of unique tokens present in the data). Usually we use word-level representation. For our exemple we will use NLTK Tokenizer()
Construct a vocablary_index mapper based on word frequency: the index would be inversely proportional to the word occurrence frequency in the overall dataset. the most frequent world would have index=1.. And every single word would get a unique index.
These two steps are factorized as follows:
Some explanation about NLTK tokenizer:
fit_on_texts() method 🤖: it creates a vocabulary index based on word frequency. Example :“the ghost in the shell” would generate word_index[“the”] = 1; word_index[“ghost”] = 2.. -> So every word gets a unique integer value. Starting from 1 (0 is reserved for padding) and the more frequent is the word, the lower the corresponding index gets. (PS often the first few are stop words because they appear a lot but it is recommended to drop them during the data cleaning).textes_to_sequences() method📟: Transforms each text to a sequence of integers: each word is mapped to its index from the word_index dictionary.pad_sequences() method 🎞: in order to make standard the output’s shape, we define a unique vector length (in our example MAX_SEQUENCE_LENGTH is fixed it to 50) : Any longer sequence will be truncated and any shorter sequence will be 0-padded.
fit_on_texts() method 🤖: it creates a vocabulary index based on word frequency. Example :“the ghost in the shell” would generate word_index[“the”] = 1; word_index[“ghost”] = 2.. -> So every word gets a unique integer value. Starting from 1 (0 is reserved for padding) and the more frequent is the word, the lower the corresponding index gets. (PS often the first few are stop words because they appear a lot but it is recommended to drop them during the data cleaning).
textes_to_sequences() method📟: Transforms each text to a sequence of integers: each word is mapped to its index from the word_index dictionary.
pad_sequences() method 🎞: in order to make standard the output’s shape, we define a unique vector length (in our example MAX_SEQUENCE_LENGTH is fixed it to 50) : Any longer sequence will be truncated and any shorter sequence will be 0-padded.
First of we will download Glove pre-trained embedding from the official site, (because of some technical constraints I had to download it via a code :
Then we will create an embedding matrix that maps each word index to its corresponding embedding vector:
We will create a recurrent neural network using a Sequential keras model that will contain:
An Embedding layer with the embedding matrix as initial weightA dropout layer to avoid over-fitting (check out this excellent post about dropout layers in neural networks and their utilities)An LSTM layer : including long short term memory cellsAn activation layer using the binary_crossentropy loss function
An Embedding layer with the embedding matrix as initial weight
A dropout layer to avoid over-fitting (check out this excellent post about dropout layers in neural networks and their utilities)
An LSTM layer : including long short term memory cells
An activation layer using the binary_crossentropy loss function
If we want to compute, in addition to the accuracy, the precision, recall and F1-score for our binary Keras Classifier model, we have to calculate them manually, because these metrics are not supported by keras since 2.0 version.
(solution from here)
Now compile and train the model:
To get the validation performances results, use the evaluate() method:
loss, accuracy, f1_score, precision, recall = model.evaluate(tokenized_val, y_val, verbose=0)
Lets checkout the results:
These results seems to be pretty good but of course it can be enhanced by fine-tuning the neural network hyper-parameters, or by using auto-ml tools such as prevision, which apply many other transformations, in addition to the wor2vec, such as ngram tokenization, tf-idf or more advanced technics such as BERT transformers.
In this post I showed you, step by step, how to apply wor2vec transformation from Glove pre-trained word embedding, and how to use it to train a recurrent neural network. Please note that the approach and the code can be reused in other similar use cases. The overall source code can be found in this kaggle notebook.I also applied on the same dataset a complete different approach : I used tf-idf naive Bayes classifiers, if you want to get more information visit my last post.
I am intending to write a post about how to use a breakthrough algorithm called Bert and compare it with other NLP algorithms
Thanks for reading my post 🤗!! If you have any question you can find me at the chat session in prevision cloud instance or send me an email to : [email protected]
|
[
{
"code": null,
"e": 750,
"s": 172,
"text": "In this post we will go through the overall text classification pipeline, and especially the data pre-processing steps, we will be using a Glove pre-trained word embedding. Textual features processing is a little bit more tricky than linear or categorical features. In fact, machine learning algorithms are more about scalars and vectors rather than characters or words. So we have to convert the text input into scalars, and the keystone 🗝 element consists in how to find out the best representation of the input words. This is the main idea behind Natural Language Processing"
},
{
"code": null,
"e": 1223,
"s": 750,
"text": "We will use a dataset from a Kaggle competition called Real or Not? NLP with Disaster Tweets. The task consists in predicting whether or not a given tweet is about a real disaster. To address this text classification task we will use word embedding transformation followed by a recurrent deep learning model. Other less sophisticated solutions, but still efficient, are also possible such as combining tf-idf encoding and a naive Bayes classifier (check out my last post)."
},
{
"code": null,
"e": 1372,
"s": 1223,
"text": "Also I will include some handy Python code that can be reproduced in other NLP tasks. The overall source code is accessible in this kaggle notebook."
},
{
"code": null,
"e": 1602,
"s": 1372,
"text": "Models such as LSTM or CNN are more efficient to capture the words order and the semantic relationship between them, which usually is critical to the text’s meaning : a sample from our dataset that is labelled as a real disaster:"
},
{
"code": null,
"e": 1715,
"s": 1602,
"text": "'#RockyFire Update => California Hwy. 20 closed in both directions due to Lake County fire - #CAfire #wildfires'"
},
{
"code": null,
"e": 1786,
"s": 1715,
"text": "It is obvious that the words order was important in the example above."
},
{
"code": null,
"e": 1897,
"s": 1786,
"text": "In the other hand, we need to convert input text to a machine readable format. It exists many technics such as"
},
{
"code": null,
"e": 2226,
"s": 1897,
"text": "one-hot encoding: each sequence text input is represented in d- dimensional space where d is size of the dataset vocabulary. Each term would get 1 if it is present in the document 0 otherwise. with a large corpus, the vocabulary would be about tens of thousands of tokens, making the one-hot vectors very sparse and inefficient."
},
{
"code": null,
"e": 2460,
"s": 2226,
"text": "TF-IDF encoding: words are mapped to numerics generated using tf-idf metric. The platform has integrated fast algorithms making it possible to keep all uni-grams and bi-grams tf-idf encoding without having to apply dimension reducing"
},
{
"code": null,
"e": 2610,
"s": 2460,
"text": "Word embedding transformation : words are projected to a dense vector space, where semantic distance between words are preserved: (see Figure below):"
},
{
"code": null,
"e": 2647,
"s": 2610,
"text": "What is pre-trained Word Embeddings?"
},
{
"code": null,
"e": 3067,
"s": 2647,
"text": "An embedding is a dense vector that represents a word (or a symbol). By default, the embedding vectors are randomly initialized, then will gradually be improved during the training phase, with the gradient descent algorithm at each back-propagation step, so that similar words or words in the same lexical field or with common stem ... will end up close in terms of distance in the new vector space; (see figure below):"
},
{
"code": null,
"e": 3450,
"s": 3067,
"text": "Pre-trained word embedding is an example of Transfer Learning. The main idea behind it is to use public embeddings that are already trained on large datasets. Specifically, instead of initializing our neural network weights randomly, we will set these pre trained embeddings as initialization weights. This trick helps to accelerate training and boost the performance of NLP models."
},
{
"code": null,
"e": 3561,
"s": 3450,
"text": "Before all, let’s import the required libraries and tools that will help us perform the NLP processing and the"
},
{
"code": null,
"e": 4238,
"s": 3561,
"text": "import pandas as pdimport numpy as npfrom nltk.corpus import stopwordsfrom nltk.util import ngramsfrom sklearn.feature_extraction.text import CountVectorizerfrom collections import defaultdictfrom collections import Counterstop=set(stopwords.words('english'))import refrom nltk.tokenize import word_tokenizeimport gensimimport stringfrom keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequencesfrom tqdm import tqdmfrom keras.models import Sequentialfrom keras.layers import Embedding,LSTM,Dense,SpatialDropout1Dfrom keras.initializers import Constantfrom sklearn.model_selection import train_test_splitfrom keras.optimizers import Adam"
},
{
"code": null,
"e": 4500,
"s": 4238,
"text": "Regardless of the EDA step that can bring out the uncleaned elements and help us to customize the cleaning code, we can apply some basic data cleaning that are recurrent in tweeters such as removing punctuation, html tags urls and emojis, spelling correction,.."
},
{
"code": null,
"e": 4575,
"s": 4500,
"text": "Below a python code that can be be reproduced in other similar use cases 😉"
},
{
"code": null,
"e": 4611,
"s": 4575,
"text": "Then we will split the datset into:"
},
{
"code": null,
"e": 4660,
"s": 4611,
"text": "a training dataset (80% of the training dataset)"
},
{
"code": null,
"e": 4788,
"s": 4660,
"text": "a validation dataset : the remaining 20% of the training dataset that will be used to validate model performences at each epoch"
},
{
"code": null,
"e": 4877,
"s": 4788,
"text": "the test dataset (optional here) : it is provided by kaggle to make prediction subission"
},
{
"code": null,
"e": 5015,
"s": 4877,
"text": "train = df[~df['target'].isna()]X_train, X_val, y_train, y_val = train_test_split(train, train['target'], test_size=0.2, random_state=42)"
},
{
"code": null,
"e": 5190,
"s": 5015,
"text": "As mentioned before, machine learning algorithms take numbers as inputs, not text, which means that we need to convert the texts into numerical vectors.We proceed as follows:"
},
{
"code": null,
"e": 5445,
"s": 5190,
"text": "It consists in dividing the texts into words or smaller sub-texts, allowing us to determine the “vocabulary” of the dataset (set of unique tokens present in the data). Usually we use word-level representation. For our exemple we will use NLTK Tokenizer()"
},
{
"code": null,
"e": 5697,
"s": 5445,
"text": "Construct a vocablary_index mapper based on word frequency: the index would be inversely proportional to the word occurrence frequency in the overall dataset. the most frequent world would have index=1.. And every single word would get a unique index."
},
{
"code": null,
"e": 5740,
"s": 5697,
"text": "These two steps are factorized as follows:"
},
{
"code": null,
"e": 5779,
"s": 5740,
"text": "Some explanation about NLTK tokenizer:"
},
{
"code": null,
"e": 6634,
"s": 5779,
"text": "fit_on_texts() method 🤖: it creates a vocabulary index based on word frequency. Example :“the ghost in the shell” would generate word_index[“the”] = 1; word_index[“ghost”] = 2.. -> So every word gets a unique integer value. Starting from 1 (0 is reserved for padding) and the more frequent is the word, the lower the corresponding index gets. (PS often the first few are stop words because they appear a lot but it is recommended to drop them during the data cleaning).textes_to_sequences() method📟: Transforms each text to a sequence of integers: each word is mapped to its index from the word_index dictionary.pad_sequences() method 🎞: in order to make standard the output’s shape, we define a unique vector length (in our example MAX_SEQUENCE_LENGTH is fixed it to 50) : Any longer sequence will be truncated and any shorter sequence will be 0-padded."
},
{
"code": null,
"e": 7104,
"s": 6634,
"text": "fit_on_texts() method 🤖: it creates a vocabulary index based on word frequency. Example :“the ghost in the shell” would generate word_index[“the”] = 1; word_index[“ghost”] = 2.. -> So every word gets a unique integer value. Starting from 1 (0 is reserved for padding) and the more frequent is the word, the lower the corresponding index gets. (PS often the first few are stop words because they appear a lot but it is recommended to drop them during the data cleaning)."
},
{
"code": null,
"e": 7248,
"s": 7104,
"text": "textes_to_sequences() method📟: Transforms each text to a sequence of integers: each word is mapped to its index from the word_index dictionary."
},
{
"code": null,
"e": 7491,
"s": 7248,
"text": "pad_sequences() method 🎞: in order to make standard the output’s shape, we define a unique vector length (in our example MAX_SEQUENCE_LENGTH is fixed it to 50) : Any longer sequence will be truncated and any shorter sequence will be 0-padded."
},
{
"code": null,
"e": 7642,
"s": 7491,
"text": "First of we will download Glove pre-trained embedding from the official site, (because of some technical constraints I had to download it via a code :"
},
{
"code": null,
"e": 7747,
"s": 7642,
"text": "Then we will create an embedding matrix that maps each word index to its corresponding embedding vector:"
},
{
"code": null,
"e": 7839,
"s": 7747,
"text": "We will create a recurrent neural network using a Sequential keras model that will contain:"
},
{
"code": null,
"e": 8148,
"s": 7839,
"text": "An Embedding layer with the embedding matrix as initial weightA dropout layer to avoid over-fitting (check out this excellent post about dropout layers in neural networks and their utilities)An LSTM layer : including long short term memory cellsAn activation layer using the binary_crossentropy loss function"
},
{
"code": null,
"e": 8211,
"s": 8148,
"text": "An Embedding layer with the embedding matrix as initial weight"
},
{
"code": null,
"e": 8341,
"s": 8211,
"text": "A dropout layer to avoid over-fitting (check out this excellent post about dropout layers in neural networks and their utilities)"
},
{
"code": null,
"e": 8396,
"s": 8341,
"text": "An LSTM layer : including long short term memory cells"
},
{
"code": null,
"e": 8460,
"s": 8396,
"text": "An activation layer using the binary_crossentropy loss function"
},
{
"code": null,
"e": 8690,
"s": 8460,
"text": "If we want to compute, in addition to the accuracy, the precision, recall and F1-score for our binary Keras Classifier model, we have to calculate them manually, because these metrics are not supported by keras since 2.0 version."
},
{
"code": null,
"e": 8711,
"s": 8690,
"text": "(solution from here)"
},
{
"code": null,
"e": 8744,
"s": 8711,
"text": "Now compile and train the model:"
},
{
"code": null,
"e": 8815,
"s": 8744,
"text": "To get the validation performances results, use the evaluate() method:"
},
{
"code": null,
"e": 8909,
"s": 8815,
"text": "loss, accuracy, f1_score, precision, recall = model.evaluate(tokenized_val, y_val, verbose=0)"
},
{
"code": null,
"e": 8936,
"s": 8909,
"text": "Lets checkout the results:"
},
{
"code": null,
"e": 9260,
"s": 8936,
"text": "These results seems to be pretty good but of course it can be enhanced by fine-tuning the neural network hyper-parameters, or by using auto-ml tools such as prevision, which apply many other transformations, in addition to the wor2vec, such as ngram tokenization, tf-idf or more advanced technics such as BERT transformers."
},
{
"code": null,
"e": 9739,
"s": 9260,
"text": "In this post I showed you, step by step, how to apply wor2vec transformation from Glove pre-trained word embedding, and how to use it to train a recurrent neural network. Please note that the approach and the code can be reused in other similar use cases. The overall source code can be found in this kaggle notebook.I also applied on the same dataset a complete different approach : I used tf-idf naive Bayes classifiers, if you want to get more information visit my last post."
},
{
"code": null,
"e": 9865,
"s": 9739,
"text": "I am intending to write a post about how to use a breakthrough algorithm called Bert and compare it with other NLP algorithms"
}
] |
Python program to sort a list according to the second element in the sublist.
|
List is given, our task is to sort a list according to the second element in the sublist. Here we apply simple bubble sort.
Input : [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]]
Output : [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
Step 1: Given a list.
Step 2: We have tried to access the second element of the sublists using the nested loops.
Step 3: Traverse through all array elements.
Step 4: Last i elements are already in place.
Step 5: traverse the array from 0 to n-i-1.
Step 6: Swap if the element found is greater than the next element.
# Python program to sort the lists using the second element of sublist
# In place way to sort, use of third variable.
def sortlist(A):
l = len(A)
for i in range(0, l):
for j in range(0, l-i-1):
if (A[j][1] > A[j + 1][1]):
tempo = A[j]
A[j]= A[j + 1]
A[j + 1]= tempo
return A
# Driver Code
A = [['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]]
print(sortlist(A))
[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "List is given, our task is to sort a list according to the second element in the sublist. Here we apply simple bubble sort."
},
{
"code": null,
"e": 1312,
"s": 1186,
"text": "Input : [['CCC', 15], ['AAA', 10], ['RRRR', 2],['XXXX', 150]]\nOutput : [['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]"
},
{
"code": null,
"e": 1628,
"s": 1312,
"text": "Step 1: Given a list.\nStep 2: We have tried to access the second element of the sublists using the nested loops.\nStep 3: Traverse through all array elements.\nStep 4: Last i elements are already in place.\nStep 5: traverse the array from 0 to n-i-1.\nStep 6: Swap if the element found is greater than the next element."
},
{
"code": null,
"e": 2035,
"s": 1628,
"text": "# Python program to sort the lists using the second element of sublist\n# In place way to sort, use of third variable.\ndef sortlist(A):\n l = len(A)\n for i in range(0, l):\n for j in range(0, l-i-1):\n if (A[j][1] > A[j + 1][1]):\n tempo = A[j]\n A[j]= A[j + 1]\n A[j + 1]= tempo\n return A\n\n # Driver Code\nA = [['AAA', 10], ['CCC', 15], ['RRRR', 2], ['XXXX', 150]]\nprint(sortlist(A))"
},
{
"code": null,
"e": 2090,
"s": 2035,
"text": "[['RRRR', 2], ['AAA', 10], ['CCC', 15], ['XXXX', 150]]"
}
] |
Sort and Reverse Vector | Practice | GeeksforGeeks
|
You are given a vector V of size n. You need to sort it and reverse it.
Example 1:
Input:
n = 5
V = 1 2 3 4 5
Output:
1 2 3 4 5
5 4 3 2 1
Your Task:
Since this is a function problem, you don't need to take any input. Just complete the provided functions sortVector() and reverseVector(). Return the vector after performing suitable operations.
Constraints:
1 <= n <= 107
0 <= Vi <= 107
0
mayank180919991 week ago
vector<int> sortVector(vector<int>v)
{
//Your code here. Use library function
sort(v.begin(),v.end());
return v;
}
vector<int> reverseVector(vector<int>v)
{
//Your code here. Use library function
sort(v.rbegin(),v.rend());
return v;
}
0
akash119027401 month ago
vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}
0
bickyjha0553 months ago
vector<int> sortVector(vector<int>v){ sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //both are correct use one sort(v.begin(),v.end(), greater<int> ()); // reverse(v.begin(), v.end()) ; return v;}
+1
gaurlakshya24265 months ago
C++ Solution →
vector<int> sortVector(vector<int>v)
{
//Your code here. Use library function
sort(v.begin(),v.end());
return v;
}
vector<int> reverseVector(vector<int>v)
{
//Your code here. Use library function
reverse(v.begin(),v.end());
return v;
}
0
vs6968716 months ago
why this code not submit ??
whats wrong??
vector<int> reverseVector(vector<int>v){ sort(v.begin() , v.end()); reverse(v.begin(), v.end()); return v;}
0
Dhruv Mishra_18267 months ago
Dhruv Mishra_1826
vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}
0
Shapnesh Singh Tiwari8 months ago
Shapnesh Singh Tiwari
https://youtu.be/7_FRLQoP26c
0
Purushottam Bca9 months ago
Purushottam Bca
CORRECT ANSWER
vector<int> sortVector(vector<int>v){ sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ sort(v.begin(),v.end(), greater<int>()); return v;}
0
ArBoss
This comment was deleted.
0
Manikanth Kr1 year ago
Manikanth Kr
c++ code:vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}
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": 298,
"s": 226,
"text": "You are given a vector V of size n. You need to sort it and reverse it."
},
{
"code": null,
"e": 310,
"s": 298,
"text": "Example 1: "
},
{
"code": null,
"e": 367,
"s": 310,
"text": "Input:\nn = 5\nV = 1 2 3 4 5\nOutput: \n1 2 3 4 5\n5 4 3 2 1\n"
},
{
"code": null,
"e": 573,
"s": 367,
"text": "Your Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided functions sortVector() and reverseVector(). Return the vector after performing suitable operations."
},
{
"code": null,
"e": 615,
"s": 573,
"text": "Constraints:\n1 <= n <= 107\n0 <= Vi <= 107"
},
{
"code": null,
"e": 617,
"s": 615,
"text": "0"
},
{
"code": null,
"e": 642,
"s": 617,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 901,
"s": 642,
"text": "vector<int> sortVector(vector<int>v)\n{\n //Your code here. Use library function\n sort(v.begin(),v.end());\n return v;\n}\nvector<int> reverseVector(vector<int>v)\n{\n //Your code here. Use library function\n sort(v.rbegin(),v.rend());\n return v;\n}"
},
{
"code": null,
"e": 903,
"s": 901,
"text": "0"
},
{
"code": null,
"e": 928,
"s": 903,
"text": "akash119027401 month ago"
},
{
"code": null,
"e": 1171,
"s": 928,
"text": "vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}"
},
{
"code": null,
"e": 1173,
"s": 1171,
"text": "0"
},
{
"code": null,
"e": 1197,
"s": 1173,
"text": "bickyjha0553 months ago"
},
{
"code": null,
"e": 1442,
"s": 1197,
"text": "vector<int> sortVector(vector<int>v){ sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //both are correct use one sort(v.begin(),v.end(), greater<int> ()); // reverse(v.begin(), v.end()) ; return v;}"
},
{
"code": null,
"e": 1445,
"s": 1442,
"text": "+1"
},
{
"code": null,
"e": 1473,
"s": 1445,
"text": "gaurlakshya24265 months ago"
},
{
"code": null,
"e": 1488,
"s": 1473,
"text": "C++ Solution →"
},
{
"code": null,
"e": 1750,
"s": 1488,
"text": "vector<int> sortVector(vector<int>v)\n{\n //Your code here. Use library function\n sort(v.begin(),v.end());\n \n return v;\n}\nvector<int> reverseVector(vector<int>v)\n{\n //Your code here. Use library function\n reverse(v.begin(),v.end());\n return v;\n}"
},
{
"code": null,
"e": 1752,
"s": 1750,
"text": "0"
},
{
"code": null,
"e": 1773,
"s": 1752,
"text": "vs6968716 months ago"
},
{
"code": null,
"e": 1801,
"s": 1773,
"text": "why this code not submit ??"
},
{
"code": null,
"e": 1815,
"s": 1801,
"text": "whats wrong??"
},
{
"code": null,
"e": 1933,
"s": 1819,
"text": "vector<int> reverseVector(vector<int>v){ sort(v.begin() , v.end()); reverse(v.begin(), v.end()); return v;}"
},
{
"code": null,
"e": 1935,
"s": 1933,
"text": "0"
},
{
"code": null,
"e": 1965,
"s": 1935,
"text": "Dhruv Mishra_18267 months ago"
},
{
"code": null,
"e": 1983,
"s": 1965,
"text": "Dhruv Mishra_1826"
},
{
"code": null,
"e": 2232,
"s": 1983,
"text": "vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}"
},
{
"code": null,
"e": 2234,
"s": 2232,
"text": "0"
},
{
"code": null,
"e": 2268,
"s": 2234,
"text": "Shapnesh Singh Tiwari8 months ago"
},
{
"code": null,
"e": 2290,
"s": 2268,
"text": "Shapnesh Singh Tiwari"
},
{
"code": null,
"e": 2319,
"s": 2290,
"text": "https://youtu.be/7_FRLQoP26c"
},
{
"code": null,
"e": 2321,
"s": 2319,
"text": "0"
},
{
"code": null,
"e": 2349,
"s": 2321,
"text": "Purushottam Bca9 months ago"
},
{
"code": null,
"e": 2365,
"s": 2349,
"text": "Purushottam Bca"
},
{
"code": null,
"e": 2382,
"s": 2365,
"text": "CORRECT ANSWER "
},
{
"code": null,
"e": 2562,
"s": 2382,
"text": " vector<int> sortVector(vector<int>v){ sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ sort(v.begin(),v.end(), greater<int>()); return v;}"
},
{
"code": null,
"e": 2564,
"s": 2562,
"text": "0"
},
{
"code": null,
"e": 2571,
"s": 2564,
"text": "ArBoss"
},
{
"code": null,
"e": 2597,
"s": 2571,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2599,
"s": 2597,
"text": "0"
},
{
"code": null,
"e": 2622,
"s": 2599,
"text": "Manikanth Kr1 year ago"
},
{
"code": null,
"e": 2635,
"s": 2622,
"text": "Manikanth Kr"
},
{
"code": null,
"e": 2893,
"s": 2635,
"text": "c++ code:vector<int> sortVector(vector<int>v){ //Your code here. Use library function sort(v.begin(),v.end()); return v;}vector<int> reverseVector(vector<int>v){ //Your code here. Use library function reverse(v.begin(),v.end()); return v;}"
},
{
"code": null,
"e": 3039,
"s": 2893,
"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": 3075,
"s": 3039,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3085,
"s": 3075,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3095,
"s": 3085,
"text": "\nContest\n"
},
{
"code": null,
"e": 3158,
"s": 3095,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3306,
"s": 3158,
"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": 3514,
"s": 3306,
"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": 3620,
"s": 3514,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Lagrange Interpolation
|
For constructing new data points within a range of a discrete set of given data point, the interpolation technique is used. Lagrange interpolation technique is one of them. When the given data points are not evenly distributed, we can use this interpolation method to find the solution. For the Lagrange interpolation, we have to follow this equation.
Input:
List of x and f(x) values. find f(3.25)
x: {0,1,2,3,4,5,6}
f(x): {0,1,8,27,64,125,216}
Output:
Result after Lagrange interpolation f(3.25) = 34.3281
largrangeInterpolation(x: array, fx: array, x1)
Input − x array and fx array for getting previously known data, and point x1.
Output: The value of f(x1).
Begin
res := 0 and tempSum := 0
for i := 1 to n, do
tempProd := 1
for j := 1 to n, do
if i ≠ j, then
tempProf := tempProd * (x1 – x[j])/(x[i] – x[j])
done
tempPord := tempProd * fx[i]
res := res + tempProd
done
return res
End
#include<iostream>
#define N 6
using namespace std;
double lagrange(double x[], double fx[], double x1) {
double res = 0, tempSum = 0;
for(int i = 1; i<=N; i++) {
double tempProd = 1; //for each iteration initialize temp product
for(int j = 1; j<=N; j++) {
if(i != j) { //if i = j, then denominator will be 0
tempProd *= (x1 - x[j])/(x[i] - x[j]); //multiply each term using formula
}
}
tempProd *= fx[i]; //multiply f(xi)
res += tempProd;
}
return res;
}
main() {
double x[N+1] = {0,1,2,3,4,5,6};
double y[N+1] = {0,1,8,27,64,125,216};
double x1 = 3.25;
cout << "Result after lagrange interpolation f("<<x1<<") = " << lagrange(x, y, x1);
}
Result after lagrange interpolation f(3.25) = 34.3281
|
[
{
"code": null,
"e": 1414,
"s": 1062,
"text": "For constructing new data points within a range of a discrete set of given data point, the interpolation technique is used. Lagrange interpolation technique is one of them. When the given data points are not evenly distributed, we can use this interpolation method to find the solution. For the Lagrange interpolation, we have to follow this equation."
},
{
"code": null,
"e": 1570,
"s": 1414,
"text": "Input:\nList of x and f(x) values. find f(3.25)\nx: {0,1,2,3,4,5,6}\nf(x): {0,1,8,27,64,125,216}\nOutput:\nResult after Lagrange interpolation f(3.25) = 34.3281"
},
{
"code": null,
"e": 1618,
"s": 1570,
"text": "largrangeInterpolation(x: array, fx: array, x1)"
},
{
"code": null,
"e": 1696,
"s": 1618,
"text": "Input − x array and fx array for getting previously known data, and point x1."
},
{
"code": null,
"e": 1724,
"s": 1696,
"text": "Output: The value of f(x1)."
},
{
"code": null,
"e": 2015,
"s": 1724,
"text": "Begin\n res := 0 and tempSum := 0\n for i := 1 to n, do\n tempProd := 1\n for j := 1 to n, do\n if i ≠ j, then\n tempProf := tempProd * (x1 – x[j])/(x[i] – x[j])\n done\n\n tempPord := tempProd * fx[i]\n res := res + tempProd\n done\n return res\nEnd"
},
{
"code": null,
"e": 2786,
"s": 2015,
"text": "#include<iostream>\n#define N 6\nusing namespace std;\n\ndouble lagrange(double x[], double fx[], double x1) {\n double res = 0, tempSum = 0;\n\n for(int i = 1; i<=N; i++) {\n double tempProd = 1; //for each iteration initialize temp product\n for(int j = 1; j<=N; j++) {\n if(i != j) { //if i = j, then denominator will be 0\n tempProd *= (x1 - x[j])/(x[i] - x[j]); //multiply each term using formula\n }\n }\n tempProd *= fx[i]; //multiply f(xi)\n res += tempProd;\n }\n return res;\n}\n\nmain() {\n double x[N+1] = {0,1,2,3,4,5,6};\n double y[N+1] = {0,1,8,27,64,125,216};\n double x1 = 3.25;\n cout << \"Result after lagrange interpolation f(\"<<x1<<\") = \" << lagrange(x, y, x1);\n}"
},
{
"code": null,
"e": 2840,
"s": 2786,
"text": "Result after lagrange interpolation f(3.25) = 34.3281"
}
] |
Delete Tree Nodes in C++
|
Suppose we have a tree, this tree is rooted at node 0, this is given as follows −
Number of nodes is nodesValue of ith node is value[i]Parent of ith node is parent[i]
Number of nodes is nodes
Value of ith node is value[i]
Parent of ith node is parent[i]
We have to remove every subtree whose sum of values of nodes is 0, after doing that return the number of nodes remaining in the tree. So if the tree is like −
There are 7 nodes, the output will be 2
To solve this, we will follow these steps −
Create a map called children
define a method called dfs(), this will take node, an array value and graph
temp := a pair (value[node], 1)
for i in range 0 to size of graph[node]temp2 := dfs(graph[node, i], value, graph)increase first by first of temp2, increase second by second of temp2
temp2 := dfs(graph[node, i], value, graph)
increase first by first of temp2, increase second by second of temp2
if first of temp is 0, then ans := ans – second of temp, set second of temp := 0
return temp
From the main method, it will take nodes, parents array and values array
n := number of values present in values array
ans := n
define an array graph of size n + 1
for i in range 1 to n – 1insert i into graph[parent[i]]
insert i into graph[parent[i]]
dfs(0, value, graph)
return ans
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
map <int, int> children;
int ans;
pair <int, int> dfs(int node, vector<int>& value, vector <int> graph[]){
pair <int, int> temp = {value[node], 1};
for(int i = 0; i < graph[node].size(); i++){
pair <int, int> temp2 = dfs(graph[node][i], value, graph);
temp.first += temp2.first;
temp.second += temp2.second;
}
if(temp.first == 0){
ans -= temp.second;
temp.second = 0;
}
return temp;
}
int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {
int n = value.size();
ans = n;
children.clear();
vector < int > graph[n + 1];
for(int i = 1; i < n; i++){
graph[parent[i]].push_back(i);
}
dfs(0, value, graph);
return ans;
}
};
main(){
vector<int> v1 = {-1,0,0,1,2,2,2};
vector<int> v2 = {1,-2,4,0,-2,-1,-1};
Solution ob;
cout << (ob.deleteTreeNodes(7,v1, v2));
}
7
[-1,0,0,1,2,2,2]
[1,-2,4,0,-2,-1,-1]
2
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Suppose we have a tree, this tree is rooted at node 0, this is given as follows −"
},
{
"code": null,
"e": 1229,
"s": 1144,
"text": "Number of nodes is nodesValue of ith node is value[i]Parent of ith node is parent[i]"
},
{
"code": null,
"e": 1254,
"s": 1229,
"text": "Number of nodes is nodes"
},
{
"code": null,
"e": 1284,
"s": 1254,
"text": "Value of ith node is value[i]"
},
{
"code": null,
"e": 1316,
"s": 1284,
"text": "Parent of ith node is parent[i]"
},
{
"code": null,
"e": 1475,
"s": 1316,
"text": "We have to remove every subtree whose sum of values of nodes is 0, after doing that return the number of nodes remaining in the tree. So if the tree is like −"
},
{
"code": null,
"e": 1515,
"s": 1475,
"text": "There are 7 nodes, the output will be 2"
},
{
"code": null,
"e": 1559,
"s": 1515,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1588,
"s": 1559,
"text": "Create a map called children"
},
{
"code": null,
"e": 1664,
"s": 1588,
"text": "define a method called dfs(), this will take node, an array value and graph"
},
{
"code": null,
"e": 1696,
"s": 1664,
"text": "temp := a pair (value[node], 1)"
},
{
"code": null,
"e": 1846,
"s": 1696,
"text": "for i in range 0 to size of graph[node]temp2 := dfs(graph[node, i], value, graph)increase first by first of temp2, increase second by second of temp2"
},
{
"code": null,
"e": 1889,
"s": 1846,
"text": "temp2 := dfs(graph[node, i], value, graph)"
},
{
"code": null,
"e": 1958,
"s": 1889,
"text": "increase first by first of temp2, increase second by second of temp2"
},
{
"code": null,
"e": 2039,
"s": 1958,
"text": "if first of temp is 0, then ans := ans – second of temp, set second of temp := 0"
},
{
"code": null,
"e": 2051,
"s": 2039,
"text": "return temp"
},
{
"code": null,
"e": 2124,
"s": 2051,
"text": "From the main method, it will take nodes, parents array and values array"
},
{
"code": null,
"e": 2170,
"s": 2124,
"text": "n := number of values present in values array"
},
{
"code": null,
"e": 2179,
"s": 2170,
"text": "ans := n"
},
{
"code": null,
"e": 2215,
"s": 2179,
"text": "define an array graph of size n + 1"
},
{
"code": null,
"e": 2271,
"s": 2215,
"text": "for i in range 1 to n – 1insert i into graph[parent[i]]"
},
{
"code": null,
"e": 2302,
"s": 2271,
"text": "insert i into graph[parent[i]]"
},
{
"code": null,
"e": 2323,
"s": 2302,
"text": "dfs(0, value, graph)"
},
{
"code": null,
"e": 2334,
"s": 2323,
"text": "return ans"
},
{
"code": null,
"e": 2406,
"s": 2334,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2417,
"s": 2406,
"text": " Live Demo"
},
{
"code": null,
"e": 3429,
"s": 2417,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n map <int, int> children;\n int ans;\n pair <int, int> dfs(int node, vector<int>& value, vector <int> graph[]){\n pair <int, int> temp = {value[node], 1};\n for(int i = 0; i < graph[node].size(); i++){\n pair <int, int> temp2 = dfs(graph[node][i], value, graph);\n temp.first += temp2.first;\n temp.second += temp2.second;\n }\n if(temp.first == 0){\n ans -= temp.second;\n temp.second = 0;\n }\n return temp;\n }\n int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {\n int n = value.size();\n ans = n;\n children.clear();\n vector < int > graph[n + 1];\n for(int i = 1; i < n; i++){\n graph[parent[i]].push_back(i);\n }\n dfs(0, value, graph);\n return ans;\n }\n};\nmain(){\n vector<int> v1 = {-1,0,0,1,2,2,2};\n vector<int> v2 = {1,-2,4,0,-2,-1,-1};\n Solution ob;\n cout << (ob.deleteTreeNodes(7,v1, v2));\n}"
},
{
"code": null,
"e": 3468,
"s": 3429,
"text": "7\n[-1,0,0,1,2,2,2]\n[1,-2,4,0,-2,-1,-1]"
},
{
"code": null,
"e": 3470,
"s": 3468,
"text": "2"
}
] |
Bitwise Operators in C++
|
There are 3 bitwise operators available in c++. These are the bitwise AND(&), bitwise OR(|) and the bitwise XOR(^).
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive AND operator must be of integral types. For example,
#include <iostream>
using namespace std;
int main() {
unsigned short a = 0x5555; // pattern 0101 ...
unsigned short b = 0xAAAA; // pattern 1010 ...
cout << hex << ( a & b ) << endl;
}
This gives the output −
0
The bitwise OR operator (|) compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive OR operator must be of integral types. For example,
#include <iostream>
using namespace std;
int main() {
unsigned short a = 0x5555; // pattern 0101 ...
unsigned short b = 0xAAAA; // pattern 1010 ...
cout << hex << ( a | b ) << endl;
}
This gives the output −
ffff
The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise exclusive OR operator must be of integral types. For example,
#include <iostream>
using namespace std;
int main() {
short a = 0x5555; // pattern 0101 ...
unsigned short b = 0xFFFF; // pattern 1111 ...
cout << hex << ( a ^ b ) << endl;
}
This gives the output −
aaaa
Which represents the pattern 1010...
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "There are 3 bitwise operators available in c++. These are the bitwise AND(&), bitwise OR(|) and the bitwise XOR(^)."
},
{
"code": null,
"e": 1501,
"s": 1178,
"text": "The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive AND operator must be of integral types. For example,"
},
{
"code": null,
"e": 1714,
"s": 1501,
"text": "#include <iostream> \nusing namespace std; \nint main() { \n unsigned short a = 0x5555; // pattern 0101 ... \n unsigned short b = 0xAAAA; // pattern 1010 ... \n cout << hex << ( a & b ) << endl;\n}"
},
{
"code": null,
"e": 1738,
"s": 1714,
"text": "This gives the output −"
},
{
"code": null,
"e": 1740,
"s": 1738,
"text": "0"
},
{
"code": null,
"e": 2061,
"s": 1740,
"text": "The bitwise OR operator (|) compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive OR operator must be of integral types. For example,"
},
{
"code": null,
"e": 2274,
"s": 2061,
"text": "#include <iostream> \nusing namespace std; \nint main() { \n unsigned short a = 0x5555; // pattern 0101 ... \n unsigned short b = 0xAAAA; // pattern 1010 ... \n cout << hex << ( a | b ) << endl;\n}"
},
{
"code": null,
"e": 2298,
"s": 2274,
"text": "This gives the output −"
},
{
"code": null,
"e": 2303,
"s": 2298,
"text": "ffff"
},
{
"code": null,
"e": 2654,
"s": 2303,
"text": "The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise exclusive OR operator must be of integral types. For example,"
},
{
"code": null,
"e": 2859,
"s": 2654,
"text": "#include <iostream> \nusing namespace std; \nint main() { \n short a = 0x5555; // pattern 0101 ... \n unsigned short b = 0xFFFF; // pattern 1111 ... \n cout << hex << ( a ^ b ) << endl;\n}"
},
{
"code": null,
"e": 2883,
"s": 2859,
"text": "This gives the output −"
},
{
"code": null,
"e": 2888,
"s": 2883,
"text": "aaaa"
},
{
"code": null,
"e": 2925,
"s": 2888,
"text": "Which represents the pattern 1010..."
}
] |
SVM (Support Vector Machine) for classification | by Aditya Kumar | Towards Data Science
|
SVM: Support Vector Machine is a supervised classification algorithm where we draw a line between two different categories to differentiate between them. SVM is also known as the support vector network.
Consider an example where we have cats and dogs together.
We want our model to differentiate between cats and dogs.
There are many cases where the differentiation is not so simple as shown above. In that case, the hyperplane dimension needs to be changed from 1 dimension to the Nth dimension. This is called Kernel. To be more simple, its the functional relationship between the two observations. It will add more dimensions to the data so we can easily differentiate among them.
We can have three types of kernels.
Linear KernelsPolynomial KernelsRadial Basis Function Kernel
Linear Kernels
Polynomial Kernels
Radial Basis Function Kernel
In practical life, it’s very difficult to get a straight hyperplane. Consider the image below where the points are mixed together. You cannot separate the points using a straight 2d hyperplane.
Some use cases of SVM:
Face detectionHandwriting detectionImage ClassificationsText and Hypertext Categorization
Face detection
Handwriting detection
Image Classifications
Text and Hypertext Categorization
let’s check how SVM works for regression.
import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinepath = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/automobileEDA.csv'df = pd.read_csv(path)df.head()
df.head() will give us the details of the top 5 rows of every column. We can use df.tail() to get the last 5 rows and similarly df.head(10) to get to the top 10 rows.
The data is about cars and we need to predict the price of cars using the above data
We will be using the Decision Tree to get the price of the car.
df.dtypessymboling int64normalized-losses int64make objectaspiration objectnum-of-doors objectbody-style objectdrive-wheels objectengine-location objectwheel-base float64length float64width float64height float64curb-weight int64engine-type objectnum-of-cylinders objectengine-size int64fuel-system objectbore float64stroke float64compression-ratio float64horsepower float64peak-rpm float64city-mpg int64highway-mpg int64price float64city-L/100km float64horsepower-binned objectdiesel int64gas int64dtype: object
dtypes give the data type of column
df.describe()
In the above data frame, some of the columns are not numeric. So we will consider only those columns whose values are in numeric and will make all numeric to float.
df.dtypesfor x in df: if df[x].dtypes == "int64": df[x] = df[x].astype(float) print (df[x].dtypes)
Out:
float64float64float64float64float64float64float64float64
Preparing the Data As with the classification task, in this section, we will divide our data into attributes and labels and consequently into training and test sets. We will create 2 data sets, one for the price while the other (df-price). Since our data frame has various data in object format, for this analysis we are removing all the columns with object type and for all NaN values, we are removing that row.
df = df.select_dtypes(exclude=['object'])df=df.fillna(df.mean())X = df.drop('price',axis=1)y = df['price']
Here the X variable contains all the columns from the dataset, except the ‘Price’ column, which is the label. The y variable contains values from the ‘Price’ column, which means that the X variable contains the attribute set and y variable contains the corresponding labels.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
Training SVM
from sklearn.svm import SVR
We will create an object svr using the function SVM. We will use the kernel as linear.
svr = SVR(kernel = 'linear',C = 1000)
in order to work in an efficient manner, we will standardize our data.SVM works at a distance of points so it's necessary that all our data should be of the same standard.
from sklearn.preprocessing import StandardScalerX_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)X_test_stdsc= StandardScaler().fit(X_train)
Out:
array([[ 0.17453157, -0.7473421 , -0.70428107, -1.4995245 , -1.05619832, -0.67877552, -1.30249126, -0.87278899, -1.15396095, -0.47648372, -0.09140157, -0.90774727, 0.59090608, 2.00340082, 1.79022864, -1.50033307, -0.29738086, 0.29738086], [-1.42118568, -1.74885637, 0.63398001, 0.14076744, 0.30739662, 0.50614488, -0.1142863 , -0.38613195, -0.24348674, 0.32881569, 3.4734668 , -0.82496629, -1.30634872, 0.73955013, 0.31375141, -0.82735207, 3.36269123, -3.36269123], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.74841125, 0.63584784, 1.38777956, 0.89923611, 3.05894722, -0.2179058 , -2.04417004, -0.05035655, -0.86743037, -0.18802012, 3.36269123, -3.36269123], [-0.62332705, 0.16312543, 0.29517974, 0.64867509, 0.30739662, 0.58786352, 1.09156527, 1.34150055, 0.36349607, 0.06038255, -0.2572094 , 1.35493275, 0.16929391, -1.31420724, -1.31037354, 1.61715245, -0.29738086, 0.29738086], [-1.42118568, -0.01896807, 0.9897203 , 1.15658275, 0.30739662, 0.17927028, 1.20136639, 0.85484351, -0.24348674, 0.32881569, -0.20194012, 1.46530738, 0.16929391, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.51623682, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.49384238, 0.27469695, 0.26560612, 0.46139913, -0.47216765, -0.29738086, 0.29738086], [ 0.9723902 , -0.01896807, 0.19353966, 0.28231547, 0.21335559, -0.22932296, -0.06134647, 0.24652221, -0.54697814, 0.4965864 , -0.39538259, 0.19599908, 0.80171217, -0.99824457, -0.86743037, 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -1.08118019, -0.50100091, -1.26638656, -1.05619832, 0.34270758, -1.08484976, -0.82412328, -1.07808809, -0.74491686, -0.2572094 , -1.12849654, -0.67393045, 1.52945681, 1.19963775, -1.28401775, -0.29738086, 0.29738086], [-0.62332705, 1.98406049, 0.43069985, 0.2406837 , -0.49195214, 0.26098893, 0.44452297, 0.92784206, -0.09174103, -0.20805059, -0.2572094 , 0.49952933, -1.83336395, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [-0.62332705, -0.95978452, -0.50100091, -0.63358358, -0.6800342 , -0.27018228, -0.89661927, -0.67812617, -0.54697814, -0.74491686, -0.2572094 , -0.90774727, -0.67393045, 0.73955013, 0.9043423 , -0.82735207, -0.29738086, 0.29738086], [-0.62332705, -0.2314105 , 0.02413952, 0.32394725, 0.30739662, 0.75130082, -0.22212668, -0.09413772, 0.21175037, 0.46303226, -0.36774795, -0.52143604, -0.67393045, 0.10762479, 0.16610369, -0.33555826, -0.29738086, 0.29738086], [ 1.77024883, -0.01896807, -1.55128176, -0.41709835, -0.39791111, -0.84221282, 0.51314867, 1.65782762, 1.53952526, -1.18112071, -0.11903621, 2.87258398, 1.64493653, -1.31420724, -0.86743037, 1.61715245, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.5378049 , -0.70245902, -1.2298338 , 0.4965864 , 3.61163999, -1.40443312, -0.67393045, 1.84541948, 2.23317181, -1.43212554, 3.36269123, -3.36269123], [-0.62332705, -0.95978452, -0.50100091, -0.63358358, -0.6800342 , -0.27018228, -0.51623682, -0.38613195, -0.24348674, 0.32881569, 3.4734668 , -1.29405849, -1.30634872, 1.37147547, 0.75669458, -1.20342969, 3.36269123, -3.36269123], [ 1.77024883, -0.01896807, -0.46712088, -0.05906508, 0.21335559, -1.41424335, 0.75039751, 0.73317925, 0.97047888, 2.04007695, -0.80990217, 1.16177714, -0.25231827, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -0.01896807, 1.20994048, 1.56457414, 2.61140185, 0.83301947, 0.81510174, 0.24652221, -0.54697814, 0.4965864 , -0.39538259, 0.19599908, 0.80171217, -0.99824457, -0.86743037, 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -0.65629534, -0.83980118, -1.99077944, -0.86811626, -0.43361958, -1.14171105, -0.82412328, -1.60919805, 0.53014054, -0.20194012, -0.74218531, 1.85574262, 0.73955013, 0.46139913, -0.82735207, -0.29738086, 0.29738086], [ 1.77024883, 0.83080162, 0.07495956, 1.05666649, 0.30739662, 0.99645676, 0.33080038, -0.11847057, -3.01284579, -3.96611452, -0.17430548, 0.19599908, 0.27469695, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [-0.62332705, -0.50455075, -0.3654808 , -0.53366732, -0.30387008, -0.14760431, -0.48878654, -0.38613195, -0.69872384, 1.10056096, -0.2572094 , -0.46624873, 1.43413044, 0.26560612, 0.31375141, -0.47216765, -0.29738086, 0.29738086], [ 0.9723902 , 1.16463971, -0.83980118, -1.38295553, -0.6800342 , -1.16908741, -1.16523986, -0.82412328, -1.3815795 , -0.07383402, -0.14667084, -0.96293458, 0.80171217, 0.89753147, 1.05199003, -0.93047013, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.42996451, -0.70245902, -1.2298338 , 0.4965864 , 3.61163999, -0.96293458, -1.30634872, 1.84541948, 1.64258092, -1.43212554, 3.36269123, -3.36269123], [-0.62332705, -1.14187802, -0.29772074, -0.02575966, -0.20982905, 0.50614488, 0.21903853, -0.43479765, 1.08428815, -2.05352841, -0.6164597 , 0.22359274, -0.67393045, -0.36631922, -1.16272582, 0.14554438, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.42962147, 2.13909264, 1.76503258, -0.35190093, 2.99543824, 3.21513015, 1.12222458, 3.08025536, -0.50592114, 2.01718056, -0.7793335 , -1.63016991, -1.75331671, 2.36930768, -0.29738086, 0.29738086], [ 0.17453157, 1.37708213, -0.70428107, -0.43375106, -0.86811626, -0.43361958, -0.72407465, -0.67812617, -0.54697814, -0.74491686, -0.2572094 , -0.90774727, -0.67393045, 0.58156879, 0.46139913, -0.71712242, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 0.02413952, 0.32394725, 0.30739662, 0.75130082, -0.18683347, -0.09413772, 0.21175037, 0.46303226, 3.52873607, -1.07330922, -0.99013959, 1.68743815, 1.64258092, -1.3601287 , 3.36269123, -3.36269123], [ 1.77024883, -0.01896807, -1.55128176, -0.41709835, -0.39791111, -0.84221282, 0.42687636, 1.65782762, 1.53952526, -1.18112071, -0.11903621, 2.87258398, 1.64493653, -1.31420724, -0.86743037, 1.61715245, -0.29738086, 0.29738086], [ 0.9723902 , -0.01896807, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.64564528, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.49384238, 0.27469695, 0.26560612, 0.46139913, -0.47216765, -0.29738086, 0.29738086], [ 1.77024883, -0.01896807, -0.70428107, -1.21642843, -0.77407523, 0.79216014, -0.55741224, -0.4104648 , -0.54697814, 0.4965864 , -0.39538259, -0.35587409, 0.80171217, -0.20833789, -0.27683948, -0.02818713, -0.29738086, 0.29738086], [ 1.77024883, 1.92336265, -0.70428107, -0.41709835, 1.15376589, -1.41424335, 0.47001251, 0.61151499, 2.29825376, -0.47648372, -0.11903621, 1.10658982, 0.80171217, -0.99824457, -0.57213493, 1.02334568, -0.29738086, 0.29738086], [-0.62332705, 0.67905703, 2.42962147, 2.13909264, 1.76503258, -0.35190093, 2.99543824, 3.21513015, 1.12222458, 3.08025536, -0.50592114, 2.01718056, -0.7793335 , -1.63016991, -1.75331671, 2.36930768, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 1.92142106, 1.92260741, 2.37629928, 1.07817541, 1.89546632, 2.0228204 , 1.08428815, 0.46303226, -0.53355578, 2.18274251, 0.59090608, -1.63016991, -1.60566899, 2.36930768, -0.29738086, 0.29738086], [ 1.77024883, 0.83080162, -0.56876096, -0.40877199, -0.0687675 , -1.6593993 , -0.07507161, -1.11611751, -0.01681188, 0.01643855, -0.14667084, 0.88584055, 1.85574262, -1.47218858, -1.16272582, 1.96972521, -0.29738086, 0.29738086], [-0.62332705, -1.26327369, -0.50100091, -0.35048751, -1.05619832, 2.22223648, -0.48682581, -0.82412328, -1.07808809, -0.74491686, -0.2572094 , -1.12849654, -0.67393045, 0.26560612, 0.16610369, -0.47216765, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.85625163, 0.63584784, 1.38777956, 0.89923611, 3.05894722, -0.2179058 , -2.04417004, -0.05035655, -0.86743037, -0.18802012, 3.36269123, -3.36269123], [ 0.17453157, -0.14036374, -0.83980118, -1.38295553, -0.96215729, -1.16908741, -0.80446476, -0.67812617, -1.15396095, 0.46303226, -0.64409434, -0.02475019, 0.80171217, -0.20833789, -0.12919176, -0.02818713, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 0.29517974, 0.76524406, 0.49547868, 0.58786352, 0.04845465, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.41106141, 0.80171217, -0.05035655, 0.01845597, -0.18802012, -0.29738086, 0.29738086], [ 0.9723902 , -0.56524859, 0.07495956, 1.05666649, 0.30739662, 0.99645676, 0.30727157, -0.11847057, 0.78079675, -0.61070029, -0.17430548, 0.19599908, 0.27469695, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [ 0.9723902 , 1.25568646, 0.1257796 , 0.22403099, 0.2603761 , 0.26098893, 0.56020629, 0.24652221, -0.54697814, 0.4965864 , -0.53355578, 0.33396738, 0.80171217, -1.1562259 , -1.31037354, 1.30375443, -0.29738086, 0.29738086], [ 0.17453157, 0.07207868, -0.39936082, -0.12567592, -0.20982905, -0.84221282, -0.26134137, -0.09413772, 0.06000467, 0.69791126, -0.39538259, -0.41106141, -0.25231827, -0.05035655, 0.16610369, -0.18802012, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.3562644 , -0.14280343, 0.47730535, -0.20805059, -0.42301723, -0.16271848, -0.25231827, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.9723902 , -1.20257586, -0.83980118, -1.41626095, -1.15023935, 0.01583299, -0.95740203, -0.70245902, 1.08428815, -2.99304439, -0.2572094 , -0.93534092, -0.46312436, 0.89753147, 0.75669458, -0.93047013, -0.29738086, 0.29738086]])
Our data has been standardized.
svr.fit(X_train_std,y_train)y_test_pred = svr.predict(X_test_std)y_train_pred = svr.predict(X_train_std)
Check our predicted values
y_test_pred
Out:
array([ 5957.14966842, 14468.92070095, 20448.68298715, 21478.92571603, 20124.68107731, 9079.70352739, 15827.33391626, 6005.66841863, 16069.42347072, 7254.92359917, 9776.48212662, 20670.10877046, 12433.67581456, 11143.00652033, 13539.9142024 , 19226.71716277, 6548.30452181, 20166.24495046, 8818.8454487 , 6470.62142339, 12170.16325257, 10461.81392719, 30525.17977575, 6766.09198268, 13432.63305394, 20616.74081099, 8883.9869784 , 8581.12259715, 14982.54291298, 30430.16956057, 28911.77849742, 13980.97058004, 7824.82285653, 20515.39293649, 8003.99866007, 11357.89548277, 13718.79721617, 16467.89155357, 9304.60919156, 18705.27852977, 6421.02399024]
Time to check modal performance.
from sklearn.metrics import r2_scorer2_score(y_train,y_train_pred)
Out:
0.8510467833352241r2_score(y_test,y_test_pred)
Out:
0.720783662521954
Our R sqrt score for the test data is 0.72 and for the train data, it is 0.85 which is good value.
import seaborn as snsplt.figure(figsize=(5, 7))ax = sns.distplot(y, hist=False, color="r", label="Actual Value")sns.distplot(y_test_pred, hist=False, color="b", label="Fitted Values" , ax=ax)plt.title('Actual vs Fitted Values for Price')plt.show()plt.close()
The above is the graph between the actual and predicted values.
SVM for classification
Here we will use the diabetes data that I used in my earlier story for KNN.https://towardsdatascience.com/knn-algorithm-what-when-why-how-41405c16c36f
let’s predict the same dataset result using SVM for classification.
import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltdata = pd.read_csv("../input/diabetes.csv")data.head()
We will read the CSV file through pd.read.csv.And through head() we can see the top 5 rows. There are some factors where the values cannot be zero. For example, Glucose value cannot be 0 for a human. Similarly, blood pressure, skin thickness, Insulin, and BMI cannot be zero for a human.
non_zero = ['Glucose','BloodPressure','SkinThickness','Insulin','BMI']for coloumn in non_zero: data[coloumn] = data[coloumn].replace(0,np.NaN) mean = int(data[coloumn].mean(skipna = True)) data[coloumn] = data[coloumn].replace(np.NaN,mean) print(data[coloumn])from sklearn.model_selection import train_test_splitX =data.iloc[:,0:8]y =data.iloc[:,8]X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0, stratify=y)X.head()
For data X we are taking all the rows of columns ranging from 0 to 7. Similarly, for y, we are taking all the rows for the 8th column.
We have train_test_split which we had imported during the start of the program and we have defined test size as 0.2 which implies out of all the data 20% will be kept aside to test the data at a later stage.
from sklearn.preprocessing import StandardScalersc_X = StandardScaler()X_train = sc_X.fit_transform(X_train)X_test = sc_X.transform(X_test)from sklearn import svmsvm1 = svm.SVC(kernel='linear', C = 0.01)svm1.fit(X_test,y_test)SVC(C=0.01, kernel='linear')y_train_pred = svm1.predict(X_train)y_test_pred = svm1.predict(X_test)y_test_pred
Out:
array([0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0])
We have an array of data but we need to evaluate our model to check the accuracy. Let's start it with confusion matrix
from sklearn.metrics import accuracy_score,confusion_matrix
Let's check the confusion matrix
confusion_matrix(y_test,y_test_pred)
Out:
array([[92, 8], [26, 28]])
We have the confusion matrix where the diagonal with 118 and 36 shows the correct value and 0,0 shows the prediction that we missed.
We will check the accuracy score
accuracy_score(y_test,y_test_pred)
Out:
0.7792207792207793
We have an accuracy score of 0.78
Let’s figure out the difference between the actual and predicted values.
df=pd.DataFrame({'Actual':y_test, 'Predicted':y_test_pred})df
We created our linear model with C as 0.01. But how to ensure its the best value. One option is to change is manual. We can assign different values and run the code one by one. but this process is very lengthy and time-consuming.
We will use a grid search where we will assign different values of C and from the dictionary of the value, our model will tell users which is the best value for C as per the model. To do so we need to import GridsearchCV
from sklearn.model_selection import GridSearchCVparam = {'C':(0,0.01,0.5,0.1,1,2,5,10,50,100,500,1000)}
Here we have defined 10 different values for C.
svm1 = svm.SVC(kernel = 'linear')svm.grid = GridSearchCV(svm1,param,n_jobs=1,cv=10,verbose=1,scoring='accuracy')
cv represents cross-validation. verbose is 1: represents the boolean, the message will be created.
svm.grid.fit(X_train,y_train)[Parallel(n_jobs=1)]: Done 120 out of 120 | elapsed: 43.8s finished
Out:
GridSearchCV(cv=10, estimator=SVC(kernel='linear'), n_jobs=1, param_grid={'C': (0, 0.01, 0.5, 0.1, 1, 2, 5, 10, 50, 100, 500, 1000)}, scoring='accuracy', verbose=1)svm.grid.best_params_
Out:
{'C': 0.1}
This will give us the result of the best C value for the model
linsvm_clf = svm.grid.best_estimator_accuracy_score(y_test,linsvm_clf.predict(X_test))
Out:
0.7597402597402597
This is the best accuracy we can get out of the above C values.
In the similar way we can try for Kernel ='poly'. But for ‘rbf’ we need to define gaama values as well. param = {'C':(0,0.01,0.5,0.1,1,2,5,10,50,100,500,1000)}, 'gamma':(0,0.1,0.2,2,10) and with normal one value of C from sklearn import svm svm1 = svm.SVC(kernel='rbf',gamma=0.5, C = 0.01) svm1.fit(X_test,y_test).
The above code can be checked at https://www.kaggle.com/adityakumar529/svm-claasifier.
You can check my codes on
|
[
{
"code": null,
"e": 374,
"s": 171,
"text": "SVM: Support Vector Machine is a supervised classification algorithm where we draw a line between two different categories to differentiate between them. SVM is also known as the support vector network."
},
{
"code": null,
"e": 432,
"s": 374,
"text": "Consider an example where we have cats and dogs together."
},
{
"code": null,
"e": 490,
"s": 432,
"text": "We want our model to differentiate between cats and dogs."
},
{
"code": null,
"e": 855,
"s": 490,
"text": "There are many cases where the differentiation is not so simple as shown above. In that case, the hyperplane dimension needs to be changed from 1 dimension to the Nth dimension. This is called Kernel. To be more simple, its the functional relationship between the two observations. It will add more dimensions to the data so we can easily differentiate among them."
},
{
"code": null,
"e": 891,
"s": 855,
"text": "We can have three types of kernels."
},
{
"code": null,
"e": 952,
"s": 891,
"text": "Linear KernelsPolynomial KernelsRadial Basis Function Kernel"
},
{
"code": null,
"e": 967,
"s": 952,
"text": "Linear Kernels"
},
{
"code": null,
"e": 986,
"s": 967,
"text": "Polynomial Kernels"
},
{
"code": null,
"e": 1015,
"s": 986,
"text": "Radial Basis Function Kernel"
},
{
"code": null,
"e": 1209,
"s": 1015,
"text": "In practical life, it’s very difficult to get a straight hyperplane. Consider the image below where the points are mixed together. You cannot separate the points using a straight 2d hyperplane."
},
{
"code": null,
"e": 1232,
"s": 1209,
"text": "Some use cases of SVM:"
},
{
"code": null,
"e": 1322,
"s": 1232,
"text": "Face detectionHandwriting detectionImage ClassificationsText and Hypertext Categorization"
},
{
"code": null,
"e": 1337,
"s": 1322,
"text": "Face detection"
},
{
"code": null,
"e": 1359,
"s": 1337,
"text": "Handwriting detection"
},
{
"code": null,
"e": 1381,
"s": 1359,
"text": "Image Classifications"
},
{
"code": null,
"e": 1415,
"s": 1381,
"text": "Text and Hypertext Categorization"
},
{
"code": null,
"e": 1457,
"s": 1415,
"text": "let’s check how SVM works for regression."
},
{
"code": null,
"e": 1691,
"s": 1457,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinepath = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/automobileEDA.csv'df = pd.read_csv(path)df.head()"
},
{
"code": null,
"e": 1858,
"s": 1691,
"text": "df.head() will give us the details of the top 5 rows of every column. We can use df.tail() to get the last 5 rows and similarly df.head(10) to get to the top 10 rows."
},
{
"code": null,
"e": 1943,
"s": 1858,
"text": "The data is about cars and we need to predict the price of cars using the above data"
},
{
"code": null,
"e": 2007,
"s": 1943,
"text": "We will be using the Decision Tree to get the price of the car."
},
{
"code": null,
"e": 2842,
"s": 2007,
"text": "df.dtypessymboling int64normalized-losses int64make objectaspiration objectnum-of-doors objectbody-style objectdrive-wheels objectengine-location objectwheel-base float64length float64width float64height float64curb-weight int64engine-type objectnum-of-cylinders objectengine-size int64fuel-system objectbore float64stroke float64compression-ratio float64horsepower float64peak-rpm float64city-mpg int64highway-mpg int64price float64city-L/100km float64horsepower-binned objectdiesel int64gas int64dtype: object"
},
{
"code": null,
"e": 2878,
"s": 2842,
"text": "dtypes give the data type of column"
},
{
"code": null,
"e": 2892,
"s": 2878,
"text": "df.describe()"
},
{
"code": null,
"e": 3057,
"s": 2892,
"text": "In the above data frame, some of the columns are not numeric. So we will consider only those columns whose values are in numeric and will make all numeric to float."
},
{
"code": null,
"e": 3173,
"s": 3057,
"text": "df.dtypesfor x in df: if df[x].dtypes == \"int64\": df[x] = df[x].astype(float) print (df[x].dtypes)"
},
{
"code": null,
"e": 3178,
"s": 3173,
"text": "Out:"
},
{
"code": null,
"e": 3235,
"s": 3178,
"text": "float64float64float64float64float64float64float64float64"
},
{
"code": null,
"e": 3648,
"s": 3235,
"text": "Preparing the Data As with the classification task, in this section, we will divide our data into attributes and labels and consequently into training and test sets. We will create 2 data sets, one for the price while the other (df-price). Since our data frame has various data in object format, for this analysis we are removing all the columns with object type and for all NaN values, we are removing that row."
},
{
"code": null,
"e": 3755,
"s": 3648,
"text": "df = df.select_dtypes(exclude=['object'])df=df.fillna(df.mean())X = df.drop('price',axis=1)y = df['price']"
},
{
"code": null,
"e": 4030,
"s": 3755,
"text": "Here the X variable contains all the columns from the dataset, except the ‘Price’ column, which is the label. The y variable contains values from the ‘Price’ column, which means that the X variable contains the attribute set and y variable contains the corresponding labels."
},
{
"code": null,
"e": 4171,
"s": 4030,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)"
},
{
"code": null,
"e": 4184,
"s": 4171,
"text": "Training SVM"
},
{
"code": null,
"e": 4212,
"s": 4184,
"text": "from sklearn.svm import SVR"
},
{
"code": null,
"e": 4299,
"s": 4212,
"text": "We will create an object svr using the function SVM. We will use the kernel as linear."
},
{
"code": null,
"e": 4337,
"s": 4299,
"text": "svr = SVR(kernel = 'linear',C = 1000)"
},
{
"code": null,
"e": 4509,
"s": 4337,
"text": "in order to work in an efficient manner, we will standardize our data.SVM works at a distance of points so it's necessary that all our data should be of the same standard."
},
{
"code": null,
"e": 4669,
"s": 4509,
"text": "from sklearn.preprocessing import StandardScalerX_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)X_test_stdsc= StandardScaler().fit(X_train)"
},
{
"code": null,
"e": 4674,
"s": 4669,
"text": "Out:"
},
{
"code": null,
"e": 15459,
"s": 4674,
"text": "array([[ 0.17453157, -0.7473421 , -0.70428107, -1.4995245 , -1.05619832, -0.67877552, -1.30249126, -0.87278899, -1.15396095, -0.47648372, -0.09140157, -0.90774727, 0.59090608, 2.00340082, 1.79022864, -1.50033307, -0.29738086, 0.29738086], [-1.42118568, -1.74885637, 0.63398001, 0.14076744, 0.30739662, 0.50614488, -0.1142863 , -0.38613195, -0.24348674, 0.32881569, 3.4734668 , -0.82496629, -1.30634872, 0.73955013, 0.31375141, -0.82735207, 3.36269123, -3.36269123], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.74841125, 0.63584784, 1.38777956, 0.89923611, 3.05894722, -0.2179058 , -2.04417004, -0.05035655, -0.86743037, -0.18802012, 3.36269123, -3.36269123], [-0.62332705, 0.16312543, 0.29517974, 0.64867509, 0.30739662, 0.58786352, 1.09156527, 1.34150055, 0.36349607, 0.06038255, -0.2572094 , 1.35493275, 0.16929391, -1.31420724, -1.31037354, 1.61715245, -0.29738086, 0.29738086], [-1.42118568, -0.01896807, 0.9897203 , 1.15658275, 0.30739662, 0.17927028, 1.20136639, 0.85484351, -0.24348674, 0.32881569, -0.20194012, 1.46530738, 0.16929391, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.51623682, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.49384238, 0.27469695, 0.26560612, 0.46139913, -0.47216765, -0.29738086, 0.29738086], [ 0.9723902 , -0.01896807, 0.19353966, 0.28231547, 0.21335559, -0.22932296, -0.06134647, 0.24652221, -0.54697814, 0.4965864 , -0.39538259, 0.19599908, 0.80171217, -0.99824457, -0.86743037, 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -1.08118019, -0.50100091, -1.26638656, -1.05619832, 0.34270758, -1.08484976, -0.82412328, -1.07808809, -0.74491686, -0.2572094 , -1.12849654, -0.67393045, 1.52945681, 1.19963775, -1.28401775, -0.29738086, 0.29738086], [-0.62332705, 1.98406049, 0.43069985, 0.2406837 , -0.49195214, 0.26098893, 0.44452297, 0.92784206, -0.09174103, -0.20805059, -0.2572094 , 0.49952933, -1.83336395, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [-0.62332705, -0.95978452, -0.50100091, -0.63358358, -0.6800342 , -0.27018228, -0.89661927, -0.67812617, -0.54697814, -0.74491686, -0.2572094 , -0.90774727, -0.67393045, 0.73955013, 0.9043423 , -0.82735207, -0.29738086, 0.29738086], [-0.62332705, -0.2314105 , 0.02413952, 0.32394725, 0.30739662, 0.75130082, -0.22212668, -0.09413772, 0.21175037, 0.46303226, -0.36774795, -0.52143604, -0.67393045, 0.10762479, 0.16610369, -0.33555826, -0.29738086, 0.29738086], [ 1.77024883, -0.01896807, -1.55128176, -0.41709835, -0.39791111, -0.84221282, 0.51314867, 1.65782762, 1.53952526, -1.18112071, -0.11903621, 2.87258398, 1.64493653, -1.31420724, -0.86743037, 1.61715245, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.5378049 , -0.70245902, -1.2298338 , 0.4965864 , 3.61163999, -1.40443312, -0.67393045, 1.84541948, 2.23317181, -1.43212554, 3.36269123, -3.36269123], [-0.62332705, -0.95978452, -0.50100091, -0.63358358, -0.6800342 , -0.27018228, -0.51623682, -0.38613195, -0.24348674, 0.32881569, 3.4734668 , -1.29405849, -1.30634872, 1.37147547, 0.75669458, -1.20342969, 3.36269123, -3.36269123], [ 1.77024883, -0.01896807, -0.46712088, -0.05906508, 0.21335559, -1.41424335, 0.75039751, 0.73317925, 0.97047888, 2.04007695, -0.80990217, 1.16177714, -0.25231827, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -0.01896807, 1.20994048, 1.56457414, 2.61140185, 0.83301947, 0.81510174, 0.24652221, -0.54697814, 0.4965864 , -0.39538259, 0.19599908, 0.80171217, -0.99824457, -0.86743037, 1.02334568, -0.29738086, 0.29738086], [ 0.17453157, -0.65629534, -0.83980118, -1.99077944, -0.86811626, -0.43361958, -1.14171105, -0.82412328, -1.60919805, 0.53014054, -0.20194012, -0.74218531, 1.85574262, 0.73955013, 0.46139913, -0.82735207, -0.29738086, 0.29738086], [ 1.77024883, 0.83080162, 0.07495956, 1.05666649, 0.30739662, 0.99645676, 0.33080038, -0.11847057, -3.01284579, -3.96611452, -0.17430548, 0.19599908, 0.27469695, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [-0.62332705, -0.50455075, -0.3654808 , -0.53366732, -0.30387008, -0.14760431, -0.48878654, -0.38613195, -0.69872384, 1.10056096, -0.2572094 , -0.46624873, 1.43413044, 0.26560612, 0.31375141, -0.47216765, -0.29738086, 0.29738086], [ 0.9723902 , 1.16463971, -0.83980118, -1.38295553, -0.6800342 , -1.16908741, -1.16523986, -0.82412328, -1.3815795 , -0.07383402, -0.14667084, -0.96293458, 0.80171217, 0.89753147, 1.05199003, -0.93047013, -0.29738086, 0.29738086], [ 0.9723902 , -0.86873777, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.42996451, -0.70245902, -1.2298338 , 0.4965864 , 3.61163999, -0.96293458, -1.30634872, 1.84541948, 1.64258092, -1.43212554, 3.36269123, -3.36269123], [-0.62332705, -1.14187802, -0.29772074, -0.02575966, -0.20982905, 0.50614488, 0.21903853, -0.43479765, 1.08428815, -2.05352841, -0.6164597 , 0.22359274, -0.67393045, -0.36631922, -1.16272582, 0.14554438, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.42962147, 2.13909264, 1.76503258, -0.35190093, 2.99543824, 3.21513015, 1.12222458, 3.08025536, -0.50592114, 2.01718056, -0.7793335 , -1.63016991, -1.75331671, 2.36930768, -0.29738086, 0.29738086], [ 0.17453157, 1.37708213, -0.70428107, -0.43375106, -0.86811626, -0.43361958, -0.72407465, -0.67812617, -0.54697814, -0.74491686, -0.2572094 , -0.90774727, -0.67393045, 0.58156879, 0.46139913, -0.71712242, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 0.02413952, 0.32394725, 0.30739662, 0.75130082, -0.18683347, -0.09413772, 0.21175037, 0.46303226, 3.52873607, -1.07330922, -0.99013959, 1.68743815, 1.64258092, -1.3601287 , 3.36269123, -3.36269123], [ 1.77024883, -0.01896807, -1.55128176, -0.41709835, -0.39791111, -0.84221282, 0.42687636, 1.65782762, 1.53952526, -1.18112071, -0.11903621, 2.87258398, 1.64493653, -1.31420724, -0.86743037, 1.61715245, -0.29738086, 0.29738086], [ 0.9723902 , -0.01896807, -0.22996069, -0.18396041, -0.16280853, 0.83301947, -0.64564528, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.49384238, 0.27469695, 0.26560612, 0.46139913, -0.47216765, -0.29738086, 0.29738086], [ 1.77024883, -0.01896807, -0.70428107, -1.21642843, -0.77407523, 0.79216014, -0.55741224, -0.4104648 , -0.54697814, 0.4965864 , -0.39538259, -0.35587409, 0.80171217, -0.20833789, -0.27683948, -0.02818713, -0.29738086, 0.29738086], [ 1.77024883, 1.92336265, -0.70428107, -0.41709835, 1.15376589, -1.41424335, 0.47001251, 0.61151499, 2.29825376, -0.47648372, -0.11903621, 1.10658982, 0.80171217, -0.99824457, -0.57213493, 1.02334568, -0.29738086, 0.29738086], [-0.62332705, 0.67905703, 2.42962147, 2.13909264, 1.76503258, -0.35190093, 2.99543824, 3.21513015, 1.12222458, 3.08025536, -0.50592114, 2.01718056, -0.7793335 , -1.63016991, -1.75331671, 2.36930768, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 1.92142106, 1.92260741, 2.37629928, 1.07817541, 1.89546632, 2.0228204 , 1.08428815, 0.46303226, -0.53355578, 2.18274251, 0.59090608, -1.63016991, -1.60566899, 2.36930768, -0.29738086, 0.29738086], [ 1.77024883, 0.83080162, -0.56876096, -0.40877199, -0.0687675 , -1.6593993 , -0.07507161, -1.11611751, -0.01681188, 0.01643855, -0.14667084, 0.88584055, 1.85574262, -1.47218858, -1.16272582, 1.96972521, -0.29738086, 0.29738086], [-0.62332705, -1.26327369, -0.50100091, -0.35048751, -1.05619832, 2.22223648, -0.48682581, -0.82412328, -1.07808809, -0.74491686, -0.2572094 , -1.12849654, -0.67393045, 0.26560612, 0.16610369, -0.47216765, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.85625163, 0.63584784, 1.38777956, 0.89923611, 3.05894722, -0.2179058 , -2.04417004, -0.05035655, -0.86743037, -0.18802012, 3.36269123, -3.36269123], [ 0.17453157, -0.14036374, -0.83980118, -1.38295553, -0.96215729, -1.16908741, -0.80446476, -0.67812617, -1.15396095, 0.46303226, -0.64409434, -0.02475019, 0.80171217, -0.20833789, -0.12919176, -0.02818713, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 0.29517974, 0.76524406, 0.49547868, 0.58786352, 0.04845465, -0.4104648 , -0.54697814, 0.4965864 , -0.2572094 , -0.41106141, 0.80171217, -0.05035655, 0.01845597, -0.18802012, -0.29738086, 0.29738086], [ 0.9723902 , -0.56524859, 0.07495956, 1.05666649, 0.30739662, 0.99645676, 0.30727157, -0.11847057, 0.78079675, -0.61070029, -0.17430548, 0.19599908, 0.27469695, -0.6822819 , -0.4244872 , 0.54264497, -0.29738086, 0.29738086], [ 0.9723902 , 1.25568646, 0.1257796 , 0.22403099, 0.2603761 , 0.26098893, 0.56020629, 0.24652221, -0.54697814, 0.4965864 , -0.53355578, 0.33396738, 0.80171217, -1.1562259 , -1.31037354, 1.30375443, -0.29738086, 0.29738086], [ 0.17453157, 0.07207868, -0.39936082, -0.12567592, -0.20982905, -0.84221282, -0.26134137, -0.09413772, 0.06000467, 0.69791126, -0.39538259, -0.41106141, -0.25231827, -0.05035655, 0.16610369, -0.18802012, -0.29738086, 0.29738086], [-0.62332705, -0.01896807, 2.63290164, 2.08080815, 1.2007864 , 2.05879919, 1.3562644 , -0.14280343, 0.47730535, -0.20805059, -0.42301723, -0.16271848, -0.25231827, -0.99824457, -1.0150781 , 1.02334568, -0.29738086, 0.29738086], [ 0.9723902 , -1.20257586, -0.83980118, -1.41626095, -1.15023935, 0.01583299, -0.95740203, -0.70245902, 1.08428815, -2.99304439, -0.2572094 , -0.93534092, -0.46312436, 0.89753147, 0.75669458, -0.93047013, -0.29738086, 0.29738086]])"
},
{
"code": null,
"e": 15491,
"s": 15459,
"text": "Our data has been standardized."
},
{
"code": null,
"e": 15596,
"s": 15491,
"text": "svr.fit(X_train_std,y_train)y_test_pred = svr.predict(X_test_std)y_train_pred = svr.predict(X_train_std)"
},
{
"code": null,
"e": 15623,
"s": 15596,
"text": "Check our predicted values"
},
{
"code": null,
"e": 15635,
"s": 15623,
"text": "y_test_pred"
},
{
"code": null,
"e": 15640,
"s": 15635,
"text": "Out:"
},
{
"code": null,
"e": 16363,
"s": 15640,
"text": "array([ 5957.14966842, 14468.92070095, 20448.68298715, 21478.92571603, 20124.68107731, 9079.70352739, 15827.33391626, 6005.66841863, 16069.42347072, 7254.92359917, 9776.48212662, 20670.10877046, 12433.67581456, 11143.00652033, 13539.9142024 , 19226.71716277, 6548.30452181, 20166.24495046, 8818.8454487 , 6470.62142339, 12170.16325257, 10461.81392719, 30525.17977575, 6766.09198268, 13432.63305394, 20616.74081099, 8883.9869784 , 8581.12259715, 14982.54291298, 30430.16956057, 28911.77849742, 13980.97058004, 7824.82285653, 20515.39293649, 8003.99866007, 11357.89548277, 13718.79721617, 16467.89155357, 9304.60919156, 18705.27852977, 6421.02399024]"
},
{
"code": null,
"e": 16396,
"s": 16363,
"text": "Time to check modal performance."
},
{
"code": null,
"e": 16463,
"s": 16396,
"text": "from sklearn.metrics import r2_scorer2_score(y_train,y_train_pred)"
},
{
"code": null,
"e": 16468,
"s": 16463,
"text": "Out:"
},
{
"code": null,
"e": 16515,
"s": 16468,
"text": "0.8510467833352241r2_score(y_test,y_test_pred)"
},
{
"code": null,
"e": 16520,
"s": 16515,
"text": "Out:"
},
{
"code": null,
"e": 16538,
"s": 16520,
"text": "0.720783662521954"
},
{
"code": null,
"e": 16637,
"s": 16538,
"text": "Our R sqrt score for the test data is 0.72 and for the train data, it is 0.85 which is good value."
},
{
"code": null,
"e": 16896,
"s": 16637,
"text": "import seaborn as snsplt.figure(figsize=(5, 7))ax = sns.distplot(y, hist=False, color=\"r\", label=\"Actual Value\")sns.distplot(y_test_pred, hist=False, color=\"b\", label=\"Fitted Values\" , ax=ax)plt.title('Actual vs Fitted Values for Price')plt.show()plt.close()"
},
{
"code": null,
"e": 16960,
"s": 16896,
"text": "The above is the graph between the actual and predicted values."
},
{
"code": null,
"e": 16983,
"s": 16960,
"text": "SVM for classification"
},
{
"code": null,
"e": 17134,
"s": 16983,
"text": "Here we will use the diabetes data that I used in my earlier story for KNN.https://towardsdatascience.com/knn-algorithm-what-when-why-how-41405c16c36f"
},
{
"code": null,
"e": 17202,
"s": 17134,
"text": "let’s predict the same dataset result using SVM for classification."
},
{
"code": null,
"e": 17346,
"s": 17202,
"text": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltdata = pd.read_csv(\"../input/diabetes.csv\")data.head()"
},
{
"code": null,
"e": 17634,
"s": 17346,
"text": "We will read the CSV file through pd.read.csv.And through head() we can see the top 5 rows. There are some factors where the values cannot be zero. For example, Glucose value cannot be 0 for a human. Similarly, blood pressure, skin thickness, Insulin, and BMI cannot be zero for a human."
},
{
"code": null,
"e": 18097,
"s": 17634,
"text": "non_zero = ['Glucose','BloodPressure','SkinThickness','Insulin','BMI']for coloumn in non_zero: data[coloumn] = data[coloumn].replace(0,np.NaN) mean = int(data[coloumn].mean(skipna = True)) data[coloumn] = data[coloumn].replace(np.NaN,mean) print(data[coloumn])from sklearn.model_selection import train_test_splitX =data.iloc[:,0:8]y =data.iloc[:,8]X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0, stratify=y)X.head()"
},
{
"code": null,
"e": 18232,
"s": 18097,
"text": "For data X we are taking all the rows of columns ranging from 0 to 7. Similarly, for y, we are taking all the rows for the 8th column."
},
{
"code": null,
"e": 18440,
"s": 18232,
"text": "We have train_test_split which we had imported during the start of the program and we have defined test size as 0.2 which implies out of all the data 20% will be kept aside to test the data at a later stage."
},
{
"code": null,
"e": 18776,
"s": 18440,
"text": "from sklearn.preprocessing import StandardScalersc_X = StandardScaler()X_train = sc_X.fit_transform(X_train)X_test = sc_X.transform(X_test)from sklearn import svmsvm1 = svm.SVC(kernel='linear', C = 0.01)svm1.fit(X_test,y_test)SVC(C=0.01, kernel='linear')y_train_pred = svm1.predict(X_train)y_test_pred = svm1.predict(X_test)y_test_pred"
},
{
"code": null,
"e": 18781,
"s": 18776,
"text": "Out:"
},
{
"code": null,
"e": 19287,
"s": 18781,
"text": "array([0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0])"
},
{
"code": null,
"e": 19406,
"s": 19287,
"text": "We have an array of data but we need to evaluate our model to check the accuracy. Let's start it with confusion matrix"
},
{
"code": null,
"e": 19466,
"s": 19406,
"text": "from sklearn.metrics import accuracy_score,confusion_matrix"
},
{
"code": null,
"e": 19499,
"s": 19466,
"text": "Let's check the confusion matrix"
},
{
"code": null,
"e": 19536,
"s": 19499,
"text": "confusion_matrix(y_test,y_test_pred)"
},
{
"code": null,
"e": 19541,
"s": 19536,
"text": "Out:"
},
{
"code": null,
"e": 19575,
"s": 19541,
"text": "array([[92, 8], [26, 28]])"
},
{
"code": null,
"e": 19708,
"s": 19575,
"text": "We have the confusion matrix where the diagonal with 118 and 36 shows the correct value and 0,0 shows the prediction that we missed."
},
{
"code": null,
"e": 19741,
"s": 19708,
"text": "We will check the accuracy score"
},
{
"code": null,
"e": 19776,
"s": 19741,
"text": "accuracy_score(y_test,y_test_pred)"
},
{
"code": null,
"e": 19781,
"s": 19776,
"text": "Out:"
},
{
"code": null,
"e": 19800,
"s": 19781,
"text": "0.7792207792207793"
},
{
"code": null,
"e": 19834,
"s": 19800,
"text": "We have an accuracy score of 0.78"
},
{
"code": null,
"e": 19907,
"s": 19834,
"text": "Let’s figure out the difference between the actual and predicted values."
},
{
"code": null,
"e": 19969,
"s": 19907,
"text": "df=pd.DataFrame({'Actual':y_test, 'Predicted':y_test_pred})df"
},
{
"code": null,
"e": 20199,
"s": 19969,
"text": "We created our linear model with C as 0.01. But how to ensure its the best value. One option is to change is manual. We can assign different values and run the code one by one. but this process is very lengthy and time-consuming."
},
{
"code": null,
"e": 20420,
"s": 20199,
"text": "We will use a grid search where we will assign different values of C and from the dictionary of the value, our model will tell users which is the best value for C as per the model. To do so we need to import GridsearchCV"
},
{
"code": null,
"e": 20524,
"s": 20420,
"text": "from sklearn.model_selection import GridSearchCVparam = {'C':(0,0.01,0.5,0.1,1,2,5,10,50,100,500,1000)}"
},
{
"code": null,
"e": 20572,
"s": 20524,
"text": "Here we have defined 10 different values for C."
},
{
"code": null,
"e": 20685,
"s": 20572,
"text": "svm1 = svm.SVC(kernel = 'linear')svm.grid = GridSearchCV(svm1,param,n_jobs=1,cv=10,verbose=1,scoring='accuracy')"
},
{
"code": null,
"e": 20784,
"s": 20685,
"text": "cv represents cross-validation. verbose is 1: represents the boolean, the message will be created."
},
{
"code": null,
"e": 20883,
"s": 20784,
"text": "svm.grid.fit(X_train,y_train)[Parallel(n_jobs=1)]: Done 120 out of 120 | elapsed: 43.8s finished"
},
{
"code": null,
"e": 20888,
"s": 20883,
"text": "Out:"
},
{
"code": null,
"e": 21128,
"s": 20888,
"text": "GridSearchCV(cv=10, estimator=SVC(kernel='linear'), n_jobs=1, param_grid={'C': (0, 0.01, 0.5, 0.1, 1, 2, 5, 10, 50, 100, 500, 1000)}, scoring='accuracy', verbose=1)svm.grid.best_params_"
},
{
"code": null,
"e": 21133,
"s": 21128,
"text": "Out:"
},
{
"code": null,
"e": 21144,
"s": 21133,
"text": "{'C': 0.1}"
},
{
"code": null,
"e": 21207,
"s": 21144,
"text": "This will give us the result of the best C value for the model"
},
{
"code": null,
"e": 21294,
"s": 21207,
"text": "linsvm_clf = svm.grid.best_estimator_accuracy_score(y_test,linsvm_clf.predict(X_test))"
},
{
"code": null,
"e": 21299,
"s": 21294,
"text": "Out:"
},
{
"code": null,
"e": 21318,
"s": 21299,
"text": "0.7597402597402597"
},
{
"code": null,
"e": 21382,
"s": 21318,
"text": "This is the best accuracy we can get out of the above C values."
},
{
"code": null,
"e": 21697,
"s": 21382,
"text": "In the similar way we can try for Kernel ='poly'. But for ‘rbf’ we need to define gaama values as well. param = {'C':(0,0.01,0.5,0.1,1,2,5,10,50,100,500,1000)}, 'gamma':(0,0.1,0.2,2,10) and with normal one value of C from sklearn import svm svm1 = svm.SVC(kernel='rbf',gamma=0.5, C = 0.01) svm1.fit(X_test,y_test)."
},
{
"code": null,
"e": 21784,
"s": 21697,
"text": "The above code can be checked at https://www.kaggle.com/adityakumar529/svm-claasifier."
}
] |
AWT TextListener Interface
|
The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method.
Following is the declaration for java.awt.event.TextListener interface:
public interface TextListener
extends EventListener
void textValueChanged(TextEvent e)
Invoked when the value of the text has changed.
This interface inherits methods from the following interfaces:
java.awt.EventListener
java.awt.EventListener
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private TextField textField;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showTextListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextListenerDemo(){
headerLabel.setText("Listener in action: TextListener");
textField = new TextField(10);
textField.addTextListener(new CustomTextListener());
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: "
+ textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class CustomTextListener implements TextListener {
public void textValueChanged(TextEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1947,
"s": 1747,
"text": "The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method. "
},
{
"code": null,
"e": 2019,
"s": 1947,
"text": "Following is the declaration for java.awt.event.TextListener interface:"
},
{
"code": null,
"e": 2074,
"s": 2019,
"text": "public interface TextListener\n extends EventListener"
},
{
"code": null,
"e": 2110,
"s": 2074,
"text": "void textValueChanged(TextEvent e) "
},
{
"code": null,
"e": 2158,
"s": 2110,
"text": "Invoked when the value of the text has changed."
},
{
"code": null,
"e": 2221,
"s": 2158,
"text": "This interface inherits methods from the following interfaces:"
},
{
"code": null,
"e": 2244,
"s": 2221,
"text": "java.awt.EventListener"
},
{
"code": null,
"e": 2267,
"s": 2244,
"text": "java.awt.EventListener"
},
{
"code": null,
"e": 2381,
"s": 2267,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 4437,
"s": 2381,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtListenerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private TextField textField;\n\n public AwtListenerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtListenerDemo awtListenerDemo = new AwtListenerDemo(); \n awtListenerDemo.showTextListenerDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showTextListenerDemo(){\n headerLabel.setText(\"Listener in action: TextListener\"); \n\n textField = new TextField(10);\n\n textField.addTextListener(new CustomTextListener());\n Button okButton = new Button(\"OK\");\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n statusLabel.setText(\"Entered text: \" \n + textField.getText()); \n }\n });\n\n controlPanel.add(textField);\n controlPanel.add(okButton); \n mainFrame.setVisible(true); \n }\n\n class CustomTextListener implements TextListener {\n public void textValueChanged(TextEvent e) {\n statusLabel.setText(\"Entered text: \" + textField.getText()); \n }\n }\n}"
},
{
"code": null,
"e": 4528,
"s": 4437,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 4585,
"s": 4528,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtListenerDemo.java"
},
{
"code": null,
"e": 4682,
"s": 4585,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 4733,
"s": 4682,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtListenerDemo"
},
{
"code": null,
"e": 4761,
"s": 4733,
"text": "Verify the following output"
},
{
"code": null,
"e": 4794,
"s": 4761,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4802,
"s": 4794,
"text": " EduOLC"
},
{
"code": null,
"e": 4809,
"s": 4802,
"text": " Print"
},
{
"code": null,
"e": 4820,
"s": 4809,
"text": " Add Notes"
}
] |
C++ Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
|
If a binary tree is traversed post-order, the left subtree is visited first, then the right sub-tree and later the root. This is a C++ Program for Post Order Tree traversal without recursion. We do the program here by using stack.
For postorder traversal:
Begin
Declare postorder_traversal(struct node*t,struct tree**top)
if(t==NULL) then
print “Empty Tree”.
Return.
Print “Postorder Data Using Stack :”.
Call push(t,top) function to insert values.
Declare a pointer store against tree structure.
Initialize struct tree*store=NULL.
while(t!=NULL)
store=*top;
if(store->v==0) then
if(t->r!=NULL) then
(store->v)++
push(t->r,top)
if(t->l!=NULL) then
(store->v)++
push(t->l,top)
if(store->v==0) then
cout<d
t=NULL
pop(top)
else
cout<d
t=NULL
pop(top)
if(*top!=NULL) then
t=(*top)->link
End
Live Demo
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node {
int d;
struct node *l,*r;
};
struct tree {
int v;
struct node*link;
struct tree*n;
};
struct node*create_node(int);
struct node*create_node(int value) {
struct node*new_node=(struct node*)malloc(sizeof(struct node));
if(new_node!=NULL) {
new_node->d=value;
new_node->l=new_node->r=NULL;
return new_node;
} else {
printf("\n Memory overflow.");
return NULL;
}
}
void push(struct node*,struct tree*);
void push(struct node*node,struct tree**top) {
struct tree*new_node=(struct tree*)malloc(sizeof(struct tree));
if(new_node!=NULL) {
new_node->link=node;
new_node->n=*top;
new_node->v=0;
*top=new_node;
} else {
cout<<"\n Memory overflow.";
return ;
}
}
void pop(struct tree**);
void pop(struct tree**top) {
if(*top!=NULL) {
struct tree*remove=*top;
*top=(*top)->n;
remove->link=NULL;
remove->n=NULL;
remove=NULL;
}
}
void postorder_traversal(struct node*,struct tree**);
void postorder_traversal(struct node*t,struct tree**top) {
if(t==NULL) {
cout<<"\n Empty Tree";
return;
}
cout<<"\n Postorder Data Using Stack :";
push(t,top);
struct tree*store=NULL;
while(t!=NULL) {
store=*top;
if(store->v==0) {
if(t->r!=NULL) {
(store->v)++;
push(t->r,top);
}
if(t->l!=NULL) {
(store->v)++;
push(t->l,top);
}
if(store->v==0) {
cout<<t->d;
t=NULL;
pop(top);
}
}
else {
cout<<t->d;
t=NULL;
pop(top);
}
if(*top!=NULL)
t=(*top)->link;
}
}
int main(){
struct node*root=NULL;
struct tree*top=NULL;
root = create_node(20);
root->l = create_node(10);
root->r = create_node(30);
root->r->r = create_node(7);
root->l->l = create_node(25);
root->l->r = create_node(35);
root->l->r->r = create_node(40);
root->l->l->r = create_node(26);
postorder_traversal(root,&top);
return 0;
}
Postorder Data Using Stack :26 25 40 35 10 7 30 20
|
[
{
"code": null,
"e": 1293,
"s": 1062,
"text": "If a binary tree is traversed post-order, the left subtree is visited first, then the right sub-tree and later the root. This is a C++ Program for Post Order Tree traversal without recursion. We do the program here by using stack."
},
{
"code": null,
"e": 1318,
"s": 1293,
"text": "For postorder traversal:"
},
{
"code": null,
"e": 2134,
"s": 1318,
"text": "Begin\n Declare postorder_traversal(struct node*t,struct tree**top)\n if(t==NULL) then\n print “Empty Tree”.\n Return.\n Print “Postorder Data Using Stack :”.\n Call push(t,top) function to insert values.\n Declare a pointer store against tree structure.\n Initialize struct tree*store=NULL.\n while(t!=NULL)\n store=*top;\n if(store->v==0) then\n if(t->r!=NULL) then\n (store->v)++\n push(t->r,top)\n if(t->l!=NULL) then\n (store->v)++\n push(t->l,top)\n if(store->v==0) then\n cout<d\n t=NULL\n pop(top)\n else\n cout<d\n t=NULL\n pop(top)\n if(*top!=NULL) then\n t=(*top)->link\nEnd"
},
{
"code": null,
"e": 2145,
"s": 2134,
"text": " Live Demo"
},
{
"code": null,
"e": 4296,
"s": 2145,
"text": "#include<iostream>\n#include<stdlib.h>\nusing namespace std;\nstruct node {\n int d;\n struct node *l,*r;\n};\nstruct tree {\n int v;\n struct node*link;\n struct tree*n;\n};\nstruct node*create_node(int);\nstruct node*create_node(int value) {\n struct node*new_node=(struct node*)malloc(sizeof(struct node));\n if(new_node!=NULL) {\n new_node->d=value;\n new_node->l=new_node->r=NULL;\n return new_node;\n } else {\n printf(\"\\n Memory overflow.\");\n return NULL;\n }\n}\nvoid push(struct node*,struct tree*);\nvoid push(struct node*node,struct tree**top) {\n struct tree*new_node=(struct tree*)malloc(sizeof(struct tree));\n if(new_node!=NULL) {\n new_node->link=node;\n new_node->n=*top;\n new_node->v=0;\n *top=new_node;\n } else {\n cout<<\"\\n Memory overflow.\";\n return ;\n }\n}\nvoid pop(struct tree**);\nvoid pop(struct tree**top) {\n if(*top!=NULL) {\n struct tree*remove=*top;\n *top=(*top)->n;\n remove->link=NULL;\n remove->n=NULL;\n remove=NULL;\n }\n}\nvoid postorder_traversal(struct node*,struct tree**);\nvoid postorder_traversal(struct node*t,struct tree**top) {\n if(t==NULL) {\n cout<<\"\\n Empty Tree\";\n return;\n }\n cout<<\"\\n Postorder Data Using Stack :\";\n push(t,top);\n struct tree*store=NULL;\n while(t!=NULL) {\n store=*top;\n if(store->v==0) {\n if(t->r!=NULL) {\n (store->v)++;\n push(t->r,top);\n }\n if(t->l!=NULL) {\n (store->v)++;\n push(t->l,top);\n }\n if(store->v==0) {\n cout<<t->d;\n t=NULL;\n pop(top);\n }\n }\n else {\n cout<<t->d;\n t=NULL;\n pop(top);\n }\n if(*top!=NULL)\n t=(*top)->link;\n }\n}\nint main(){\n struct node*root=NULL;\n struct tree*top=NULL;\n root = create_node(20);\n root->l = create_node(10);\n root->r = create_node(30);\n root->r->r = create_node(7);\n root->l->l = create_node(25);\n root->l->r = create_node(35);\n root->l->r->r = create_node(40);\n root->l->l->r = create_node(26);\n postorder_traversal(root,&top);\n return 0;\n}"
},
{
"code": null,
"e": 4347,
"s": 4296,
"text": "Postorder Data Using Stack :26 25 40 35 10 7 30 20"
}
] |
A comprehensive Machine Learning workflow with multiple modelling using caret and caretEnsemble in R | by Gabriel Pierobon | Towards Data Science
|
I’ll use a very interesting dataset presented in the book Machine Learning with R from Packt Publishing, written by Brett Lantz. My intention is to expand the analysis on this dataset by executing a full supervised machine learning workflow which I’ve been laying out for some time now in order to help me attack any similar problem with a systematic, methodical approach.
If you are thinking this is nothing new, then you’re absolutely right! I’m not coming up with anything new here, just making sure I have all the tools necessary to follow a full process without leaving behind any big detail. Hopefully some of you will find it useful too and be sure you are going to find some judgment errors from my part and/or things you would do differently. Feel free to leave me a comment and help me improve!
Let’s jump ahead and begin to understand what information we are going to work with:
From the book:
“In the field of engineering, it is crucial to have accurate estimates of the performance of building materials. These estimates are required in order to develop safety guidelines governing the materials used in the construction of building, bridges, and roadways.Estimating the strength of concrete is a challenge of particular interest. Although it is used in nearly every construction project, concrete performance varies greatly due to a wide variety of ingredients that interact in complex ways. As a result, it is difficult to accurately predict the strength of the final product. A model that could reliably predict concrete strength given a listing of the composition of the input materials could result in safer construction practices.
For this analysis, we will utilize data on the compressive strength of concrete donated to the UCI Machine Learning Data Repository (http://archive.ics.uci.edu/ml) by I-Cheng Yeh.
According to the website, the concrete dataset contains 1,030 examples of concrete with eight features describing the components used in the mixture. These features are thought to be related to the final compressive strength and they include the amount(in kilograms per cubic meter) of cement, slag, ash, water, superplasticizer, coarse aggregate, and fine aggregate used in the product in addition to the aging time (measured in days).”
I’ve found that splitting the workflow into 6 phases works best for myself. In that sense, I’ll describe this instances as: 1) Setting 2) Exploratory Data Analysis 3) Feature Engineering 4) Data Preparation 5) Modelling 6) Conclusion
In practice, I end up jumping from one to another, many times regardless of order and often in loop. So think of this just as an initial structure and more of a checklist, rather than a step by step guide.
The checklist is quite comprehending and covers most of what you would follow in supervised learning, both for classification and regression problems. In practice, you will most likely end up skipping some of the points from the list because there are things you do for a classification problem that you don’t do for a regression problem, vice versa. Even some of them are sometimes a little redundant (although double checking is always useful in my opinion). I’m sure that with more practice and experience, this list will get tuned and I’m hoping I can also share that again in the future.
I’ll limit myself to short-direct answers, and will expand whenever necessary. Otherwise I’m afraid I might make it too long for anyone to stick around!
You will see that even though I’m including the full checklist, in many cases we don’t have to do absolutely anything. This is because this dataset is pretty straightforward. It feels a little bit like cheating, however, I’ll make sure to mention why we don’t have to do anything and the idea behind that checkpoint.
The last thing I wanted to mention is that when I get to the modelling phase, I will change my approach and showcase some useful modelling tools with R packages caret and caretEnsemble. So instead of going step by step trying out some baseline models and them some more advanced models with hyper-parameter tuning and regularization to reduce overfitting, I’m just going to train a bunch of models at once, since it allows me to make this last phase much concise and straightforward for interpretation. Also because the modelling phase is where one likes to do it’s own thing and get creative by using different approaches. In my opinion, this checklist is very important for phases 1 to 4, but then starting phase 5, it can become less strict.
Enough said, let’s begin:
Find the working files and codes here: https://github.com/gabrielpierobon/ML-workflow-caret
1.1) What are we trying to predict?
We need to accurately estimate the performance of building materials for the field of engineering.
1.2) What type of problem is it? Supervised or Unsupervised Learning? Classification or Regression? Binary or Multi-class? Uni-variate or Multi-variate?
This is a multivariate supervised machine learning problem in which we have to predict numeric outcomes, thus we’ll be using regression techniques.
1.3) What type of data do we have?
Our data is in “csv” format. It presents a header row with the column names. It seems to contain only numeric information.
1.4) Import the dataset
We can simply load it with this code:
concrete <- read.csv(“/Users/Gabriel Pierobon/Desktop/Datasets para cargar/concrete.csv”)#use your own directory!
This is the size of our dataset:
dim(concrete)[1] 1030 9
1,030 rows and 9 columns, one of which is our response/target variable.
We can see that it was imported as a data frame which is the format that we require to work with this data:
class(concrete)[1] "data.frame"
We can also check that the names of our columns were correctly imported.
names(concrete)
From that list, we identify strength as our response/target variable.
We can conclude that our data was correctly imported and thus end our setting phase.
Before we do that, I’d like to require all our libraries altogether. It’s useful to do it all at once at the begging, to improve readability of this work:
library(dplyr)library(ggplot2)library(PerformanceAnalytics)library(ggthemes)library(corrplot)library(car)library(psych)library(caret)library(caretEnsemble)library(doParallel)
With that taken care of, let’s move on to exploratory data analysis:
2.1) View Data (str or dplyr’s glimpse). First look. Anything strange?
The fist way we want to double check what we did in the setting phase is to quickly view our full dataset. We do it like this:
View(concrete)
This will display a window with the dataset. I like to quickly look at it from top to bottom and left to right to reassure the fact that the data was loaded correctly. It’s also a quick and dirty way to detect issues that could be observable at first glance. You don’t want to do this for significantly large datasets.
Next, we are going to take a glimpse at our data and observe just the first few rows of the data frame:
glimpse(concrete)
head(concrete)
2.2) Is it a “tidy” dataset? Need to “gather” or “spread” it? Is it presented in a way we can work with?
We need our data to be presented with individual observations as rows and features as columns. Fortunately for us, this is the case of this dataset, so we won’t have to transform it. Otherwise, we would have to use some sort of function to pivot the data frame to accommodate to our needs (refer to this site for more about that)
2.3) rownames and colnames ok? Should we change them?
We have already checked how these were loaded. Do we need to update/change anything to have clearer understanding of our variables? I don’t think this is the case, we can move on. The idea here is to make sure we move forward comfortably with our feature names, avoiding unnecessary long names or any other sort of confusing situation.
2.4) Check data types. Are they OK? If not, convert
As we have seen, all our variables are of the double type, except for the variable age which is integer. Fortunately, we don’t have to convert anything! It’s very important that we check this in order to avoid some type of error when loading the data. Sometimes a single character in a numeric column can result in the whole column being loaded as character.
2.5) What is our response/target variable? Class imbalance? Study it
Our response variable is strength. Let’s look at some useful statistics about it:
summary(concrete$strength)
We can see that it ranges from 2.3 to 82.6. The median and the mean are really close, but since median is actually smaller, this results in a slight skew of the variable distribution to the right.
We can observe that with a plot using ggplot2:
As we can see, the distribution of the strength variable is not perfectly normal, but we are going to proceed regardless. This shouldn’t be a problem because it’s close. A qqplot also helps with the visual analysis of normality (I leave that to you)
Lastly, since this is a regression problem, we don’t have to worry about class imbalance. In classification, you want to have balanced classes in your response variable (here’s a nice post about class imbalance)
2.6) Rest of the features. Summary statistics. Understand your data
Here we extend the statistical analysis to our other variables/features. We want to pay attention at the minimums and maximums (this is a first check for potential outliers). Also, mean and median difference is something to be concerned about. We would like all our variables to follow the normal distribution as much as possible.
summary(concrete)
We can follow our analysis with a correlation plot. This will present us with a chart showing the correlation between all variables. It will also let us think for the first time if we need all our variables in our model. We don’t want our feature variables to present a high correlation between them. We will take care of this later.
corrplot(cor(concrete), method = “square”)
Another nice way of looking at all of this together is with this correlation plot:
chart.Correlation(concrete)
On one of the diagonals, we can see the distribution of each feature. Not all of them resemble normality, so we will deal with this later.
At this point my first conclusion is that the variable ash has low correlation with our response variable strength and a high correlation with four of the eight other features. It is thus a strong candidate to be removed, we’ll cover this later as well.
2.7) Categorical data/Factors: create count tables to understand different categories. Check all of them.
In this case we are not working with categorical features. You want to make sure you understand your categories, sometimes misspells can introduce problems for factor variables.
We can move on.
2.8) Unnecessary columns? Columns we can quickly understand we don’t need. Drop them
Here we want to look for columns which are totally useless. Anything that would come in the dataset that is really uninformative and we can determine that we should drop. Additional index columns, uninformative string columns, etc. This is not the case for this dataset. You could perfectly do this as soon as you import the dataset, no need to do it specifically at this point.
2.9) Check for missing values. How many? Where? Delete them? Impute them?
Let’s first do an overall check for NAs:
anyNA(concrete)[1] FALSE
Wonderful! no missing values in the whole set! Let me also show you a way we could have detected this for every column:
sapply(concrete, {function(x) any(is.na(x))})
(Some tools for dealing with missing values)
2.10) Check for outliers and other inconsistent data points. Box-plots. DBSCAN for outlier detection?
Outlier detection is more of a craft than anything else, in my opinion. I really like the approach of using DBSCAN clustering for outlier detection but I’m not going to proceed with this so I don’t overextend this analysis. DBSCAN is a clustering algorithm that can detect noise points in the data and not assign them to any cluster. I find it very compelling for outlier detection (more about DBSCAN here)
Instead, I’ll just go ahead with a boxplot and try to work with the points I consider relevant just by sight:
boxplot(concrete[-9], col = “orange”, main = “Features Boxplot”)
We see that there are several potential outliers, however I consider that the age feature could be the most problematic. Let’s look at it isolated:
boxplot(concrete$age, col = “red”)
Are these just 4 outliers? If so, we could just get rid of them. Or shouldn’t we? Let’s find out what this values are and how many of them are there.
age_outliers <- which(concrete$age > 100)concrete[age_outliers, “age”]
Oh my! so there were 62 of them instead of just 4! Obviously this is simply because the same numbers are repeated several times. This makes me think that this age points are actually relevant and we don’t want to get rid of them. 62 data points from our 1,030 dataset seems too high a number to just eliminate (we would be losing plenty of information).
2.11) Check for multicollinearity in numeric data. Variance Inflation Factors (VIF)
We’ve already seen in the correlation plot presented before that there seems to be significant correlation between some features. We want to make sure that multicollinearity is not an issue that prevents us to move forward. In order to do this, we will compute a score called Variance Inflation Factor (VIF) which measures how much the variance of a regression coefficient is inflated due to multicollinearity in the model. If VIF score is more than 10, multicollinearity is strongly suggested and we should try to get rid of the features that are causing it.
First, we generate a simple linear regression model of our target variable explained by each other feature. Afterwards, we call function vif()on the model object and we take a look at the named list output:
simple_lm <- lm(strength ~ ., data = concrete)vif(simple_lm)
Even though there are many variables scoring 5 and higher, none of them surpasses the threshold of 10 so we will consider multicollinearity not to be a big issue. However, some would argue that it could indeed be a problem to have as many features with scores of 7. We will not worry about that at this time.
With this, we consider the Exploratory Data Analysis (EDA) phase over and we move on to Feature Engineering. Feel free to disagree with this being over! I’m sure there still plenty of exploration left to do.
Feature engineering could also be considered a very important craft for a data scientist. It involves the production of new features obtained from the features present in the dataset. This could be as simple as extracting some dates information from string columns, or producing interaction terms. Moreover, it will certainly require some degree of subject matter expertise and domain knowledge, since coming up with new informative features is something intrinsic to the nature of the data and the overall field of application.
Here, we will go super quick, since our data seems to be already very informative and complete (engineers might disagree!).
I wanted to mention that engineering new features will most likely require that we repeat some of the previous analysis we have already done, since we don’t want to introduce new features that add noise to the dataset. So bear in mind that we must always look at our checklist back again and define if we need to analyze things one more time.
3.1) Create new useful features. Interaction Terms. Basic math and statistics. Create categories with if-else structures
Because I’m not a subject matter expert in engineering, I won’t create new features from interaction terms. I’ll just limit myself to verify if any of the variables require any type of transformation.
The first thing that I want to do is to check two variables which seem to have unusual distributions. It is the case of age and superplastic. Let’s plot their original form and also logs below (in red).
par(mfrow = c(2,2))hist(concrete$age)hist(concrete$superplastic)hist(log(concrete$age), col = “red”)hist(log(concrete$superplastic), col = “red”)
While I feel comfortable with converting age to it’s logarithmic form, in the case of superplastic, with as many observations being 0, I’ll have some issues when taking the log of 0, so I’ll take the log and then manually set those to 0.
Below, the code to convert both features:
concrete$age <- log(concrete$age)concrete$superplastic <- log(concrete$superplastic)concrete$superplastic <- ifelse(concrete$superplastic == -Inf, 0, concrete$superplastic)head(concrete)
Note: I spent quite some time at this point trying to create a new superplastic feature by binning the original superplastic feature into 3 numeric categories. However, I didn’t have much success in terms of importance to explain the target variable. I won’t show those attempts, but just know that I indeed tried to work on that for some time unsuccessfully. Failing is also part of learning!
3.2) Create dummies for categorical features. Preferably using One-Hot-Encoding
We are not working with categorical features at this time, so this section will be skipped. However, if you were presented with some factor columns, you will have to make sure your algorithm can work with those, or otherwise proceed with one-hot-encoding them.
3.3) Can we extract some important text from string columns using regular expressions?
We are not working with sting data at this time, so this section will be skipped. This should be a very useful tool when you have some relevant information in character type from which you can create new useful categories.
Thankfully we didn’t have to go through all of that! However, those last 3 sections are a MUST if we are working with that type of information. I’ll make sure to analyze a dataset in which I can show some of that.
Let’s move on to the Data Preparation phase:
4.1) Manual feature selection. Remove noisy, uninformative, highly-correlated, or duplicated features.
Here’s where we take spend time for the second time in this workflow looking at our features and detecting if any of them are uninformative enough or should be dropped because of introducing problems as could be multicollinearity.
As I already had decided, I’ll first drop the ash feature (you might want to leave it and remove it after trying some baseline models, deciding to drop it if it does not help with performance, I already did that, so I’ll drop it now, as was my initial assessment)
concrete$ash <- NULLhead(concrete)
Besides that, I won’t remove anything else.
4.2) Transform data if needed. Scale or normalize if required.
Most of the algorithms we will use require our numeric features to be scaled or normalized (here’s why)
We won’t be doing that in this precise section, but leave it for later, since caret allows us to do some pre-processing within it’s training functionality. This is specifically useful because the algorithm will automatically transform back to it’s original scale when presenting us with predictions and results. If I manually normalized the dataset here, then I would have to manually transform back the predictions.
4.3) Automatic Feature extraction. Dimensionality Reduction (PCA, NMF, t-SNE)
If removing features manually isn’t straightforward enough but we still consider our dataset to contain too many features or too correlated features, we can apply dimensonality reduction techniques. Principal Components Analysis is one of those techniques, and a really useful one to both simplify our dataset, and also remove the issue of multicollinearity for good.
Non-negative Matrix Factorization (NMF) and t-SNE are other two useful dimensionality reduction techniques.
With just 8 features in our dataset and 1 already dropped manually, I don’t consider we require to reduce dimensionality any further.
4.4) Is our dataset randomized?
We are not sure it is randomized, so we will shuffle it just in case:
set.seed(123)concrete_rand <- concrete[sample(1:nrow(concrete)), ]dim(concrete_rand)
4.5) Define an evaluation protocol: how many samples do we have? Hold out method. Cross validation needed?
We have 1,030 samples, so this is definitely a small dataset. We will divide the dataset into train and test sets and make sure we use cross-validation when we train our model. In that way we ensure we are using our few observations as well as we can.
4.6) Split dataset into train & test sets (set seed for replicability)
We first create a set of predictors and a set of our target variable
X = concrete_rand[, -8]y = concrete_rand[, 8]
We check everything is OK:
str(X)
str(y)
We then proceed to split our new X(predictors) and y (target) sets into training and test sets.
Note: you don’t have to separate the sets, and can perfectly go ahead using the formula method. I just prefer to do it this way, because this way I’m sure I align my proceeding to how I’d work with Python’s scikit-learn.
We will use caret’s createDataPartition() function, which generates the partition indexes for us, and we will use them to perform the splits:
set.seed(123)part.index <- createDataPartition(concrete_rand$strength, p = 0.75, list = FALSE)X_train <- X[part.index, ]X_test <- X[-part.index, ]y_train <- y[part.index]y_test <- y[-part.index]
So now we have 4 sets. Two predictors sets splitted into train and test, and two target sets splitted into train and test as well. All of them using the same index for partitioning.
Once again, let’s check everything worked just fine:
str(X_train)str(X_test)str(y_train)str(y_test)
OK! We are good to go! Now to the modeling phase!
As I mentioned in the introduction, in this phase I will change my approach, and instead of going through a check-list of things to do, I will summarize altogether how we will proceed.
We will use package caretEnsemble in order to train a list of models all at the same time
This will allow us to use the same 5 fold cross-validation for each model, thanks to caret’s functionality
We will allow parallel processing to boost speed
We won’t focus on the nature of the algorithms. We will just use them and comment on the results
We will use a linear model, a support vector machines with radial kernel, a random forest, a gradient boosting tree based model and a gradient boosting linear based model
We won’t do manual hyper-parameter tuning, instead we will allow caret to go through some default tuning in each model
We will compare performance over training and test sets, focusing on RMSE as our metric (root mean squared error)
We will use a very cool functionality from caretEnsemble package and will ensemble the model list and then stack them in order to try to produce an ultimate combination of models to hopefully improve performance even more
So let’s move on.
We first set up parallel processing and cross-validation in trainControl()
registerDoParallel(4)getDoParWorkers()set.seed(123)my_control <- trainControl(method = “cv”, # for “cross-validation” number = 5, # number of k-folds savePredictions = “final”, allowParallel = TRUE)
We then train our list of models using the caretList() function by calling our X_train and y_train sets. We specify trControl with our trainControl object created above, and set methodList to a list of algorithms (check the caret package information to understand what models are available and how to use them).
set.seed(222)model_list <- caretList(X_train, y_train, trControl = my_control, methodList = c(“lm”, “svmRadial”, “rf”, “xgbTree”, “xgbLinear”), tuneList = NULL, continue_on_fail = FALSE, preProcess = c(“center”,”scale”))
I use X_train and y_train, but you can perfectly use y ~ x1 + x2 + ... + xn formula instead
my_control specified the 5-fold cross-validation and activated the parallel processing
tuneList is FALSE because we are not specifying manual hyper-parameter tuning
continue_on_fail is set to FALSE so it stops if something goes wrong
in preProcessing is where we scale the dataset. We choose “center” and “scale”
Now that our caretList was trained, we can take a look at the results. We can access each separate model. Here’s the SVM result:
model_list$svmRadial
Notice caret tries some automatic tuning of the available parameters for the model, and chooses the best model using RMSE as performance metric.
This is the same for each of the other models in our list of models. We won’t go through each one of them. That’s for you to check!
Let’s go straight to our goal, which is finding the model that has the lowest RMSE. We first asses this for the training data.
options(digits = 3)model_results <- data.frame( LM = min(model_list$lm$results$RMSE), SVM = min(model_list$svmRadial$results$RMSE), RF = min(model_list$rf$results$RMSE), XGBT = min(model_list$xgbTree$results$RMSE), XGBL = min(model_list$xgbLinear$results$RMSE) )print(model_results)
In terms of RMSE, the the xgbTree model offers the best result, scoring 4.36 (remember the mean strength was 35.8).
caretEnsemble offers a functionality to resample the performance of this model list and plot it:
resamples <- resamples(model_list)dotplot(resamples, metric = “RMSE”)
We can also see that the xgbTree is also presenting a smaller variance compared to the other models.
Next, we will attempt to create a new model by ensembling our model_list in order to find the best possible model, hopefully a model that takes the best of the 5 we have trained and optimizes performance.
Ideally, we would ensemble models that are low correlated with each other. In this case we will see that some high correlation is present, but we will choose to move on regardless, just for the sake of showcasing this feature:
modelCor(resamples)
Firstly, we train an ensemble of our models using caretEnsemble(), which is going to perform a linear combination with all of them.
set.seed(222)ensemble_1 <- caretEnsemble(model_list, metric = “RMSE”, trControl = my_control)summary(ensemble_1)
As we can see, we managed to reduce RMSE for the training set to 4.156
Here’s a plot of our ensemble
plot(ensemble_1)
The red dashed line is the ensemble’s RMSE performance.
Next, we can be more specific and try to do an ensemble using other algorithms with caretStack().
Note: I tried some models but wasn’t able to improve performance. I’ll show just one of them which yielded the same performance over the training data. We will use both ensembles regardless, in order to check which one does better with unseen data.
set.seed(222)ensemble_2 <- caretStack(model_list, method = “glmnet”, metric = “RMSE”, trControl = my_control)print(ensemble_2)
Notice RMSE for the best model using glmnet was 4.15, the same as our first ensemble.
Finally, it’s time to evaluate the performance of our models over unseen data, which is in our test set.
We first predict the test set with each model and then compute RMSE:
# PREDICTIONSpred_lm <- predict.train(model_list$lm, newdata = X_test)pred_svm <- predict.train(model_list$svmRadial, newdata = X_test)pred_rf <- predict.train(model_list$rf, newdata = X_test)pred_xgbT <- predict.train(model_list$xgbTree, newdata = X_test)pred_xgbL <- predict.train(model_list$xgbLinear, newdata = X_test)predict_ens1 <- predict(ensemble_1, newdata = X_test)predict_ens2 <- predict(ensemble_2, newdata = X_test)# RMSEpred_RMSE <- data.frame(ensemble_1 = RMSE(predict_ens1, y_test), ensemble_2 = RMSE(predict_ens2, y_test), LM = RMSE(pred_lm, y_test), SVM = RMSE(pred_svm, y_test), RF = RMSE(pred_rf, y_test), XGBT = RMSE(pred_xgbT, y_test), XGBL = RMSE(pred_xgbL, y_test))print(pred_RMSE)
Surprisingly, the xgbLinear model out performs every other model on the test set, including our ensemble_1 and matching the performance of the ensemble_2
We also observe that in general , there is a difference in performance compared to the training set. This is to be expected. We could still try to manually tune hyper-parameters in order to reduce some overfitting, but at this point I believe we have achieved very strong performance over unseen data and I will leave further optimization for a future publication.
The last thing I wanted to show is variable importance. In order to do this, I will calculate our xgbLinear model separately, indicating I want to retain the variable importance and then plot it:
set.seed(123)xgbTree_model <- train(X_train, y_train, trControl = my_control, method = “xgbLinear”, metric = “RMSE”, preProcess = c(“center”,”scale”), importance = TRUE)plot(varImp(xgbTree_model))
Here we can see the high importance of variables age and cement to the prediction of concrete’s strength. This was to be expected since we had already observed a high correlation between them in our initial correlation plot.
Working with the log of age has also allowed us to improve predictability (as verified separately).
Notice some “unimportant” features present in the chart. Should we have dropped them? Can we simplify our model without impacting performance? We could certainly keep working on that if we needed a simpler model for any reason.
This has been quite the journey! We moved along most of the necessary steps in order to execute a complete and careful machine learning workflow. Even though we didn’t have to do a whole lot of changes and transformation to the original data as imported from the csv, we made sure we understood why and what we should have done otherwise.
Moreover, I was able to showcase the interesting work one can do with caret and caretEnsemble in terms of doing multiple modelling, quick and dirty, all at once and being able to quickly compare model performance. The more advanced data scientists and machine learning enthusiasts could possibly take this as a first draft before proceeding with the more advanced algorithms and fine hyper-parameter tuning that will get those extra bits of performance. For the sake of this work, it proved to be really strong even with the basic configuration.
In the book mentioned in the introduction, the author calculates correlation between predictions (using a neural network with 5 hidden layers) and the true values, obtaining a score of 0.924. It also mentions that compared to the original publication (the one his work was based on), this was a significant improvement (original publication achieved 0.885 using a similar neural network)
So how did we do computing the same correlation score as the book’s author?
pred_cor <- data.frame(ensemble_1 = cor(predict_ens1, y_test), ensemble_2 = cor(predict_ens2, y_test), LM = cor(pred_lm, y_test), SVM = cor(pred_svm, y_test), RF = cor(pred_rf, y_test), XGBT = cor(pred_xgbT, y_test), XGBL = cor(pred_xgbL, y_test))print(pred_cor)
Pretty strong performance!
|
[
{
"code": null,
"e": 545,
"s": 172,
"text": "I’ll use a very interesting dataset presented in the book Machine Learning with R from Packt Publishing, written by Brett Lantz. My intention is to expand the analysis on this dataset by executing a full supervised machine learning workflow which I’ve been laying out for some time now in order to help me attack any similar problem with a systematic, methodical approach."
},
{
"code": null,
"e": 977,
"s": 545,
"text": "If you are thinking this is nothing new, then you’re absolutely right! I’m not coming up with anything new here, just making sure I have all the tools necessary to follow a full process without leaving behind any big detail. Hopefully some of you will find it useful too and be sure you are going to find some judgment errors from my part and/or things you would do differently. Feel free to leave me a comment and help me improve!"
},
{
"code": null,
"e": 1062,
"s": 977,
"text": "Let’s jump ahead and begin to understand what information we are going to work with:"
},
{
"code": null,
"e": 1077,
"s": 1062,
"text": "From the book:"
},
{
"code": null,
"e": 1822,
"s": 1077,
"text": "“In the field of engineering, it is crucial to have accurate estimates of the performance of building materials. These estimates are required in order to develop safety guidelines governing the materials used in the construction of building, bridges, and roadways.Estimating the strength of concrete is a challenge of particular interest. Although it is used in nearly every construction project, concrete performance varies greatly due to a wide variety of ingredients that interact in complex ways. As a result, it is difficult to accurately predict the strength of the final product. A model that could reliably predict concrete strength given a listing of the composition of the input materials could result in safer construction practices."
},
{
"code": null,
"e": 2002,
"s": 1822,
"text": "For this analysis, we will utilize data on the compressive strength of concrete donated to the UCI Machine Learning Data Repository (http://archive.ics.uci.edu/ml) by I-Cheng Yeh."
},
{
"code": null,
"e": 2440,
"s": 2002,
"text": "According to the website, the concrete dataset contains 1,030 examples of concrete with eight features describing the components used in the mixture. These features are thought to be related to the final compressive strength and they include the amount(in kilograms per cubic meter) of cement, slag, ash, water, superplasticizer, coarse aggregate, and fine aggregate used in the product in addition to the aging time (measured in days).”"
},
{
"code": null,
"e": 2674,
"s": 2440,
"text": "I’ve found that splitting the workflow into 6 phases works best for myself. In that sense, I’ll describe this instances as: 1) Setting 2) Exploratory Data Analysis 3) Feature Engineering 4) Data Preparation 5) Modelling 6) Conclusion"
},
{
"code": null,
"e": 2880,
"s": 2674,
"text": "In practice, I end up jumping from one to another, many times regardless of order and often in loop. So think of this just as an initial structure and more of a checklist, rather than a step by step guide."
},
{
"code": null,
"e": 3473,
"s": 2880,
"text": "The checklist is quite comprehending and covers most of what you would follow in supervised learning, both for classification and regression problems. In practice, you will most likely end up skipping some of the points from the list because there are things you do for a classification problem that you don’t do for a regression problem, vice versa. Even some of them are sometimes a little redundant (although double checking is always useful in my opinion). I’m sure that with more practice and experience, this list will get tuned and I’m hoping I can also share that again in the future."
},
{
"code": null,
"e": 3626,
"s": 3473,
"text": "I’ll limit myself to short-direct answers, and will expand whenever necessary. Otherwise I’m afraid I might make it too long for anyone to stick around!"
},
{
"code": null,
"e": 3943,
"s": 3626,
"text": "You will see that even though I’m including the full checklist, in many cases we don’t have to do absolutely anything. This is because this dataset is pretty straightforward. It feels a little bit like cheating, however, I’ll make sure to mention why we don’t have to do anything and the idea behind that checkpoint."
},
{
"code": null,
"e": 4688,
"s": 3943,
"text": "The last thing I wanted to mention is that when I get to the modelling phase, I will change my approach and showcase some useful modelling tools with R packages caret and caretEnsemble. So instead of going step by step trying out some baseline models and them some more advanced models with hyper-parameter tuning and regularization to reduce overfitting, I’m just going to train a bunch of models at once, since it allows me to make this last phase much concise and straightforward for interpretation. Also because the modelling phase is where one likes to do it’s own thing and get creative by using different approaches. In my opinion, this checklist is very important for phases 1 to 4, but then starting phase 5, it can become less strict."
},
{
"code": null,
"e": 4714,
"s": 4688,
"text": "Enough said, let’s begin:"
},
{
"code": null,
"e": 4806,
"s": 4714,
"text": "Find the working files and codes here: https://github.com/gabrielpierobon/ML-workflow-caret"
},
{
"code": null,
"e": 4842,
"s": 4806,
"text": "1.1) What are we trying to predict?"
},
{
"code": null,
"e": 4941,
"s": 4842,
"text": "We need to accurately estimate the performance of building materials for the field of engineering."
},
{
"code": null,
"e": 5094,
"s": 4941,
"text": "1.2) What type of problem is it? Supervised or Unsupervised Learning? Classification or Regression? Binary or Multi-class? Uni-variate or Multi-variate?"
},
{
"code": null,
"e": 5242,
"s": 5094,
"text": "This is a multivariate supervised machine learning problem in which we have to predict numeric outcomes, thus we’ll be using regression techniques."
},
{
"code": null,
"e": 5277,
"s": 5242,
"text": "1.3) What type of data do we have?"
},
{
"code": null,
"e": 5400,
"s": 5277,
"text": "Our data is in “csv” format. It presents a header row with the column names. It seems to contain only numeric information."
},
{
"code": null,
"e": 5424,
"s": 5400,
"text": "1.4) Import the dataset"
},
{
"code": null,
"e": 5462,
"s": 5424,
"text": "We can simply load it with this code:"
},
{
"code": null,
"e": 5576,
"s": 5462,
"text": "concrete <- read.csv(“/Users/Gabriel Pierobon/Desktop/Datasets para cargar/concrete.csv”)#use your own directory!"
},
{
"code": null,
"e": 5609,
"s": 5576,
"text": "This is the size of our dataset:"
},
{
"code": null,
"e": 5636,
"s": 5609,
"text": "dim(concrete)[1] 1030 9"
},
{
"code": null,
"e": 5708,
"s": 5636,
"text": "1,030 rows and 9 columns, one of which is our response/target variable."
},
{
"code": null,
"e": 5816,
"s": 5708,
"text": "We can see that it was imported as a data frame which is the format that we require to work with this data:"
},
{
"code": null,
"e": 5848,
"s": 5816,
"text": "class(concrete)[1] \"data.frame\""
},
{
"code": null,
"e": 5921,
"s": 5848,
"text": "We can also check that the names of our columns were correctly imported."
},
{
"code": null,
"e": 5937,
"s": 5921,
"text": "names(concrete)"
},
{
"code": null,
"e": 6007,
"s": 5937,
"text": "From that list, we identify strength as our response/target variable."
},
{
"code": null,
"e": 6092,
"s": 6007,
"text": "We can conclude that our data was correctly imported and thus end our setting phase."
},
{
"code": null,
"e": 6247,
"s": 6092,
"text": "Before we do that, I’d like to require all our libraries altogether. It’s useful to do it all at once at the begging, to improve readability of this work:"
},
{
"code": null,
"e": 6422,
"s": 6247,
"text": "library(dplyr)library(ggplot2)library(PerformanceAnalytics)library(ggthemes)library(corrplot)library(car)library(psych)library(caret)library(caretEnsemble)library(doParallel)"
},
{
"code": null,
"e": 6491,
"s": 6422,
"text": "With that taken care of, let’s move on to exploratory data analysis:"
},
{
"code": null,
"e": 6562,
"s": 6491,
"text": "2.1) View Data (str or dplyr’s glimpse). First look. Anything strange?"
},
{
"code": null,
"e": 6689,
"s": 6562,
"text": "The fist way we want to double check what we did in the setting phase is to quickly view our full dataset. We do it like this:"
},
{
"code": null,
"e": 6704,
"s": 6689,
"text": "View(concrete)"
},
{
"code": null,
"e": 7023,
"s": 6704,
"text": "This will display a window with the dataset. I like to quickly look at it from top to bottom and left to right to reassure the fact that the data was loaded correctly. It’s also a quick and dirty way to detect issues that could be observable at first glance. You don’t want to do this for significantly large datasets."
},
{
"code": null,
"e": 7127,
"s": 7023,
"text": "Next, we are going to take a glimpse at our data and observe just the first few rows of the data frame:"
},
{
"code": null,
"e": 7145,
"s": 7127,
"text": "glimpse(concrete)"
},
{
"code": null,
"e": 7160,
"s": 7145,
"text": "head(concrete)"
},
{
"code": null,
"e": 7265,
"s": 7160,
"text": "2.2) Is it a “tidy” dataset? Need to “gather” or “spread” it? Is it presented in a way we can work with?"
},
{
"code": null,
"e": 7595,
"s": 7265,
"text": "We need our data to be presented with individual observations as rows and features as columns. Fortunately for us, this is the case of this dataset, so we won’t have to transform it. Otherwise, we would have to use some sort of function to pivot the data frame to accommodate to our needs (refer to this site for more about that)"
},
{
"code": null,
"e": 7649,
"s": 7595,
"text": "2.3) rownames and colnames ok? Should we change them?"
},
{
"code": null,
"e": 7985,
"s": 7649,
"text": "We have already checked how these were loaded. Do we need to update/change anything to have clearer understanding of our variables? I don’t think this is the case, we can move on. The idea here is to make sure we move forward comfortably with our feature names, avoiding unnecessary long names or any other sort of confusing situation."
},
{
"code": null,
"e": 8037,
"s": 7985,
"text": "2.4) Check data types. Are they OK? If not, convert"
},
{
"code": null,
"e": 8396,
"s": 8037,
"text": "As we have seen, all our variables are of the double type, except for the variable age which is integer. Fortunately, we don’t have to convert anything! It’s very important that we check this in order to avoid some type of error when loading the data. Sometimes a single character in a numeric column can result in the whole column being loaded as character."
},
{
"code": null,
"e": 8465,
"s": 8396,
"text": "2.5) What is our response/target variable? Class imbalance? Study it"
},
{
"code": null,
"e": 8547,
"s": 8465,
"text": "Our response variable is strength. Let’s look at some useful statistics about it:"
},
{
"code": null,
"e": 8574,
"s": 8547,
"text": "summary(concrete$strength)"
},
{
"code": null,
"e": 8771,
"s": 8574,
"text": "We can see that it ranges from 2.3 to 82.6. The median and the mean are really close, but since median is actually smaller, this results in a slight skew of the variable distribution to the right."
},
{
"code": null,
"e": 8818,
"s": 8771,
"text": "We can observe that with a plot using ggplot2:"
},
{
"code": null,
"e": 9068,
"s": 8818,
"text": "As we can see, the distribution of the strength variable is not perfectly normal, but we are going to proceed regardless. This shouldn’t be a problem because it’s close. A qqplot also helps with the visual analysis of normality (I leave that to you)"
},
{
"code": null,
"e": 9280,
"s": 9068,
"text": "Lastly, since this is a regression problem, we don’t have to worry about class imbalance. In classification, you want to have balanced classes in your response variable (here’s a nice post about class imbalance)"
},
{
"code": null,
"e": 9348,
"s": 9280,
"text": "2.6) Rest of the features. Summary statistics. Understand your data"
},
{
"code": null,
"e": 9679,
"s": 9348,
"text": "Here we extend the statistical analysis to our other variables/features. We want to pay attention at the minimums and maximums (this is a first check for potential outliers). Also, mean and median difference is something to be concerned about. We would like all our variables to follow the normal distribution as much as possible."
},
{
"code": null,
"e": 9697,
"s": 9679,
"text": "summary(concrete)"
},
{
"code": null,
"e": 10031,
"s": 9697,
"text": "We can follow our analysis with a correlation plot. This will present us with a chart showing the correlation between all variables. It will also let us think for the first time if we need all our variables in our model. We don’t want our feature variables to present a high correlation between them. We will take care of this later."
},
{
"code": null,
"e": 10074,
"s": 10031,
"text": "corrplot(cor(concrete), method = “square”)"
},
{
"code": null,
"e": 10157,
"s": 10074,
"text": "Another nice way of looking at all of this together is with this correlation plot:"
},
{
"code": null,
"e": 10185,
"s": 10157,
"text": "chart.Correlation(concrete)"
},
{
"code": null,
"e": 10324,
"s": 10185,
"text": "On one of the diagonals, we can see the distribution of each feature. Not all of them resemble normality, so we will deal with this later."
},
{
"code": null,
"e": 10578,
"s": 10324,
"text": "At this point my first conclusion is that the variable ash has low correlation with our response variable strength and a high correlation with four of the eight other features. It is thus a strong candidate to be removed, we’ll cover this later as well."
},
{
"code": null,
"e": 10684,
"s": 10578,
"text": "2.7) Categorical data/Factors: create count tables to understand different categories. Check all of them."
},
{
"code": null,
"e": 10862,
"s": 10684,
"text": "In this case we are not working with categorical features. You want to make sure you understand your categories, sometimes misspells can introduce problems for factor variables."
},
{
"code": null,
"e": 10878,
"s": 10862,
"text": "We can move on."
},
{
"code": null,
"e": 10963,
"s": 10878,
"text": "2.8) Unnecessary columns? Columns we can quickly understand we don’t need. Drop them"
},
{
"code": null,
"e": 11342,
"s": 10963,
"text": "Here we want to look for columns which are totally useless. Anything that would come in the dataset that is really uninformative and we can determine that we should drop. Additional index columns, uninformative string columns, etc. This is not the case for this dataset. You could perfectly do this as soon as you import the dataset, no need to do it specifically at this point."
},
{
"code": null,
"e": 11416,
"s": 11342,
"text": "2.9) Check for missing values. How many? Where? Delete them? Impute them?"
},
{
"code": null,
"e": 11457,
"s": 11416,
"text": "Let’s first do an overall check for NAs:"
},
{
"code": null,
"e": 11482,
"s": 11457,
"text": "anyNA(concrete)[1] FALSE"
},
{
"code": null,
"e": 11602,
"s": 11482,
"text": "Wonderful! no missing values in the whole set! Let me also show you a way we could have detected this for every column:"
},
{
"code": null,
"e": 11648,
"s": 11602,
"text": "sapply(concrete, {function(x) any(is.na(x))})"
},
{
"code": null,
"e": 11693,
"s": 11648,
"text": "(Some tools for dealing with missing values)"
},
{
"code": null,
"e": 11795,
"s": 11693,
"text": "2.10) Check for outliers and other inconsistent data points. Box-plots. DBSCAN for outlier detection?"
},
{
"code": null,
"e": 12202,
"s": 11795,
"text": "Outlier detection is more of a craft than anything else, in my opinion. I really like the approach of using DBSCAN clustering for outlier detection but I’m not going to proceed with this so I don’t overextend this analysis. DBSCAN is a clustering algorithm that can detect noise points in the data and not assign them to any cluster. I find it very compelling for outlier detection (more about DBSCAN here)"
},
{
"code": null,
"e": 12312,
"s": 12202,
"text": "Instead, I’ll just go ahead with a boxplot and try to work with the points I consider relevant just by sight:"
},
{
"code": null,
"e": 12377,
"s": 12312,
"text": "boxplot(concrete[-9], col = “orange”, main = “Features Boxplot”)"
},
{
"code": null,
"e": 12525,
"s": 12377,
"text": "We see that there are several potential outliers, however I consider that the age feature could be the most problematic. Let’s look at it isolated:"
},
{
"code": null,
"e": 12560,
"s": 12525,
"text": "boxplot(concrete$age, col = “red”)"
},
{
"code": null,
"e": 12710,
"s": 12560,
"text": "Are these just 4 outliers? If so, we could just get rid of them. Or shouldn’t we? Let’s find out what this values are and how many of them are there."
},
{
"code": null,
"e": 12781,
"s": 12710,
"text": "age_outliers <- which(concrete$age > 100)concrete[age_outliers, “age”]"
},
{
"code": null,
"e": 13135,
"s": 12781,
"text": "Oh my! so there were 62 of them instead of just 4! Obviously this is simply because the same numbers are repeated several times. This makes me think that this age points are actually relevant and we don’t want to get rid of them. 62 data points from our 1,030 dataset seems too high a number to just eliminate (we would be losing plenty of information)."
},
{
"code": null,
"e": 13219,
"s": 13135,
"text": "2.11) Check for multicollinearity in numeric data. Variance Inflation Factors (VIF)"
},
{
"code": null,
"e": 13779,
"s": 13219,
"text": "We’ve already seen in the correlation plot presented before that there seems to be significant correlation between some features. We want to make sure that multicollinearity is not an issue that prevents us to move forward. In order to do this, we will compute a score called Variance Inflation Factor (VIF) which measures how much the variance of a regression coefficient is inflated due to multicollinearity in the model. If VIF score is more than 10, multicollinearity is strongly suggested and we should try to get rid of the features that are causing it."
},
{
"code": null,
"e": 13986,
"s": 13779,
"text": "First, we generate a simple linear regression model of our target variable explained by each other feature. Afterwards, we call function vif()on the model object and we take a look at the named list output:"
},
{
"code": null,
"e": 14047,
"s": 13986,
"text": "simple_lm <- lm(strength ~ ., data = concrete)vif(simple_lm)"
},
{
"code": null,
"e": 14356,
"s": 14047,
"text": "Even though there are many variables scoring 5 and higher, none of them surpasses the threshold of 10 so we will consider multicollinearity not to be a big issue. However, some would argue that it could indeed be a problem to have as many features with scores of 7. We will not worry about that at this time."
},
{
"code": null,
"e": 14564,
"s": 14356,
"text": "With this, we consider the Exploratory Data Analysis (EDA) phase over and we move on to Feature Engineering. Feel free to disagree with this being over! I’m sure there still plenty of exploration left to do."
},
{
"code": null,
"e": 15093,
"s": 14564,
"text": "Feature engineering could also be considered a very important craft for a data scientist. It involves the production of new features obtained from the features present in the dataset. This could be as simple as extracting some dates information from string columns, or producing interaction terms. Moreover, it will certainly require some degree of subject matter expertise and domain knowledge, since coming up with new informative features is something intrinsic to the nature of the data and the overall field of application."
},
{
"code": null,
"e": 15217,
"s": 15093,
"text": "Here, we will go super quick, since our data seems to be already very informative and complete (engineers might disagree!)."
},
{
"code": null,
"e": 15560,
"s": 15217,
"text": "I wanted to mention that engineering new features will most likely require that we repeat some of the previous analysis we have already done, since we don’t want to introduce new features that add noise to the dataset. So bear in mind that we must always look at our checklist back again and define if we need to analyze things one more time."
},
{
"code": null,
"e": 15681,
"s": 15560,
"text": "3.1) Create new useful features. Interaction Terms. Basic math and statistics. Create categories with if-else structures"
},
{
"code": null,
"e": 15882,
"s": 15681,
"text": "Because I’m not a subject matter expert in engineering, I won’t create new features from interaction terms. I’ll just limit myself to verify if any of the variables require any type of transformation."
},
{
"code": null,
"e": 16085,
"s": 15882,
"text": "The first thing that I want to do is to check two variables which seem to have unusual distributions. It is the case of age and superplastic. Let’s plot their original form and also logs below (in red)."
},
{
"code": null,
"e": 16231,
"s": 16085,
"text": "par(mfrow = c(2,2))hist(concrete$age)hist(concrete$superplastic)hist(log(concrete$age), col = “red”)hist(log(concrete$superplastic), col = “red”)"
},
{
"code": null,
"e": 16469,
"s": 16231,
"text": "While I feel comfortable with converting age to it’s logarithmic form, in the case of superplastic, with as many observations being 0, I’ll have some issues when taking the log of 0, so I’ll take the log and then manually set those to 0."
},
{
"code": null,
"e": 16511,
"s": 16469,
"text": "Below, the code to convert both features:"
},
{
"code": null,
"e": 16731,
"s": 16511,
"text": "concrete$age <- log(concrete$age)concrete$superplastic <- log(concrete$superplastic)concrete$superplastic <- ifelse(concrete$superplastic == -Inf, 0, concrete$superplastic)head(concrete)"
},
{
"code": null,
"e": 17125,
"s": 16731,
"text": "Note: I spent quite some time at this point trying to create a new superplastic feature by binning the original superplastic feature into 3 numeric categories. However, I didn’t have much success in terms of importance to explain the target variable. I won’t show those attempts, but just know that I indeed tried to work on that for some time unsuccessfully. Failing is also part of learning!"
},
{
"code": null,
"e": 17205,
"s": 17125,
"text": "3.2) Create dummies for categorical features. Preferably using One-Hot-Encoding"
},
{
"code": null,
"e": 17466,
"s": 17205,
"text": "We are not working with categorical features at this time, so this section will be skipped. However, if you were presented with some factor columns, you will have to make sure your algorithm can work with those, or otherwise proceed with one-hot-encoding them."
},
{
"code": null,
"e": 17553,
"s": 17466,
"text": "3.3) Can we extract some important text from string columns using regular expressions?"
},
{
"code": null,
"e": 17776,
"s": 17553,
"text": "We are not working with sting data at this time, so this section will be skipped. This should be a very useful tool when you have some relevant information in character type from which you can create new useful categories."
},
{
"code": null,
"e": 17990,
"s": 17776,
"text": "Thankfully we didn’t have to go through all of that! However, those last 3 sections are a MUST if we are working with that type of information. I’ll make sure to analyze a dataset in which I can show some of that."
},
{
"code": null,
"e": 18035,
"s": 17990,
"text": "Let’s move on to the Data Preparation phase:"
},
{
"code": null,
"e": 18138,
"s": 18035,
"text": "4.1) Manual feature selection. Remove noisy, uninformative, highly-correlated, or duplicated features."
},
{
"code": null,
"e": 18369,
"s": 18138,
"text": "Here’s where we take spend time for the second time in this workflow looking at our features and detecting if any of them are uninformative enough or should be dropped because of introducing problems as could be multicollinearity."
},
{
"code": null,
"e": 18633,
"s": 18369,
"text": "As I already had decided, I’ll first drop the ash feature (you might want to leave it and remove it after trying some baseline models, deciding to drop it if it does not help with performance, I already did that, so I’ll drop it now, as was my initial assessment)"
},
{
"code": null,
"e": 18668,
"s": 18633,
"text": "concrete$ash <- NULLhead(concrete)"
},
{
"code": null,
"e": 18712,
"s": 18668,
"text": "Besides that, I won’t remove anything else."
},
{
"code": null,
"e": 18775,
"s": 18712,
"text": "4.2) Transform data if needed. Scale or normalize if required."
},
{
"code": null,
"e": 18879,
"s": 18775,
"text": "Most of the algorithms we will use require our numeric features to be scaled or normalized (here’s why)"
},
{
"code": null,
"e": 19296,
"s": 18879,
"text": "We won’t be doing that in this precise section, but leave it for later, since caret allows us to do some pre-processing within it’s training functionality. This is specifically useful because the algorithm will automatically transform back to it’s original scale when presenting us with predictions and results. If I manually normalized the dataset here, then I would have to manually transform back the predictions."
},
{
"code": null,
"e": 19374,
"s": 19296,
"text": "4.3) Automatic Feature extraction. Dimensionality Reduction (PCA, NMF, t-SNE)"
},
{
"code": null,
"e": 19742,
"s": 19374,
"text": "If removing features manually isn’t straightforward enough but we still consider our dataset to contain too many features or too correlated features, we can apply dimensonality reduction techniques. Principal Components Analysis is one of those techniques, and a really useful one to both simplify our dataset, and also remove the issue of multicollinearity for good."
},
{
"code": null,
"e": 19850,
"s": 19742,
"text": "Non-negative Matrix Factorization (NMF) and t-SNE are other two useful dimensionality reduction techniques."
},
{
"code": null,
"e": 19984,
"s": 19850,
"text": "With just 8 features in our dataset and 1 already dropped manually, I don’t consider we require to reduce dimensionality any further."
},
{
"code": null,
"e": 20016,
"s": 19984,
"text": "4.4) Is our dataset randomized?"
},
{
"code": null,
"e": 20086,
"s": 20016,
"text": "We are not sure it is randomized, so we will shuffle it just in case:"
},
{
"code": null,
"e": 20171,
"s": 20086,
"text": "set.seed(123)concrete_rand <- concrete[sample(1:nrow(concrete)), ]dim(concrete_rand)"
},
{
"code": null,
"e": 20278,
"s": 20171,
"text": "4.5) Define an evaluation protocol: how many samples do we have? Hold out method. Cross validation needed?"
},
{
"code": null,
"e": 20530,
"s": 20278,
"text": "We have 1,030 samples, so this is definitely a small dataset. We will divide the dataset into train and test sets and make sure we use cross-validation when we train our model. In that way we ensure we are using our few observations as well as we can."
},
{
"code": null,
"e": 20601,
"s": 20530,
"text": "4.6) Split dataset into train & test sets (set seed for replicability)"
},
{
"code": null,
"e": 20670,
"s": 20601,
"text": "We first create a set of predictors and a set of our target variable"
},
{
"code": null,
"e": 20716,
"s": 20670,
"text": "X = concrete_rand[, -8]y = concrete_rand[, 8]"
},
{
"code": null,
"e": 20743,
"s": 20716,
"text": "We check everything is OK:"
},
{
"code": null,
"e": 20750,
"s": 20743,
"text": "str(X)"
},
{
"code": null,
"e": 20757,
"s": 20750,
"text": "str(y)"
},
{
"code": null,
"e": 20853,
"s": 20757,
"text": "We then proceed to split our new X(predictors) and y (target) sets into training and test sets."
},
{
"code": null,
"e": 21074,
"s": 20853,
"text": "Note: you don’t have to separate the sets, and can perfectly go ahead using the formula method. I just prefer to do it this way, because this way I’m sure I align my proceeding to how I’d work with Python’s scikit-learn."
},
{
"code": null,
"e": 21216,
"s": 21074,
"text": "We will use caret’s createDataPartition() function, which generates the partition indexes for us, and we will use them to perform the splits:"
},
{
"code": null,
"e": 21503,
"s": 21216,
"text": "set.seed(123)part.index <- createDataPartition(concrete_rand$strength, p = 0.75, list = FALSE)X_train <- X[part.index, ]X_test <- X[-part.index, ]y_train <- y[part.index]y_test <- y[-part.index]"
},
{
"code": null,
"e": 21685,
"s": 21503,
"text": "So now we have 4 sets. Two predictors sets splitted into train and test, and two target sets splitted into train and test as well. All of them using the same index for partitioning."
},
{
"code": null,
"e": 21738,
"s": 21685,
"text": "Once again, let’s check everything worked just fine:"
},
{
"code": null,
"e": 21785,
"s": 21738,
"text": "str(X_train)str(X_test)str(y_train)str(y_test)"
},
{
"code": null,
"e": 21835,
"s": 21785,
"text": "OK! We are good to go! Now to the modeling phase!"
},
{
"code": null,
"e": 22020,
"s": 21835,
"text": "As I mentioned in the introduction, in this phase I will change my approach, and instead of going through a check-list of things to do, I will summarize altogether how we will proceed."
},
{
"code": null,
"e": 22110,
"s": 22020,
"text": "We will use package caretEnsemble in order to train a list of models all at the same time"
},
{
"code": null,
"e": 22217,
"s": 22110,
"text": "This will allow us to use the same 5 fold cross-validation for each model, thanks to caret’s functionality"
},
{
"code": null,
"e": 22266,
"s": 22217,
"text": "We will allow parallel processing to boost speed"
},
{
"code": null,
"e": 22363,
"s": 22266,
"text": "We won’t focus on the nature of the algorithms. We will just use them and comment on the results"
},
{
"code": null,
"e": 22534,
"s": 22363,
"text": "We will use a linear model, a support vector machines with radial kernel, a random forest, a gradient boosting tree based model and a gradient boosting linear based model"
},
{
"code": null,
"e": 22653,
"s": 22534,
"text": "We won’t do manual hyper-parameter tuning, instead we will allow caret to go through some default tuning in each model"
},
{
"code": null,
"e": 22767,
"s": 22653,
"text": "We will compare performance over training and test sets, focusing on RMSE as our metric (root mean squared error)"
},
{
"code": null,
"e": 22989,
"s": 22767,
"text": "We will use a very cool functionality from caretEnsemble package and will ensemble the model list and then stack them in order to try to produce an ultimate combination of models to hopefully improve performance even more"
},
{
"code": null,
"e": 23007,
"s": 22989,
"text": "So let’s move on."
},
{
"code": null,
"e": 23082,
"s": 23007,
"text": "We first set up parallel processing and cross-validation in trainControl()"
},
{
"code": null,
"e": 23359,
"s": 23082,
"text": "registerDoParallel(4)getDoParWorkers()set.seed(123)my_control <- trainControl(method = “cv”, # for “cross-validation” number = 5, # number of k-folds savePredictions = “final”, allowParallel = TRUE)"
},
{
"code": null,
"e": 23671,
"s": 23359,
"text": "We then train our list of models using the caretList() function by calling our X_train and y_train sets. We specify trControl with our trainControl object created above, and set methodList to a list of algorithms (check the caret package information to understand what models are available and how to use them)."
},
{
"code": null,
"e": 24070,
"s": 23671,
"text": "set.seed(222)model_list <- caretList(X_train, y_train, trControl = my_control, methodList = c(“lm”, “svmRadial”, “rf”, “xgbTree”, “xgbLinear”), tuneList = NULL, continue_on_fail = FALSE, preProcess = c(“center”,”scale”))"
},
{
"code": null,
"e": 24162,
"s": 24070,
"text": "I use X_train and y_train, but you can perfectly use y ~ x1 + x2 + ... + xn formula instead"
},
{
"code": null,
"e": 24249,
"s": 24162,
"text": "my_control specified the 5-fold cross-validation and activated the parallel processing"
},
{
"code": null,
"e": 24327,
"s": 24249,
"text": "tuneList is FALSE because we are not specifying manual hyper-parameter tuning"
},
{
"code": null,
"e": 24396,
"s": 24327,
"text": "continue_on_fail is set to FALSE so it stops if something goes wrong"
},
{
"code": null,
"e": 24475,
"s": 24396,
"text": "in preProcessing is where we scale the dataset. We choose “center” and “scale”"
},
{
"code": null,
"e": 24604,
"s": 24475,
"text": "Now that our caretList was trained, we can take a look at the results. We can access each separate model. Here’s the SVM result:"
},
{
"code": null,
"e": 24625,
"s": 24604,
"text": "model_list$svmRadial"
},
{
"code": null,
"e": 24770,
"s": 24625,
"text": "Notice caret tries some automatic tuning of the available parameters for the model, and chooses the best model using RMSE as performance metric."
},
{
"code": null,
"e": 24902,
"s": 24770,
"text": "This is the same for each of the other models in our list of models. We won’t go through each one of them. That’s for you to check!"
},
{
"code": null,
"e": 25029,
"s": 24902,
"text": "Let’s go straight to our goal, which is finding the model that has the lowest RMSE. We first asses this for the training data."
},
{
"code": null,
"e": 25312,
"s": 25029,
"text": "options(digits = 3)model_results <- data.frame( LM = min(model_list$lm$results$RMSE), SVM = min(model_list$svmRadial$results$RMSE), RF = min(model_list$rf$results$RMSE), XGBT = min(model_list$xgbTree$results$RMSE), XGBL = min(model_list$xgbLinear$results$RMSE) )print(model_results)"
},
{
"code": null,
"e": 25428,
"s": 25312,
"text": "In terms of RMSE, the the xgbTree model offers the best result, scoring 4.36 (remember the mean strength was 35.8)."
},
{
"code": null,
"e": 25525,
"s": 25428,
"text": "caretEnsemble offers a functionality to resample the performance of this model list and plot it:"
},
{
"code": null,
"e": 25595,
"s": 25525,
"text": "resamples <- resamples(model_list)dotplot(resamples, metric = “RMSE”)"
},
{
"code": null,
"e": 25696,
"s": 25595,
"text": "We can also see that the xgbTree is also presenting a smaller variance compared to the other models."
},
{
"code": null,
"e": 25901,
"s": 25696,
"text": "Next, we will attempt to create a new model by ensembling our model_list in order to find the best possible model, hopefully a model that takes the best of the 5 we have trained and optimizes performance."
},
{
"code": null,
"e": 26128,
"s": 25901,
"text": "Ideally, we would ensemble models that are low correlated with each other. In this case we will see that some high correlation is present, but we will choose to move on regardless, just for the sake of showcasing this feature:"
},
{
"code": null,
"e": 26148,
"s": 26128,
"text": "modelCor(resamples)"
},
{
"code": null,
"e": 26280,
"s": 26148,
"text": "Firstly, we train an ensemble of our models using caretEnsemble(), which is going to perform a linear combination with all of them."
},
{
"code": null,
"e": 26449,
"s": 26280,
"text": "set.seed(222)ensemble_1 <- caretEnsemble(model_list, metric = “RMSE”, trControl = my_control)summary(ensemble_1)"
},
{
"code": null,
"e": 26520,
"s": 26449,
"text": "As we can see, we managed to reduce RMSE for the training set to 4.156"
},
{
"code": null,
"e": 26550,
"s": 26520,
"text": "Here’s a plot of our ensemble"
},
{
"code": null,
"e": 26567,
"s": 26550,
"text": "plot(ensemble_1)"
},
{
"code": null,
"e": 26623,
"s": 26567,
"text": "The red dashed line is the ensemble’s RMSE performance."
},
{
"code": null,
"e": 26721,
"s": 26623,
"text": "Next, we can be more specific and try to do an ensemble using other algorithms with caretStack()."
},
{
"code": null,
"e": 26970,
"s": 26721,
"text": "Note: I tried some models but wasn’t able to improve performance. I’ll show just one of them which yielded the same performance over the training data. We will use both ensembles regardless, in order to check which one does better with unseen data."
},
{
"code": null,
"e": 27172,
"s": 26970,
"text": "set.seed(222)ensemble_2 <- caretStack(model_list, method = “glmnet”, metric = “RMSE”, trControl = my_control)print(ensemble_2)"
},
{
"code": null,
"e": 27258,
"s": 27172,
"text": "Notice RMSE for the best model using glmnet was 4.15, the same as our first ensemble."
},
{
"code": null,
"e": 27363,
"s": 27258,
"text": "Finally, it’s time to evaluate the performance of our models over unseen data, which is in our test set."
},
{
"code": null,
"e": 27432,
"s": 27363,
"text": "We first predict the test set with each model and then compute RMSE:"
},
{
"code": null,
"e": 28276,
"s": 27432,
"text": "# PREDICTIONSpred_lm <- predict.train(model_list$lm, newdata = X_test)pred_svm <- predict.train(model_list$svmRadial, newdata = X_test)pred_rf <- predict.train(model_list$rf, newdata = X_test)pred_xgbT <- predict.train(model_list$xgbTree, newdata = X_test)pred_xgbL <- predict.train(model_list$xgbLinear, newdata = X_test)predict_ens1 <- predict(ensemble_1, newdata = X_test)predict_ens2 <- predict(ensemble_2, newdata = X_test)# RMSEpred_RMSE <- data.frame(ensemble_1 = RMSE(predict_ens1, y_test), ensemble_2 = RMSE(predict_ens2, y_test), LM = RMSE(pred_lm, y_test), SVM = RMSE(pred_svm, y_test), RF = RMSE(pred_rf, y_test), XGBT = RMSE(pred_xgbT, y_test), XGBL = RMSE(pred_xgbL, y_test))print(pred_RMSE)"
},
{
"code": null,
"e": 28430,
"s": 28276,
"text": "Surprisingly, the xgbLinear model out performs every other model on the test set, including our ensemble_1 and matching the performance of the ensemble_2"
},
{
"code": null,
"e": 28795,
"s": 28430,
"text": "We also observe that in general , there is a difference in performance compared to the training set. This is to be expected. We could still try to manually tune hyper-parameters in order to reduce some overfitting, but at this point I believe we have achieved very strong performance over unseen data and I will leave further optimization for a future publication."
},
{
"code": null,
"e": 28991,
"s": 28795,
"text": "The last thing I wanted to show is variable importance. In order to do this, I will calculate our xgbLinear model separately, indicating I want to retain the variable importance and then plot it:"
},
{
"code": null,
"e": 29320,
"s": 28991,
"text": "set.seed(123)xgbTree_model <- train(X_train, y_train, trControl = my_control, method = “xgbLinear”, metric = “RMSE”, preProcess = c(“center”,”scale”), importance = TRUE)plot(varImp(xgbTree_model))"
},
{
"code": null,
"e": 29545,
"s": 29320,
"text": "Here we can see the high importance of variables age and cement to the prediction of concrete’s strength. This was to be expected since we had already observed a high correlation between them in our initial correlation plot."
},
{
"code": null,
"e": 29645,
"s": 29545,
"text": "Working with the log of age has also allowed us to improve predictability (as verified separately)."
},
{
"code": null,
"e": 29873,
"s": 29645,
"text": "Notice some “unimportant” features present in the chart. Should we have dropped them? Can we simplify our model without impacting performance? We could certainly keep working on that if we needed a simpler model for any reason."
},
{
"code": null,
"e": 30212,
"s": 29873,
"text": "This has been quite the journey! We moved along most of the necessary steps in order to execute a complete and careful machine learning workflow. Even though we didn’t have to do a whole lot of changes and transformation to the original data as imported from the csv, we made sure we understood why and what we should have done otherwise."
},
{
"code": null,
"e": 30758,
"s": 30212,
"text": "Moreover, I was able to showcase the interesting work one can do with caret and caretEnsemble in terms of doing multiple modelling, quick and dirty, all at once and being able to quickly compare model performance. The more advanced data scientists and machine learning enthusiasts could possibly take this as a first draft before proceeding with the more advanced algorithms and fine hyper-parameter tuning that will get those extra bits of performance. For the sake of this work, it proved to be really strong even with the basic configuration."
},
{
"code": null,
"e": 31146,
"s": 30758,
"text": "In the book mentioned in the introduction, the author calculates correlation between predictions (using a neural network with 5 hidden layers) and the true values, obtaining a score of 0.924. It also mentions that compared to the original publication (the one his work was based on), this was a significant improvement (original publication achieved 0.885 using a similar neural network)"
},
{
"code": null,
"e": 31222,
"s": 31146,
"text": "So how did we do computing the same correlation score as the book’s author?"
},
{
"code": null,
"e": 31617,
"s": 31222,
"text": "pred_cor <- data.frame(ensemble_1 = cor(predict_ens1, y_test), ensemble_2 = cor(predict_ens2, y_test), LM = cor(pred_lm, y_test), SVM = cor(pred_svm, y_test), RF = cor(pred_rf, y_test), XGBT = cor(pred_xgbT, y_test), XGBL = cor(pred_xgbL, y_test))print(pred_cor)"
}
] |
C - typedef
|
The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example..
BYTE b1, b2;
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −
typedef unsigned char byte;
You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
#define is a C-directive which is also used to define the aliases for various data types similar to typedef but with the following differences −
typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc.
typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.
The following example shows how to use #define in a program −
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main( ) {
printf( "Value of TRUE : %d\n", TRUE);
printf( "Value of FALSE : %d\n", FALSE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of TRUE : 1
Value of FALSE : 0
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2260,
"s": 2084,
"text": "The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers −"
},
{
"code": null,
"e": 2289,
"s": 2260,
"text": "typedef unsigned char BYTE;\n"
},
{
"code": null,
"e": 2410,
"s": 2289,
"text": "After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example.."
},
{
"code": null,
"e": 2425,
"s": 2410,
"text": "BYTE b1, b2;\n"
},
{
"code": null,
"e": 2602,
"s": 2425,
"text": "By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows −"
},
{
"code": null,
"e": 2631,
"s": 2602,
"text": "typedef unsigned char byte;\n"
},
{
"code": null,
"e": 2861,
"s": 2631,
"text": "You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −"
},
{
"code": null,
"e": 3409,
"s": 2861,
"text": "#include <stdio.h>\n#include <string.h>\n \ntypedef struct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} Book;\n \nint main( ) {\n\n Book book;\n \n strcpy( book.title, \"C Programming\");\n strcpy( book.author, \"Nuha Ali\"); \n strcpy( book.subject, \"C Programming Tutorial\");\n book.book_id = 6495407;\n \n printf( \"Book title : %s\\n\", book.title);\n printf( \"Book author : %s\\n\", book.author);\n printf( \"Book subject : %s\\n\", book.subject);\n printf( \"Book book_id : %d\\n\", book.book_id);\n\n return 0;\n}"
},
{
"code": null,
"e": 3490,
"s": 3409,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3606,
"s": 3490,
"text": "Book title : C Programming\nBook author : Nuha Ali\nBook subject : C Programming Tutorial\nBook book_id : 6495407\n"
},
{
"code": null,
"e": 3751,
"s": 3606,
"text": "#define is a C-directive which is also used to define the aliases for various data types similar to typedef but with the following differences −"
},
{
"code": null,
"e": 3907,
"s": 3751,
"text": "typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc."
},
{
"code": null,
"e": 4063,
"s": 3907,
"text": "typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, q., you can define 1 as ONE etc."
},
{
"code": null,
"e": 4178,
"s": 4063,
"text": "typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor."
},
{
"code": null,
"e": 4293,
"s": 4178,
"text": "typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor."
},
{
"code": null,
"e": 4355,
"s": 4293,
"text": "The following example shows how to use #define in a program −"
},
{
"code": null,
"e": 4526,
"s": 4355,
"text": "#include <stdio.h>\n \n#define TRUE 1\n#define FALSE 0\n \nint main( ) {\n printf( \"Value of TRUE : %d\\n\", TRUE);\n printf( \"Value of FALSE : %d\\n\", FALSE);\n\n return 0;\n}"
},
{
"code": null,
"e": 4607,
"s": 4526,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4645,
"s": 4607,
"text": "Value of TRUE : 1\nValue of FALSE : 0\n"
},
{
"code": null,
"e": 4652,
"s": 4645,
"text": " Print"
},
{
"code": null,
"e": 4663,
"s": 4652,
"text": " Add Notes"
}
] |
ES6 - Arrays
|
The use of variables to store values poses the following limitations −
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
JavaScript introduces the concept of arrays to tackle the same.
An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user-defined type.
An array declaration allocates sequential memory blocks.
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Arrays are static. This means that an array once initialized cannot be resized.
Each memory block represents an array element.
Each memory block represents an array element.
Array elements are identified by a unique integer called as the subscript/index of the element.
Array elements are identified by a unique integer called as the subscript/index of the element.
Arrays too, like variables, should be declared before they are used.
Arrays too, like variables, should be declared before they are used.
Array initialization refers to populating the array elements.
Array initialization refers to populating the array elements.
Array element values can be updated or modified but cannot be deleted.
Array element values can be updated or modified but cannot be deleted.
To declare and initialize an array in JavaScript use the following syntax −
var array_name; //declaration
array_name = [val1,val2,valn..] //initialization
OR
var array_name = [val1,val2...valn]
Note − The pair of [] is called the dimension of the array.
For example, a declaration like: var numlist = [2,4,6,8] will create an array as shown in the following figure.
The array name followed by the subscript is used to refer to an array element.
Following is the syntax for the same.
array_name[subscript]
var alphas;
alphas = ["1","2","3","4"]
console.log(alphas[0]);
console.log(alphas[1]);
The following output is displayed on successful execution of the above code.
1
2
var nums = [1,2,3,3]
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
console.log(nums[3]);
The following output is displayed on successful execution of the above code.
1
2
3
3
An array can also be created using the Array object. The Array constructor can be passed as −
A numeric value that represents the size of the array or.
A numeric value that represents the size of the array or.
A list of comma separated values.
A list of comma separated values.
The following Examples create an array using this method.
var arr_names = new Array(4)
for(var i = 0;i<arr_names.length;i++) {
arr_names[i] = i * 2
console.log(arr_names[i])
}
The following output is displayed on successful execution of the above code.
0
2
4
6
var names = new Array("Mary","Tom","Jack","Jill")
for(var i = 0;i<names.length;i++) {
console.log(names[i])
}
The following output is displayed on successful execution of the above code.
Mary
Tom
Jack
Jill
Following is the list of the methods of the Array object along with their description.
Returns a new array comprised of this array joined with other array(s) and/or value(s)
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Applies a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element slice.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
toSource()
Represents the source code of an object.
Sorts the elements of an array.
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
Following are some new array methods introduced in ES6.
find lets you iterate through an array and get the first element back that causes the given callback function to return true. Once an element has been found, the function immediately returns. It’s an efficient way to get at just the first item that matches a given condition.
Example
var numbers = [1, 2, 3];
var oddNumber = numbers.find((x) => x % 2 == 1);
console.log(oddNumber); // 1
The following output is displayed on successful execution of the above code.
1
Note − The ES5 filter() and the ES6 find() are not synonymous. Filter always returns an array of matches (and will return multiple matches), find always returns the actual element.
findIndex behaves similar to find, but instead of returning the element that matched, it returns the index of that element.
var numbers = [1, 2, 3];
var oddNumber = numbers.findIndex((x) => x % 2 == 1);
console.log(oddNumber); // 0
The above example will return the index of the value 1 (0) as output.
entries is a function that returns an Array Iterator that can be used to loop through the array’s keys and values. Entries will return an array of arrays, where each child array is an array of [index, value].
var numbers = [1, 2, 3];
var val = numbers.entries();
console.log(val.next().value);
console.log(val.next().value);
console.log(val.next().value);
The following output is displayed on successful execution of the above code.
[0,1]
[1.2]
[2,3]
Alternatively, we can also use the spread operator to get back an array of the entries in one go.
var numbers = [1, 2, 3];
var val= numbers.entries();
console.log([...val]);
The following output is displayed on successful execution of the above code.
[[0,1],[1,2],[2,3]]
Array.from() enables the creation of a new array from an array like object. The basic functionality of Array.from() is to convert two kinds of values to Arrays −
Array-like values.
Array-like values.
Iterable values like Set and Map.
Iterable values like Set and Map.
Example
"use strict"
for (let i of Array.from('hello')) {
console.log(i)
}
The following output is displayed on successful execution of the above code.
h
e
l
l
o
This function returns the array indexes.
Example
console.log(Array.from(['a', 'b'].keys()))
The following output is displayed on successful execution of the above code.
[ 0, 1 ]
One can use the for... in loop to traverse through an array.
"use strict"
var nums = [1001,1002,1003,1004]
for(let j in nums) {
console.log(nums[j])
}
The loop performs an index-based array traversal. The following output is displayed on successful execution of the above code.
1001
1002
1003
1004
JavaScript supports the following concepts about Arrays −
JavaScript supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array
You can pass to the function a pointer to an array by specifying the array's name without an index.
Allows a function to return an array.
Destructuring refers to extracting individual values from an array or an object into distinct variables. Consider a scenario where the values of an array need to be assigned to individual variables. The traditional way of doing this is given below −
var a= array1[0]
var b= array1[1]
var c= array1[2]
Destructuring helps to achieve the same in a concise way.
//destructuring an array
let [variable1,variable2]=[item1,item2]
//destructuring an object
let {property1,property2} = {property1:value1,property2:value2}
<script>
let names = ['Mohtashim','Kannan','Kiran']
let [n1,n2,n3] = names;
console.log(n1)
console.log(n2)
console.log(n3);
//rest operator with array destructuring
let locations=['Mumbai','Hyderabad','Chennai']
let [l1,...otherValues] =locations
console.log(l1)
console.log(otherValues)
//variables already declared
let name1,name2;
[name1,name2] =names
console.log(name1)
console.log(name2)
//swapping
let first=10,second=20;
[second,first] = [first,second]
console.log("second is ",second) //10
console.log("first is ",first) //20
</script>
The output of the above code will be as shown below −
Mohtashim
Kannan
Kiran
Mumbai
["Hyderabad", "Chennai"]
Mohtashim
Kannan
second is 10
first is 20
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2348,
"s": 2277,
"text": "The use of variables to store values poses the following limitations −"
},
{
"code": null,
"e": 2643,
"s": 2348,
"text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values."
},
{
"code": null,
"e": 2938,
"s": 2643,
"text": "Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values."
},
{
"code": null,
"e": 3090,
"s": 2938,
"text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration."
},
{
"code": null,
"e": 3242,
"s": 3090,
"text": "Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration."
},
{
"code": null,
"e": 3306,
"s": 3242,
"text": "JavaScript introduces the concept of arrays to tackle the same."
},
{
"code": null,
"e": 3451,
"s": 3306,
"text": "An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user-defined type."
},
{
"code": null,
"e": 3508,
"s": 3451,
"text": "An array declaration allocates sequential memory blocks."
},
{
"code": null,
"e": 3565,
"s": 3508,
"text": "An array declaration allocates sequential memory blocks."
},
{
"code": null,
"e": 3645,
"s": 3565,
"text": "Arrays are static. This means that an array once initialized cannot be resized."
},
{
"code": null,
"e": 3725,
"s": 3645,
"text": "Arrays are static. This means that an array once initialized cannot be resized."
},
{
"code": null,
"e": 3772,
"s": 3725,
"text": "Each memory block represents an array element."
},
{
"code": null,
"e": 3819,
"s": 3772,
"text": "Each memory block represents an array element."
},
{
"code": null,
"e": 3915,
"s": 3819,
"text": "Array elements are identified by a unique integer called as the subscript/index of the element."
},
{
"code": null,
"e": 4011,
"s": 3915,
"text": "Array elements are identified by a unique integer called as the subscript/index of the element."
},
{
"code": null,
"e": 4080,
"s": 4011,
"text": "Arrays too, like variables, should be declared before they are used."
},
{
"code": null,
"e": 4149,
"s": 4080,
"text": "Arrays too, like variables, should be declared before they are used."
},
{
"code": null,
"e": 4211,
"s": 4149,
"text": "Array initialization refers to populating the array elements."
},
{
"code": null,
"e": 4273,
"s": 4211,
"text": "Array initialization refers to populating the array elements."
},
{
"code": null,
"e": 4344,
"s": 4273,
"text": "Array element values can be updated or modified but cannot be deleted."
},
{
"code": null,
"e": 4415,
"s": 4344,
"text": "Array element values can be updated or modified but cannot be deleted."
},
{
"code": null,
"e": 4491,
"s": 4415,
"text": "To declare and initialize an array in JavaScript use the following syntax −"
},
{
"code": null,
"e": 4615,
"s": 4491,
"text": "var array_name; //declaration \narray_name = [val1,val2,valn..] //initialization \nOR \nvar array_name = [val1,val2...valn]\n"
},
{
"code": null,
"e": 4675,
"s": 4615,
"text": "Note − The pair of [] is called the dimension of the array."
},
{
"code": null,
"e": 4787,
"s": 4675,
"text": "For example, a declaration like: var numlist = [2,4,6,8] will create an array as shown in the following figure."
},
{
"code": null,
"e": 4866,
"s": 4787,
"text": "The array name followed by the subscript is used to refer to an array element."
},
{
"code": null,
"e": 4904,
"s": 4866,
"text": "Following is the syntax for the same."
},
{
"code": null,
"e": 4927,
"s": 4904,
"text": "array_name[subscript]\n"
},
{
"code": null,
"e": 5017,
"s": 4927,
"text": "var alphas; \nalphas = [\"1\",\"2\",\"3\",\"4\"] \nconsole.log(alphas[0]); \nconsole.log(alphas[1]);"
},
{
"code": null,
"e": 5094,
"s": 5017,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5100,
"s": 5094,
"text": "1 \n2\n"
},
{
"code": null,
"e": 5213,
"s": 5100,
"text": "var nums = [1,2,3,3] \nconsole.log(nums[0]); \nconsole.log(nums[1]); \nconsole.log(nums[2]); \nconsole.log(nums[3]);"
},
{
"code": null,
"e": 5290,
"s": 5213,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5302,
"s": 5290,
"text": "1 \n2 \n3 \n3\n"
},
{
"code": null,
"e": 5396,
"s": 5302,
"text": "An array can also be created using the Array object. The Array constructor can be passed as −"
},
{
"code": null,
"e": 5454,
"s": 5396,
"text": "A numeric value that represents the size of the array or."
},
{
"code": null,
"e": 5512,
"s": 5454,
"text": "A numeric value that represents the size of the array or."
},
{
"code": null,
"e": 5546,
"s": 5512,
"text": "A list of comma separated values."
},
{
"code": null,
"e": 5580,
"s": 5546,
"text": "A list of comma separated values."
},
{
"code": null,
"e": 5638,
"s": 5580,
"text": "The following Examples create an array using this method."
},
{
"code": null,
"e": 5767,
"s": 5638,
"text": "var arr_names = new Array(4) \nfor(var i = 0;i<arr_names.length;i++) { \n arr_names[i] = i * 2 \n console.log(arr_names[i]) \n}"
},
{
"code": null,
"e": 5844,
"s": 5767,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 5857,
"s": 5844,
"text": "0 \n2 \n4 \n6 \n"
},
{
"code": null,
"e": 5973,
"s": 5857,
"text": "var names = new Array(\"Mary\",\"Tom\",\"Jack\",\"Jill\") \nfor(var i = 0;i<names.length;i++) { \n console.log(names[i]) \n}"
},
{
"code": null,
"e": 6050,
"s": 5973,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 6073,
"s": 6050,
"text": "Mary \nTom \nJack \nJill\n"
},
{
"code": null,
"e": 6160,
"s": 6073,
"text": "Following is the list of the methods of the Array object along with their description."
},
{
"code": null,
"e": 6247,
"s": 6160,
"text": "Returns a new array comprised of this array joined with other array(s) and/or value(s)"
},
{
"code": null,
"e": 6332,
"s": 6247,
"text": "Returns true if every element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 6447,
"s": 6332,
"text": "Creates a new array with all of the elements of this array for which the provided filtering function returns true."
},
{
"code": null,
"e": 6495,
"s": 6447,
"text": "Calls a function for each element in the array."
},
{
"code": null,
"e": 6612,
"s": 6495,
"text": "Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 6658,
"s": 6612,
"text": "Joins all elements of an array into a string."
},
{
"code": null,
"e": 6777,
"s": 6658,
"text": "Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found."
},
{
"code": null,
"e": 6877,
"s": 6777,
"text": "Creates a new array with the results of calling a provided function on every element in this array."
},
{
"code": null,
"e": 6942,
"s": 6877,
"text": "Removes the last element from an array and returns that element."
},
{
"code": null,
"e": 7032,
"s": 6942,
"text": "Adds one or more elements to the end of an array and returns the new length of the array."
},
{
"code": null,
"e": 7154,
"s": 7032,
"text": "Applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value."
},
{
"code": null,
"e": 7276,
"s": 7154,
"text": "Applies a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value."
},
{
"code": null,
"e": 7386,
"s": 7276,
"text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first."
},
{
"code": null,
"e": 7458,
"s": 7386,
"text": "Removes the first element from an array and returns that element slice."
},
{
"code": null,
"e": 7514,
"s": 7458,
"text": "Extracts a section of an array and returns a new array."
},
{
"code": null,
"e": 7606,
"s": 7514,
"text": "Returns true if at least one element in this array satisfies the provided testing function."
},
{
"code": null,
"e": 7617,
"s": 7606,
"text": "toSource()"
},
{
"code": null,
"e": 7658,
"s": 7617,
"text": "Represents the source code of an object."
},
{
"code": null,
"e": 7690,
"s": 7658,
"text": "Sorts the elements of an array."
},
{
"code": null,
"e": 7734,
"s": 7690,
"text": "Adds and/or removes elements from an array."
},
{
"code": null,
"e": 7792,
"s": 7734,
"text": "Returns a string representing the array and its elements."
},
{
"code": null,
"e": 7884,
"s": 7792,
"text": "Adds one or more elements to the front of an array and returns the new length of the array."
},
{
"code": null,
"e": 7940,
"s": 7884,
"text": "Following are some new array methods introduced in ES6."
},
{
"code": null,
"e": 8216,
"s": 7940,
"text": "find lets you iterate through an array and get the first element back that causes the given callback function to return true. Once an element has been found, the function immediately returns. It’s an efficient way to get at just the first item that matches a given condition."
},
{
"code": null,
"e": 8224,
"s": 8216,
"text": "Example"
},
{
"code": null,
"e": 8329,
"s": 8224,
"text": "var numbers = [1, 2, 3]; \nvar oddNumber = numbers.find((x) => x % 2 == 1); \nconsole.log(oddNumber); // 1"
},
{
"code": null,
"e": 8406,
"s": 8329,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 8409,
"s": 8406,
"text": "1\n"
},
{
"code": null,
"e": 8590,
"s": 8409,
"text": "Note − The ES5 filter() and the ES6 find() are not synonymous. Filter always returns an array of matches (and will return multiple matches), find always returns the actual element."
},
{
"code": null,
"e": 8714,
"s": 8590,
"text": "findIndex behaves similar to find, but instead of returning the element that matched, it returns the index of that element."
},
{
"code": null,
"e": 8825,
"s": 8714,
"text": "var numbers = [1, 2, 3]; \nvar oddNumber = numbers.findIndex((x) => x % 2 == 1); \nconsole.log(oddNumber); // 0 "
},
{
"code": null,
"e": 8895,
"s": 8825,
"text": "The above example will return the index of the value 1 (0) as output."
},
{
"code": null,
"e": 9104,
"s": 8895,
"text": "entries is a function that returns an Array Iterator that can be used to loop through the array’s keys and values. Entries will return an array of arrays, where each child array is an array of [index, value]."
},
{
"code": null,
"e": 9257,
"s": 9104,
"text": "var numbers = [1, 2, 3]; \nvar val = numbers.entries(); \nconsole.log(val.next().value); \nconsole.log(val.next().value); \nconsole.log(val.next().value);"
},
{
"code": null,
"e": 9334,
"s": 9257,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 9355,
"s": 9334,
"text": "[0,1] \n[1.2] \n[2,3]\n"
},
{
"code": null,
"e": 9453,
"s": 9355,
"text": "Alternatively, we can also use the spread operator to get back an array of the entries in one go."
},
{
"code": null,
"e": 9532,
"s": 9453,
"text": "var numbers = [1, 2, 3]; \nvar val= numbers.entries(); \nconsole.log([...val]);\n"
},
{
"code": null,
"e": 9609,
"s": 9532,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 9630,
"s": 9609,
"text": "[[0,1],[1,2],[2,3]]\n"
},
{
"code": null,
"e": 9792,
"s": 9630,
"text": "Array.from() enables the creation of a new array from an array like object. The basic functionality of Array.from() is to convert two kinds of values to Arrays −"
},
{
"code": null,
"e": 9811,
"s": 9792,
"text": "Array-like values."
},
{
"code": null,
"e": 9830,
"s": 9811,
"text": "Array-like values."
},
{
"code": null,
"e": 9864,
"s": 9830,
"text": "Iterable values like Set and Map."
},
{
"code": null,
"e": 9898,
"s": 9864,
"text": "Iterable values like Set and Map."
},
{
"code": null,
"e": 9906,
"s": 9898,
"text": "Example"
},
{
"code": null,
"e": 9979,
"s": 9906,
"text": "\"use strict\" \nfor (let i of Array.from('hello')) { \n console.log(i) \n}"
},
{
"code": null,
"e": 10056,
"s": 9979,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 10191,
"s": 10056,
"text": "h \ne \nl \nl \no\n"
},
{
"code": null,
"e": 10232,
"s": 10191,
"text": "This function returns the array indexes."
},
{
"code": null,
"e": 10240,
"s": 10232,
"text": "Example"
},
{
"code": null,
"e": 10283,
"s": 10240,
"text": "console.log(Array.from(['a', 'b'].keys()))"
},
{
"code": null,
"e": 10360,
"s": 10283,
"text": "The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 10371,
"s": 10360,
"text": "[ 0, 1 ] \n"
},
{
"code": null,
"e": 10432,
"s": 10371,
"text": "One can use the for... in loop to traverse through an array."
},
{
"code": null,
"e": 10529,
"s": 10432,
"text": "\"use strict\" \nvar nums = [1001,1002,1003,1004] \nfor(let j in nums) { \n console.log(nums[j]) \n}"
},
{
"code": null,
"e": 10656,
"s": 10529,
"text": "The loop performs an index-based array traversal. The following output is displayed on successful execution of the above code."
},
{
"code": null,
"e": 10680,
"s": 10656,
"text": "1001 \n1002 \n1003 \n1004\n"
},
{
"code": null,
"e": 10738,
"s": 10680,
"text": "JavaScript supports the following concepts about Arrays −"
},
{
"code": null,
"e": 10860,
"s": 10738,
"text": "JavaScript supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array"
},
{
"code": null,
"e": 10960,
"s": 10860,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 10998,
"s": 10960,
"text": "Allows a function to return an array."
},
{
"code": null,
"e": 11248,
"s": 10998,
"text": "Destructuring refers to extracting individual values from an array or an object into distinct variables. Consider a scenario where the values of an array need to be assigned to individual variables. The traditional way of doing this is given below −"
},
{
"code": null,
"e": 11300,
"s": 11248,
"text": "var a= array1[0]\nvar b= array1[1]\nvar c= array1[2]\n"
},
{
"code": null,
"e": 11358,
"s": 11300,
"text": "Destructuring helps to achieve the same in a concise way."
},
{
"code": null,
"e": 11514,
"s": 11358,
"text": "//destructuring an array\nlet [variable1,variable2]=[item1,item2]\n//destructuring an object\nlet {property1,property2} = {property1:value1,property2:value2}\n"
},
{
"code": null,
"e": 12119,
"s": 11514,
"text": "<script>\n let names = ['Mohtashim','Kannan','Kiran']\n let [n1,n2,n3] = names;\n console.log(n1)\n console.log(n2)\n console.log(n3);\n //rest operator with array destructuring\n let locations=['Mumbai','Hyderabad','Chennai']\n let [l1,...otherValues] =locations\n console.log(l1)\n console.log(otherValues)\n //variables already declared\n let name1,name2;\n [name1,name2] =names\n console.log(name1)\n console.log(name2)\n //swapping\n let first=10,second=20;\n [second,first] = [first,second]\n console.log(\"second is \",second) //10\n console.log(\"first is \",first) //20\n</script>"
},
{
"code": null,
"e": 12173,
"s": 12119,
"text": "The output of the above code will be as shown below −"
},
{
"code": null,
"e": 12271,
"s": 12173,
"text": "Mohtashim\nKannan\nKiran\nMumbai\n[\"Hyderabad\", \"Chennai\"]\nMohtashim\nKannan\nsecond is 10\nfirst is 20\n"
},
{
"code": null,
"e": 12306,
"s": 12271,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12320,
"s": 12306,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 12353,
"s": 12320,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12371,
"s": 12353,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 12404,
"s": 12371,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12418,
"s": 12404,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 12453,
"s": 12418,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 12470,
"s": 12453,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 12503,
"s": 12470,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12519,
"s": 12503,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 12554,
"s": 12519,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12562,
"s": 12554,
"text": " Shweta"
},
{
"code": null,
"e": 12569,
"s": 12562,
"text": " Print"
},
{
"code": null,
"e": 12580,
"s": 12569,
"text": " Add Notes"
}
] |
Changing the color a Tkinter rectangle on clicking
|
The Canvas widget in Tkinter is one of the versatile widgets in Tkinter which is used for developing dynamic GUI interface of the application such as shapes, logo, arcs, animating objects, and many more. With the help of the create_rectangle(top, left, bottom, right, **options) constructor, we can create a rectangular shape in our canvas widget. All the Canvas items support multiple features such as shapes property, size, color, outline, etc.
Let us suppose that we want to change the color of the drawn rectangle with the help of a button event. Defining a callback function that extends the property such as fill= color would change the color of the rectangle.
# Import the required libraries
from tkinter import *
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry of Tkinter Frame
win.geometry("700x250")
# Define a function to change the color of the rectangle
def change_color(*args):
canvas.itemconfig(shape, fill='blue')
# Add a canvas inside the frame
canvas = Canvas(win, width=500, height=250)
canvas.pack()
# Add a rectangle inside the canvas widget
shape = canvas.create_rectangle(500, 100, 50, 50, fill='red')
# Add a button to change the color of the rectangle
button = Button(win, text="Change Color", font=('Helvectica 11'),
command = lambda: change_color(canvas))
button.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()
If we run the above code, it will display a window with a rectangle and a button widget.
On clicking the "Change Color" button, it will change the color of the rectangle to blue.
|
[
{
"code": null,
"e": 1509,
"s": 1062,
"text": "The Canvas widget in Tkinter is one of the versatile widgets in Tkinter which is used for developing dynamic GUI interface of the application such as shapes, logo, arcs, animating objects, and many more. With the help of the create_rectangle(top, left, bottom, right, **options) constructor, we can create a rectangular shape in our canvas widget. All the Canvas items support multiple features such as shapes property, size, color, outline, etc."
},
{
"code": null,
"e": 1729,
"s": 1509,
"text": "Let us suppose that we want to change the color of the drawn rectangle with the help of a button event. Defining a callback function that extends the property such as fill= color would change the color of the rectangle."
},
{
"code": null,
"e": 2435,
"s": 1729,
"text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of Tkinter Frame\nwin = Tk()\n\n# Set the geometry of Tkinter Frame\nwin.geometry(\"700x250\")\n\n# Define a function to change the color of the rectangle\ndef change_color(*args):\n canvas.itemconfig(shape, fill='blue')\n\n# Add a canvas inside the frame\ncanvas = Canvas(win, width=500, height=250)\ncanvas.pack()\n\n# Add a rectangle inside the canvas widget\nshape = canvas.create_rectangle(500, 100, 50, 50, fill='red')\n\n# Add a button to change the color of the rectangle\nbutton = Button(win, text=\"Change Color\", font=('Helvectica 11'),\ncommand = lambda: change_color(canvas))\nbutton.place(relx=.5, rely=.5, anchor=CENTER)\nwin.mainloop()"
},
{
"code": null,
"e": 2524,
"s": 2435,
"text": "If we run the above code, it will display a window with a rectangle and a button widget."
},
{
"code": null,
"e": 2614,
"s": 2524,
"text": "On clicking the \"Change Color\" button, it will change the color of the rectangle to blue."
}
] |
Dijkstra’s Shortest Path Algorithm
|
The main problem is the same as the previous one, from the starting node to any other node, find the smallest distances. In this problem, the main difference is that the graph is represented using the adjacency matrix. (Cost matrix and adjacency matrix is similar for this purpose).
For the adjacency list representation, the time complexity is O(V^2) where V is the number of nodes in the graph G(V, E)
Input:
The adjacency matrix:
Output:
0 to 1, Using: 0, Cost: 3
0 to 2, Using: 1, Cost: 5
0 to 3, Using: 1, Cost: 4
0 to 4, Using: 3, Cost: 6
0 to 5, Using: 2, Cost: 7
0 to 6, Using: 4, Cost: 7
dijkstraShortestPath(n, dist, next, start)
Input − Total number of nodes n, distance list for each vertex, next list to store which node comes next, and the seed or start vertex.
Output − The shortest paths from start to all other vertices.
Begin
create a status list to hold the current status of the selected node
for all vertices u in V do
status[u] := unconsidered
dist[u] := distance from source using cost matrix
next[u] := start
done
status[start] := considered, dist[start] := 0 and next[start] := φ
while take unconsidered vertex u as distance is minimum do
status[u] := considered
for all vertex v in V do
if status[v] = unconsidered then
if dist[v] > dist[u] + cost[u,v] then
dist[v] := dist[u] + cost[u,v]
next[v] := u
done
done
End
#include<iostream>
#define V 7
#define INF 999
using namespace std;
// Cost matrix of the graph
int costMat[V][V] = {
{0, 3, 6, INF, INF, INF, INF},
{3, 0, 2, 1, INF, INF, INF},
{6, 2, 0, 1, 4, 2, INF},
{INF, 1, 1, 0, 2, INF, 4},
{INF, INF, 4, 2, 0, 2, 1},
{INF, INF, 2, INF, 2, 0, 1},
{INF, INF, INF, 4, 1, 1, 0}
};
int minimum(int *status, int *dis, int n) {
int i, min, index;
min = INF;
for(i = 0; i<n; i++)
if(dis[i] < min && status[i] == 1) {
min = dis[i];
index = i;
}
if(status[index] == 1)
return index; //minimum unconsidered vertex distance
else
return -1; //when all vertices considered
}
void dijkstra(int n, int *dist,int *next, int s) {
int status[V];
int u, v;
//initialization
for(u = 0; u<n; u++) {
status[u] = 1; //unconsidered vertex
dist[u] = costMat[u][s]; //distance from source
next[u] = s;
}
//for source vertex
status[s] = 2; dist[s] = 0; next[s] = -1; //-1 for starting vertex
while((u = minimum(status, dist, n)) > -1) {
status[u] = 2;//now considered
for(v = 0; v<n; v++)
if(status[v] == 1)
if(dist[v] > dist[u] + costMat[u][v]) {
dist[v] = dist[u] + costMat[u][v]; //update distance
next[v] = u;
}
}
}
main() {
int dis[V], next[V], i, start = 0;
dijkstra(V, dis, next, start);
for(i = 0; i<V; i++)
if(i != start)
cout << start << " to " << i <<", Using: " << next[i] << ",
Cost: " << dis[i] << endl;
}
0 to 1, Using: 0, Cost: 3
0 to 2, Using: 1, Cost: 5
0 to 3, Using: 1, Cost: 4
0 to 4, Using: 3, Cost: 6
0 to 5, Using: 2, Cost: 7
0 to 6, Using: 4, Cost: 7
|
[
{
"code": null,
"e": 1345,
"s": 1062,
"text": "The main problem is the same as the previous one, from the starting node to any other node, find the smallest distances. In this problem, the main difference is that the graph is represented using the adjacency matrix. (Cost matrix and adjacency matrix is similar for this purpose)."
},
{
"code": null,
"e": 1466,
"s": 1345,
"text": "For the adjacency list representation, the time complexity is O(V^2) where V is the number of nodes in the graph G(V, E)"
},
{
"code": null,
"e": 1660,
"s": 1466,
"text": "Input:\nThe adjacency matrix:\n\nOutput:\n0 to 1, Using: 0, Cost: 3\n0 to 2, Using: 1, Cost: 5\n0 to 3, Using: 1, Cost: 4\n0 to 4, Using: 3, Cost: 6\n0 to 5, Using: 2, Cost: 7\n0 to 6, Using: 4, Cost: 7"
},
{
"code": null,
"e": 1703,
"s": 1660,
"text": "dijkstraShortestPath(n, dist, next, start)"
},
{
"code": null,
"e": 1839,
"s": 1703,
"text": "Input − Total number of nodes n, distance list for each vertex, next list to store which node comes next, and the seed or start vertex."
},
{
"code": null,
"e": 1901,
"s": 1839,
"text": "Output − The shortest paths from start to all other vertices."
},
{
"code": null,
"e": 2511,
"s": 1901,
"text": "Begin\n create a status list to hold the current status of the selected node\n for all vertices u in V do\n status[u] := unconsidered\n dist[u] := distance from source using cost matrix\n next[u] := start\n done\n\n status[start] := considered, dist[start] := 0 and next[start] := φ\n while take unconsidered vertex u as distance is minimum do\n status[u] := considered\n for all vertex v in V do\n if status[v] = unconsidered then\n if dist[v] > dist[u] + cost[u,v] then\n dist[v] := dist[u] + cost[u,v]\n next[v] := u\n done\n done\nEnd"
},
{
"code": null,
"e": 4101,
"s": 2511,
"text": "#include<iostream>\n#define V 7\n#define INF 999\nusing namespace std;\n\n// Cost matrix of the graph\nint costMat[V][V] = {\n {0, 3, 6, INF, INF, INF, INF},\n {3, 0, 2, 1, INF, INF, INF},\n {6, 2, 0, 1, 4, 2, INF},\n {INF, 1, 1, 0, 2, INF, 4},\n {INF, INF, 4, 2, 0, 2, 1},\n {INF, INF, 2, INF, 2, 0, 1},\n {INF, INF, INF, 4, 1, 1, 0}\n};\n\nint minimum(int *status, int *dis, int n) {\n int i, min, index;\n min = INF;\n\n for(i = 0; i<n; i++)\n if(dis[i] < min && status[i] == 1) {\n min = dis[i];\n index = i;\n }\n\n if(status[index] == 1)\n return index; //minimum unconsidered vertex distance\n else\n return -1; //when all vertices considered\n}\n\nvoid dijkstra(int n, int *dist,int *next, int s) {\n int status[V];\n int u, v;\n\n //initialization\n for(u = 0; u<n; u++) {\n status[u] = 1; //unconsidered vertex\n dist[u] = costMat[u][s]; //distance from source\n next[u] = s;\n }\n\n //for source vertex\n status[s] = 2; dist[s] = 0; next[s] = -1; //-1 for starting vertex\n\n while((u = minimum(status, dist, n)) > -1) {\n status[u] = 2;//now considered\n for(v = 0; v<n; v++)\n if(status[v] == 1)\n if(dist[v] > dist[u] + costMat[u][v]) {\n dist[v] = dist[u] + costMat[u][v]; //update distance\n next[v] = u;\n }\n }\n}\n\nmain() {\n int dis[V], next[V], i, start = 0;\n dijkstra(V, dis, next, start);\n\n for(i = 0; i<V; i++)\n if(i != start)\n cout << start << \" to \" << i <<\", Using: \" << next[i] << \",\n Cost: \" << dis[i] << endl;\n}"
},
{
"code": null,
"e": 4257,
"s": 4101,
"text": "0 to 1, Using: 0, Cost: 3\n0 to 2, Using: 1, Cost: 5\n0 to 3, Using: 1, Cost: 4\n0 to 4, Using: 3, Cost: 6\n0 to 5, Using: 2, Cost: 7\n0 to 6, Using: 4, Cost: 7"
}
] |
How can we implement Flow API using Publisher-Subscriber in Java 9?
|
Flow API (java.util.concurrent.Flow) has introduced in Java 9. It helps to understand different ways in which the Publisher and Subscriber interfaces interact to perform desired operations.
Flow API consists of Publisher, Subscriber, Subscription, and Processor interfaces, which can be based on reactive stream specification.
In the below example, we can implement Flow API by using Publisher-Subscriber interfaces.
import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
public class FlowAPITest {
public static void main(String args[]) {
Publisher<Integer> publisherSync = new Publisher<Integer>() { // Create publisher
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
subscriber.onNext(i);
}
subscriber.onComplete();
}
};
Subscriber<Integer> subscriberSync = new Subscriber<Integer>() { // Create subscriber
@Override
public void onSubscribe(Subscription subscription) {
}
@Override
public void onNext(Integer item) {
System.out.println(Thread.currentThread().getName() + " | Received = " + item);
try {
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
publisherSync.subscribe(subscriberSync);
}
}
main | Publishing = 0
main | Received = 0
main | Publishing = 1
main | Received = 1
main | Publishing = 2
main | Received = 2
main | Publishing = 3
main | Received = 3
main | Publishing = 4
main | Received = 4
main | Publishing = 5
main | Received = 5
main | Publishing = 6
main | Received = 6
main | Publishing = 7
main | Received = 7
main | Publishing = 8
main | Received = 8
main | Publishing = 9
main | Received = 9
|
[
{
"code": null,
"e": 1252,
"s": 1062,
"text": "Flow API (java.util.concurrent.Flow) has introduced in Java 9. It helps to understand different ways in which the Publisher and Subscriber interfaces interact to perform desired operations."
},
{
"code": null,
"e": 1389,
"s": 1252,
"text": "Flow API consists of Publisher, Subscriber, Subscription, and Processor interfaces, which can be based on reactive stream specification."
},
{
"code": null,
"e": 1479,
"s": 1389,
"text": "In the below example, we can implement Flow API by using Publisher-Subscriber interfaces."
},
{
"code": null,
"e": 2824,
"s": 1479,
"text": "import java.util.concurrent.Flow.Publisher;\nimport java.util.concurrent.Flow.Subscriber;\nimport java.util.concurrent.Flow.Subscription;\n\npublic class FlowAPITest {\n public static void main(String args[]) {\n Publisher<Integer> publisherSync = new Publisher<Integer>() { // Create publisher\n @Override\n public void subscribe(Subscriber<? super Integer> subscriber) {\n for(int i = 0; i < 10; i++) {\n System.out.println(Thread.currentThread().getName() + \" | Publishing = \" + i);\n subscriber.onNext(i);\n }\n subscriber.onComplete();\n }\n };\n Subscriber<Integer> subscriberSync = new Subscriber<Integer>() { // Create subscriber\n @Override\n public void onSubscribe(Subscription subscription) {\n }\n @Override\n public void onNext(Integer item) {\n System.out.println(Thread.currentThread().getName() + \" | Received = \" + item);\n try {\n Thread.sleep(100);\n } catch(InterruptedException e) {\n e.printStackTrace();\n }\n }\n @Override\n public void onError(Throwable throwable) {\n }\n @Override\n public void onComplete() {\n }\n };\n publisherSync.subscribe(subscriberSync);\n }\n}"
},
{
"code": null,
"e": 3244,
"s": 2824,
"text": "main | Publishing = 0\nmain | Received = 0\nmain | Publishing = 1\nmain | Received = 1\nmain | Publishing = 2\nmain | Received = 2\nmain | Publishing = 3\nmain | Received = 3\nmain | Publishing = 4\nmain | Received = 4\nmain | Publishing = 5\nmain | Received = 5\nmain | Publishing = 6\nmain | Received = 6\nmain | Publishing = 7\nmain | Received = 7\nmain | Publishing = 8\nmain | Received = 8\nmain | Publishing = 9\nmain | Received = 9"
}
] |
Predicting destination countries for new users of Airbnb | by Tanmayee W | Towards Data Science
|
I found this interesting challenge posted by Airbnb on Kaggle 3 years ago. But it is never too late to get you hands dirty with a stimulating data challenge! :)
This Kaggle challenge presents a problem to predict which country will be a new user’s booking destination. For the purpose of this challenge, we will make use of three datasets provided by Airbnb.
Training setTesting setSessions data
Training set
Testing set
Sessions data
Let us understand how user profile looks like in training and testing datasets.
There are 16 features to describe each user which are as follows
id: user iddate_account_created: the date of account creationtimestamp_first_active: timestamp of the first activity, note that it can be earlier than date_account_created or date_first_booking because a user can search before signing update_first_booking: date of first bookinggenderagesignup_methodsignup_flow: the page a user came to signup up fromlanguage: international language preferenceaffiliate_channel: what kind of paid marketingaffiliate_provider: where the marketing is e.g. google, craigslist, otherfirst_affiliate_tracked: whats the first marketing the user interacted with before the signing upsignup_appfirst_device_typefirst_browsercountry_destination: this is the target variable we are to predict
id: user id
date_account_created: the date of account creation
timestamp_first_active: timestamp of the first activity, note that it can be earlier than date_account_created or date_first_booking because a user can search before signing up
date_first_booking: date of first booking
gender
age
signup_method
signup_flow: the page a user came to signup up from
language: international language preference
affiliate_channel: what kind of paid marketing
affiliate_provider: where the marketing is e.g. google, craigslist, other
first_affiliate_tracked: whats the first marketing the user interacted with before the signing up
signup_app
first_device_type
first_browser
country_destination: this is the target variable we are to predict
Similarly, there are 6 features to describe each web session of a user which are as follows:
user_id: to be joined with the column ‘id’ in users tableactionaction_typeaction_detaildevice_typesecs_elapsed
user_id: to be joined with the column ‘id’ in users table
action
action_type
action_detail
device_type
secs_elapsed
I have divided the analysis for this challenge into two parts —
I. Exploratory analysis
II. Predictive Modelling
Let us first get started with exploring the datasets.
# Importing the necessary librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings("ignore")
Let us load the data now.
train_users = pd.read_csv("train_users_2.csv")test_users = pd.read_csv("test_users.csv")print("There were", train_users.shape[0], "users in the training set and", test_users.shape[0], "users in the test set.") print("In total there were",train_users.shape[0] + test_users.shape[0], "users in total." )
Now we will explore all the users in the train and test sets.
df = pd.concat((train_users, test_users), axis = 0, ignore_index = True, sort = True)
Checking the null values.
display(df.isnull().sum())
We see that there are null values in the columns ‘age’, ‘country_destination’, ‘date_first_booking’, ‘first_affiliate_tracked’.
We try to check the unique values in each column to identify if there is any missing data. We find that there unknowns in the columns ‘gender’ and ‘first_browser’.
df.gender.unique()
df.first_browser.unique()
We replace the unknowns with NaNs and drop the column ‘date_first_booking’ as it does not feature any values in our test set.
df.gender.replace("-unknown-", np.nan, inplace=True)df.first_browser.replace("-unknown-", np.nan, inplace=True)df.drop("date_first_booking", axis = 1, inplace=True)
Let us now check summary statistics of age to find if there are any apparent anomalies.
df.age.describe()
Maximum age is 2014 which is not possible. It looks like the users have inadvertently filled in the year instead of their age. Also, the minimum age of 1 looks absurd.
df.loc[df['age']>1000]['age'].describe()
df.loc[df['age']<18]['age'].describe()
We correct the mistakenly filled ages and then set age limits (18 — lower bound and 95 — upper bound).
df_with_year = df['age'] > 1000df.loc[df_with_year, 'age'] = 2015 - df.loc[df_with_year, 'age']df.loc[df_with_year, 'age'].describe()
df.loc[df.age > 95, 'age'] = np.nandf.loc[df.age < 18, 'age'] = np.nan
Visualizing the users’ ages.
plt.figure(figsize=(12,6))sns.distplot(df.age.dropna(), rug=True)plt.show()
As we see in Fig.1, most of the user base falls in the age bracket of 20 to 40 as expected.
plt.figure(figsize=(12,6))sns.countplot(x='gender', data=df)plt.ylabel('Number of users')plt.title('Users gender distribution')plt.show()
As we see in Fig.2, there is no significant difference between the male and female users.
This our target variable for the prediction problem.
plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data=df)plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.show()
We see in Fig.3, nearly 60% of the users did not end up booking any trip represented by NDF. A majority of users booked a destination in US (about 30%) considering that user population in this problem is from US. Thus, my inference is that US travelers tend to travel within US itself.
We will now only analyze those users who made atleast one booking.
plt.figure(figsize=(12,6))df_without_NDF = df[df['country_destination']!='NDF']sns.boxplot(y='age' , x='country_destination',data=df_without_NDF)plt.xlabel('Destination Country')plt.ylabel('Age of users')plt.title('Country destination vs. age')plt.show()
Fig. 4 shows that there is no significant age difference among the users booking trips to the destinations displayed in the graph. However, the users booking trips to Great Britain seem to be relatively older than those booking trips to Spain and Netherlands.
plt.figure(figsize=(12,6))sns.countplot(x='signup_method', data = df_without_NDF)plt.xlabel('Signup Method')plt.ylabel('Number of users')plt.title('Users sign up method distribution')plt.show()
Fig.5 shows out of all the users who made atleast one booking, nearly 70% used the basic method (email) to sign up with Airbnb.
plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data = df_without_NDF, hue = 'signup_method')plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.title('Users sign up method vs. destinations')plt.legend(loc='upper right')plt.show()
Fig. 6 tells us among the users who made atleast one booking, most of them used email method to signup with Airbnb irrespective of the destination country booked.
plt.figure(figsize=(12,6))sns.countplot(x='signup_app', data=df_without_NDF)plt.xlabel('Signup app')plt.ylabel('Number of users')plt.title('Signup app distribution')plt.show()
Among all the bookers, most of them signed up using Airbnb’s website. Next majority of users signed up using iOS (Fig.7).
plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data=df_without_NDF, hue='signup_app')plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.title('Destination country based on signup app')plt.legend(loc = 'upper right')plt.show()
We see that the users in US display a variety in usage of apps to sign up on Airbnb. For rest other countries, it looks like users prefer to sign up using the Airbnb’s website only (Fig.8).
plt.figure(figsize=(12,6))sns.countplot(x='affiliate_channel', data=df_without_NDF)plt.xlabel('Affiliate channel')plt.ylabel('Number of users')plt.title('Affiliate channel distribution')plt.show()
We see that nearly 70% of the users came to the Airbnb’s website directly without any affiliate involvement (Fig.9).
plt.figure(figsize=(18,6))sns.countplot(x='first_device_type', data=df_without_NDF)plt.xlabel('First device type')plt.ylabel('Number of users')plt.title('First device type distribution')plt.show()
Form Fig.10, it seems that the most popular device that users use to first access Airbnb’s website is Mac desktop (40%) followed by Windows desktop (30%).
plt.figure(figsize=(18,6))sns.countplot(x='country_destination', data=df_without_NDF, hue='first_device_type')plt.ylabel('Number of users')plt.title('First device type vs. country destination')plt.legend(loc = 'upper right')plt.show()
From Fig.11, irrespective of the destination country booked, Mac Desktop emerges as the clear favourite device for the users to access Airbnb’s website. This seems to be the highest in the US. Closely following it on its heels is Windows Desktop.
df_without_NDF_US = df_without_NDF[df_without_NDF['country_destination']!='US']plt.figure(figsize=(18,6))sns.countplot(x='country_destination', data=df_without_NDF_US, hue='first_device_type')plt.ylabel('Number of users')plt.title('First device type vs. country destination without the US')plt.legend(loc = 'upper right')plt.show()
Outside of the US too, Apple devices seem more popular than the Windows devices (Fig.12).
plt.figure(figsize=(20,6))sns.countplot(x='first_browser', data=df_without_NDF)plt.xlabel('First browser')plt.ylabel('Number of users')plt.title('First browser distribution')plt.xticks(rotation=90)plt.show()
As expected, 30% of the bookers used Chrome browser to access Airbnb website. Next favourite seems to be Safari browser (Fig.13).
plt.figure(figsize=(12,6))sns.countplot(x='language', data=df_without_NDF)plt.xlabel('language')plt.ylabel('Number of users')plt.title('Users language distribution')plt.show()
Almost all the users language preference is English. This is reasonable as our population for the problem comes from US.
To visualize how bookings varying across months and years, let us first convert the date columns to datetime type.
df_without_NDF['date_account_created'] = pd.to_datetime(df_without_NDF['date_account_created'])df_without_NDF['timestamp_first_active'] = pd.to_datetime((df_without_NDF.timestamp_first_active)//1000000, format='%Y%m%d')plt.figure(figsize=(12,6))df_without_NDF.date_account_created.value_counts().plot(kind='line', linewidth=1.2)plt.xlabel('Date')plt.title('New account created over time')plt.show()
There is a huge jump in account creation after 2014. Airbnb has grown leaps and bounds after 2014 (Fig.15).
#Creating a separate dataframe for the year 2013 to analyse it further.df_2013 = df_without_NDF[df_without_NDF['timestamp_first_active'] > pd.to_datetime(20130101, format='%Y%m%d')]df_2013 = df_2013[df_2013['timestamp_first_active'] < pd.to_datetime(20140101, format='%Y%m%d')]plt.figure(figsize=(12,6))df_2013.timestamp_first_active.value_counts().plot(kind='line', linewidth=2)plt.xlabel('Date')plt.title('First active date 2013')plt.show()
If we see month wise activty of the users then the peak months were July, August and October. On the other hand, least active month was December (Fig.16).
Loading the sessions data.
sessions = pd.read_csv("sessions.csv")print("There were", len(sessions.user_id.unique()),"unique user ids in the sessions data.")
Checking null values.
display(sessions.isnull().sum())
Checking unknowns.
sessions.action_type.unique()
We see that there are NaNs and unknown in column ‘action_type’ so we convert all unknowns to NaNs.
sessions.action_type.replace('-unknown-', np.nan, inplace=True)sessions.action.value_counts().head(10)
sessions.action_type.value_counts().head(10)
sessions.action_detail.value_counts().head(10)
plt.figure(figsize=(18,6))sns.countplot(x='device_type', data=sessions)plt.xlabel('Device type')plt.ylabel('Number of sessions')plt.title('Device type distribution')plt.xticks(rotation=90)plt.show()
As we discovered even earlier when we explored the users data that the most popular device to access Airbnb seems to be Mac Desktop. Let us now look at how sessions behavior look like for users who made atleast one booking (Fig. 17).
session_booked = pd.merge(df_without_NDF, sessions, how = 'left', left_on = 'id', right_on = 'user_id')#Let us see what all columns we have for session_bookedsession_booked.columns
Let us look at the top 5 actions that bookers usually do.
session_booked.action.value_counts().head(5)
#Importing necessary librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt
Loading the data sets and doing some data prepocessing along the way.
train_users = pd.read_csv('train_users_2.csv')test_users = pd.read_csv('test_users.csv')df = pd.concat((train_users, test_users), axis=0, ignore_index=True)df.drop('date_first_booking', axis=1, inplace=True)
Feature engineering
df['date_account_created'] = pd.to_datetime(df['date_account_created'])df['timestamp_first_active'] = pd.to_datetime((df.timestamp_first_active // 1000000), format='%Y%m%d')df['weekday_account_created'] = df.date_account_created.dt.weekday_namedf['day_account_created'] = df.date_account_created.dt.daydf['month_account_created'] = df.date_account_created.dt.monthdf['year_account_created'] = df.date_account_created.dt.yeardf['weekday_first_active'] = df.timestamp_first_active.dt.weekday_namedf['day_first_active'] = df.timestamp_first_active.dt.daydf['month_first_active'] = df.timestamp_first_active.dt.monthdf['year_first_active'] = df.timestamp_first_active.dt.year
Calculating the time lag variables.
df['time_lag'] = (df['date_account_created'] - df['timestamp_first_active'])df['time_lag'] = df['time_lag'].astype(pd.Timedelta).apply(lambda l: l.days)df.drop( ['date_account_created', 'timestamp_first_active'], axis=1, inplace=True)
Let us fill -1 in place of NaNs in the age column.
df['age'].fillna(-1, inplace=True)
Let us group by user_id and count the number of actions, action_types, and action details for each user.
#First we rename the column user_id as just id to match the train and test columnssessions.rename(columns = {'user_id': 'id'}, inplace=True)action_count = sessions.groupby(['id', 'action'])['secs_elapsed'].agg(len).unstack()action_type_count = sessions.groupby(['id', 'action_type'])['secs_elapsed'].agg(len).unstack()action_detail_count = sessions.groupby(['id', 'action_detail'])['secs_elapsed'].agg(len).unstack()device_type_sum = sessions.groupby(['id', 'device_type'])['secs_elapsed'].agg(sum).unstack()sessions_data = pd.concat([action_count, action_type_count, action_detail_count, device_type_sum],axis=1)sessions_data.columns = sessions_data.columns.map(lambda x: str(x) + '_count')# Most used devicesessions_data['most_used_device'] = sessions.groupby('id')['device_type'].max()print('There were', sessions.shape[0], 'recorded sessions in which there were', sessions.id.nunique(), 'unique users.')
secs_elapsed = sessions.groupby('id')['secs_elapsed']secs_elapsed = secs_elapsed.agg( { 'secs_elapsed_sum': np.sum, 'secs_elapsed_mean': np.mean, 'secs_elapsed_min': np.min, 'secs_elapsed_max': np.max, 'secs_elapsed_median': np.median, 'secs_elapsed_std': np.std, 'secs_elapsed_var': np.var, 'day_pauses': lambda x: (x > 86400).sum(), 'long_pauses': lambda x: (x > 300000).sum(), 'short_pauses': lambda x: (x < 3600).sum(), 'session_length' : np.count_nonzero })secs_elapsed.reset_index(inplace=True)sessions_secs_elapsed = pd.merge(sessions_data, secs_elapsed, on='id', how='left')df = pd.merge(df, sessions_secs_elapsed, on='id', how = 'left')print('There are', df.id.nunique(), 'users from the entire user data set that have session information.')
#Encoding the categorical featurescategorical_features = ['gender', 'signup_method', 'signup_flow', 'language','affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_app', 'first_device_type', 'first_browser', 'most_used_device', 'weekday_account_created', 'weekday_first_active']df = pd.get_dummies(df, columns=categorical_features)df.set_index('id', inplace=True)
#Creating train datasettrain_df = df.loc[train_users['id']]train_df.reset_index(inplace=True)train_df.fillna(-1, inplace=True)#Creating target variable for the train datasety_train = train_df['country_destination']train_df.drop(['country_destination', 'id'], axis=1, inplace=True)from sklearn.preprocessing import LabelEncoderlabel_encoder = LabelEncoder()encoded_y_train = label_encoder.fit_transform(y_train) #Transforming the target variable using labels#We see that the destination countries have been successfully encoded nowencoded_y_train
#Creating test settest_df = df.loc[test_users['id']].drop('country_destination', axis=1)test_df.reset_index(inplace=True)id_test = test_df['id']test_df.drop('id', axis=1, inplace=True)
Removing duplicates from train and test if any.
duplicate_columns = train_df.columns[train_df.columns.duplicated()]duplicate_columns
We find that there are duplicates, we thus remove them.
#Removing the duplicates train_df = train_df.loc[:,~train_df.columns.duplicated()]
Similarly, treating the duplicates in the test set.
test_df.columns[test_df.columns.duplicated()]
test_df = test_df.loc[:,~test_df.columns.duplicated()]
We use XGBoost model for the given prediction problem.
import xgboost as xgbxg_train = xgb.DMatrix(train_df, label=encoded_y_train)#Specifying the hyperparametersparams = {'max_depth': 10, 'learning_rate': 1, 'n_estimators': 5, 'objective': 'multi:softprob', 'num_class': 12, 'gamma': 0, 'min_child_weight': 1, 'max_delta_step': 0, 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'reg_alpha': 0, 'reg_lambda': 1, 'scale_pos_weight': 1, 'base_score': 0.5, 'missing': None, 'nthread': 4, 'seed': 42 }num_boost_round = 5print("Train a XGBoost model")gbm = xgb.train(params, xg_train, num_boost_round)
y_pred = gbm.predict(xgb.DMatrix(test_df))
Selecting top 5 destinations for each userid.
ids = [] #list of idscts = [] #list of countriesfor i in range(len(id_test)): idx = id_test[i] ids += [idx] * 5 cts += label_encoder.inverse_transform(np.argsort(y_pred[i])[::-1])[:5].tolist()
Creating a dataframe with users and their top five destination countries.
predict = pd.DataFrame(np.column_stack((ids, cts)), columns=['id', 'country'])
Creating the final prediction csv.
predict.to_csv('prediction.csv',index=False)
We have successfully predicted destination countries for the Airbnb’s new users!
Next Steps:
Since, we know which destination countries are more popular with the users, Airbnb can implement targeted marketing. This means, focusing marketing strategies for these specific countries to the users identified in the above exercise.Airbnb can plan ahead which countries they should scout more to get accomodation-providers onboard as they can clearly see the users inclination to visit those countries.Depending on the choice of the destination country of a particular user, Airbnb can possibly think of similar destination countries (in terms of climate, topography, choices of recreation etc.) to offer as other viable travel options to that user.This analysis offers extensive idea about how user profile looks like. Airbnb was leverage it to its advantage to experiment new marketing strategies or brainstorm about what changes in demand could follow in the coming years.
Since, we know which destination countries are more popular with the users, Airbnb can implement targeted marketing. This means, focusing marketing strategies for these specific countries to the users identified in the above exercise.
Airbnb can plan ahead which countries they should scout more to get accomodation-providers onboard as they can clearly see the users inclination to visit those countries.
Depending on the choice of the destination country of a particular user, Airbnb can possibly think of similar destination countries (in terms of climate, topography, choices of recreation etc.) to offer as other viable travel options to that user.
This analysis offers extensive idea about how user profile looks like. Airbnb was leverage it to its advantage to experiment new marketing strategies or brainstorm about what changes in demand could follow in the coming years.
If you enjoyed reading my analysis, do send me claps! :)
Source code is hosted on GitHub.
|
[
{
"code": null,
"e": 207,
"s": 46,
"text": "I found this interesting challenge posted by Airbnb on Kaggle 3 years ago. But it is never too late to get you hands dirty with a stimulating data challenge! :)"
},
{
"code": null,
"e": 405,
"s": 207,
"text": "This Kaggle challenge presents a problem to predict which country will be a new user’s booking destination. For the purpose of this challenge, we will make use of three datasets provided by Airbnb."
},
{
"code": null,
"e": 442,
"s": 405,
"text": "Training setTesting setSessions data"
},
{
"code": null,
"e": 455,
"s": 442,
"text": "Training set"
},
{
"code": null,
"e": 467,
"s": 455,
"text": "Testing set"
},
{
"code": null,
"e": 481,
"s": 467,
"text": "Sessions data"
},
{
"code": null,
"e": 561,
"s": 481,
"text": "Let us understand how user profile looks like in training and testing datasets."
},
{
"code": null,
"e": 626,
"s": 561,
"text": "There are 16 features to describe each user which are as follows"
},
{
"code": null,
"e": 1343,
"s": 626,
"text": "id: user iddate_account_created: the date of account creationtimestamp_first_active: timestamp of the first activity, note that it can be earlier than date_account_created or date_first_booking because a user can search before signing update_first_booking: date of first bookinggenderagesignup_methodsignup_flow: the page a user came to signup up fromlanguage: international language preferenceaffiliate_channel: what kind of paid marketingaffiliate_provider: where the marketing is e.g. google, craigslist, otherfirst_affiliate_tracked: whats the first marketing the user interacted with before the signing upsignup_appfirst_device_typefirst_browsercountry_destination: this is the target variable we are to predict"
},
{
"code": null,
"e": 1355,
"s": 1343,
"text": "id: user id"
},
{
"code": null,
"e": 1406,
"s": 1355,
"text": "date_account_created: the date of account creation"
},
{
"code": null,
"e": 1583,
"s": 1406,
"text": "timestamp_first_active: timestamp of the first activity, note that it can be earlier than date_account_created or date_first_booking because a user can search before signing up"
},
{
"code": null,
"e": 1625,
"s": 1583,
"text": "date_first_booking: date of first booking"
},
{
"code": null,
"e": 1632,
"s": 1625,
"text": "gender"
},
{
"code": null,
"e": 1636,
"s": 1632,
"text": "age"
},
{
"code": null,
"e": 1650,
"s": 1636,
"text": "signup_method"
},
{
"code": null,
"e": 1702,
"s": 1650,
"text": "signup_flow: the page a user came to signup up from"
},
{
"code": null,
"e": 1746,
"s": 1702,
"text": "language: international language preference"
},
{
"code": null,
"e": 1793,
"s": 1746,
"text": "affiliate_channel: what kind of paid marketing"
},
{
"code": null,
"e": 1867,
"s": 1793,
"text": "affiliate_provider: where the marketing is e.g. google, craigslist, other"
},
{
"code": null,
"e": 1965,
"s": 1867,
"text": "first_affiliate_tracked: whats the first marketing the user interacted with before the signing up"
},
{
"code": null,
"e": 1976,
"s": 1965,
"text": "signup_app"
},
{
"code": null,
"e": 1994,
"s": 1976,
"text": "first_device_type"
},
{
"code": null,
"e": 2008,
"s": 1994,
"text": "first_browser"
},
{
"code": null,
"e": 2075,
"s": 2008,
"text": "country_destination: this is the target variable we are to predict"
},
{
"code": null,
"e": 2168,
"s": 2075,
"text": "Similarly, there are 6 features to describe each web session of a user which are as follows:"
},
{
"code": null,
"e": 2279,
"s": 2168,
"text": "user_id: to be joined with the column ‘id’ in users tableactionaction_typeaction_detaildevice_typesecs_elapsed"
},
{
"code": null,
"e": 2337,
"s": 2279,
"text": "user_id: to be joined with the column ‘id’ in users table"
},
{
"code": null,
"e": 2344,
"s": 2337,
"text": "action"
},
{
"code": null,
"e": 2356,
"s": 2344,
"text": "action_type"
},
{
"code": null,
"e": 2370,
"s": 2356,
"text": "action_detail"
},
{
"code": null,
"e": 2382,
"s": 2370,
"text": "device_type"
},
{
"code": null,
"e": 2395,
"s": 2382,
"text": "secs_elapsed"
},
{
"code": null,
"e": 2459,
"s": 2395,
"text": "I have divided the analysis for this challenge into two parts —"
},
{
"code": null,
"e": 2483,
"s": 2459,
"text": "I. Exploratory analysis"
},
{
"code": null,
"e": 2508,
"s": 2483,
"text": "II. Predictive Modelling"
},
{
"code": null,
"e": 2562,
"s": 2508,
"text": "Let us first get started with exploring the datasets."
},
{
"code": null,
"e": 2753,
"s": 2562,
"text": "# Importing the necessary librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport warningswarnings.filterwarnings(\"ignore\")"
},
{
"code": null,
"e": 2779,
"s": 2753,
"text": "Let us load the data now."
},
{
"code": null,
"e": 3081,
"s": 2779,
"text": "train_users = pd.read_csv(\"train_users_2.csv\")test_users = pd.read_csv(\"test_users.csv\")print(\"There were\", train_users.shape[0], \"users in the training set and\", test_users.shape[0], \"users in the test set.\") print(\"In total there were\",train_users.shape[0] + test_users.shape[0], \"users in total.\" )"
},
{
"code": null,
"e": 3143,
"s": 3081,
"text": "Now we will explore all the users in the train and test sets."
},
{
"code": null,
"e": 3229,
"s": 3143,
"text": "df = pd.concat((train_users, test_users), axis = 0, ignore_index = True, sort = True)"
},
{
"code": null,
"e": 3255,
"s": 3229,
"text": "Checking the null values."
},
{
"code": null,
"e": 3282,
"s": 3255,
"text": "display(df.isnull().sum())"
},
{
"code": null,
"e": 3410,
"s": 3282,
"text": "We see that there are null values in the columns ‘age’, ‘country_destination’, ‘date_first_booking’, ‘first_affiliate_tracked’."
},
{
"code": null,
"e": 3574,
"s": 3410,
"text": "We try to check the unique values in each column to identify if there is any missing data. We find that there unknowns in the columns ‘gender’ and ‘first_browser’."
},
{
"code": null,
"e": 3593,
"s": 3574,
"text": "df.gender.unique()"
},
{
"code": null,
"e": 3619,
"s": 3593,
"text": "df.first_browser.unique()"
},
{
"code": null,
"e": 3745,
"s": 3619,
"text": "We replace the unknowns with NaNs and drop the column ‘date_first_booking’ as it does not feature any values in our test set."
},
{
"code": null,
"e": 3910,
"s": 3745,
"text": "df.gender.replace(\"-unknown-\", np.nan, inplace=True)df.first_browser.replace(\"-unknown-\", np.nan, inplace=True)df.drop(\"date_first_booking\", axis = 1, inplace=True)"
},
{
"code": null,
"e": 3998,
"s": 3910,
"text": "Let us now check summary statistics of age to find if there are any apparent anomalies."
},
{
"code": null,
"e": 4016,
"s": 3998,
"text": "df.age.describe()"
},
{
"code": null,
"e": 4184,
"s": 4016,
"text": "Maximum age is 2014 which is not possible. It looks like the users have inadvertently filled in the year instead of their age. Also, the minimum age of 1 looks absurd."
},
{
"code": null,
"e": 4225,
"s": 4184,
"text": "df.loc[df['age']>1000]['age'].describe()"
},
{
"code": null,
"e": 4264,
"s": 4225,
"text": "df.loc[df['age']<18]['age'].describe()"
},
{
"code": null,
"e": 4367,
"s": 4264,
"text": "We correct the mistakenly filled ages and then set age limits (18 — lower bound and 95 — upper bound)."
},
{
"code": null,
"e": 4501,
"s": 4367,
"text": "df_with_year = df['age'] > 1000df.loc[df_with_year, 'age'] = 2015 - df.loc[df_with_year, 'age']df.loc[df_with_year, 'age'].describe()"
},
{
"code": null,
"e": 4572,
"s": 4501,
"text": "df.loc[df.age > 95, 'age'] = np.nandf.loc[df.age < 18, 'age'] = np.nan"
},
{
"code": null,
"e": 4601,
"s": 4572,
"text": "Visualizing the users’ ages."
},
{
"code": null,
"e": 4677,
"s": 4601,
"text": "plt.figure(figsize=(12,6))sns.distplot(df.age.dropna(), rug=True)plt.show()"
},
{
"code": null,
"e": 4769,
"s": 4677,
"text": "As we see in Fig.1, most of the user base falls in the age bracket of 20 to 40 as expected."
},
{
"code": null,
"e": 4907,
"s": 4769,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='gender', data=df)plt.ylabel('Number of users')plt.title('Users gender distribution')plt.show()"
},
{
"code": null,
"e": 4997,
"s": 4907,
"text": "As we see in Fig.2, there is no significant difference between the male and female users."
},
{
"code": null,
"e": 5050,
"s": 4997,
"text": "This our target variable for the prediction problem."
},
{
"code": null,
"e": 5196,
"s": 5050,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data=df)plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.show()"
},
{
"code": null,
"e": 5482,
"s": 5196,
"text": "We see in Fig.3, nearly 60% of the users did not end up booking any trip represented by NDF. A majority of users booked a destination in US (about 30%) considering that user population in this problem is from US. Thus, my inference is that US travelers tend to travel within US itself."
},
{
"code": null,
"e": 5549,
"s": 5482,
"text": "We will now only analyze those users who made atleast one booking."
},
{
"code": null,
"e": 5804,
"s": 5549,
"text": "plt.figure(figsize=(12,6))df_without_NDF = df[df['country_destination']!='NDF']sns.boxplot(y='age' , x='country_destination',data=df_without_NDF)plt.xlabel('Destination Country')plt.ylabel('Age of users')plt.title('Country destination vs. age')plt.show()"
},
{
"code": null,
"e": 6064,
"s": 5804,
"text": "Fig. 4 shows that there is no significant age difference among the users booking trips to the destinations displayed in the graph. However, the users booking trips to Great Britain seem to be relatively older than those booking trips to Spain and Netherlands."
},
{
"code": null,
"e": 6258,
"s": 6064,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='signup_method', data = df_without_NDF)plt.xlabel('Signup Method')plt.ylabel('Number of users')plt.title('Users sign up method distribution')plt.show()"
},
{
"code": null,
"e": 6386,
"s": 6258,
"text": "Fig.5 shows out of all the users who made atleast one booking, nearly 70% used the basic method (email) to sign up with Airbnb."
},
{
"code": null,
"e": 6648,
"s": 6386,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data = df_without_NDF, hue = 'signup_method')plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.title('Users sign up method vs. destinations')plt.legend(loc='upper right')plt.show()"
},
{
"code": null,
"e": 6811,
"s": 6648,
"text": "Fig. 6 tells us among the users who made atleast one booking, most of them used email method to signup with Airbnb irrespective of the destination country booked."
},
{
"code": null,
"e": 6987,
"s": 6811,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='signup_app', data=df_without_NDF)plt.xlabel('Signup app')plt.ylabel('Number of users')plt.title('Signup app distribution')plt.show()"
},
{
"code": null,
"e": 7109,
"s": 6987,
"text": "Among all the bookers, most of them signed up using Airbnb’s website. Next majority of users signed up using iOS (Fig.7)."
},
{
"code": null,
"e": 7368,
"s": 7109,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='country_destination', data=df_without_NDF, hue='signup_app')plt.xlabel('Destination Country')plt.ylabel('Number of users')plt.title('Destination country based on signup app')plt.legend(loc = 'upper right')plt.show()"
},
{
"code": null,
"e": 7558,
"s": 7368,
"text": "We see that the users in US display a variety in usage of apps to sign up on Airbnb. For rest other countries, it looks like users prefer to sign up using the Airbnb’s website only (Fig.8)."
},
{
"code": null,
"e": 7755,
"s": 7558,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='affiliate_channel', data=df_without_NDF)plt.xlabel('Affiliate channel')plt.ylabel('Number of users')plt.title('Affiliate channel distribution')plt.show()"
},
{
"code": null,
"e": 7872,
"s": 7755,
"text": "We see that nearly 70% of the users came to the Airbnb’s website directly without any affiliate involvement (Fig.9)."
},
{
"code": null,
"e": 8069,
"s": 7872,
"text": "plt.figure(figsize=(18,6))sns.countplot(x='first_device_type', data=df_without_NDF)plt.xlabel('First device type')plt.ylabel('Number of users')plt.title('First device type distribution')plt.show()"
},
{
"code": null,
"e": 8224,
"s": 8069,
"text": "Form Fig.10, it seems that the most popular device that users use to first access Airbnb’s website is Mac desktop (40%) followed by Windows desktop (30%)."
},
{
"code": null,
"e": 8459,
"s": 8224,
"text": "plt.figure(figsize=(18,6))sns.countplot(x='country_destination', data=df_without_NDF, hue='first_device_type')plt.ylabel('Number of users')plt.title('First device type vs. country destination')plt.legend(loc = 'upper right')plt.show()"
},
{
"code": null,
"e": 8706,
"s": 8459,
"text": "From Fig.11, irrespective of the destination country booked, Mac Desktop emerges as the clear favourite device for the users to access Airbnb’s website. This seems to be the highest in the US. Closely following it on its heels is Windows Desktop."
},
{
"code": null,
"e": 9038,
"s": 8706,
"text": "df_without_NDF_US = df_without_NDF[df_without_NDF['country_destination']!='US']plt.figure(figsize=(18,6))sns.countplot(x='country_destination', data=df_without_NDF_US, hue='first_device_type')plt.ylabel('Number of users')plt.title('First device type vs. country destination without the US')plt.legend(loc = 'upper right')plt.show()"
},
{
"code": null,
"e": 9128,
"s": 9038,
"text": "Outside of the US too, Apple devices seem more popular than the Windows devices (Fig.12)."
},
{
"code": null,
"e": 9336,
"s": 9128,
"text": "plt.figure(figsize=(20,6))sns.countplot(x='first_browser', data=df_without_NDF)plt.xlabel('First browser')plt.ylabel('Number of users')plt.title('First browser distribution')plt.xticks(rotation=90)plt.show()"
},
{
"code": null,
"e": 9466,
"s": 9336,
"text": "As expected, 30% of the bookers used Chrome browser to access Airbnb website. Next favourite seems to be Safari browser (Fig.13)."
},
{
"code": null,
"e": 9642,
"s": 9466,
"text": "plt.figure(figsize=(12,6))sns.countplot(x='language', data=df_without_NDF)plt.xlabel('language')plt.ylabel('Number of users')plt.title('Users language distribution')plt.show()"
},
{
"code": null,
"e": 9763,
"s": 9642,
"text": "Almost all the users language preference is English. This is reasonable as our population for the problem comes from US."
},
{
"code": null,
"e": 9878,
"s": 9763,
"text": "To visualize how bookings varying across months and years, let us first convert the date columns to datetime type."
},
{
"code": null,
"e": 10277,
"s": 9878,
"text": "df_without_NDF['date_account_created'] = pd.to_datetime(df_without_NDF['date_account_created'])df_without_NDF['timestamp_first_active'] = pd.to_datetime((df_without_NDF.timestamp_first_active)//1000000, format='%Y%m%d')plt.figure(figsize=(12,6))df_without_NDF.date_account_created.value_counts().plot(kind='line', linewidth=1.2)plt.xlabel('Date')plt.title('New account created over time')plt.show()"
},
{
"code": null,
"e": 10385,
"s": 10277,
"text": "There is a huge jump in account creation after 2014. Airbnb has grown leaps and bounds after 2014 (Fig.15)."
},
{
"code": null,
"e": 10828,
"s": 10385,
"text": "#Creating a separate dataframe for the year 2013 to analyse it further.df_2013 = df_without_NDF[df_without_NDF['timestamp_first_active'] > pd.to_datetime(20130101, format='%Y%m%d')]df_2013 = df_2013[df_2013['timestamp_first_active'] < pd.to_datetime(20140101, format='%Y%m%d')]plt.figure(figsize=(12,6))df_2013.timestamp_first_active.value_counts().plot(kind='line', linewidth=2)plt.xlabel('Date')plt.title('First active date 2013')plt.show()"
},
{
"code": null,
"e": 10983,
"s": 10828,
"text": "If we see month wise activty of the users then the peak months were July, August and October. On the other hand, least active month was December (Fig.16)."
},
{
"code": null,
"e": 11010,
"s": 10983,
"text": "Loading the sessions data."
},
{
"code": null,
"e": 11140,
"s": 11010,
"text": "sessions = pd.read_csv(\"sessions.csv\")print(\"There were\", len(sessions.user_id.unique()),\"unique user ids in the sessions data.\")"
},
{
"code": null,
"e": 11162,
"s": 11140,
"text": "Checking null values."
},
{
"code": null,
"e": 11195,
"s": 11162,
"text": "display(sessions.isnull().sum())"
},
{
"code": null,
"e": 11214,
"s": 11195,
"text": "Checking unknowns."
},
{
"code": null,
"e": 11244,
"s": 11214,
"text": "sessions.action_type.unique()"
},
{
"code": null,
"e": 11343,
"s": 11244,
"text": "We see that there are NaNs and unknown in column ‘action_type’ so we convert all unknowns to NaNs."
},
{
"code": null,
"e": 11446,
"s": 11343,
"text": "sessions.action_type.replace('-unknown-', np.nan, inplace=True)sessions.action.value_counts().head(10)"
},
{
"code": null,
"e": 11491,
"s": 11446,
"text": "sessions.action_type.value_counts().head(10)"
},
{
"code": null,
"e": 11538,
"s": 11491,
"text": "sessions.action_detail.value_counts().head(10)"
},
{
"code": null,
"e": 11737,
"s": 11538,
"text": "plt.figure(figsize=(18,6))sns.countplot(x='device_type', data=sessions)plt.xlabel('Device type')plt.ylabel('Number of sessions')plt.title('Device type distribution')plt.xticks(rotation=90)plt.show()"
},
{
"code": null,
"e": 11971,
"s": 11737,
"text": "As we discovered even earlier when we explored the users data that the most popular device to access Airbnb seems to be Mac Desktop. Let us now look at how sessions behavior look like for users who made atleast one booking (Fig. 17)."
},
{
"code": null,
"e": 12152,
"s": 11971,
"text": "session_booked = pd.merge(df_without_NDF, sessions, how = 'left', left_on = 'id', right_on = 'user_id')#Let us see what all columns we have for session_bookedsession_booked.columns"
},
{
"code": null,
"e": 12210,
"s": 12152,
"text": "Let us look at the top 5 actions that bookers usually do."
},
{
"code": null,
"e": 12255,
"s": 12210,
"text": "session_booked.action.value_counts().head(5)"
},
{
"code": null,
"e": 12375,
"s": 12255,
"text": "#Importing necessary librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 12445,
"s": 12375,
"text": "Loading the data sets and doing some data prepocessing along the way."
},
{
"code": null,
"e": 12653,
"s": 12445,
"text": "train_users = pd.read_csv('train_users_2.csv')test_users = pd.read_csv('test_users.csv')df = pd.concat((train_users, test_users), axis=0, ignore_index=True)df.drop('date_first_booking', axis=1, inplace=True)"
},
{
"code": null,
"e": 12673,
"s": 12653,
"text": "Feature engineering"
},
{
"code": null,
"e": 13345,
"s": 12673,
"text": "df['date_account_created'] = pd.to_datetime(df['date_account_created'])df['timestamp_first_active'] = pd.to_datetime((df.timestamp_first_active // 1000000), format='%Y%m%d')df['weekday_account_created'] = df.date_account_created.dt.weekday_namedf['day_account_created'] = df.date_account_created.dt.daydf['month_account_created'] = df.date_account_created.dt.monthdf['year_account_created'] = df.date_account_created.dt.yeardf['weekday_first_active'] = df.timestamp_first_active.dt.weekday_namedf['day_first_active'] = df.timestamp_first_active.dt.daydf['month_first_active'] = df.timestamp_first_active.dt.monthdf['year_first_active'] = df.timestamp_first_active.dt.year"
},
{
"code": null,
"e": 13381,
"s": 13345,
"text": "Calculating the time lag variables."
},
{
"code": null,
"e": 13616,
"s": 13381,
"text": "df['time_lag'] = (df['date_account_created'] - df['timestamp_first_active'])df['time_lag'] = df['time_lag'].astype(pd.Timedelta).apply(lambda l: l.days)df.drop( ['date_account_created', 'timestamp_first_active'], axis=1, inplace=True)"
},
{
"code": null,
"e": 13667,
"s": 13616,
"text": "Let us fill -1 in place of NaNs in the age column."
},
{
"code": null,
"e": 13702,
"s": 13667,
"text": "df['age'].fillna(-1, inplace=True)"
},
{
"code": null,
"e": 13807,
"s": 13702,
"text": "Let us group by user_id and count the number of actions, action_types, and action details for each user."
},
{
"code": null,
"e": 14715,
"s": 13807,
"text": "#First we rename the column user_id as just id to match the train and test columnssessions.rename(columns = {'user_id': 'id'}, inplace=True)action_count = sessions.groupby(['id', 'action'])['secs_elapsed'].agg(len).unstack()action_type_count = sessions.groupby(['id', 'action_type'])['secs_elapsed'].agg(len).unstack()action_detail_count = sessions.groupby(['id', 'action_detail'])['secs_elapsed'].agg(len).unstack()device_type_sum = sessions.groupby(['id', 'device_type'])['secs_elapsed'].agg(sum).unstack()sessions_data = pd.concat([action_count, action_type_count, action_detail_count, device_type_sum],axis=1)sessions_data.columns = sessions_data.columns.map(lambda x: str(x) + '_count')# Most used devicesessions_data['most_used_device'] = sessions.groupby('id')['device_type'].max()print('There were', sessions.shape[0], 'recorded sessions in which there were', sessions.id.nunique(), 'unique users.')"
},
{
"code": null,
"e": 15549,
"s": 14715,
"text": "secs_elapsed = sessions.groupby('id')['secs_elapsed']secs_elapsed = secs_elapsed.agg( { 'secs_elapsed_sum': np.sum, 'secs_elapsed_mean': np.mean, 'secs_elapsed_min': np.min, 'secs_elapsed_max': np.max, 'secs_elapsed_median': np.median, 'secs_elapsed_std': np.std, 'secs_elapsed_var': np.var, 'day_pauses': lambda x: (x > 86400).sum(), 'long_pauses': lambda x: (x > 300000).sum(), 'short_pauses': lambda x: (x < 3600).sum(), 'session_length' : np.count_nonzero })secs_elapsed.reset_index(inplace=True)sessions_secs_elapsed = pd.merge(sessions_data, secs_elapsed, on='id', how='left')df = pd.merge(df, sessions_secs_elapsed, on='id', how = 'left')print('There are', df.id.nunique(), 'users from the entire user data set that have session information.')"
},
{
"code": null,
"e": 15938,
"s": 15549,
"text": "#Encoding the categorical featurescategorical_features = ['gender', 'signup_method', 'signup_flow', 'language','affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_app', 'first_device_type', 'first_browser', 'most_used_device', 'weekday_account_created', 'weekday_first_active']df = pd.get_dummies(df, columns=categorical_features)df.set_index('id', inplace=True)"
},
{
"code": null,
"e": 16484,
"s": 15938,
"text": "#Creating train datasettrain_df = df.loc[train_users['id']]train_df.reset_index(inplace=True)train_df.fillna(-1, inplace=True)#Creating target variable for the train datasety_train = train_df['country_destination']train_df.drop(['country_destination', 'id'], axis=1, inplace=True)from sklearn.preprocessing import LabelEncoderlabel_encoder = LabelEncoder()encoded_y_train = label_encoder.fit_transform(y_train) #Transforming the target variable using labels#We see that the destination countries have been successfully encoded nowencoded_y_train"
},
{
"code": null,
"e": 16669,
"s": 16484,
"text": "#Creating test settest_df = df.loc[test_users['id']].drop('country_destination', axis=1)test_df.reset_index(inplace=True)id_test = test_df['id']test_df.drop('id', axis=1, inplace=True)"
},
{
"code": null,
"e": 16717,
"s": 16669,
"text": "Removing duplicates from train and test if any."
},
{
"code": null,
"e": 16802,
"s": 16717,
"text": "duplicate_columns = train_df.columns[train_df.columns.duplicated()]duplicate_columns"
},
{
"code": null,
"e": 16858,
"s": 16802,
"text": "We find that there are duplicates, we thus remove them."
},
{
"code": null,
"e": 16941,
"s": 16858,
"text": "#Removing the duplicates train_df = train_df.loc[:,~train_df.columns.duplicated()]"
},
{
"code": null,
"e": 16993,
"s": 16941,
"text": "Similarly, treating the duplicates in the test set."
},
{
"code": null,
"e": 17039,
"s": 16993,
"text": "test_df.columns[test_df.columns.duplicated()]"
},
{
"code": null,
"e": 17094,
"s": 17039,
"text": "test_df = test_df.loc[:,~test_df.columns.duplicated()]"
},
{
"code": null,
"e": 17149,
"s": 17094,
"text": "We use XGBoost model for the given prediction problem."
},
{
"code": null,
"e": 17767,
"s": 17149,
"text": "import xgboost as xgbxg_train = xgb.DMatrix(train_df, label=encoded_y_train)#Specifying the hyperparametersparams = {'max_depth': 10, 'learning_rate': 1, 'n_estimators': 5, 'objective': 'multi:softprob', 'num_class': 12, 'gamma': 0, 'min_child_weight': 1, 'max_delta_step': 0, 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'reg_alpha': 0, 'reg_lambda': 1, 'scale_pos_weight': 1, 'base_score': 0.5, 'missing': None, 'nthread': 4, 'seed': 42 }num_boost_round = 5print(\"Train a XGBoost model\")gbm = xgb.train(params, xg_train, num_boost_round)"
},
{
"code": null,
"e": 17810,
"s": 17767,
"text": "y_pred = gbm.predict(xgb.DMatrix(test_df))"
},
{
"code": null,
"e": 17856,
"s": 17810,
"text": "Selecting top 5 destinations for each userid."
},
{
"code": null,
"e": 18060,
"s": 17856,
"text": "ids = [] #list of idscts = [] #list of countriesfor i in range(len(id_test)): idx = id_test[i] ids += [idx] * 5 cts += label_encoder.inverse_transform(np.argsort(y_pred[i])[::-1])[:5].tolist()"
},
{
"code": null,
"e": 18134,
"s": 18060,
"text": "Creating a dataframe with users and their top five destination countries."
},
{
"code": null,
"e": 18213,
"s": 18134,
"text": "predict = pd.DataFrame(np.column_stack((ids, cts)), columns=['id', 'country'])"
},
{
"code": null,
"e": 18248,
"s": 18213,
"text": "Creating the final prediction csv."
},
{
"code": null,
"e": 18293,
"s": 18248,
"text": "predict.to_csv('prediction.csv',index=False)"
},
{
"code": null,
"e": 18374,
"s": 18293,
"text": "We have successfully predicted destination countries for the Airbnb’s new users!"
},
{
"code": null,
"e": 18386,
"s": 18374,
"text": "Next Steps:"
},
{
"code": null,
"e": 19264,
"s": 18386,
"text": "Since, we know which destination countries are more popular with the users, Airbnb can implement targeted marketing. This means, focusing marketing strategies for these specific countries to the users identified in the above exercise.Airbnb can plan ahead which countries they should scout more to get accomodation-providers onboard as they can clearly see the users inclination to visit those countries.Depending on the choice of the destination country of a particular user, Airbnb can possibly think of similar destination countries (in terms of climate, topography, choices of recreation etc.) to offer as other viable travel options to that user.This analysis offers extensive idea about how user profile looks like. Airbnb was leverage it to its advantage to experiment new marketing strategies or brainstorm about what changes in demand could follow in the coming years."
},
{
"code": null,
"e": 19499,
"s": 19264,
"text": "Since, we know which destination countries are more popular with the users, Airbnb can implement targeted marketing. This means, focusing marketing strategies for these specific countries to the users identified in the above exercise."
},
{
"code": null,
"e": 19670,
"s": 19499,
"text": "Airbnb can plan ahead which countries they should scout more to get accomodation-providers onboard as they can clearly see the users inclination to visit those countries."
},
{
"code": null,
"e": 19918,
"s": 19670,
"text": "Depending on the choice of the destination country of a particular user, Airbnb can possibly think of similar destination countries (in terms of climate, topography, choices of recreation etc.) to offer as other viable travel options to that user."
},
{
"code": null,
"e": 20145,
"s": 19918,
"text": "This analysis offers extensive idea about how user profile looks like. Airbnb was leverage it to its advantage to experiment new marketing strategies or brainstorm about what changes in demand could follow in the coming years."
},
{
"code": null,
"e": 20202,
"s": 20145,
"text": "If you enjoyed reading my analysis, do send me claps! :)"
}
] |
spaCy - Command Line Helpers
|
This chapter gives information about the command line helpers used in spaCy.
spaCy v1.7.0 and above comes with new command line helpers. It is used to download as well as link the models. You can also use it to show the useful debugging information. In short, command line helpers are used to download, train, package models, and also to debug spaCy.
You can check the available commands by using spacy - -help command.
The example to check the available commands in spaCy is given below −
C:\Users\Leekha>python -m spacy --help
The output shows the available commands.
Available commands
download, link, info, train, pretrain, debug-data, evaluate, convert, package, init-model, profile, validate
The commands available in spaCy are given below along with their respective descriptions.
To download models for spaCy.
To create shortcut links for models.
To print the information.
To check compatibility of the installed models.
To convert the files into spaCy's JSON format.
To pre-train the “token to vector (tok2vec)” layer of pipeline components.
To create a new model directory from raw data.
To evaluate a model's accuracy and speed.
To generate a model python package from an existing model data directory.
To analyse, debug, and validate our training and development data.
To train a model.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2149,
"s": 2072,
"text": "This chapter gives information about the command line helpers used in spaCy."
},
{
"code": null,
"e": 2423,
"s": 2149,
"text": "spaCy v1.7.0 and above comes with new command line helpers. It is used to download as well as link the models. You can also use it to show the useful debugging information. In short, command line helpers are used to download, train, package models, and also to debug spaCy."
},
{
"code": null,
"e": 2492,
"s": 2423,
"text": "You can check the available commands by using spacy - -help command."
},
{
"code": null,
"e": 2562,
"s": 2492,
"text": "The example to check the available commands in spaCy is given below −"
},
{
"code": null,
"e": 2601,
"s": 2562,
"text": "C:\\Users\\Leekha>python -m spacy --help"
},
{
"code": null,
"e": 2642,
"s": 2601,
"text": "The output shows the available commands."
},
{
"code": null,
"e": 2771,
"s": 2642,
"text": "Available commands\ndownload, link, info, train, pretrain, debug-data, evaluate, convert, package, init-model, profile, validate\n"
},
{
"code": null,
"e": 2861,
"s": 2771,
"text": "The commands available in spaCy are given below along with their respective descriptions."
},
{
"code": null,
"e": 2891,
"s": 2861,
"text": "To download models for spaCy."
},
{
"code": null,
"e": 2928,
"s": 2891,
"text": "To create shortcut links for models."
},
{
"code": null,
"e": 2954,
"s": 2928,
"text": "To print the information."
},
{
"code": null,
"e": 3002,
"s": 2954,
"text": "To check compatibility of the installed models."
},
{
"code": null,
"e": 3049,
"s": 3002,
"text": "To convert the files into spaCy's JSON format."
},
{
"code": null,
"e": 3124,
"s": 3049,
"text": "To pre-train the “token to vector (tok2vec)” layer of pipeline components."
},
{
"code": null,
"e": 3171,
"s": 3124,
"text": "To create a new model directory from raw data."
},
{
"code": null,
"e": 3213,
"s": 3171,
"text": "To evaluate a model's accuracy and speed."
},
{
"code": null,
"e": 3287,
"s": 3213,
"text": "To generate a model python package from an existing model data directory."
},
{
"code": null,
"e": 3354,
"s": 3287,
"text": "To analyse, debug, and validate our training and development data."
},
{
"code": null,
"e": 3372,
"s": 3354,
"text": "To train a model."
},
{
"code": null,
"e": 3379,
"s": 3372,
"text": " Print"
},
{
"code": null,
"e": 3390,
"s": 3379,
"text": " Add Notes"
}
] |
MySQL query to increment one of the column values
|
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(100),
-> Score int
-> );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Score) values('John',68);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(Name,Score) values('Carol',98);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable(Name,Score) values('David',89);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Name,Score) values('Robert',67);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name | Score |
+----+--------+-------+
| 1 | John | 68 |
| 2 | Carol | 98 |
| 3 | David | 89 |
| 4 | Robert | 67 |
+----+--------+-------+
4 rows in set (0.00 sec)
Following is the query to increment one of the column values by 1 −
mysql> update DemoTable set Score=Score+1 where Id=3;
Query OK, 1 row affected (0.22 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name | Score |
+----+--------+-------+
| 1 | John | 68 |
| 2 | Carol | 98 |
| 3 | David | 90 |
| 4 | Robert | 67 |
+----+--------+-------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1252,
"s": 1092,
"text": "mysql> create table DemoTable\n-> (\n-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n-> Name varchar(100),\n-> Score int\n-> );\nQuery OK, 0 rows affected (0.78 sec)"
},
{
"code": null,
"e": 1308,
"s": 1252,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1699,
"s": 1308,
"text": "mysql> insert into DemoTable(Name,Score) values('John',68);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable(Name,Score) values('Carol',98);\nQuery OK, 1 row affected (0.27 sec)\n\nmysql> insert into DemoTable(Name,Score) values('David',89);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DemoTable(Name,Score) values('Robert',67);\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1759,
"s": 1699,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1790,
"s": 1759,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1831,
"s": 1790,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2048,
"s": 1831,
"text": "+----+--------+-------+\n| Id | Name | Score |\n+----+--------+-------+\n| 1 | John | 68 |\n| 2 | Carol | 98 |\n| 3 | David | 89 |\n| 4 | Robert | 67 |\n+----+--------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2116,
"s": 2048,
"text": "Following is the query to increment one of the column values by 1 −"
},
{
"code": null,
"e": 2245,
"s": 2116,
"text": "mysql> update DemoTable set Score=Score+1 where Id=3;\nQuery OK, 1 row affected (0.22 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2285,
"s": 2245,
"text": "Let us check table records once again −"
},
{
"code": null,
"e": 2316,
"s": 2285,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2357,
"s": 2316,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2575,
"s": 2357,
"text": "+----+--------+-------+\n| Id | Name | Score |\n+----+--------+-------+\n| 1 | John | 68 |\n| 2 | Carol | 98 | \n| 3 | David | 90 |\n| 4 | Robert | 67 |\n+----+--------+-------+\n4 rows in set (0.00 sec)"
}
] |
Building Machine Learning Pipelines using Snowflake and Dask | by Daniel Foley | Towards Data Science
|
Recently I have been trying to find better ways to improve my workflow as a data scientist. I tend to spend a decent chunk of my time modelling and building ETLs in my job. This has meant that more and more I need to rely on tools to reliably and efficiently handle large datasets. I quickly realised that using pandas for manipulating these datasets is not always a good approach and this prompted me to look into other alternatives.
In this post, I want to share some of the tools that I have been exploring recently and show you how I use them and how they helped improve the efficiency of my workflow. The two I will talk about in particular are Snowflake and Dask. Two very different tools but ones that complement each other well especially as part of the ML Lifecycle. My hope is that after reading this post you will have a good understanding of what Snowflake and Dask are, how they can be used effectively and be able to get up and running with your own use cases.
More specifically, I want to show you how you can build an ETL pipeline using Snowflake and Python to generate training data for a machine learning task. I then want to introduce Dask and Saturn Cloud and show you how you can take advantage of parallel processing in the cloud to really speed up the ML training process so you can increase your productivity as a data scientist.
Before we jump into coding I better briefly explain what Snowflake is. This is a question I recently asked when my team decided to start using it. At a high level, it is a data warehouse in the cloud. After playing around with it for a while I realised how powerful it was. I think for me, one of the most useful features is the virtual warehouses that you can use. A virtual warehouse gives you access to the same data but is completely independent of other virtual warehouses so compute resources are not shared across teams. This has proven very useful as it removes any potential for performance issues caused by other users executing queries throughout the day. This has resulted in less frustration and time wasted waiting for queries to run.
Since we are going to be using Snowflake I will briefly outline how you can set it up and start experimenting with it yourself. We need to do the following:
Get a Snowflake account set up
Get our data into Snowflake
Write and test our queries using SQL and the Snowflake UI
Write a Python class that can execute our queries to generate our final dataset for modelling
Setting up an account is as easy as signing up for a free trial on their website. Once you have done that you can download the snowsql CLI here. This will make it straightforward to add data to Snowflake. After following these steps we can try and connect to Snowflake using our credentials and the command line.
snowsql -a <account_name> -u <user_name>
You can find your account name in the URL when you log in to the Snowflake UI. It should look something like this: xxxxx.europe-west2.gcp. Ok, let’s move onto the next step and get our data into Snowflake. There are a few steps we need to follow here namely:
Create our virtual warehouse
Create a database
Define and Create our tables
Create a staging table for our CSV files
Copying the data into our tables
Luckily this isn’t too difficult and we can do this entirely using the snowsql CLI. For this project, I will be using a smaller dataset than I would like but unfortunately, I cannot use any of my company’s data and it can be pretty difficult to find large suitable datasets online. I did however find some transaction data from Dunnhumby which is freely available on Kaggle. Just for kicks though I create a much larger synthetic dataset using this data to test how well Dask handles the challenge compared to sklearn.
First of all, we need to set up a virtual warehouse and a database using the following commands in the Snowflake UI.
create or replace warehouse analytics_wh with warehouse_size=”X-SMALL” auto_suspend=180 auto_resume=true initially_suspended=true;
create or replace database dunnhumby;
Our data consists of 6 CSVs which we will convert into 6 tables. I won’t spend too much time going over the dataset as this post is more about using Snowflake and Dask rather than interpreting data.
Below are the commands we can use to create our tables. All you will need to know in advance is what columns and data types you will be working with.
create or replace table campaign_desc ( description string, campaign number,start_day number,end_day number );create or replace table campaign_table ( description string, Household_key number, campaign number );create or replace table coupon ( COUPON_UPC number, product_id number, campaign number );create or replace table coupon_redempt ( household_key number, day number, coupon_upc number, campaign number );create or replace table transactions ( household_key number, BASKET_ID number, day number, product_id number, quantity number, sales_value number, store_id number, retail_disc decimal, trans_time number, week_no number, coupon_disc decimal, coupon_match_disc decimal );create or replace table demographic_data ( age_dec string, marital_status_code string, income_desc string, homeowner_desc string, hh_comp_desc string, household_size_desc string, kid_category_desc string, Household_key number);
Now that we have our tables created we can start thinking about how to get data into them. For this, we will need to stage our CSV files. This is basically just an intermediary step so Snowflake can directly load the files from our stage into our tables. We can use the PUT command to put local files in our stage and then the COPY INTO command to instruct Snowflake where to put this data.
use database dunnhumby;create or replace stage dunnhumby_stage;PUT file://campaigns_table.csv @dunnhumby.public.dunnhumby_stage;PUT file://campaigns_desc.csv @dunnhumby.public.dunnhumby_stage;PUT file://coupon.csv @dunnhumby.public.dunnhumby_stage;PUT file://coupon_d=redempt.csv @dunnhumby.public.dunnhumby_stage; PUT file://transaction_data.csv @dunnhumby.public.dunnhumby_stage; PUT file://demographics.csv @dunnhumby.public.dunnhumby_stage;
As a quick check, you can run this command to check what is in the staging area.
ls @dunnhumby.public.dunnhumby_stage;
Now we just need to copy the data into our tables using the queries below. You can execute these either in the Snowflake UI or in the command line after logging into Snowflake.
copy into campaign_table from @dunnhumby.public.dunnhumby_stage/campaigns_table.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into campaign_desc from @dunnhumby.public.dunnhumby_stage/campaign_desc.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into coupon from @dunnhumby.public.dunnhumby_stage/coupon.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into coupon_redempt from @dunnhumby.public.dunnhumby_stage/coupon_redempt.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into transactions from @dunnhumby.public.dunnhumby_stage/transaction_data.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into demographic_data from @dunnhumby.public.dunnhumby_stage/demographics.csv.gz file_format = ( type = csv skip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);
Ok great, with any luck we have our data in our tables first try. Oh, if only it was that simple, this whole process took me a few tries to get right (beware of spelling things wrong). Hopefully, you can follow along with this and be good to go. We are getting closer to the interesting stuff but the steps above are a vital part of the process so make sure you understand each of these steps.
In this next step, we will be writing the queries to generate our target, our features and then finally produce a training data set. One approach to creating a dataset for modelling is to read this data into memory and use pandas to create new features and join all the data frames together. This is typically the approach you see on Kaggle and in other online tutorials. The issue with this is that it is not very efficient, particularly when you are working with any reasonably sized datasets. For this reason, it is a much better idea to outsource the heavy lifting to something like Snowflake which handles massive datasets extremely well and will likely save you a huge amount of time. I won’t be spending much time diving into the specifics of our dataset here as it isn’t really vital for what I am trying to show. In general, though, you would want to spend a considerable amount of time exploring and understanding your data before you start modelling. The goal of these queries will be to preprocess the data and create some simple features which we can later use in our models.
Obviously, a vital component of supervised machine learning is defining an appropriate target to predict. For our use case, we will be predicting churn by calculating whether or not a user makes another visit within two weeks after a cutoff week. The choice of 2 weeks is pretty arbitrary and will depend on the specific problem we are trying to solve but let’s just assume that it is fine for this project. In general, you would want to carefully analyse your customers to understand the distribution in gaps between visits to arrive at a suitable definition of churn.
The main idea here is that for each table we want to have one row per household_key containing values for each of our features.
Below we create some simple metrics based on aggregate statistics such as the average, the max and standard deviation.
This dataset has lots of missing data so I decided to use imputation here. There are plenty of techniques out there for missing data from dropping the missing data, to advanced imputation methods. I have just made life easy for myself here and replaced missing values with the mode. I wouldn’t necessarily recommend taking this approach in general as understanding why this data is missing is really important in deciding how to deal with it but for the purposes of this example, I will go ahead and take the easy approach. We first compute the mode for each of our features and then use coalesce to replace each row with the mode if data is missing.
Finally, we build a query for our training data by joining our main tables together and end up with a table containing our target, our campaign, transactions and demographic features which we can use to build a model.
As a brief aside, for those interested in learning more about the features and nuances of Snowflake I would recommend the following book: Snowflake Cookbook. I started reading this book and it is full of really helpful information on how to use Snowflake and goes into far more detail than I do here.
The final piece we require for this ETL is to write a script to execute it. Now, this is only really required if you plan on running an ETL like this regularly but this is good practice and makes it much easier to run the ETL as and when needed.
Let’s briefly discuss the main components of our EtlTraining class. Our class takes one input which is the cutoff week. This is due to the way data is defined in our dataset but ordinarily, this would be in a date format that corresponds to the cutoff date we want to choose for generating training data.
We initialise a list of our queries so we can easily loop through these and execute them. We also create a dictionary containing our parameters which we pass to our Snowflake connection. Here we use environment variables that we set up in Saturn Cloud. Here is a guide on how to do this. It is not too difficult to connect to Snowflake, all we need to do is use the Snowflake connector and pass in our dictionary of credentials. We implement this in the Snowflake connect method and return this connection as an attribute.
To make these queries a little bit easier to run I save each query as a python string variable in the ml_query_pipeline.py file. The execute_etl method does exactly what it says on the tin. We loop through each query, format it, execute it and finish off by closing the Snowflake connection.
To run this ETL we can simply type the commands below into the terminal. (where ml_pipeline is the name of the script above.)
python -m ml_pipeline -w 102 -j ‘train’
As a brief aside, you will probably want to run an ETL like this at regular intervals. For example, if you want to make daily predictions then you will need to generate a dataset like this each day to pass to your model so you can identify which of your customers are likely to churn. I won’t go into this in detail here but in my job, we use Airflow to orchestrate our ETLs so I would recommend checking it out if you are interested. In fact, I recently bought a book ‘Data Pipelines with Apache Airflow’ which I think is great and really gives some solid examples and advice on how to use airflow.
Now that we have our data pipeline built, we can begin to think about modelling. The other main goal I have for this post is to highlight the advantages of using Dask as part of the ML development process and show you guys how easy it is to use.
For this part of the project, I also used Saturn Cloud which is a really nice tool I came across recently that allows us to harness the power of Dask across a cluster of computers in the cloud. The main advantages of using Saturn for me are that it is really easy to share your work, super simple to scale up your compute as and when you need it and it has a free tier option. Model development in general is a really good use case for Dask as we usually want to train a bunch of different models and see what works best. The faster we can do this the better as we have more time to focus on other important aspects of model development. Similar to Snowflake you just need to sign up here and you can very quickly spin up an instance of Jupyter lab and start experimenting with it yourself.
Now, I realise at this point I have mentioned Dask a few times but have never really explained what it is. So let me take a moment to give you a very high-level overview of Dask and why I think it is awesome. Very simply, Dask is a python library that takes advantage of parallel computing to allow you to process and perform operations on very large datasets. And, the best part is, if you are already familiar with Python, then Dask should be very straightforward as the syntax is very similar.
The graph below highlights the main components of Dask.
Source: Dask Documentation
Collections allow us to create a graph of tasks which can then be executed across multiple computers. Some of these data structures probably sound pretty familiar such as arrays and data frames and they are similar to what you would find in python but with some important differences. For example, you can think of a Dask data frame as a bunch of pandas data frames built in such a way that allows us to perform operations in parallel.
Moving on from collections we have the scheduler. Once we create the task graph the scheduler handles the rest for us. It manages the workflow and sends these tasks to either a single machine or distributes them across a cluster. Hopefully, that gives you a very brief overview of how Dask works. For more info, I suggest checking out the documentation or this book. Both are very good resources to dig deeper into this topic.
When modelling, I tend to have a small number of go-to algorithms that I will always try out first. This will generally give me a good idea of what might be suited to the specific problem I have. These models are Logistic Regression, Random Forest and GradientBoosting. In my experience, when working with tabular data these algorithms will usually give you pretty good results. Below we build a sklearn modelling pipeline using these 3 models. The exact models we use here are not really important as the pipeline should work for any sklearn classification model, this is just my preference.
Without further ado, let’s dive into the code. Luckily we outsourced most of our preprocessing to Snowflake so we don’t have to mess around with our training data too much here but we will add a few additional steps using sklearn pipelines.
The first code snippet below shows the pipeline when using sklearn. Notice our dataset is a plain old pandas data frame and our preprocessing steps are all carried out using sklearn methods. There is nothing particularly out of the ordinary going on here. We are reading in our data from the table produced by our Snowflake ETL and passing this into a sklearn pipeline. The usual modelling steps apply here. We split the dataset into train and test and do some preprocessing, namely impute missing values using the median, scale the data and one-hot encode our categorical data. I am a big fan of sklearn pipelines and basically use them whenever I develop models nowadays, they really facilitate clean and concise code.
How does this pipeline perform on a dataset with about 2 million rows? Well, running this model without any hyperparameter tuning takes about 34 minutes. Ouch, kinda slow. You can imagine how prohibitively long this would take if we wanted to do any type of hyperparameter tuning. Ok, so not ideal but let’s see how Dask handles the challenge.
Our goal here is to see if we can beat the sklearn pipeline above, spoiler alert, we definitely can. The cool thing about Dask is that the barrier to entry when you are already familiar with python is pretty low. We can get this pipeline up and running in Dask with only a few changes.
The first change you probably will notice is that we have some different imports. One of the key differences between this pipeline and the previous one is that we will be using a Dask data frame instead of a pandas data frame to train our model. You can think of a Dask data frame as a bunch of pandas data frames where we can perform computations on each one at the same time. This is the core of Dask’s parallelism and is what is going to reduce the training time for this pipeline.
Notice we use @dask.delayed as a decorator to our load_training_data function. This instructs Dask to parallelise this function for us.
We are also going to import some preprocessing and pipeline methods from Dask and most importantly, we will need to import SaturnCluster which will allow us to create a cluster for training our models. Another key difference with this code is that we use dask.persist after our train test split. Before this point, none of our functions has actually been computed due to Dask’s lazy evaluation. Once we use the persist method though we are telling Dask to send our data to the workers and execute the tasks we have created up until this point and leave these objects on the cluster.
Finally, we train our models using the delayed method. Again, this enables us to create our pipeline in a lazy way. The pipeline is not executed until we reach this code:
fit_pipelines = dask.compute(*pipelines_)
This time it only took us around 10 minutes to run this pipeline on the exact same dataset. That is a speedup by a factor of 3.4, not too shabby. Now, if we wanted to, we could speed this up even more by scaling up our compute resources at the touch of a button in Saturn.
I mentioned earlier that you will probably want to run a pipeline like this quite regularly using something like airflow. It just so happens that if you don’t want the initial hassle of setting everything up for airflow Saturn Cloud offers a simple alternative with Jobs. Jobs allow us to package up our code and run it at regular intervals or as needed. All you need to do is go to an existing project and click on create a job. Once we do that, it should look like the following:
From here, all we need to do is make sure our python files above are in the directory in the image and we can enter our python command above
python -m ml_pipeline -w 102 -j 'train'
We can also set up a schedule using cron syntax to run the ETL on a daily basis if we like. For those interested, here is a Tutorial that goes into all the nitty-gritty.
Well, we have reached the end of our project at this point. Now obviously I have left out some key parts of the ML development cycle such as hyperparameter tuning and deploying our model but perhaps I will leave that for another day. Do I think you should try Dask? I am no expert by any means but from what I have seen so far it certainly seems really useful and I am super excited to experiment more with it and find more opportunities to incorporate it into my daily work as a data scientist. Hopefully, you found this useful and you too can see some of the advantages of Snowflake and Dask and you will start experimenting with them on your own.
Data Pipelines with Apache Airflow
Snowflake Cookbook
Data Science at Scale with Python and Dask
Coursera: SQL for Data Science
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Note: Some of the links in this post are affiliate links.
|
[
{
"code": null,
"e": 607,
"s": 172,
"text": "Recently I have been trying to find better ways to improve my workflow as a data scientist. I tend to spend a decent chunk of my time modelling and building ETLs in my job. This has meant that more and more I need to rely on tools to reliably and efficiently handle large datasets. I quickly realised that using pandas for manipulating these datasets is not always a good approach and this prompted me to look into other alternatives."
},
{
"code": null,
"e": 1147,
"s": 607,
"text": "In this post, I want to share some of the tools that I have been exploring recently and show you how I use them and how they helped improve the efficiency of my workflow. The two I will talk about in particular are Snowflake and Dask. Two very different tools but ones that complement each other well especially as part of the ML Lifecycle. My hope is that after reading this post you will have a good understanding of what Snowflake and Dask are, how they can be used effectively and be able to get up and running with your own use cases."
},
{
"code": null,
"e": 1526,
"s": 1147,
"text": "More specifically, I want to show you how you can build an ETL pipeline using Snowflake and Python to generate training data for a machine learning task. I then want to introduce Dask and Saturn Cloud and show you how you can take advantage of parallel processing in the cloud to really speed up the ML training process so you can increase your productivity as a data scientist."
},
{
"code": null,
"e": 2275,
"s": 1526,
"text": "Before we jump into coding I better briefly explain what Snowflake is. This is a question I recently asked when my team decided to start using it. At a high level, it is a data warehouse in the cloud. After playing around with it for a while I realised how powerful it was. I think for me, one of the most useful features is the virtual warehouses that you can use. A virtual warehouse gives you access to the same data but is completely independent of other virtual warehouses so compute resources are not shared across teams. This has proven very useful as it removes any potential for performance issues caused by other users executing queries throughout the day. This has resulted in less frustration and time wasted waiting for queries to run."
},
{
"code": null,
"e": 2432,
"s": 2275,
"text": "Since we are going to be using Snowflake I will briefly outline how you can set it up and start experimenting with it yourself. We need to do the following:"
},
{
"code": null,
"e": 2463,
"s": 2432,
"text": "Get a Snowflake account set up"
},
{
"code": null,
"e": 2491,
"s": 2463,
"text": "Get our data into Snowflake"
},
{
"code": null,
"e": 2549,
"s": 2491,
"text": "Write and test our queries using SQL and the Snowflake UI"
},
{
"code": null,
"e": 2643,
"s": 2549,
"text": "Write a Python class that can execute our queries to generate our final dataset for modelling"
},
{
"code": null,
"e": 2956,
"s": 2643,
"text": "Setting up an account is as easy as signing up for a free trial on their website. Once you have done that you can download the snowsql CLI here. This will make it straightforward to add data to Snowflake. After following these steps we can try and connect to Snowflake using our credentials and the command line."
},
{
"code": null,
"e": 2997,
"s": 2956,
"text": "snowsql -a <account_name> -u <user_name>"
},
{
"code": null,
"e": 3256,
"s": 2997,
"text": "You can find your account name in the URL when you log in to the Snowflake UI. It should look something like this: xxxxx.europe-west2.gcp. Ok, let’s move onto the next step and get our data into Snowflake. There are a few steps we need to follow here namely:"
},
{
"code": null,
"e": 3285,
"s": 3256,
"text": "Create our virtual warehouse"
},
{
"code": null,
"e": 3303,
"s": 3285,
"text": "Create a database"
},
{
"code": null,
"e": 3332,
"s": 3303,
"text": "Define and Create our tables"
},
{
"code": null,
"e": 3373,
"s": 3332,
"text": "Create a staging table for our CSV files"
},
{
"code": null,
"e": 3406,
"s": 3373,
"text": "Copying the data into our tables"
},
{
"code": null,
"e": 3925,
"s": 3406,
"text": "Luckily this isn’t too difficult and we can do this entirely using the snowsql CLI. For this project, I will be using a smaller dataset than I would like but unfortunately, I cannot use any of my company’s data and it can be pretty difficult to find large suitable datasets online. I did however find some transaction data from Dunnhumby which is freely available on Kaggle. Just for kicks though I create a much larger synthetic dataset using this data to test how well Dask handles the challenge compared to sklearn."
},
{
"code": null,
"e": 4042,
"s": 3925,
"text": "First of all, we need to set up a virtual warehouse and a database using the following commands in the Snowflake UI."
},
{
"code": null,
"e": 4176,
"s": 4042,
"text": "create or replace warehouse analytics_wh with warehouse_size=”X-SMALL” auto_suspend=180 auto_resume=true initially_suspended=true;"
},
{
"code": null,
"e": 4214,
"s": 4176,
"text": "create or replace database dunnhumby;"
},
{
"code": null,
"e": 4413,
"s": 4214,
"text": "Our data consists of 6 CSVs which we will convert into 6 tables. I won’t spend too much time going over the dataset as this post is more about using Snowflake and Dask rather than interpreting data."
},
{
"code": null,
"e": 4563,
"s": 4413,
"text": "Below are the commands we can use to create our tables. All you will need to know in advance is what columns and data types you will be working with."
},
{
"code": null,
"e": 5472,
"s": 4563,
"text": "create or replace table campaign_desc ( description string, campaign number,start_day number,end_day number );create or replace table campaign_table ( description string, Household_key number, campaign number );create or replace table coupon ( COUPON_UPC number, product_id number, campaign number );create or replace table coupon_redempt ( household_key number, day number, coupon_upc number, campaign number );create or replace table transactions ( household_key number, BASKET_ID number, day number, product_id number, quantity number, sales_value number, store_id number, retail_disc decimal, trans_time number, week_no number, coupon_disc decimal, coupon_match_disc decimal );create or replace table demographic_data ( age_dec string, marital_status_code string, income_desc string, homeowner_desc string, hh_comp_desc string, household_size_desc string, kid_category_desc string, Household_key number);"
},
{
"code": null,
"e": 5863,
"s": 5472,
"text": "Now that we have our tables created we can start thinking about how to get data into them. For this, we will need to stage our CSV files. This is basically just an intermediary step so Snowflake can directly load the files from our stage into our tables. We can use the PUT command to put local files in our stage and then the COPY INTO command to instruct Snowflake where to put this data."
},
{
"code": null,
"e": 6308,
"s": 5863,
"text": "use database dunnhumby;create or replace stage dunnhumby_stage;PUT file://campaigns_table.csv @dunnhumby.public.dunnhumby_stage;PUT file://campaigns_desc.csv @dunnhumby.public.dunnhumby_stage;PUT file://coupon.csv @dunnhumby.public.dunnhumby_stage;PUT file://coupon_d=redempt.csv @dunnhumby.public.dunnhumby_stage; PUT file://transaction_data.csv @dunnhumby.public.dunnhumby_stage; PUT file://demographics.csv @dunnhumby.public.dunnhumby_stage;"
},
{
"code": null,
"e": 6389,
"s": 6308,
"text": "As a quick check, you can run this command to check what is in the staging area."
},
{
"code": null,
"e": 6427,
"s": 6389,
"text": "ls @dunnhumby.public.dunnhumby_stage;"
},
{
"code": null,
"e": 6604,
"s": 6427,
"text": "Now we just need to copy the data into our tables using the queries below. You can execute these either in the Snowflake UI or in the command line after logging into Snowflake."
},
{
"code": null,
"e": 7783,
"s": 6604,
"text": "copy into campaign_table from @dunnhumby.public.dunnhumby_stage/campaigns_table.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into campaign_desc from @dunnhumby.public.dunnhumby_stage/campaign_desc.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into coupon from @dunnhumby.public.dunnhumby_stage/coupon.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into coupon_redempt from @dunnhumby.public.dunnhumby_stage/coupon_redempt.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into transactions from @dunnhumby.public.dunnhumby_stage/transaction_data.csv.gz file_format = ( type = csvskip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);copy into demographic_data from @dunnhumby.public.dunnhumby_stage/demographics.csv.gz file_format = ( type = csv skip_header=1 error_on_column_count_mismatch = false field_optionally_enclosed_by=’”’);"
},
{
"code": null,
"e": 8177,
"s": 7783,
"text": "Ok great, with any luck we have our data in our tables first try. Oh, if only it was that simple, this whole process took me a few tries to get right (beware of spelling things wrong). Hopefully, you can follow along with this and be good to go. We are getting closer to the interesting stuff but the steps above are a vital part of the process so make sure you understand each of these steps."
},
{
"code": null,
"e": 9266,
"s": 8177,
"text": "In this next step, we will be writing the queries to generate our target, our features and then finally produce a training data set. One approach to creating a dataset for modelling is to read this data into memory and use pandas to create new features and join all the data frames together. This is typically the approach you see on Kaggle and in other online tutorials. The issue with this is that it is not very efficient, particularly when you are working with any reasonably sized datasets. For this reason, it is a much better idea to outsource the heavy lifting to something like Snowflake which handles massive datasets extremely well and will likely save you a huge amount of time. I won’t be spending much time diving into the specifics of our dataset here as it isn’t really vital for what I am trying to show. In general, though, you would want to spend a considerable amount of time exploring and understanding your data before you start modelling. The goal of these queries will be to preprocess the data and create some simple features which we can later use in our models."
},
{
"code": null,
"e": 9836,
"s": 9266,
"text": "Obviously, a vital component of supervised machine learning is defining an appropriate target to predict. For our use case, we will be predicting churn by calculating whether or not a user makes another visit within two weeks after a cutoff week. The choice of 2 weeks is pretty arbitrary and will depend on the specific problem we are trying to solve but let’s just assume that it is fine for this project. In general, you would want to carefully analyse your customers to understand the distribution in gaps between visits to arrive at a suitable definition of churn."
},
{
"code": null,
"e": 9964,
"s": 9836,
"text": "The main idea here is that for each table we want to have one row per household_key containing values for each of our features."
},
{
"code": null,
"e": 10083,
"s": 9964,
"text": "Below we create some simple metrics based on aggregate statistics such as the average, the max and standard deviation."
},
{
"code": null,
"e": 10734,
"s": 10083,
"text": "This dataset has lots of missing data so I decided to use imputation here. There are plenty of techniques out there for missing data from dropping the missing data, to advanced imputation methods. I have just made life easy for myself here and replaced missing values with the mode. I wouldn’t necessarily recommend taking this approach in general as understanding why this data is missing is really important in deciding how to deal with it but for the purposes of this example, I will go ahead and take the easy approach. We first compute the mode for each of our features and then use coalesce to replace each row with the mode if data is missing."
},
{
"code": null,
"e": 10952,
"s": 10734,
"text": "Finally, we build a query for our training data by joining our main tables together and end up with a table containing our target, our campaign, transactions and demographic features which we can use to build a model."
},
{
"code": null,
"e": 11253,
"s": 10952,
"text": "As a brief aside, for those interested in learning more about the features and nuances of Snowflake I would recommend the following book: Snowflake Cookbook. I started reading this book and it is full of really helpful information on how to use Snowflake and goes into far more detail than I do here."
},
{
"code": null,
"e": 11499,
"s": 11253,
"text": "The final piece we require for this ETL is to write a script to execute it. Now, this is only really required if you plan on running an ETL like this regularly but this is good practice and makes it much easier to run the ETL as and when needed."
},
{
"code": null,
"e": 11804,
"s": 11499,
"text": "Let’s briefly discuss the main components of our EtlTraining class. Our class takes one input which is the cutoff week. This is due to the way data is defined in our dataset but ordinarily, this would be in a date format that corresponds to the cutoff date we want to choose for generating training data."
},
{
"code": null,
"e": 12327,
"s": 11804,
"text": "We initialise a list of our queries so we can easily loop through these and execute them. We also create a dictionary containing our parameters which we pass to our Snowflake connection. Here we use environment variables that we set up in Saturn Cloud. Here is a guide on how to do this. It is not too difficult to connect to Snowflake, all we need to do is use the Snowflake connector and pass in our dictionary of credentials. We implement this in the Snowflake connect method and return this connection as an attribute."
},
{
"code": null,
"e": 12619,
"s": 12327,
"text": "To make these queries a little bit easier to run I save each query as a python string variable in the ml_query_pipeline.py file. The execute_etl method does exactly what it says on the tin. We loop through each query, format it, execute it and finish off by closing the Snowflake connection."
},
{
"code": null,
"e": 12745,
"s": 12619,
"text": "To run this ETL we can simply type the commands below into the terminal. (where ml_pipeline is the name of the script above.)"
},
{
"code": null,
"e": 12785,
"s": 12745,
"text": "python -m ml_pipeline -w 102 -j ‘train’"
},
{
"code": null,
"e": 13385,
"s": 12785,
"text": "As a brief aside, you will probably want to run an ETL like this at regular intervals. For example, if you want to make daily predictions then you will need to generate a dataset like this each day to pass to your model so you can identify which of your customers are likely to churn. I won’t go into this in detail here but in my job, we use Airflow to orchestrate our ETLs so I would recommend checking it out if you are interested. In fact, I recently bought a book ‘Data Pipelines with Apache Airflow’ which I think is great and really gives some solid examples and advice on how to use airflow."
},
{
"code": null,
"e": 13631,
"s": 13385,
"text": "Now that we have our data pipeline built, we can begin to think about modelling. The other main goal I have for this post is to highlight the advantages of using Dask as part of the ML development process and show you guys how easy it is to use."
},
{
"code": null,
"e": 14422,
"s": 13631,
"text": "For this part of the project, I also used Saturn Cloud which is a really nice tool I came across recently that allows us to harness the power of Dask across a cluster of computers in the cloud. The main advantages of using Saturn for me are that it is really easy to share your work, super simple to scale up your compute as and when you need it and it has a free tier option. Model development in general is a really good use case for Dask as we usually want to train a bunch of different models and see what works best. The faster we can do this the better as we have more time to focus on other important aspects of model development. Similar to Snowflake you just need to sign up here and you can very quickly spin up an instance of Jupyter lab and start experimenting with it yourself."
},
{
"code": null,
"e": 14919,
"s": 14422,
"text": "Now, I realise at this point I have mentioned Dask a few times but have never really explained what it is. So let me take a moment to give you a very high-level overview of Dask and why I think it is awesome. Very simply, Dask is a python library that takes advantage of parallel computing to allow you to process and perform operations on very large datasets. And, the best part is, if you are already familiar with Python, then Dask should be very straightforward as the syntax is very similar."
},
{
"code": null,
"e": 14975,
"s": 14919,
"text": "The graph below highlights the main components of Dask."
},
{
"code": null,
"e": 15002,
"s": 14975,
"text": "Source: Dask Documentation"
},
{
"code": null,
"e": 15438,
"s": 15002,
"text": "Collections allow us to create a graph of tasks which can then be executed across multiple computers. Some of these data structures probably sound pretty familiar such as arrays and data frames and they are similar to what you would find in python but with some important differences. For example, you can think of a Dask data frame as a bunch of pandas data frames built in such a way that allows us to perform operations in parallel."
},
{
"code": null,
"e": 15865,
"s": 15438,
"text": "Moving on from collections we have the scheduler. Once we create the task graph the scheduler handles the rest for us. It manages the workflow and sends these tasks to either a single machine or distributes them across a cluster. Hopefully, that gives you a very brief overview of how Dask works. For more info, I suggest checking out the documentation or this book. Both are very good resources to dig deeper into this topic."
},
{
"code": null,
"e": 16458,
"s": 15865,
"text": "When modelling, I tend to have a small number of go-to algorithms that I will always try out first. This will generally give me a good idea of what might be suited to the specific problem I have. These models are Logistic Regression, Random Forest and GradientBoosting. In my experience, when working with tabular data these algorithms will usually give you pretty good results. Below we build a sklearn modelling pipeline using these 3 models. The exact models we use here are not really important as the pipeline should work for any sklearn classification model, this is just my preference."
},
{
"code": null,
"e": 16699,
"s": 16458,
"text": "Without further ado, let’s dive into the code. Luckily we outsourced most of our preprocessing to Snowflake so we don’t have to mess around with our training data too much here but we will add a few additional steps using sklearn pipelines."
},
{
"code": null,
"e": 17420,
"s": 16699,
"text": "The first code snippet below shows the pipeline when using sklearn. Notice our dataset is a plain old pandas data frame and our preprocessing steps are all carried out using sklearn methods. There is nothing particularly out of the ordinary going on here. We are reading in our data from the table produced by our Snowflake ETL and passing this into a sklearn pipeline. The usual modelling steps apply here. We split the dataset into train and test and do some preprocessing, namely impute missing values using the median, scale the data and one-hot encode our categorical data. I am a big fan of sklearn pipelines and basically use them whenever I develop models nowadays, they really facilitate clean and concise code."
},
{
"code": null,
"e": 17764,
"s": 17420,
"text": "How does this pipeline perform on a dataset with about 2 million rows? Well, running this model without any hyperparameter tuning takes about 34 minutes. Ouch, kinda slow. You can imagine how prohibitively long this would take if we wanted to do any type of hyperparameter tuning. Ok, so not ideal but let’s see how Dask handles the challenge."
},
{
"code": null,
"e": 18050,
"s": 17764,
"text": "Our goal here is to see if we can beat the sklearn pipeline above, spoiler alert, we definitely can. The cool thing about Dask is that the barrier to entry when you are already familiar with python is pretty low. We can get this pipeline up and running in Dask with only a few changes."
},
{
"code": null,
"e": 18535,
"s": 18050,
"text": "The first change you probably will notice is that we have some different imports. One of the key differences between this pipeline and the previous one is that we will be using a Dask data frame instead of a pandas data frame to train our model. You can think of a Dask data frame as a bunch of pandas data frames where we can perform computations on each one at the same time. This is the core of Dask’s parallelism and is what is going to reduce the training time for this pipeline."
},
{
"code": null,
"e": 18671,
"s": 18535,
"text": "Notice we use @dask.delayed as a decorator to our load_training_data function. This instructs Dask to parallelise this function for us."
},
{
"code": null,
"e": 19254,
"s": 18671,
"text": "We are also going to import some preprocessing and pipeline methods from Dask and most importantly, we will need to import SaturnCluster which will allow us to create a cluster for training our models. Another key difference with this code is that we use dask.persist after our train test split. Before this point, none of our functions has actually been computed due to Dask’s lazy evaluation. Once we use the persist method though we are telling Dask to send our data to the workers and execute the tasks we have created up until this point and leave these objects on the cluster."
},
{
"code": null,
"e": 19425,
"s": 19254,
"text": "Finally, we train our models using the delayed method. Again, this enables us to create our pipeline in a lazy way. The pipeline is not executed until we reach this code:"
},
{
"code": null,
"e": 19467,
"s": 19425,
"text": "fit_pipelines = dask.compute(*pipelines_)"
},
{
"code": null,
"e": 19740,
"s": 19467,
"text": "This time it only took us around 10 minutes to run this pipeline on the exact same dataset. That is a speedup by a factor of 3.4, not too shabby. Now, if we wanted to, we could speed this up even more by scaling up our compute resources at the touch of a button in Saturn."
},
{
"code": null,
"e": 20222,
"s": 19740,
"text": "I mentioned earlier that you will probably want to run a pipeline like this quite regularly using something like airflow. It just so happens that if you don’t want the initial hassle of setting everything up for airflow Saturn Cloud offers a simple alternative with Jobs. Jobs allow us to package up our code and run it at regular intervals or as needed. All you need to do is go to an existing project and click on create a job. Once we do that, it should look like the following:"
},
{
"code": null,
"e": 20363,
"s": 20222,
"text": "From here, all we need to do is make sure our python files above are in the directory in the image and we can enter our python command above"
},
{
"code": null,
"e": 20403,
"s": 20363,
"text": "python -m ml_pipeline -w 102 -j 'train'"
},
{
"code": null,
"e": 20573,
"s": 20403,
"text": "We can also set up a schedule using cron syntax to run the ETL on a daily basis if we like. For those interested, here is a Tutorial that goes into all the nitty-gritty."
},
{
"code": null,
"e": 21223,
"s": 20573,
"text": "Well, we have reached the end of our project at this point. Now obviously I have left out some key parts of the ML development cycle such as hyperparameter tuning and deploying our model but perhaps I will leave that for another day. Do I think you should try Dask? I am no expert by any means but from what I have seen so far it certainly seems really useful and I am super excited to experiment more with it and find more opportunities to incorporate it into my daily work as a data scientist. Hopefully, you found this useful and you too can see some of the advantages of Snowflake and Dask and you will start experimenting with them on your own."
},
{
"code": null,
"e": 21258,
"s": 21223,
"text": "Data Pipelines with Apache Airflow"
},
{
"code": null,
"e": 21277,
"s": 21258,
"text": "Snowflake Cookbook"
},
{
"code": null,
"e": 21320,
"s": 21277,
"text": "Data Science at Scale with Python and Dask"
},
{
"code": null,
"e": 21351,
"s": 21320,
"text": "Coursera: SQL for Data Science"
},
{
"code": null,
"e": 21374,
"s": 21351,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 21397,
"s": 21374,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 21420,
"s": 21397,
"text": "towardsdatascience.com"
}
] |
Supply Chain Optimization with Python | by Samir Saci | Towards Data Science
|
Supply chain optimization makes the best use of data analytics to find an optimal combination of factories and distribution centres to match supply and demand.
Because of the current surge in shipping costs, companies start to challenge their current footprint to adapt to the post-covid “New Normal”.
In this article, we will present a simple methodology using Linear Programming for Supply Chain Optimization considering
Fixed production costs of your facilities ($/Month)
Variable production costs per unit produced ($/Unit)
Shipping costs ($)
Customer’s demand (Units)
Should we keep outsourcing with shipping costs that have tripled in the last 12 months?
As the Head of Supply Chain Management of an international manufacturing company, you want to redefine the Supply Chain Network for the next 5 years considering the recent increase in shipping costs and the forecasts of future demand.
Your Supply Chain Network
5 markets in Brazil, USA, India, Japan, Germany
2 types of manufacturing facilities: low capacity and high capacity sites
Shipping costs ($/container)
Customer’s demand (Units/year)
Manufacturing Facility Fixed Costs
Capital Expenditure for the equipment (Machines, Storage, ..)
Utilities (Electricity, Water, ..)
Factory management, administrative staff
Space Rental
These costs depend on the country and the type of plant.
Production Variable Costs
Production lines operators
Raw materials
For instance, the variable cost of a unit produced in Germany is 13$/Unit.
Shipping Variable Costs
Cost per container ($/Container)
Assumption: 1 container can contain 1000 units
For instance, if you want to ship a container from Germany to Japan it will cost you 1,231 ($/Container).
Manufacturing Capacity by Site
For instance, a high capacity factory in Brazil can produce 1,500,000 (Units/month).
Customers demand per market
You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci
Let us try three scenarios
Scenario 1: initial parameters
Scenario 2: we increase the production capacity of India (x2)
Scenario 3: surging shipping costs due to container shortage
Brazil plant is producing for the local market and the USA
Facilities: 1 high capacity plant('Brazil','Brazil') = 145,000 (Units/Month)('Brazil','USA') = 1,250,000 (Units/Month)
India plants produce for all countries except Brazil
Facilities: 1 high capacity plant and 1 low capacity plant('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','Japan') = 200,000 (Units/Month)('India','USA') = 1,550,000 (Units/Month)
Japan needs to produce locally because of the limited capacity of India
Facilities: 1 high capacity plant('Japan','Japan') = 1,500,000 (Units/Month)
Final Costs
Total Costs = 62,038,000 ($/Month)
What if we double the size of high capacity plants in India?
Let us try to double the size of the India High Capacity plant with the assumption that it will double the fixed costs.
Brazil plant is still producing for the local market and the USA
Facilities: 1 high capacity plant('Brazil','Brazil') = 145,000 (Units/Month)('Brazil','USA') = 1,250,000 (Units/Month)
India plants produce for all countries except Brazil
Facilities: 2 high capacity and 1 low capacity plants('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','Japan') = 1,700,000 (Units/Month)('India','USA') = 1,550,000 (Units/Month)
Japan does not produce locally anymore.
Final Costs
-19.4(%) vs. Scenario 1Total Costs = 51,352,000 ($/Month)
What if we have containers cost multiplied by 5?
Brazil is producing for the local market only
Facilities: 1 low capacity plant('Brazil','Brazil') = 145,000 (Units/Month)
The USA started to produce for the local market and Japan
Facilities: 1 high capacity plant('USA','Japan') = 200,000 (Units/Month)('USA','USA') = 1,300,000 (Units/Month)
India closed its low capacity factory
Facilities: 1 high capacity plant('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','USA') = 1,500,000 (Units/Month)
Japan starts to produce for its local market
Facilities: 1 high capacity plant('Japan','Japan') = 1,500,000 (Units/Month)
Because of their limited production capacity, Japan and the USA still rely on the Indian plant.
Final Costs
Total Costs = 92,981,000 ($/Month)
samirsaci.com
We will be using the PuLP library of python. PuLP is a modelling framework for Linear (LP) and Integer Programming (IP) problems written in Python maintained by COIN-OR Foundation (Computational Infrastructure for Operations Research).
LpMinimize: your objective is to minimize your costs
lowBound =0: you cannot have negative values of units produced
This model gives you the flexibility to simulate several scenarios influencing operational and commercial parameters.
What if the demand explodes in India?
What if we have to close our plant in Brazil?
What if we triple the production capacity in Japan?
Scenario 3 showed is an example of shipping costs surge that could push companies to switch to a more local footprint with plants producing for their local market only.
Is it sustainable to produce in India for the North American market?
If you want to include the environmental impact in your optimization problem, you can calculate the CO2 emissions of your distribution network.
towardsdatascience.com
This simple model can help you to get the potential of linear optimization for Supply Chain Network Optimization. We can easily improve this model by adding constraints
Storage Costs
Carbon emissions limitations (CO2 = f(distance, weight))
Delivery lead time
Customer Clearance Fees
Currency change
Feel free to share suggestions of additional constraints to improve the model and meet the business requirements in your own industry.
Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com
[1] Computational Infrastructure for Operations Research, Optimization with PuLP (Documentation), Link
|
[
{
"code": null,
"e": 332,
"s": 172,
"text": "Supply chain optimization makes the best use of data analytics to find an optimal combination of factories and distribution centres to match supply and demand."
},
{
"code": null,
"e": 474,
"s": 332,
"text": "Because of the current surge in shipping costs, companies start to challenge their current footprint to adapt to the post-covid “New Normal”."
},
{
"code": null,
"e": 595,
"s": 474,
"text": "In this article, we will present a simple methodology using Linear Programming for Supply Chain Optimization considering"
},
{
"code": null,
"e": 647,
"s": 595,
"text": "Fixed production costs of your facilities ($/Month)"
},
{
"code": null,
"e": 700,
"s": 647,
"text": "Variable production costs per unit produced ($/Unit)"
},
{
"code": null,
"e": 719,
"s": 700,
"text": "Shipping costs ($)"
},
{
"code": null,
"e": 745,
"s": 719,
"text": "Customer’s demand (Units)"
},
{
"code": null,
"e": 833,
"s": 745,
"text": "Should we keep outsourcing with shipping costs that have tripled in the last 12 months?"
},
{
"code": null,
"e": 1068,
"s": 833,
"text": "As the Head of Supply Chain Management of an international manufacturing company, you want to redefine the Supply Chain Network for the next 5 years considering the recent increase in shipping costs and the forecasts of future demand."
},
{
"code": null,
"e": 1094,
"s": 1068,
"text": "Your Supply Chain Network"
},
{
"code": null,
"e": 1142,
"s": 1094,
"text": "5 markets in Brazil, USA, India, Japan, Germany"
},
{
"code": null,
"e": 1216,
"s": 1142,
"text": "2 types of manufacturing facilities: low capacity and high capacity sites"
},
{
"code": null,
"e": 1245,
"s": 1216,
"text": "Shipping costs ($/container)"
},
{
"code": null,
"e": 1276,
"s": 1245,
"text": "Customer’s demand (Units/year)"
},
{
"code": null,
"e": 1311,
"s": 1276,
"text": "Manufacturing Facility Fixed Costs"
},
{
"code": null,
"e": 1373,
"s": 1311,
"text": "Capital Expenditure for the equipment (Machines, Storage, ..)"
},
{
"code": null,
"e": 1408,
"s": 1373,
"text": "Utilities (Electricity, Water, ..)"
},
{
"code": null,
"e": 1449,
"s": 1408,
"text": "Factory management, administrative staff"
},
{
"code": null,
"e": 1462,
"s": 1449,
"text": "Space Rental"
},
{
"code": null,
"e": 1519,
"s": 1462,
"text": "These costs depend on the country and the type of plant."
},
{
"code": null,
"e": 1545,
"s": 1519,
"text": "Production Variable Costs"
},
{
"code": null,
"e": 1572,
"s": 1545,
"text": "Production lines operators"
},
{
"code": null,
"e": 1586,
"s": 1572,
"text": "Raw materials"
},
{
"code": null,
"e": 1661,
"s": 1586,
"text": "For instance, the variable cost of a unit produced in Germany is 13$/Unit."
},
{
"code": null,
"e": 1685,
"s": 1661,
"text": "Shipping Variable Costs"
},
{
"code": null,
"e": 1718,
"s": 1685,
"text": "Cost per container ($/Container)"
},
{
"code": null,
"e": 1765,
"s": 1718,
"text": "Assumption: 1 container can contain 1000 units"
},
{
"code": null,
"e": 1871,
"s": 1765,
"text": "For instance, if you want to ship a container from Germany to Japan it will cost you 1,231 ($/Container)."
},
{
"code": null,
"e": 1902,
"s": 1871,
"text": "Manufacturing Capacity by Site"
},
{
"code": null,
"e": 1987,
"s": 1902,
"text": "For instance, a high capacity factory in Brazil can produce 1,500,000 (Units/month)."
},
{
"code": null,
"e": 2015,
"s": 1987,
"text": "Customers demand per market"
},
{
"code": null,
"e": 2118,
"s": 2015,
"text": "You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 2145,
"s": 2118,
"text": "Let us try three scenarios"
},
{
"code": null,
"e": 2176,
"s": 2145,
"text": "Scenario 1: initial parameters"
},
{
"code": null,
"e": 2238,
"s": 2176,
"text": "Scenario 2: we increase the production capacity of India (x2)"
},
{
"code": null,
"e": 2299,
"s": 2238,
"text": "Scenario 3: surging shipping costs due to container shortage"
},
{
"code": null,
"e": 2358,
"s": 2299,
"text": "Brazil plant is producing for the local market and the USA"
},
{
"code": null,
"e": 2477,
"s": 2358,
"text": "Facilities: 1 high capacity plant('Brazil','Brazil') = 145,000 (Units/Month)('Brazil','USA') = 1,250,000 (Units/Month)"
},
{
"code": null,
"e": 2530,
"s": 2477,
"text": "India plants produce for all countries except Brazil"
},
{
"code": null,
"e": 2754,
"s": 2530,
"text": "Facilities: 1 high capacity plant and 1 low capacity plant('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','Japan') = 200,000 (Units/Month)('India','USA') = 1,550,000 (Units/Month)"
},
{
"code": null,
"e": 2826,
"s": 2754,
"text": "Japan needs to produce locally because of the limited capacity of India"
},
{
"code": null,
"e": 2903,
"s": 2826,
"text": "Facilities: 1 high capacity plant('Japan','Japan') = 1,500,000 (Units/Month)"
},
{
"code": null,
"e": 2915,
"s": 2903,
"text": "Final Costs"
},
{
"code": null,
"e": 2950,
"s": 2915,
"text": "Total Costs = 62,038,000 ($/Month)"
},
{
"code": null,
"e": 3011,
"s": 2950,
"text": "What if we double the size of high capacity plants in India?"
},
{
"code": null,
"e": 3131,
"s": 3011,
"text": "Let us try to double the size of the India High Capacity plant with the assumption that it will double the fixed costs."
},
{
"code": null,
"e": 3196,
"s": 3131,
"text": "Brazil plant is still producing for the local market and the USA"
},
{
"code": null,
"e": 3315,
"s": 3196,
"text": "Facilities: 1 high capacity plant('Brazil','Brazil') = 145,000 (Units/Month)('Brazil','USA') = 1,250,000 (Units/Month)"
},
{
"code": null,
"e": 3368,
"s": 3315,
"text": "India plants produce for all countries except Brazil"
},
{
"code": null,
"e": 3589,
"s": 3368,
"text": "Facilities: 2 high capacity and 1 low capacity plants('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','Japan') = 1,700,000 (Units/Month)('India','USA') = 1,550,000 (Units/Month)"
},
{
"code": null,
"e": 3629,
"s": 3589,
"text": "Japan does not produce locally anymore."
},
{
"code": null,
"e": 3641,
"s": 3629,
"text": "Final Costs"
},
{
"code": null,
"e": 3699,
"s": 3641,
"text": "-19.4(%) vs. Scenario 1Total Costs = 51,352,000 ($/Month)"
},
{
"code": null,
"e": 3748,
"s": 3699,
"text": "What if we have containers cost multiplied by 5?"
},
{
"code": null,
"e": 3794,
"s": 3748,
"text": "Brazil is producing for the local market only"
},
{
"code": null,
"e": 3870,
"s": 3794,
"text": "Facilities: 1 low capacity plant('Brazil','Brazil') = 145,000 (Units/Month)"
},
{
"code": null,
"e": 3928,
"s": 3870,
"text": "The USA started to produce for the local market and Japan"
},
{
"code": null,
"e": 4040,
"s": 3928,
"text": "Facilities: 1 high capacity plant('USA','Japan') = 200,000 (Units/Month)('USA','USA') = 1,300,000 (Units/Month)"
},
{
"code": null,
"e": 4078,
"s": 4040,
"text": "India closed its low capacity factory"
},
{
"code": null,
"e": 4236,
"s": 4078,
"text": "Facilities: 1 high capacity plant('India','Germany') = 90,000 (Units/Month)('India','India') = 160,000 (Units/Month)('India','USA') = 1,500,000 (Units/Month)"
},
{
"code": null,
"e": 4281,
"s": 4236,
"text": "Japan starts to produce for its local market"
},
{
"code": null,
"e": 4358,
"s": 4281,
"text": "Facilities: 1 high capacity plant('Japan','Japan') = 1,500,000 (Units/Month)"
},
{
"code": null,
"e": 4454,
"s": 4358,
"text": "Because of their limited production capacity, Japan and the USA still rely on the Indian plant."
},
{
"code": null,
"e": 4466,
"s": 4454,
"text": "Final Costs"
},
{
"code": null,
"e": 4501,
"s": 4466,
"text": "Total Costs = 92,981,000 ($/Month)"
},
{
"code": null,
"e": 4515,
"s": 4501,
"text": "samirsaci.com"
},
{
"code": null,
"e": 4751,
"s": 4515,
"text": "We will be using the PuLP library of python. PuLP is a modelling framework for Linear (LP) and Integer Programming (IP) problems written in Python maintained by COIN-OR Foundation (Computational Infrastructure for Operations Research)."
},
{
"code": null,
"e": 4804,
"s": 4751,
"text": "LpMinimize: your objective is to minimize your costs"
},
{
"code": null,
"e": 4867,
"s": 4804,
"text": "lowBound =0: you cannot have negative values of units produced"
},
{
"code": null,
"e": 4985,
"s": 4867,
"text": "This model gives you the flexibility to simulate several scenarios influencing operational and commercial parameters."
},
{
"code": null,
"e": 5023,
"s": 4985,
"text": "What if the demand explodes in India?"
},
{
"code": null,
"e": 5069,
"s": 5023,
"text": "What if we have to close our plant in Brazil?"
},
{
"code": null,
"e": 5121,
"s": 5069,
"text": "What if we triple the production capacity in Japan?"
},
{
"code": null,
"e": 5290,
"s": 5121,
"text": "Scenario 3 showed is an example of shipping costs surge that could push companies to switch to a more local footprint with plants producing for their local market only."
},
{
"code": null,
"e": 5359,
"s": 5290,
"text": "Is it sustainable to produce in India for the North American market?"
},
{
"code": null,
"e": 5503,
"s": 5359,
"text": "If you want to include the environmental impact in your optimization problem, you can calculate the CO2 emissions of your distribution network."
},
{
"code": null,
"e": 5526,
"s": 5503,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5695,
"s": 5526,
"text": "This simple model can help you to get the potential of linear optimization for Supply Chain Network Optimization. We can easily improve this model by adding constraints"
},
{
"code": null,
"e": 5709,
"s": 5695,
"text": "Storage Costs"
},
{
"code": null,
"e": 5766,
"s": 5709,
"text": "Carbon emissions limitations (CO2 = f(distance, weight))"
},
{
"code": null,
"e": 5785,
"s": 5766,
"text": "Delivery lead time"
},
{
"code": null,
"e": 5809,
"s": 5785,
"text": "Customer Clearance Fees"
},
{
"code": null,
"e": 5825,
"s": 5809,
"text": "Currency change"
},
{
"code": null,
"e": 5960,
"s": 5825,
"text": "Feel free to share suggestions of additional constraints to improve the model and meet the business requirements in your own industry."
},
{
"code": null,
"e": 6114,
"s": 5960,
"text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com"
}
] |
Close Bootstrap class
|
Use the generic close icon for dismissing content like models and alerts. Use the class close to getting the close icon.
You can try to run the following code to implement a close Bootstrap class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<p>Close Icon:
<button type = "button" class = "close" aria-hidden = "true">
×
</button>
</p>
</body>
</html>
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Use the generic close icon for dismissing content like models and alerts. Use the class close to getting the close icon."
},
{
"code": null,
"e": 1258,
"s": 1183,
"text": "You can try to run the following code to implement a close Bootstrap class"
},
{
"code": null,
"e": 1268,
"s": 1258,
"text": "Live Demo"
},
{
"code": null,
"e": 1708,
"s": 1268,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Close Icon:\n <button type = \"button\" class = \"close\" aria-hidden = \"true\">\n ×\n </button>\n </p>\n </body>\n</html>"
}
] |
Find all triplets with zero sum - GeeksforGeeks
|
20 Apr, 2022
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.
Examples :
Input : arr[] = {0, -1, 2, -3, 1}
Output : (0 -1 1), (2 -3 1)
Explanation : The triplets with zero sum are
0 + -1 + 1 = 0 and 2 + -3 + 1 = 0
Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2 1
Explanation : The triplets with zero sum is
1 + -2 + 1 = 0
Method 1: This is a simple method that takes O(n3) time to arrive at the result.
Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found.
Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Run three nested loops with loop counter i, j, k
The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.
Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find three elements// whose sum is equal to zero#include<bits/stdc++.h>using namespace std; // Prints all triplets in arr[] with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { cout << arr[i] << " " << arr[j] << " " << arr[k] <<endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << " not exist "<<endl; } // Driver codeint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}
// A simple Java program to find three elements// whose sum is equal to zeroclass num{// Prints all triplets in arr[] with 0 sumstatic void findTriplets(int[] arr, int n){ boolean found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { System.out.print(arr[i]); System.out.print(" "); System.out.print(arr[j]); System.out.print(" "); System.out.print(arr[k]); System.out.print("\n"); found = true; } } } } // If no triplet with 0 sum found in array if (found == false) System.out.println(" not exist "); } // Driver codepublic static void main(String[] args){ int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }}//This code is contributed by//Smitha Dinesh Semwal
# A simple Python 3 program# to find three elements whose# sum is equal to zero # Prints all triplets in# arr[] with 0 sumdef findTriplets(arr, n): found = False for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) found = True # If no triplet with 0 sum # found in array if (found == False): print(" not exist ") # Driver codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal
// A simple C# program to find three elements// whose sum is equal to zerousing System; class GFG { // Prints all triplets in arr[] with 0 sum static void findTriplets(int []arr, int n) { bool found = false; for (int i = 0; i < n-2; i++) { for (int j = i+1; j < n-1; j++) { for (int k = j+1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { Console.Write(arr[i]); Console.Write(" "); Console.Write(arr[j]); Console.Write(" "); Console.Write(arr[k]); Console.Write("\n"); found = true; } } } } // If no triplet with 0 sum found in // array if (found == false) Console.Write(" not exist "); } // Driver code public static void Main() { int []arr = {0, -1, 2, -3, 1}; int n = arr.Length; findTriplets(arr, n); }} // This code is contributed by nitin mittal.
<?php// A simple PHP program to// find three elements whose// sum is equal to zero // Prints all triplets// in arr[] with 0 sumfunction findTriplets($arr, $n){ $found = false; for ($i = 0; $i < $n - 2; $i++) { for ($j = $i + 1; $j < $n - 1; $j++) { for ($k = $j + 1; $k < $n; $k++) { if ($arr[$i] + $arr[$j] + $arr[$k] == 0) { echo $arr[$i] , " ", $arr[$j] , " ", $arr[$k] ,"\n"; $found = true; } } } } // If no triplet with 0 // sum found in array if ($found == false) echo " not exist ", "\n"; } // Driver Code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n); // This code is contributed by m_kit?>
<script>// A simple Javascript program to find//three elements whose sum is equal to zero arr = [0, -1, 2, -3, 1]; // Prints all triplets in arr[] with 0 sum function findTriplets(arr) { let found = false; for (let i = 0; i < arr.length - 2; i++) { for (let j = i + 1; j < arr.length - 1; j++) { for (let k = j + 1; k < arr.length; k++) { if (arr[i] + arr[j] + arr[k] === 0) { document.write(arr[i]); document.write(" "); document.write(arr[j]); document.write(" "); document.write(arr[k]); document.write("<br>"); found = true; } } } // If no triplet with 0 sum found in array if(found === false) { document.write(" not exist "); } } } findTriplets(arr);// This code is contributed by Surbhi Tyagi</script>
0 -1 1
2 -3 1
Complexity Analysis:
Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3).
Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant.
Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2).
Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing.
Algorithm:
Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
Create a hashmap to store a key-value pair.
Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1
Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not
If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find triplets in a given// array whose sum is zero#include<bits/stdc++.h>using namespace std; // function to print triplets with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; for (int i=0; i<n-1; i++) { // Find all pairs with sum equals to // "-arr[i]" unordered_set<int> s; for (int j=i+1; j<n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf("%d %d %d\n", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << " No Triplet Found" << endl;} // Driver codeint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}
// Java program to find triplets in a given// array whose sum is zeroimport java.util.*; class GFG{ // function to print triplets with 0 sum static void findTriplets(int arr[], int n) { boolean found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" HashSet<Integer> s = new HashSet<Integer>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.contains(x)) { System.out.printf("%d %d %d\n", x, arr[i], arr[j]); found = true; } else { s.add(arr[j]); } } } if (found == false) { System.out.printf(" No Triplet Found\n"); } } // Driver code public static void main(String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n = arr.length; findTriplets(arr, n); }} // This code contributed by Rajput-Ji
# Python3 program to find triplets# in a given array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False for i in range(n - 1): # Find all pairs with sum # equals to "-arr[i]" s = set() for j in range(i + 1, n): x = -(arr[i] + arr[j]) if x in s: print(x, arr[i], arr[j]) found = True else: s.add(arr[j]) if found == False: print("No Triplet Found") # Driver Codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Shrikant13
// C# program to find triplets in a given// array whose sum is zerousing System;using System.Collections.Generic; class GFG{ // function to print triplets with 0 sum static void findTriplets(int []arr, int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" HashSet<int> s = new HashSet<int>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.Contains(x)) { Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]); found = true; } else { s.Add(arr[j]); } } } if (found == false) { Console.Write(" No Triplet Found\n"); } } // Driver code public static void Main(String[] args) { int []arr = {0, -1, 2, -3, 1}; int n = arr.Length; findTriplets(arr, n); }} // This code has been contributed by 29AjayKumar
<script> // Javascript program to find triplets in a given// array whose sum is zero // function to print triplets with 0 sumfunction findTriplets(arr, n){ var found = false; for (var i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" var s = new Set(); for (var j = i + 1; j < n; j++) { var x = -(arr[i] + arr[j]); if (s.has(x)) { document.write( x + " " + arr[i] + " " + arr[j] + "<br>"); found = true; } else s.add(arr[j]); } } if (found == false) document.write( " No Triplet Found" );} // Driver codevar arr = [0, -1, 2, -3, 1];var n = arr.length;findTriplets(arr, n); // This code is contributed by famously.</script>
-1 0 1
-3 2 1
Complexity Analysis:
Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2).
Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear.
Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time.
Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element.
Algorithm:
Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by decreasing the value of r the sum will decrease as the array is sorted, so array[r-1] < array [r].
Sort the array in ascending order.
Traverse the array from start to end.
For every index i, create two variables l = i + 1 and r = n – 1
Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop
If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]
If the sum is greater than zero then decrement the value of r, by decreasing the value of r the sum will decrease as the array is sorted, so array[r-1] < array [r].
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find triplets in a given// array whose sum is zero#include<bits/stdc++.h>using namespace std; // function to print triplets with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; // sort array elements sort(arr, arr+n); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf("%d %d %d\n", x, arr[l], arr[r]); l++; r--; // found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << " No Triplet Found" << endl;} // Driven sourceint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}
// Java program to find triplets in a given// array whose sum is zeroimport java.util.Arrays;import java.io.*; class GFG { // function to print triplets with 0 sumstatic void findTriplets(int arr[], int n){ boolean found = false; // sort array elements Arrays.sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero System.out.print(x + " "); System.out.print(arr[l]+ " "); System.out.println(arr[r]+ " "); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) System.out.println(" No Triplet Found");} // Driven source public static void main (String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }//This code is contributed by Tushil.. }
# python program to find triplets in a given# array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False # sort array elements arr.sort() for i in range(0, n-1): # initialize left and right l = i + 1 r = n - 1 x = arr[i] while (l < r): if (x + arr[l] + arr[r] == 0): # print elements if it's sum is zero print(x, arr[l], arr[r]) l+=1 r-=1 found = True # If sum of three elements is less # than zero then increment in left elif (x + arr[l] + arr[r] < 0): l+=1 # if sum is greater than zero then # decrement in right side else: r-=1 if (found == False): print(" No Triplet Found") # Driven sourcearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal
// C# program to find triplets in a given// array whose sum is zerousing System; public class GFG{ // function to print triplets with 0 sumstatic void findTriplets(int []arr, int n){ bool found = false; // sort array elements Array.Sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero Console.Write(x + " "); Console.Write(arr[l]+ " "); Console.WriteLine(arr[r]+ " "); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) Console.WriteLine(" No Triplet Found");} // Driven source static public void Main (){ int []arr = {0, -1, 2, -3, 1}; int n =arr.Length; findTriplets(arr, n); }//This code is contributed by akt_mit..}
<?php// PHP program to find// triplets in a given// array whose sum is zero // function to print// triplets with 0 sumfunction findTriplets($arr, $n){ $found = false; // sort array elements sort($arr); for ($i = 0; $i < $n - 1; $i++) { // initialize left // and right $l = $i + 1; $r = $n - 1; $x = $arr[$i]; while ($l < $r) { if ($x + $arr[$l] + $arr[$r] == 0) { // print elements if // it's sum is zero echo $x," ", $arr[$l], " ", $arr[$r], "\n"; $l++; $r--; $found = true; } // If sum of three elements // is less than zero then // increment in left else if ($x + $arr[$l] + $arr[$r] < 0) $l++; // if sum is greater than // zero then decrement // in right side else $r--; } } if ($found == false) echo " No Triplet Found" ,"\n";} // Driver Code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n); // This code is contributed by ajit?>
<script> // Javascript program to find triplets in a given// array whose sum is zero // function to print triplets with 0 sumfunction findTriplets(arr, n){ let found = false; // sort array elements arr.sort((a, b) => a - b); for (let i=0; i<n-1; i++) { // initialize left and right let l = i + 1; let r = n - 1; let x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero document.write(x + " "); document.write(arr[l]+ " "); document.write(arr[r]+ " " + "<br>"); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) document.write(" No Triplet Found" + "<br>");} // Driven source let arr = [0, -1, 2, -3, 1]; let n = arr.length; findTriplets(arr, n); // This code is contributed by Mayank Tyagi </script>
-3 1 2
-1 0 1
Complexity Analysis:
Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2).
Auxiliary Space : O(1), no extra space is required, so the time complexity is constant.
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
shrikanth13
Rajput-Ji
29AjayKumar
andrew1234
hasanbasri
surbhityagi15
mayanktyagi1709
shivamkrishna
srivastavaharshit848
jaydeepradadiya
famously
vikeshkumar5329
7rahult
himanshu180599
dragonuncaged
Facebook
Google
two-pointer-algorithm
Arrays
Hash
Searching
Sorting
Google
Facebook
two-pointer-algorithm
Arrays
Searching
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 40885,
"s": 40857,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 40983,
"s": 40885,
"text": "Given an array of distinct elements. The task is to find triplets in the array whose sum is zero."
},
{
"code": null,
"e": 40995,
"s": 40983,
"text": "Examples : "
},
{
"code": null,
"e": 41252,
"s": 40995,
"text": "Input : arr[] = {0, -1, 2, -3, 1}\nOutput : (0 -1 1), (2 -3 1)\n\nExplanation : The triplets with zero sum are\n0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 \n\nInput : arr[] = {1, -2, 1, 0, 5}\nOutput : 1 -2 1\nExplanation : The triplets with zero sum is\n1 + -2 + 1 = 0 "
},
{
"code": null,
"e": 41333,
"s": 41252,
"text": "Method 1: This is a simple method that takes O(n3) time to arrive at the result."
},
{
"code": null,
"e": 41527,
"s": 41333,
"text": "Approach: The naive approach runs three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found."
},
{
"code": null,
"e": 41865,
"s": 41527,
"text": "Algorithm: Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 42192,
"s": 41865,
"text": "Run three nested loops with loop counter i, j, kThe first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 42241,
"s": 42192,
"text": "Run three nested loops with loop counter i, j, k"
},
{
"code": null,
"e": 42411,
"s": 42241,
"text": "The first loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet."
},
{
"code": null,
"e": 42521,
"s": 42411,
"text": "Check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue."
},
{
"code": null,
"e": 42573,
"s": 42521,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 42577,
"s": 42573,
"text": "C++"
},
{
"code": null,
"e": 42582,
"s": 42577,
"text": "Java"
},
{
"code": null,
"e": 42590,
"s": 42582,
"text": "Python3"
},
{
"code": null,
"e": 42593,
"s": 42590,
"text": "C#"
},
{
"code": null,
"e": 42597,
"s": 42593,
"text": "PHP"
},
{
"code": null,
"e": 42608,
"s": 42597,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find three elements// whose sum is equal to zero#include<bits/stdc++.h>using namespace std; // Prints all triplets in arr[] with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { cout << arr[i] << \" \" << arr[j] << \" \" << arr[k] <<endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << \" not exist \"<<endl; } // Driver codeint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}",
"e": 43467,
"s": 42608,
"text": null
},
{
"code": "// A simple Java program to find three elements// whose sum is equal to zeroclass num{// Prints all triplets in arr[] with 0 sumstatic void findTriplets(int[] arr, int n){ boolean found = false; for (int i=0; i<n-2; i++) { for (int j=i+1; j<n-1; j++) { for (int k=j+1; k<n; k++) { if (arr[i]+arr[j]+arr[k] == 0) { System.out.print(arr[i]); System.out.print(\" \"); System.out.print(arr[j]); System.out.print(\" \"); System.out.print(arr[k]); System.out.print(\"\\n\"); found = true; } } } } // If no triplet with 0 sum found in array if (found == false) System.out.println(\" not exist \"); } // Driver codepublic static void main(String[] args){ int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }}//This code is contributed by//Smitha Dinesh Semwal",
"e": 44498,
"s": 43467,
"text": null
},
{
"code": "# A simple Python 3 program# to find three elements whose# sum is equal to zero # Prints all triplets in# arr[] with 0 sumdef findTriplets(arr, n): found = False for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) found = True # If no triplet with 0 sum # found in array if (found == False): print(\" not exist \") # Driver codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal ",
"e": 45161,
"s": 44498,
"text": null
},
{
"code": "// A simple C# program to find three elements// whose sum is equal to zerousing System; class GFG { // Prints all triplets in arr[] with 0 sum static void findTriplets(int []arr, int n) { bool found = false; for (int i = 0; i < n-2; i++) { for (int j = i+1; j < n-1; j++) { for (int k = j+1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { Console.Write(arr[i]); Console.Write(\" \"); Console.Write(arr[j]); Console.Write(\" \"); Console.Write(arr[k]); Console.Write(\"\\n\"); found = true; } } } } // If no triplet with 0 sum found in // array if (found == false) Console.Write(\" not exist \"); } // Driver code public static void Main() { int []arr = {0, -1, 2, -3, 1}; int n = arr.Length; findTriplets(arr, n); }} // This code is contributed by nitin mittal.",
"e": 46376,
"s": 45161,
"text": null
},
{
"code": "<?php// A simple PHP program to// find three elements whose// sum is equal to zero // Prints all triplets// in arr[] with 0 sumfunction findTriplets($arr, $n){ $found = false; for ($i = 0; $i < $n - 2; $i++) { for ($j = $i + 1; $j < $n - 1; $j++) { for ($k = $j + 1; $k < $n; $k++) { if ($arr[$i] + $arr[$j] + $arr[$k] == 0) { echo $arr[$i] , \" \", $arr[$j] , \" \", $arr[$k] ,\"\\n\"; $found = true; } } } } // If no triplet with 0 // sum found in array if ($found == false) echo \" not exist \", \"\\n\"; } // Driver Code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n); // This code is contributed by m_kit?>",
"e": 47244,
"s": 46376,
"text": null
},
{
"code": "<script>// A simple Javascript program to find//three elements whose sum is equal to zero arr = [0, -1, 2, -3, 1]; // Prints all triplets in arr[] with 0 sum function findTriplets(arr) { let found = false; for (let i = 0; i < arr.length - 2; i++) { for (let j = i + 1; j < arr.length - 1; j++) { for (let k = j + 1; k < arr.length; k++) { if (arr[i] + arr[j] + arr[k] === 0) { document.write(arr[i]); document.write(\" \"); document.write(arr[j]); document.write(\" \"); document.write(arr[k]); document.write(\"<br>\"); found = true; } } } // If no triplet with 0 sum found in array if(found === false) { document.write(\" not exist \"); } } } findTriplets(arr);// This code is contributed by Surbhi Tyagi</script>",
"e": 48253,
"s": 47244,
"text": null
},
{
"code": null,
"e": 48267,
"s": 48253,
"text": "0 -1 1\n2 -3 1"
},
{
"code": null,
"e": 48289,
"s": 48267,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 48382,
"s": 48289,
"text": "Time Complexity: O(n3). As three nested loops are required, so the time complexity is O(n3)."
},
{
"code": null,
"e": 48476,
"s": 48382,
"text": "Auxiliary Space: O(1). Since no extra space is required, so the space complexity is constant."
},
{
"code": null,
"e": 48599,
"s": 48476,
"text": " Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2). "
},
{
"code": null,
"e": 48790,
"s": 48599,
"text": "Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pair sum and can be solved in O(n) time using hashing."
},
{
"code": null,
"e": 48802,
"s": 48790,
"text": "Algorithm: "
},
{
"code": null,
"e": 49138,
"s": 48802,
"text": "Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap."
},
{
"code": null,
"e": 49182,
"s": 49138,
"text": "Create a hashmap to store a key-value pair."
},
{
"code": null,
"e": 49280,
"s": 49182,
"text": "Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1"
},
{
"code": null,
"e": 49372,
"s": 49280,
"text": "Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not"
},
{
"code": null,
"e": 49477,
"s": 49372,
"text": "If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap."
},
{
"code": null,
"e": 49529,
"s": 49477,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 49533,
"s": 49529,
"text": "C++"
},
{
"code": null,
"e": 49538,
"s": 49533,
"text": "Java"
},
{
"code": null,
"e": 49546,
"s": 49538,
"text": "Python3"
},
{
"code": null,
"e": 49549,
"s": 49546,
"text": "C#"
},
{
"code": null,
"e": 49560,
"s": 49549,
"text": "Javascript"
},
{
"code": "// C++ program to find triplets in a given// array whose sum is zero#include<bits/stdc++.h>using namespace std; // function to print triplets with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; for (int i=0; i<n-1; i++) { // Find all pairs with sum equals to // \"-arr[i]\" unordered_set<int> s; for (int j=i+1; j<n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf(\"%d %d %d\\n\", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << \" No Triplet Found\" << endl;} // Driver codeint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}",
"e": 50399,
"s": 49560,
"text": null
},
{
"code": "// Java program to find triplets in a given// array whose sum is zeroimport java.util.*; class GFG{ // function to print triplets with 0 sum static void findTriplets(int arr[], int n) { boolean found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"-arr[i]\" HashSet<Integer> s = new HashSet<Integer>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.contains(x)) { System.out.printf(\"%d %d %d\\n\", x, arr[i], arr[j]); found = true; } else { s.add(arr[j]); } } } if (found == false) { System.out.printf(\" No Triplet Found\\n\"); } } // Driver code public static void main(String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n = arr.length; findTriplets(arr, n); }} // This code contributed by Rajput-Ji",
"e": 51491,
"s": 50399,
"text": null
},
{
"code": "# Python3 program to find triplets# in a given array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False for i in range(n - 1): # Find all pairs with sum # equals to \"-arr[i]\" s = set() for j in range(i + 1, n): x = -(arr[i] + arr[j]) if x in s: print(x, arr[i], arr[j]) found = True else: s.add(arr[j]) if found == False: print(\"No Triplet Found\") # Driver Codearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Shrikant13",
"e": 52118,
"s": 51491,
"text": null
},
{
"code": "// C# program to find triplets in a given// array whose sum is zerousing System;using System.Collections.Generic; class GFG{ // function to print triplets with 0 sum static void findTriplets(int []arr, int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"-arr[i]\" HashSet<int> s = new HashSet<int>(); for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.Contains(x)) { Console.Write(\"{0} {1} {2}\\n\", x, arr[i], arr[j]); found = true; } else { s.Add(arr[j]); } } } if (found == false) { Console.Write(\" No Triplet Found\\n\"); } } // Driver code public static void Main(String[] args) { int []arr = {0, -1, 2, -3, 1}; int n = arr.Length; findTriplets(arr, n); }} // This code has been contributed by 29AjayKumar",
"e": 53230,
"s": 52118,
"text": null
},
{
"code": "<script> // Javascript program to find triplets in a given// array whose sum is zero // function to print triplets with 0 sumfunction findTriplets(arr, n){ var found = false; for (var i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"-arr[i]\" var s = new Set(); for (var j = i + 1; j < n; j++) { var x = -(arr[i] + arr[j]); if (s.has(x)) { document.write( x + \" \" + arr[i] + \" \" + arr[j] + \"<br>\"); found = true; } else s.add(arr[j]); } } if (found == false) document.write( \" No Triplet Found\" );} // Driver codevar arr = [0, -1, 2, -3, 1];var n = arr.length;findTriplets(arr, n); // This code is contributed by famously.</script>",
"e": 54045,
"s": 53230,
"text": null
},
{
"code": null,
"e": 54059,
"s": 54045,
"text": "-1 0 1\n-3 2 1"
},
{
"code": null,
"e": 54081,
"s": 54059,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 54175,
"s": 54081,
"text": "Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2)."
},
{
"code": null,
"e": 54262,
"s": 54175,
"text": "Auxiliary Space: O(n). Since a hashmap is required, so the space complexity is linear."
},
{
"code": null,
"e": 54361,
"s": 54262,
"text": " Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time. "
},
{
"code": null,
"e": 54557,
"s": 54361,
"text": "Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element."
},
{
"code": null,
"e": 54569,
"s": 54557,
"text": "Algorithm: "
},
{
"code": null,
"e": 55166,
"s": 54569,
"text": "Sort the array in ascending order.Traverse the array from start to end.For every index i, create two variables l = i + 1 and r = n – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]If the sum is greater than zero then decrement the value of r, by decreasing the value of r the sum will decrease as the array is sorted, so array[r-1] < array [r]."
},
{
"code": null,
"e": 55201,
"s": 55166,
"text": "Sort the array in ascending order."
},
{
"code": null,
"e": 55239,
"s": 55201,
"text": "Traverse the array from start to end."
},
{
"code": null,
"e": 55303,
"s": 55239,
"text": "For every index i, create two variables l = i + 1 and r = n – 1"
},
{
"code": null,
"e": 55442,
"s": 55303,
"text": "Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loop"
},
{
"code": null,
"e": 55603,
"s": 55442,
"text": "If the sum is less than zero then increment the value of l, by increasing the value of l the sum will increase as the array is sorted, so array[l+1] > array [l]"
},
{
"code": null,
"e": 55768,
"s": 55603,
"text": "If the sum is greater than zero then decrement the value of r, by decreasing the value of r the sum will decrease as the array is sorted, so array[r-1] < array [r]."
},
{
"code": null,
"e": 55820,
"s": 55768,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 55824,
"s": 55820,
"text": "C++"
},
{
"code": null,
"e": 55829,
"s": 55824,
"text": "Java"
},
{
"code": null,
"e": 55837,
"s": 55829,
"text": "Python3"
},
{
"code": null,
"e": 55840,
"s": 55837,
"text": "C#"
},
{
"code": null,
"e": 55844,
"s": 55840,
"text": "PHP"
},
{
"code": null,
"e": 55855,
"s": 55844,
"text": "Javascript"
},
{
"code": "// C++ program to find triplets in a given// array whose sum is zero#include<bits/stdc++.h>using namespace std; // function to print triplets with 0 sumvoid findTriplets(int arr[], int n){ bool found = false; // sort array elements sort(arr, arr+n); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf(\"%d %d %d\\n\", x, arr[l], arr[r]); l++; r--; // found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << \" No Triplet Found\" << endl;} // Driven sourceint main(){ int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0;}",
"e": 57061,
"s": 55855,
"text": null
},
{
"code": "// Java program to find triplets in a given// array whose sum is zeroimport java.util.Arrays;import java.io.*; class GFG { // function to print triplets with 0 sumstatic void findTriplets(int arr[], int n){ boolean found = false; // sort array elements Arrays.sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero System.out.print(x + \" \"); System.out.print(arr[l]+ \" \"); System.out.println(arr[r]+ \" \"); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) System.out.println(\" No Triplet Found\");} // Driven source public static void main (String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); }//This code is contributed by Tushil.. }",
"e": 58420,
"s": 57061,
"text": null
},
{
"code": "# python program to find triplets in a given# array whose sum is zero # function to print triplets with 0 sumdef findTriplets(arr, n): found = False # sort array elements arr.sort() for i in range(0, n-1): # initialize left and right l = i + 1 r = n - 1 x = arr[i] while (l < r): if (x + arr[l] + arr[r] == 0): # print elements if it's sum is zero print(x, arr[l], arr[r]) l+=1 r-=1 found = True # If sum of three elements is less # than zero then increment in left elif (x + arr[l] + arr[r] < 0): l+=1 # if sum is greater than zero then # decrement in right side else: r-=1 if (found == False): print(\" No Triplet Found\") # Driven sourcearr = [0, -1, 2, -3, 1]n = len(arr)findTriplets(arr, n) # This code is contributed by Smitha Dinesh Semwal",
"e": 59446,
"s": 58420,
"text": null
},
{
"code": "// C# program to find triplets in a given// array whose sum is zerousing System; public class GFG{ // function to print triplets with 0 sumstatic void findTriplets(int []arr, int n){ bool found = false; // sort array elements Array.Sort(arr); for (int i=0; i<n-1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero Console.Write(x + \" \"); Console.Write(arr[l]+ \" \"); Console.WriteLine(arr[r]+ \" \"); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) Console.WriteLine(\" No Triplet Found\");} // Driven source static public void Main (){ int []arr = {0, -1, 2, -3, 1}; int n =arr.Length; findTriplets(arr, n); }//This code is contributed by akt_mit..}",
"e": 60765,
"s": 59446,
"text": null
},
{
"code": "<?php// PHP program to find// triplets in a given// array whose sum is zero // function to print// triplets with 0 sumfunction findTriplets($arr, $n){ $found = false; // sort array elements sort($arr); for ($i = 0; $i < $n - 1; $i++) { // initialize left // and right $l = $i + 1; $r = $n - 1; $x = $arr[$i]; while ($l < $r) { if ($x + $arr[$l] + $arr[$r] == 0) { // print elements if // it's sum is zero echo $x,\" \", $arr[$l], \" \", $arr[$r], \"\\n\"; $l++; $r--; $found = true; } // If sum of three elements // is less than zero then // increment in left else if ($x + $arr[$l] + $arr[$r] < 0) $l++; // if sum is greater than // zero then decrement // in right side else $r--; } } if ($found == false) echo \" No Triplet Found\" ,\"\\n\";} // Driver Code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n); // This code is contributed by ajit?>",
"e": 62021,
"s": 60765,
"text": null
},
{
"code": "<script> // Javascript program to find triplets in a given// array whose sum is zero // function to print triplets with 0 sumfunction findTriplets(arr, n){ let found = false; // sort array elements arr.sort((a, b) => a - b); for (let i=0; i<n-1; i++) { // initialize left and right let l = i + 1; let r = n - 1; let x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero document.write(x + \" \"); document.write(arr[l]+ \" \"); document.write(arr[r]+ \" \" + \"<br>\"); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) document.write(\" No Triplet Found\" + \"<br>\");} // Driven source let arr = [0, -1, 2, -3, 1]; let n = arr.length; findTriplets(arr, n); // This code is contributed by Mayank Tyagi </script>",
"e": 63277,
"s": 62021,
"text": null
},
{
"code": null,
"e": 63291,
"s": 63277,
"text": "-3 1 2\n-1 0 1"
},
{
"code": null,
"e": 63313,
"s": 63291,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 63407,
"s": 63313,
"text": "Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2)."
},
{
"code": null,
"e": 63495,
"s": 63407,
"text": "Auxiliary Space : O(1), no extra space is required, so the time complexity is constant."
},
{
"code": null,
"e": 63915,
"s": 63495,
"text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 63928,
"s": 63915,
"text": "nitin mittal"
},
{
"code": null,
"e": 63934,
"s": 63928,
"text": "jit_t"
},
{
"code": null,
"e": 63946,
"s": 63934,
"text": "shrikanth13"
},
{
"code": null,
"e": 63956,
"s": 63946,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 63968,
"s": 63956,
"text": "29AjayKumar"
},
{
"code": null,
"e": 63979,
"s": 63968,
"text": "andrew1234"
},
{
"code": null,
"e": 63990,
"s": 63979,
"text": "hasanbasri"
},
{
"code": null,
"e": 64004,
"s": 63990,
"text": "surbhityagi15"
},
{
"code": null,
"e": 64020,
"s": 64004,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 64034,
"s": 64020,
"text": "shivamkrishna"
},
{
"code": null,
"e": 64055,
"s": 64034,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 64071,
"s": 64055,
"text": "jaydeepradadiya"
},
{
"code": null,
"e": 64080,
"s": 64071,
"text": "famously"
},
{
"code": null,
"e": 64096,
"s": 64080,
"text": "vikeshkumar5329"
},
{
"code": null,
"e": 64104,
"s": 64096,
"text": "7rahult"
},
{
"code": null,
"e": 64119,
"s": 64104,
"text": "himanshu180599"
},
{
"code": null,
"e": 64133,
"s": 64119,
"text": "dragonuncaged"
},
{
"code": null,
"e": 64142,
"s": 64133,
"text": "Facebook"
},
{
"code": null,
"e": 64149,
"s": 64142,
"text": "Google"
},
{
"code": null,
"e": 64171,
"s": 64149,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 64178,
"s": 64171,
"text": "Arrays"
},
{
"code": null,
"e": 64183,
"s": 64178,
"text": "Hash"
},
{
"code": null,
"e": 64193,
"s": 64183,
"text": "Searching"
},
{
"code": null,
"e": 64201,
"s": 64193,
"text": "Sorting"
},
{
"code": null,
"e": 64208,
"s": 64201,
"text": "Google"
},
{
"code": null,
"e": 64217,
"s": 64208,
"text": "Facebook"
},
{
"code": null,
"e": 64239,
"s": 64217,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 64246,
"s": 64239,
"text": "Arrays"
},
{
"code": null,
"e": 64256,
"s": 64246,
"text": "Searching"
},
{
"code": null,
"e": 64261,
"s": 64256,
"text": "Hash"
},
{
"code": null,
"e": 64269,
"s": 64261,
"text": "Sorting"
},
{
"code": null,
"e": 64367,
"s": 64269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 64376,
"s": 64367,
"text": "Comments"
},
{
"code": null,
"e": 64389,
"s": 64376,
"text": "Old Comments"
},
{
"code": null,
"e": 64404,
"s": 64389,
"text": "Arrays in Java"
},
{
"code": null,
"e": 64420,
"s": 64404,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 64447,
"s": 64420,
"text": "Program for array rotation"
},
{
"code": null,
"e": 64495,
"s": 64447,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 64539,
"s": 64495,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 64624,
"s": 64539,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 64660,
"s": 64624,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 64691,
"s": 64660,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 64718,
"s": 64691,
"text": "Count pairs with given sum"
}
] |
DSA using Java - Arrays
|
Array is a container which can hold fix number of items and these items should be of same type. Most of the datastructure make use of array to implement their algorithms. Following are important terms to understand the concepts of Array
Element − Each item stored in an array is called an element.
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index which is used to identify the element.
Index − Each location of an element in an array has a numerical index which is used to identify the element.
As per above shown illustration, following are the important points to be considered.
Index starts with 0.
Index starts with 0.
Array length is 8 which means it can store 8 elements.
Array length is 8 which means it can store 8 elements.
Each element can be accessed via its index. For example, we can fetch element at index 6 as 9.
Each element can be accessed via its index. For example, we can fetch element at index 6 as 9.
Following are the basic operations supported by an array.
Insertion − add an element at given index.
Insertion − add an element at given index.
Deletion − delete an element at given index.
Deletion − delete an element at given index.
Search − search an element using given index or by value.
Search − search an element using given index or by value.
Update − update an element at given index.
Update − update an element at given index.
In java, when an array is initialized with size, then it assigns defaults values to its elements in following order.
package com.tutorialspoint.array;
public class ArrayDemo {
public static void main(String[] args){
// Declare an array
int intArray[];
// Initialize an array of 8 int
// set aside memory of 8 int
intArray = new int[8];
System.out.println("Array before adding data.");
// Display elements of an array.
display(intArray);
// Operation : Insertion
// Add elements in the array
for(int i = 0; i< intArray.length; i++)
{
// place value of i at index i.
System.out.println("Adding "+i+" at index "+i);
intArray[i] = i;
}
System.out.println();
System.out.println("Array after adding data.");
display(intArray);
// Operation : Insertion
// Element at any location can be updated directly
int index = 5;
intArray[index] = 10;
System.out.println("Array after updating element at index " + index);
display(intArray);
// Operation : Search using index
// Search an element using index.
System.out.println("Data at index " + index + ": "+ intArray[index]);
// Operation : Search using value
// Search an element using value.
int value = 4;
for(int i = 0; i< intArray.length; i++)
{
if(intArray[i] == value ){
System.out.println(value + " Found at index "+i);
break;
}
}
System.out.println("Data at index " + index + ": "+ intArray[index]);
}
private static void display(int[] intArray){
System.out.print("Array : [");
for(int i = 0; i< intArray.length; i++)
{
// display value of element at index i.
System.out.print(" "+intArray[i]);
}
System.out.println(" ]");
System.out.println();
}
}
If we compile and run the above program then it would produce following result −
Array before adding data.
Array : [ 0 0 0 0 0 0 0 0 ]
Adding 0 at index 0
Adding 1 at index 1
Adding 2 at index 2
Adding 3 at index 3
Adding 4 at index 4
Adding 5 at index 5
Adding 6 at index 6
Adding 7 at index 7
Array after adding data.
Array : [ 0 1 2 3 4 5 6 7 ]
Array after updating element at index 5
Array : [ 0 1 2 3 4 10 6 7 ]
Data at index 5: 10
4 Found at index: 4
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2405,
"s": 2168,
"text": "Array is a container which can hold fix number of items and these items should be of same type. Most of the datastructure make use of array to implement their algorithms. Following are important terms to understand the concepts of Array"
},
{
"code": null,
"e": 2466,
"s": 2405,
"text": "Element − Each item stored in an array is called an element."
},
{
"code": null,
"e": 2527,
"s": 2466,
"text": "Element − Each item stored in an array is called an element."
},
{
"code": null,
"e": 2636,
"s": 2527,
"text": "Index − Each location of an element in an array has a numerical index which is used to identify the element."
},
{
"code": null,
"e": 2745,
"s": 2636,
"text": "Index − Each location of an element in an array has a numerical index which is used to identify the element."
},
{
"code": null,
"e": 2831,
"s": 2745,
"text": "As per above shown illustration, following are the important points to be considered."
},
{
"code": null,
"e": 2852,
"s": 2831,
"text": "Index starts with 0."
},
{
"code": null,
"e": 2873,
"s": 2852,
"text": "Index starts with 0."
},
{
"code": null,
"e": 2928,
"s": 2873,
"text": "Array length is 8 which means it can store 8 elements."
},
{
"code": null,
"e": 2983,
"s": 2928,
"text": "Array length is 8 which means it can store 8 elements."
},
{
"code": null,
"e": 3078,
"s": 2983,
"text": "Each element can be accessed via its index. For example, we can fetch element at index 6 as 9."
},
{
"code": null,
"e": 3173,
"s": 3078,
"text": "Each element can be accessed via its index. For example, we can fetch element at index 6 as 9."
},
{
"code": null,
"e": 3231,
"s": 3173,
"text": "Following are the basic operations supported by an array."
},
{
"code": null,
"e": 3274,
"s": 3231,
"text": "Insertion − add an element at given index."
},
{
"code": null,
"e": 3317,
"s": 3274,
"text": "Insertion − add an element at given index."
},
{
"code": null,
"e": 3362,
"s": 3317,
"text": "Deletion − delete an element at given index."
},
{
"code": null,
"e": 3407,
"s": 3362,
"text": "Deletion − delete an element at given index."
},
{
"code": null,
"e": 3465,
"s": 3407,
"text": "Search − search an element using given index or by value."
},
{
"code": null,
"e": 3523,
"s": 3465,
"text": "Search − search an element using given index or by value."
},
{
"code": null,
"e": 3566,
"s": 3523,
"text": "Update − update an element at given index."
},
{
"code": null,
"e": 3609,
"s": 3566,
"text": "Update − update an element at given index."
},
{
"code": null,
"e": 3726,
"s": 3609,
"text": "In java, when an array is initialized with size, then it assigns defaults values to its elements in following order."
},
{
"code": null,
"e": 5599,
"s": 3726,
"text": "package com.tutorialspoint.array;\n\npublic class ArrayDemo {\n public static void main(String[] args){\n \n // Declare an array \n int intArray[];\n\t \n // Initialize an array of 8 int\n // set aside memory of 8 int \n intArray = new int[8];\n\n System.out.println(\"Array before adding data.\");\n\n // Display elements of an array.\n display(intArray); \n \n // Operation : Insertion \n // Add elements in the array \n for(int i = 0; i< intArray.length; i++)\n {\n // place value of i at index i. \n System.out.println(\"Adding \"+i+\" at index \"+i);\n intArray[i] = i;\n } \n System.out.println();\n\n System.out.println(\"Array after adding data.\");\n display(intArray);\n\n // Operation : Insertion \n // Element at any location can be updated directly \n int index = 5;\n intArray[index] = 10;\n \n System.out.println(\"Array after updating element at index \" + index);\n display(intArray);\n\n // Operation : Search using index\n // Search an element using index.\n System.out.println(\"Data at index \" + index + \": \"+ intArray[index]);\n\t \n // Operation : Search using value\n // Search an element using value.\n int value = 4;\n for(int i = 0; i< intArray.length; i++)\n {\n if(intArray[i] == value ){\n System.out.println(value + \" Found at index \"+i);\n break;\n }\n } \n System.out.println(\"Data at index \" + index + \": \"+ intArray[index]);\n }\n\n private static void display(int[] intArray){\n System.out.print(\"Array : [\");\n for(int i = 0; i< intArray.length; i++)\n {\n // display value of element at index i. \n System.out.print(\" \"+intArray[i]);\n }\n System.out.println(\" ]\");\n System.out.println();\n }\n}"
},
{
"code": null,
"e": 5680,
"s": 5599,
"text": "If we compile and run the above program then it would produce following result −"
},
{
"code": null,
"e": 6061,
"s": 5680,
"text": "Array before adding data.\nArray : [ 0 0 0 0 0 0 0 0 ]\n\nAdding 0 at index 0\nAdding 1 at index 1\nAdding 2 at index 2\nAdding 3 at index 3\nAdding 4 at index 4\nAdding 5 at index 5\nAdding 6 at index 6\nAdding 7 at index 7\n\nArray after adding data.\nArray : [ 0 1 2 3 4 5 6 7 ]\n\nArray after updating element at index 5\nArray : [ 0 1 2 3 4 10 6 7 ]\n\nData at index 5: 10\n4 Found at index: 4\n"
},
{
"code": null,
"e": 6068,
"s": 6061,
"text": " Print"
},
{
"code": null,
"e": 6079,
"s": 6068,
"text": " Add Notes"
}
] |
How to set the layout weight of a TextView programmatically in Android using Kotlin?
|
This example demonstrates how to set the layout weight of a TextView programmatically in Android.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="expand"
android:text="Hello World"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
fun expand(view: View) {
val height = RelativeLayout.LayoutParams.WRAP_CONTENT
val width = 200
val layoutParams = RelativeLayout.LayoutParams(width, height)
val button: Button = findViewById(R.id.button)
button.layoutParams = layoutParams
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "This example demonstrates how to set the layout weight of a TextView programmatically in Android."
},
{
"code": null,
"e": 1288,
"s": 1160,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1353,
"s": 1288,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2293,
"s": 1353,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n<Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"expand\"\n android:text=\"Hello World\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2348,
"s": 2293,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3007,
"s": 2348,
"text": "import android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.RelativeLayout\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun expand(view: View) {\n val height = RelativeLayout.LayoutParams.WRAP_CONTENT\n val width = 200\n val layoutParams = RelativeLayout.LayoutParams(width, height)\n val button: Button = findViewById(R.id.button)\n button.layoutParams = layoutParams\n }\n}"
},
{
"code": null,
"e": 3062,
"s": 3007,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3733,
"s": 3062,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4081,
"s": 3733,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 4122,
"s": 4081,
"text": "Click here to download the project code."
}
] |
What is the meaning of ‘empty set’ in MySQL result set?
|
If there is ‘empty set’ in the result set of MySQL query then it means that MySQL is returning no rows and no error also in the query. It can be understood with the help of the following example −
mysql> Select * from Student_info WHERE Name = 'ABCD';
Empty set (0.00 sec)
We can see the empty set and execution time as output. It means that the query is correct but the MySQL table is not having the name ‘ABCD’.
|
[
{
"code": null,
"e": 1259,
"s": 1062,
"text": "If there is ‘empty set’ in the result set of MySQL query then it means that MySQL is returning no rows and no error also in the query. It can be understood with the help of the following example −"
},
{
"code": null,
"e": 1335,
"s": 1259,
"text": "mysql> Select * from Student_info WHERE Name = 'ABCD';\nEmpty set (0.00 sec)"
},
{
"code": null,
"e": 1476,
"s": 1335,
"text": "We can see the empty set and execution time as output. It means that the query is correct but the MySQL table is not having the name ‘ABCD’."
}
] |
PyQt5 - QDockWidget - GeeksforGeeks
|
11 Aug, 2021
QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Dock windows can be moved inside their current area, moved into new areas and floated (e.g., undocked) by the end-user. The QDockWidget API allows the programmer to restrict the dock widgets ability to move, float and close, as well as the areas in which they can be placed.Below is how the dock widget looks like
When we open this widget it looks like this
Example : We will create a dock widget and add push button to it and when push button will get pressed a message will get printed on the labelBelow is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget("GeeksforGeeks", self) # push button push = QPushButton("Press", self) # setting widget to the dock dock.setWidget(push) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # adding action to the push button push.clicked.connect(lambda: label.setText("Dock Widget's Push button pressed")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
singghakshay
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
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
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24792,
"s": 24764,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 25332,
"s": 24792,
"text": "QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). Dock windows can be moved inside their current area, moved into new areas and floated (e.g., undocked) by the end-user. The QDockWidget API allows the programmer to restrict the dock widgets ability to move, float and close, as well as the areas in which they can be placed.Below is how the dock widget looks like "
},
{
"code": null,
"e": 25378,
"s": 25332,
"text": "When we open this widget it looks like this "
},
{
"code": null,
"e": 25550,
"s": 25378,
"text": "Example : We will create a dock widget and add push button to it and when push button will get pressed a message will get printed on the labelBelow is the implementation "
},
{
"code": null,
"e": 25558,
"s": 25550,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(\"GeeksforGeeks\", self) # push button push = QPushButton(\"Press\", self) # setting widget to the dock dock.setWidget(push) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # adding action to the push button push.clicked.connect(lambda: label.setText(\"Dock Widget's Push button pressed\")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26862,
"s": 25558,
"text": null
},
{
"code": null,
"e": 26873,
"s": 26862,
"text": "Output : "
},
{
"code": null,
"e": 26888,
"s": 26875,
"text": "singghakshay"
},
{
"code": null,
"e": 26912,
"s": 26888,
"text": "Python PyQt-QDockWidget"
},
{
"code": null,
"e": 26923,
"s": 26912,
"text": "Python-gui"
},
{
"code": null,
"e": 26935,
"s": 26923,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26942,
"s": 26935,
"text": "Python"
},
{
"code": null,
"e": 27040,
"s": 26942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27049,
"s": 27040,
"text": "Comments"
},
{
"code": null,
"e": 27062,
"s": 27049,
"text": "Old Comments"
},
{
"code": null,
"e": 27080,
"s": 27062,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27112,
"s": 27080,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27147,
"s": 27112,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27169,
"s": 27147,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27199,
"s": 27169,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27241,
"s": 27199,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27284,
"s": 27241,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27321,
"s": 27284,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27365,
"s": 27321,
"text": "Reading and Writing to text files in Python"
}
] |
This will make you understand how hard Data Science really is | by Thijs Essens | Towards Data Science
|
tl;dr: it’s very hard
Every day, people try to live up to computer science savants and try to break into the field of Data Science.
How hard is it? What does it take? Where do I start?
In this blog I’ll summarize the 3 hardest challenges I faced doing my first Data Science project in this Kaggle Notebook:
You know nothingData preparation is critical and time-consumingInterpret your results
You know nothing
Data preparation is critical and time-consuming
Interpret your results
Opinions are my own.
Before getting into any details, there is quite an essential part that people seem to gloss over during explanations, or they’re simply part of their small snippet codes. In order for you to use any of the advanced libraries, you are going to have to import them into your workspace. It is best to collect them at the top of your workbook.
My example below:
For my first Data Science project, I created a short blog on starting an Airbnb in Amsterdam. I only used basic data analysis methods and regression models.
Regression models are probably the most basic parts of data science. A typical linear regression function will look like this:
This will return several outputs that you will then use to evaluate your model performance.
There are more than 40 techniques used by data scientists. This means I only used 2.5% of all the models out there.
I’ll be generous. Given my statistics course in University 8 years ago, going into this project I knew about 10% of that regression model already. That means I knew 0.25% of the entire body of knowledge that I know is out there. Then add a very large amount of things I don’t know I don’t know.
My knowledge universe in Data Science looks something like this:
Like that isn’t bad enough, you will find articles like these, exactly describing all of your shortcomings.
This current project took me about 4 weeks and let’s say that’s a pretty average rate of learning new data science models. It will take me about 4 / 0.25% = 800 weeks to learn all the models I have heard of so far and probably add another 5 times that time to learn (probably not even close to) everything in the data science field.
Between 15 and 75 years of learning ahead.
Me after my learning:
I’ve worked with data for over 5 years at Google.
Too bad all my previous experience is in SQL and Data Scientists are big fans of Pandas. They’re just such animal lovers.
The challenge here is two-fold: 1) Knowing what to do, 2) Knowing how to do them.
Even with the help described below, the data preparation part takes about 80% of your time or more.
The ways to manipulate your data to be ready for ingestion in your models are endless. It goes into the deep underbelly of Statistics and you will need to understand this thoroughly if you want to be a great Data Scientist.
Be prepared to run through these steps many times. I’ll give a couple of examples that have worked for me for each step.
Clean data quality issues
Your data sample size permitting you should probably get rid of any NaN values in your data. They can not be ingested by the regression model. To find the ratio of NaN values per column, use this:
np.sum(df.isnull())/df.shape[0]
To drop all rows with NaN values use this:
df.dropna()
Another data quality problem I ran into was having True and False data as strings instead of a Boolean data type. I solved it using this distutils.util.strtobool function:
Please don’t assume I actually knew how to use Lambda functions before starting this project.
It took me a lot of reading to understand them a little bit. I really liked this article on “What are lambda functions in python and why you should start using them right now”.
Finally, my price data was a string with $ signs and commas. I couldn’t find an elegant way to code the solution, so I botched my way into this:
Cut outliers
Check if there are any outliers in the first place, a boxplot can be very helpful:
sns.boxplot(x=df[‘price’])
Get fancy and use a modified z value (answer from StackOverflow) to cut your outliers:
Or enforce hardcoded conditions to your liking, like so:
df = df[df['price'] < 300]
Normalization & combine variables
Not to be confused with a normal distribution.
Normalization is the process of scaling individual columns the same order of magnitude, e.g. 0 to 1.
Therefore, you have to only consider this move if you want to combine certain variables or you know it affects your model otherwise.
There is a preprocessing library available as part of Sklearn. It can be instrumental in delivering on some of these data preparation aspects.
I found it hard to normalize certain columns and then neatly put them back into my DataFrame. Therefore I’ll share my own full example of combining beds/bedrooms/accommodates variables below:
Create normal distribution for your variables
It’s useful to look at all the data input variables individually and decide how to transform them to better fit a normal distribution.
I’ve used this for loop:
Once you know which you want to transform, consider using a box cox transformation like this:
Note how it is important to also return the list of lambdas that were used by the box cox transformation. You’ll need those to inverse your coefficients when you are interpreting the results.
Standardization
The StandardScaler assumes your data is already normally distributed (see box cox transformation example above) within each feature and will scale them such that the distribution is now centered around 0, with a standard deviation of 1.
My full example below:
Create dummy variables
Your categorical variables can contain some of the most valuable information in your dataset. For a machine to understand them, you need to translate every single unique value to one column with 0 or 1.
1 if it is that value, 0 if it isn’t.
There are several ways of doing this. I’ve used the following method:
Multicollinearity
You can check if some of your input variables have a correlation between themselves before you put them in your model.
You can check multicollinearity like my example below and try to take out some variables you don’t believe add any extra value.
This will hopefully prevent some Eigenvalue and Eigenvector issues.
Getting to the bottom of eigenvalue and eigenvector might cost you another 15 years. Proceed with caution.
You could go down the rabbit hole of dimensionality reduction through Principal Components Analysis (which is more commonly applied to image recognition).
Additionally, this article on Feature Selection was very eye-opening.
I frankly didn’t have time for all of these advanced methods during this project, but I want to understand all of the above better before applying data science to my work projects.
As a Dutch person, I am very proud of the origins of Python. It’s an incredibly powerful and accessible language.
The basics should take around 6–8 weeks on average according to this post.
Therefore, I haven’t even learned to basics yet with my 4 weeks of experience. On top of that weakness, I’m trying to add a couple of different specialized library packages on top, like Seaborn, Sklearn, and Pandas.
“They are foundational, regardless of what project you do.“
Thank you for all the Stackoverflow and self-publishing engineers out there, you saved many hours of my life.
In particular, Jim is my new best friend.
Copy code and learn from all those articles, they are your best hope of working code at the end of the day.
Let me summarize the three most useful articles on the above three libraries:
Seaborn: How to use Python Seaborn for Exploratory Data AnalysisPandas: A Quick Introduction to the “Pandas” Python LibrarySklearn: A Brief Tour of Scikit-learn (Sklearn)
Seaborn: How to use Python Seaborn for Exploratory Data Analysis
Pandas: A Quick Introduction to the “Pandas” Python Library
Sklearn: A Brief Tour of Scikit-learn (Sklearn)
Spend some time with your new friends:
In the previous step, you have most likely manipulated your data to an extent that it becomes unrecognizable for interpretation.
As per my project article, the listing price was boxcox transformed and 1 dollar in the output did not resemble a real dollar.
The easy way out for me was to take a measure of the relative strength of the relation with listing price, instead of commenting on the actual value of the coefficients. You can see the results in my visuals.
The more proper solution is to inverse your box cox and other transformations back to normal, e.g.:
Inv_BoxCox for the boxcox transformation
from scipy.special import boxcox, inv_boxcox>>> y = boxcox([1, 4, 10], 2.5)>>> inv_boxcox(y, 2.5)
Hopefully, you remembered to save that lambda_list in my box cox transformation example. Because the 2.5 is your lambda value to inverse the transformation.
Inverse Transform for StandardScaler:
Finally, you need to get extremely well versed in your evaluation metrics.
There are many evaluation metrics out there, like RMSE and coefficients / p-values.
Most of the machine learning models come with evaluation metrics. The same is true for LinearRegression in Sklearn: metrics.
In my example, I’ve focused on R-squared and RMSE:
One thing that made looking at RMSE very valuable was equaling the playing field between models.
I could quickly tell that throwing automated machine learning at the problem didn’t improve my model very much. H2O AutoML was reasonably easy to implement:
This thing was wild! It runs through a number (max=20 for my example) of different models and returns a leaderboard of models.
However, as said, this really didn’t improve my RMSE by much.
“It still all depends on the richness of your input”
Please also be very careful and solicit the help of more knowledgable people where available.
Use your resources and call a friend:
In this article, I tried to make you understand how hard Data Science really is.
We took a look at the amount of learning I still need to do. Only about 15 to 75 years...Then we looked at data preparation and figured out it’s a huge headache and will take about 80% of your timeFinally, we found out that interpreting your results is probably best left to a more knowledgable person. Call a friend!
We took a look at the amount of learning I still need to do. Only about 15 to 75 years...
Then we looked at data preparation and figured out it’s a huge headache and will take about 80% of your time
Finally, we found out that interpreting your results is probably best left to a more knowledgable person. Call a friend!
Staying true to the growth mindset, let this not deter you.
You are just not a Data Scientist YET.
Start your first project!
|
[
{
"code": null,
"e": 194,
"s": 172,
"text": "tl;dr: it’s very hard"
},
{
"code": null,
"e": 304,
"s": 194,
"text": "Every day, people try to live up to computer science savants and try to break into the field of Data Science."
},
{
"code": null,
"e": 357,
"s": 304,
"text": "How hard is it? What does it take? Where do I start?"
},
{
"code": null,
"e": 479,
"s": 357,
"text": "In this blog I’ll summarize the 3 hardest challenges I faced doing my first Data Science project in this Kaggle Notebook:"
},
{
"code": null,
"e": 565,
"s": 479,
"text": "You know nothingData preparation is critical and time-consumingInterpret your results"
},
{
"code": null,
"e": 582,
"s": 565,
"text": "You know nothing"
},
{
"code": null,
"e": 630,
"s": 582,
"text": "Data preparation is critical and time-consuming"
},
{
"code": null,
"e": 653,
"s": 630,
"text": "Interpret your results"
},
{
"code": null,
"e": 674,
"s": 653,
"text": "Opinions are my own."
},
{
"code": null,
"e": 1014,
"s": 674,
"text": "Before getting into any details, there is quite an essential part that people seem to gloss over during explanations, or they’re simply part of their small snippet codes. In order for you to use any of the advanced libraries, you are going to have to import them into your workspace. It is best to collect them at the top of your workbook."
},
{
"code": null,
"e": 1032,
"s": 1014,
"text": "My example below:"
},
{
"code": null,
"e": 1189,
"s": 1032,
"text": "For my first Data Science project, I created a short blog on starting an Airbnb in Amsterdam. I only used basic data analysis methods and regression models."
},
{
"code": null,
"e": 1316,
"s": 1189,
"text": "Regression models are probably the most basic parts of data science. A typical linear regression function will look like this:"
},
{
"code": null,
"e": 1408,
"s": 1316,
"text": "This will return several outputs that you will then use to evaluate your model performance."
},
{
"code": null,
"e": 1524,
"s": 1408,
"text": "There are more than 40 techniques used by data scientists. This means I only used 2.5% of all the models out there."
},
{
"code": null,
"e": 1819,
"s": 1524,
"text": "I’ll be generous. Given my statistics course in University 8 years ago, going into this project I knew about 10% of that regression model already. That means I knew 0.25% of the entire body of knowledge that I know is out there. Then add a very large amount of things I don’t know I don’t know."
},
{
"code": null,
"e": 1884,
"s": 1819,
"text": "My knowledge universe in Data Science looks something like this:"
},
{
"code": null,
"e": 1992,
"s": 1884,
"text": "Like that isn’t bad enough, you will find articles like these, exactly describing all of your shortcomings."
},
{
"code": null,
"e": 2325,
"s": 1992,
"text": "This current project took me about 4 weeks and let’s say that’s a pretty average rate of learning new data science models. It will take me about 4 / 0.25% = 800 weeks to learn all the models I have heard of so far and probably add another 5 times that time to learn (probably not even close to) everything in the data science field."
},
{
"code": null,
"e": 2368,
"s": 2325,
"text": "Between 15 and 75 years of learning ahead."
},
{
"code": null,
"e": 2390,
"s": 2368,
"text": "Me after my learning:"
},
{
"code": null,
"e": 2440,
"s": 2390,
"text": "I’ve worked with data for over 5 years at Google."
},
{
"code": null,
"e": 2562,
"s": 2440,
"text": "Too bad all my previous experience is in SQL and Data Scientists are big fans of Pandas. They’re just such animal lovers."
},
{
"code": null,
"e": 2644,
"s": 2562,
"text": "The challenge here is two-fold: 1) Knowing what to do, 2) Knowing how to do them."
},
{
"code": null,
"e": 2744,
"s": 2644,
"text": "Even with the help described below, the data preparation part takes about 80% of your time or more."
},
{
"code": null,
"e": 2968,
"s": 2744,
"text": "The ways to manipulate your data to be ready for ingestion in your models are endless. It goes into the deep underbelly of Statistics and you will need to understand this thoroughly if you want to be a great Data Scientist."
},
{
"code": null,
"e": 3089,
"s": 2968,
"text": "Be prepared to run through these steps many times. I’ll give a couple of examples that have worked for me for each step."
},
{
"code": null,
"e": 3115,
"s": 3089,
"text": "Clean data quality issues"
},
{
"code": null,
"e": 3312,
"s": 3115,
"text": "Your data sample size permitting you should probably get rid of any NaN values in your data. They can not be ingested by the regression model. To find the ratio of NaN values per column, use this:"
},
{
"code": null,
"e": 3344,
"s": 3312,
"text": "np.sum(df.isnull())/df.shape[0]"
},
{
"code": null,
"e": 3387,
"s": 3344,
"text": "To drop all rows with NaN values use this:"
},
{
"code": null,
"e": 3399,
"s": 3387,
"text": "df.dropna()"
},
{
"code": null,
"e": 3571,
"s": 3399,
"text": "Another data quality problem I ran into was having True and False data as strings instead of a Boolean data type. I solved it using this distutils.util.strtobool function:"
},
{
"code": null,
"e": 3665,
"s": 3571,
"text": "Please don’t assume I actually knew how to use Lambda functions before starting this project."
},
{
"code": null,
"e": 3842,
"s": 3665,
"text": "It took me a lot of reading to understand them a little bit. I really liked this article on “What are lambda functions in python and why you should start using them right now”."
},
{
"code": null,
"e": 3987,
"s": 3842,
"text": "Finally, my price data was a string with $ signs and commas. I couldn’t find an elegant way to code the solution, so I botched my way into this:"
},
{
"code": null,
"e": 4000,
"s": 3987,
"text": "Cut outliers"
},
{
"code": null,
"e": 4083,
"s": 4000,
"text": "Check if there are any outliers in the first place, a boxplot can be very helpful:"
},
{
"code": null,
"e": 4110,
"s": 4083,
"text": "sns.boxplot(x=df[‘price’])"
},
{
"code": null,
"e": 4197,
"s": 4110,
"text": "Get fancy and use a modified z value (answer from StackOverflow) to cut your outliers:"
},
{
"code": null,
"e": 4254,
"s": 4197,
"text": "Or enforce hardcoded conditions to your liking, like so:"
},
{
"code": null,
"e": 4281,
"s": 4254,
"text": "df = df[df['price'] < 300]"
},
{
"code": null,
"e": 4315,
"s": 4281,
"text": "Normalization & combine variables"
},
{
"code": null,
"e": 4362,
"s": 4315,
"text": "Not to be confused with a normal distribution."
},
{
"code": null,
"e": 4463,
"s": 4362,
"text": "Normalization is the process of scaling individual columns the same order of magnitude, e.g. 0 to 1."
},
{
"code": null,
"e": 4596,
"s": 4463,
"text": "Therefore, you have to only consider this move if you want to combine certain variables or you know it affects your model otherwise."
},
{
"code": null,
"e": 4739,
"s": 4596,
"text": "There is a preprocessing library available as part of Sklearn. It can be instrumental in delivering on some of these data preparation aspects."
},
{
"code": null,
"e": 4931,
"s": 4739,
"text": "I found it hard to normalize certain columns and then neatly put them back into my DataFrame. Therefore I’ll share my own full example of combining beds/bedrooms/accommodates variables below:"
},
{
"code": null,
"e": 4977,
"s": 4931,
"text": "Create normal distribution for your variables"
},
{
"code": null,
"e": 5112,
"s": 4977,
"text": "It’s useful to look at all the data input variables individually and decide how to transform them to better fit a normal distribution."
},
{
"code": null,
"e": 5137,
"s": 5112,
"text": "I’ve used this for loop:"
},
{
"code": null,
"e": 5231,
"s": 5137,
"text": "Once you know which you want to transform, consider using a box cox transformation like this:"
},
{
"code": null,
"e": 5423,
"s": 5231,
"text": "Note how it is important to also return the list of lambdas that were used by the box cox transformation. You’ll need those to inverse your coefficients when you are interpreting the results."
},
{
"code": null,
"e": 5439,
"s": 5423,
"text": "Standardization"
},
{
"code": null,
"e": 5676,
"s": 5439,
"text": "The StandardScaler assumes your data is already normally distributed (see box cox transformation example above) within each feature and will scale them such that the distribution is now centered around 0, with a standard deviation of 1."
},
{
"code": null,
"e": 5699,
"s": 5676,
"text": "My full example below:"
},
{
"code": null,
"e": 5722,
"s": 5699,
"text": "Create dummy variables"
},
{
"code": null,
"e": 5925,
"s": 5722,
"text": "Your categorical variables can contain some of the most valuable information in your dataset. For a machine to understand them, you need to translate every single unique value to one column with 0 or 1."
},
{
"code": null,
"e": 5963,
"s": 5925,
"text": "1 if it is that value, 0 if it isn’t."
},
{
"code": null,
"e": 6033,
"s": 5963,
"text": "There are several ways of doing this. I’ve used the following method:"
},
{
"code": null,
"e": 6051,
"s": 6033,
"text": "Multicollinearity"
},
{
"code": null,
"e": 6170,
"s": 6051,
"text": "You can check if some of your input variables have a correlation between themselves before you put them in your model."
},
{
"code": null,
"e": 6298,
"s": 6170,
"text": "You can check multicollinearity like my example below and try to take out some variables you don’t believe add any extra value."
},
{
"code": null,
"e": 6366,
"s": 6298,
"text": "This will hopefully prevent some Eigenvalue and Eigenvector issues."
},
{
"code": null,
"e": 6473,
"s": 6366,
"text": "Getting to the bottom of eigenvalue and eigenvector might cost you another 15 years. Proceed with caution."
},
{
"code": null,
"e": 6628,
"s": 6473,
"text": "You could go down the rabbit hole of dimensionality reduction through Principal Components Analysis (which is more commonly applied to image recognition)."
},
{
"code": null,
"e": 6698,
"s": 6628,
"text": "Additionally, this article on Feature Selection was very eye-opening."
},
{
"code": null,
"e": 6879,
"s": 6698,
"text": "I frankly didn’t have time for all of these advanced methods during this project, but I want to understand all of the above better before applying data science to my work projects."
},
{
"code": null,
"e": 6993,
"s": 6879,
"text": "As a Dutch person, I am very proud of the origins of Python. It’s an incredibly powerful and accessible language."
},
{
"code": null,
"e": 7068,
"s": 6993,
"text": "The basics should take around 6–8 weeks on average according to this post."
},
{
"code": null,
"e": 7284,
"s": 7068,
"text": "Therefore, I haven’t even learned to basics yet with my 4 weeks of experience. On top of that weakness, I’m trying to add a couple of different specialized library packages on top, like Seaborn, Sklearn, and Pandas."
},
{
"code": null,
"e": 7344,
"s": 7284,
"text": "“They are foundational, regardless of what project you do.“"
},
{
"code": null,
"e": 7454,
"s": 7344,
"text": "Thank you for all the Stackoverflow and self-publishing engineers out there, you saved many hours of my life."
},
{
"code": null,
"e": 7496,
"s": 7454,
"text": "In particular, Jim is my new best friend."
},
{
"code": null,
"e": 7604,
"s": 7496,
"text": "Copy code and learn from all those articles, they are your best hope of working code at the end of the day."
},
{
"code": null,
"e": 7682,
"s": 7604,
"text": "Let me summarize the three most useful articles on the above three libraries:"
},
{
"code": null,
"e": 7853,
"s": 7682,
"text": "Seaborn: How to use Python Seaborn for Exploratory Data AnalysisPandas: A Quick Introduction to the “Pandas” Python LibrarySklearn: A Brief Tour of Scikit-learn (Sklearn)"
},
{
"code": null,
"e": 7918,
"s": 7853,
"text": "Seaborn: How to use Python Seaborn for Exploratory Data Analysis"
},
{
"code": null,
"e": 7978,
"s": 7918,
"text": "Pandas: A Quick Introduction to the “Pandas” Python Library"
},
{
"code": null,
"e": 8026,
"s": 7978,
"text": "Sklearn: A Brief Tour of Scikit-learn (Sklearn)"
},
{
"code": null,
"e": 8065,
"s": 8026,
"text": "Spend some time with your new friends:"
},
{
"code": null,
"e": 8194,
"s": 8065,
"text": "In the previous step, you have most likely manipulated your data to an extent that it becomes unrecognizable for interpretation."
},
{
"code": null,
"e": 8321,
"s": 8194,
"text": "As per my project article, the listing price was boxcox transformed and 1 dollar in the output did not resemble a real dollar."
},
{
"code": null,
"e": 8530,
"s": 8321,
"text": "The easy way out for me was to take a measure of the relative strength of the relation with listing price, instead of commenting on the actual value of the coefficients. You can see the results in my visuals."
},
{
"code": null,
"e": 8630,
"s": 8530,
"text": "The more proper solution is to inverse your box cox and other transformations back to normal, e.g.:"
},
{
"code": null,
"e": 8671,
"s": 8630,
"text": "Inv_BoxCox for the boxcox transformation"
},
{
"code": null,
"e": 8769,
"s": 8671,
"text": "from scipy.special import boxcox, inv_boxcox>>> y = boxcox([1, 4, 10], 2.5)>>> inv_boxcox(y, 2.5)"
},
{
"code": null,
"e": 8926,
"s": 8769,
"text": "Hopefully, you remembered to save that lambda_list in my box cox transformation example. Because the 2.5 is your lambda value to inverse the transformation."
},
{
"code": null,
"e": 8964,
"s": 8926,
"text": "Inverse Transform for StandardScaler:"
},
{
"code": null,
"e": 9039,
"s": 8964,
"text": "Finally, you need to get extremely well versed in your evaluation metrics."
},
{
"code": null,
"e": 9123,
"s": 9039,
"text": "There are many evaluation metrics out there, like RMSE and coefficients / p-values."
},
{
"code": null,
"e": 9248,
"s": 9123,
"text": "Most of the machine learning models come with evaluation metrics. The same is true for LinearRegression in Sklearn: metrics."
},
{
"code": null,
"e": 9299,
"s": 9248,
"text": "In my example, I’ve focused on R-squared and RMSE:"
},
{
"code": null,
"e": 9396,
"s": 9299,
"text": "One thing that made looking at RMSE very valuable was equaling the playing field between models."
},
{
"code": null,
"e": 9553,
"s": 9396,
"text": "I could quickly tell that throwing automated machine learning at the problem didn’t improve my model very much. H2O AutoML was reasonably easy to implement:"
},
{
"code": null,
"e": 9680,
"s": 9553,
"text": "This thing was wild! It runs through a number (max=20 for my example) of different models and returns a leaderboard of models."
},
{
"code": null,
"e": 9742,
"s": 9680,
"text": "However, as said, this really didn’t improve my RMSE by much."
},
{
"code": null,
"e": 9795,
"s": 9742,
"text": "“It still all depends on the richness of your input”"
},
{
"code": null,
"e": 9889,
"s": 9795,
"text": "Please also be very careful and solicit the help of more knowledgable people where available."
},
{
"code": null,
"e": 9927,
"s": 9889,
"text": "Use your resources and call a friend:"
},
{
"code": null,
"e": 10008,
"s": 9927,
"text": "In this article, I tried to make you understand how hard Data Science really is."
},
{
"code": null,
"e": 10326,
"s": 10008,
"text": "We took a look at the amount of learning I still need to do. Only about 15 to 75 years...Then we looked at data preparation and figured out it’s a huge headache and will take about 80% of your timeFinally, we found out that interpreting your results is probably best left to a more knowledgable person. Call a friend!"
},
{
"code": null,
"e": 10416,
"s": 10326,
"text": "We took a look at the amount of learning I still need to do. Only about 15 to 75 years..."
},
{
"code": null,
"e": 10525,
"s": 10416,
"text": "Then we looked at data preparation and figured out it’s a huge headache and will take about 80% of your time"
},
{
"code": null,
"e": 10646,
"s": 10525,
"text": "Finally, we found out that interpreting your results is probably best left to a more knowledgable person. Call a friend!"
},
{
"code": null,
"e": 10706,
"s": 10646,
"text": "Staying true to the growth mindset, let this not deter you."
},
{
"code": null,
"e": 10745,
"s": 10706,
"text": "You are just not a Data Scientist YET."
}
] |
Creating a Multilevel Inheritance Hierarchy in Java
|
Inheritance involves an object acquiring the properties and behaviour of another object. So basically, using inheritance can extend the functionality of the class by creating a new class that builds on the previous class by inheriting it.
Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A.
A program that demonstrates a multilevel inheritance hierarchy in Java is given as follows:
Live Demo
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}
This is class A
This is class B
This is class C
|
[
{
"code": null,
"e": 1301,
"s": 1062,
"text": "Inheritance involves an object acquiring the properties and behaviour of another object. So basically, using inheritance can extend the functionality of the class by creating a new class that builds on the previous class by inheriting it."
},
{
"code": null,
"e": 1472,
"s": 1301,
"text": "Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A."
},
{
"code": null,
"e": 1564,
"s": 1472,
"text": "A program that demonstrates a multilevel inheritance hierarchy in Java is given as follows:"
},
{
"code": null,
"e": 1575,
"s": 1564,
"text": " Live Demo"
},
{
"code": null,
"e": 1986,
"s": 1575,
"text": "class A {\n void funcA() {\n System.out.println(\"This is class A\");\n }\n}\nclass B extends A {\n void funcB() {\n System.out.println(\"This is class B\");\n }\n}\nclass C extends B {\n void funcC() {\n System.out.println(\"This is class C\");\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n C obj = new C();\n obj.funcA();\n obj.funcB();\n obj.funcC();\n }\n}"
},
{
"code": null,
"e": 2034,
"s": 1986,
"text": "This is class A\nThis is class B\nThis is class C"
}
] |
BPEL - Quick Guide
|
SOA or the Service Oriented Architecture is an architectural approach, which makes use of technology to present business processes as reusable services.
It is focused on the business and enables process transformation to new levels of integration, visualization, monitoring, and optimization.
It is focused on the business and enables process transformation to new levels of integration, visualization, monitoring, and optimization.
It is not a technology, it is a concept and a strategy for using technologies to build business automation solutions.
It is not a technology, it is a concept and a strategy for using technologies to build business automation solutions.
We will now see what BPEL is and how it helps in the SOA.
Business Process Engineering Language is a technology used to build programs in SOA architecture.
Follow these steps to add a BPEL Process Service Component −
From the Application Navigator, select File > New > Applications > SOA Application.
From the Application Navigator, select File > New > Applications > SOA Application.
This starts the Create SOA Application wizard.
This starts the Create SOA Application wizard.
In the Application Name dialog, enter an application name in the Application Name field.
In the Application Name dialog, enter an application name in the Application Name field.
In the Directory field, enter a directory path in which to create the SOA composite application and project.
In the Directory field, enter a directory path in which to create the SOA composite application and project.
Click Next.
Click Next.
In the Project Name dialog, enter a name in the Project Name field.
In the Project Name dialog, enter a name in the Project Name field.
Click Next.
Click Next.
In the Project SOA Settings dialog, select Composite with the BPEL Process.
In the Project SOA Settings dialog, select Composite with the BPEL Process.
Click Finish.
Click Finish.
The BPEL composite contains the following files −
composite.xml − This file describes the entire composite assembly of services, service components, references, and wires.
composite.xml − This file describes the entire composite assembly of services, service components, references, and wires.
.bpel − This file contains the set of activities added to the process.
.bpel − This file contains the set of activities added to the process.
.componentType − This file describes the services and references for the BPEL process service component.
.componentType − This file describes the services and references for the BPEL process service component.
.wsdl − This file defines the input and output messages for this BPEL process flow, the supported client interface and operations, and other features.
.wsdl − This file defines the input and output messages for this BPEL process flow, the supported client interface and operations, and other features.
In this section, we will learn the different concepts involved in the BPL process.
A central process (which can be another Web service) takes control of the involved Web services.
A central process (which can be another Web service) takes control of the involved Web services.
Coordinates the execution of different operations on the web services involved in the operation.
Coordinates the execution of different operations on the web services involved in the operation.
The involved Web services do not "know" (and do not need to know) that they are involved in a composition process and that they are taking part in a higher-level business process.
Only the central coordinator of the orchestration is aware of this goal, so the orchestration is centralized with explicit definitions of operations and the order of invocation of Web services.
Only the central coordinator of the orchestration is aware of this goal, so the orchestration is centralized with explicit definitions of operations and the order of invocation of Web services.
Does not rely on a central coordinator.
Does not rely on a central coordinator.
Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact.
Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact.
Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact.
Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact.
All participants in the choreography need to be aware of the business process, operations to execute, messages to exchange, and the timing of message exchanges.
All participants in the choreography need to be aware of the business process, operations to execute, messages to exchange, and the timing of message exchanges.
In this chapter, we will learn about the different activities that make up the building blocks The building blocks of a BPEL process service component.
Oracle BPEL Designer includes a set of activities that you drag into a BPEL process service component and double-click an activity to define its attributes and property values.
An assign activity enables to manipulate data, such as copying the contents of one variable to another.
An invoke activity enables you to invoke a service (identified by its partner link) and specify an operation for this service to perform.
A receive activity waits for an asynchronous callback response message from a service.
Let us learn more about the Invoke activity in our subsequent section.
The invoke activity enables to specify an operation that is to be invoked for the service (identified by its partner link). The operation can be one-way or request-response on a port provided by the service. Variables can be automatically created in an invoke activity. An invoke activity invokes a synchronous service or initiates an asynchronous web service.
The invoke activity opens a port in the process to send and receive data. This port can be further used to submit required data and receive a response. For synchronous callbacks, only one port is needed for both the send and the receive functions.
Partner Links are defined as communication exchanges between all the parties with which the BPEL Process interacts.
They are the references to the actual implementations, through which the BPEL process interacts with the external world.
These are links to services that are invoked by the BPEL process.
These are links to services that can invoke a BPEL process.
The Partner Link Property Editor allows you to establish partner links for your BPEL processes. With the Partner Link Property Editor, you can specify the following −
Name − Specifies the name of the Invoke element.
Name − Specifies the name of the Invoke element.
WSDL File − Indicates the WSDL file associated with the Partner Link.
WSDL File − Indicates the WSDL file associated with the Partner Link.
Partner Link Type − Indicates the Partner Link type defined in the WSDL.
Partner Link Type − Indicates the Partner Link type defined in the WSDL.
My Role − Indicates the role of the business process itself.
My Role − Indicates the role of the business process itself.
Partner Pole − Indicates the role of the partner.
Partner Pole − Indicates the role of the partner.
Documentation − Accessed on the Properties window.
Documentation − Accessed on the Properties window.
Partner Links are defined in the .bpel file.
A BPEL can interact with the services in the following three ways −
Services that invoke a BPEL process
Services that are invoked by the BPEL process
Services that act both ways
In this chapter, we will learn how to create a partner link.
Follow the steps shown below to create a partner link −
In the SOA Composite Editor, double-click the BPEL process service component.
In the SOA Composite Editor, double-click the BPEL process service component.
Upon clicking the service component, the Oracle BPEL Designer is displayed.
Upon clicking the service component, the Oracle BPEL Designer is displayed.
In the Component Palette, expand BPEL Services.
In the Component Palette, expand BPEL Services.
Drag a Partner Link into the appropriate Partner Links swimlane.
Drag a Partner Link into the appropriate Partner Links swimlane.
Complete the fields for this dialog as mentioned above in the Partner Link Properties.
Complete the fields for this dialog as mentioned above in the Partner Link Properties.
Adapters enable to integrate the BPEL process service component with access to file systems, FTP servers, database tables, database queues, sockets, Java Message Services (JMS), MQ, and Oracle E-Business Suite. This wizard enables to configure the types of adapters shown in below figure for use with the BPEL process service component −
The following image shows the different adapter types −
For interaction with a queue. AQ provides a flexible mechanism for bidirectional, asynchronous communication between participating applications.
For publishing data to data objects in an Oracle BAM Server.
For interaction with Oracle and non-Oracle databases through JDBC and Oracle Business Intelligence (which is a special data source type).
For file exchange (read and write) on local file systems and remote file systems (through use of the file transfer protocol (FTP)).
For interaction with JMS. The JMS architecture uses a one client interface to many messaging servers architecture.
For message exchange with WebSphere MQ queuing systems.
For interaction with Oracle Application's set of integrated business applications.
For browsing B2B metadata in the metadata service (MDS) repository and selecting document definitions.
For modeling standard or nonstandard protocols for communication over TCP/IP sockets.
The Service Name window prompts to enter a name, when the adapter type is selected from the pallet. For this example, File Adapter was selected. When the wizard completes, a WSDL file by this service name appears in the Application Navigator for the BPEL process service component (for this example, named ReadFile.wsdl). The service name must be unique within the project. This configuration file includes the adapter configuration settings specified with this wizard. Other configuration files (such as header files and files specific to the adapter) are also created. These files are displayed in the Application Navigator.
BPEL process monitors in Oracle BPEL Designer can be configured by selecting Monitor at the top of Oracle BPEL Designer.
At this stage, the Oracle BAM Adapter needs to be configured.
The Client BPEL Process sends a message to Service BPEL Process and the Service BPEL Process is not required to reply as shown in the figure below −
The Client BPEL Process needs a valid partner link and an invoke activity.
The Client BPEL Process needs a valid partner link and an invoke activity.
The Service BPEL Process needs a receive activity.
The Service BPEL Process needs a receive activity.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
<wsdl:portType name = "BPELProcess">
<wsdl:operation name = "process">
<wsdl:input message = "client:BPELProcessRequestMessage" />
<wsdl:output message = "client:BPELProcessResponseMessage"/>
</wsdl:operation>
</wsdl:portType>
The Client BPEL Process sends a request to the Service BPEL Process (d1 in the below figure), and receives an immediate reply (d2 in the below figure). For example, a user requests a subscription to an online application form for admission to a college and immediately receives email confirmation that their request has been accepted.
The Client BPEL Process needs an invoke activity. The port on the client side sends the request and receives the reply.
The Client BPEL Process needs an invoke activity. The port on the client side sends the request and receives the reply.
The Service BPEL Process needs a receive activity to accept the incoming request, and a reply activity to return either the requested information or an error message (a fault; f1 in the below figure) defined in the WSDL.
The Service BPEL Process needs a receive activity to accept the incoming request, and a reply activity to return either the requested information or an error message (a fault; f1 in the below figure) defined in the WSDL.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
WSDL File
<wsdl:portType name = "BPELProcess">
<wsdl:operation name = "process">
<wsdl:input message = "client:BPELProcessRequestMessage" />
<wsdl:output message = "client:BPELProcessResponseMessage"/>
</wsdl:operation>
</wsdl:portType>
The Client BPEL Process sends a request to the Service BPEL Process (d1 in the figure given below), and waits until the service replies (d2 in the figure given below).
For example, a user requests a subscription to an online application form for admission to a college and the request cannot be confirmed unless it is accepted at the admission office.
The Client BPEL Process needs an invoke activity to send the request and a receive activity to receive the reply.
The Client BPEL Process needs an invoke activity to send the request and a receive activity to receive the reply.
The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.
Note − The difference between responding from a synchronous and asynchronous BPEL process is that the synchronous service uses a reply activity to respond to the client and an asynchronous service uses an invoke activity.
The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.
Note − The difference between responding from a synchronous and asynchronous BPEL process is that the synchronous service uses a reply activity to respond to the client and an asynchronous service uses an invoke activity.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below.
WSDL File
<wsdl:portType name = "BPELProcess">
<wsdl:operation name = "process">
<wsdl:input message = "client:BPELProcessRequestMessage"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:portType name = "BPELProcessCallback">
<wsdl:operation name = "processResponse">
<wsdl:input message = "client:BPELProcessResponseMessage"/>
</wsdl:operation>
</wsdl:portType>
The Client BPEL Process sends a request to the Service BPEL Process (d1 in the below figure), and waits until the service replies or until a certain time limit is reached, whichever comes first. (d2 in the below figure).
For example, a user requests a subscription to an online application form for admission to a college and the request is cancelled if the user does not receive a confirmation reply within a specified amount of time.
The Client BPEL Process needs an invoke activity to send the request and a pick activity with two branches - an onMessage branch and an onAlarm branch. If the reply comes after the time limit has expired, the message goes to the dead letter queue.
The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
In this chapter, we will learn about asynchronous interactions with a notification timer. Consider the following points related to the asynchronous interactions −
The Client BPEL Process sends a request to the Service BPEL Process and waits for a reply, although a notification is sent after a timer expires.
The Client BPEL Process sends a request to the Service BPEL Process and waits for a reply, although a notification is sent after a timer expires.
The Client BPEL Process continues to wait for the reply from the Service BPEL Process even after the timer has expired.
The Client BPEL Process continues to wait for the reply from the Service BPEL Process even after the timer has expired.
The Client BPEL Process needs a scope activity containing an invoke activity to send the request, and a receive activity to accept the reply. The onAlarm handler of the scope activity has a time limit and instructions on what to do when the timer expires.
The Client BPEL Process needs a scope activity containing an invoke activity to send the request, and a receive activity to accept the reply. The onAlarm handler of the scope activity has a time limit and instructions on what to do when the timer expires.
For example, wait 60 seconds, then send a warning indicating that the process is taking longer than expected.
For example, wait 60 seconds, then send a warning indicating that the process is taking longer than expected.
The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.
The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
In this chapter, we will learn about the concept of One Request and Multiple Responses.
The Client BPEL Process sends a single request to the Service BPEL Process and receives multiple responses in return.
For example, the request can be to order a product online, and the first response can be the estimated delivery time, the second response a payment confirmation, and the third response a notification that the product has shipped. In this example, the number and types of responses are expected.
The Client BPEL Process sends a single request to the Service BPEL Process and receives multiple responses in return.
For example, the request can be to order a product online, and the first response can be the estimated delivery time, the second response a payment confirmation, and the third response a notification that the product has shipped. In this example, the number and types of responses are expected.
The Client BPEL Process needs an invoke activity to send the request, and a sequence activity with three receive activities.
The Client BPEL Process needs an invoke activity to send the request, and a sequence activity with three receive activities.
The Service BPEL Process needs a receive activity to accept the message from the client, and a sequence attribute with three invoke activities, one for each reply.
The Service BPEL Process needs a receive activity to accept the message from the client, and a sequence attribute with three invoke activities, one for each reply.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
In this chapter, we will learn about the concept of one request and one of two possible responses.
The Client BPEL Process sends a single request to the Service BPEL Process and receives one of two possible responses.
For example, the request can be to order a product online, and the first response can be either an in-stock message, or an out-of-stock message.
The Client BPEL Process sends a single request to the Service BPEL Process and receives one of two possible responses.
For example, the request can be to order a product online, and the first response can be either an in-stock message, or an out-of-stock message.
The Client BPEL Process needs the following −
The Client BPEL Process needs the following −
An invoke activity to send the request.
An invoke activity to send the request.
A pick activity with two branches: one onMessage for the in-stock response and instructions on what to do if an in-stock message is received.
A pick activity with two branches: one onMessage for the in-stock response and instructions on what to do if an in-stock message is received.
A second onMessage for the out-of-stock response and instructions on what to do if an out-of-stock message is received.
A second onMessage for the out-of-stock response and instructions on what to do if an out-of-stock message is received.
The Service BPEL Process needs a receive activity to accept the message from the client, and a switch activity with two branches, one with an invoke activity sending the in-stock message if the item is available, and a second branch with an invoke activity sending the out-of-stock message if the item is not available.
The Service BPEL Process needs a receive activity to accept the message from the client, and a switch activity with two branches, one with an invoke activity sending the in-stock message if the item is available, and a second branch with an invoke activity sending the out-of-stock message if the item is not available.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
In this chapter, we will understand the concept of one request, a mandatory response, and an optional response.
The Client BPEL Service sends a single request to the Service BPEL Process and receives one or two responses.
The Client BPEL Service sends a single request to the Service BPEL Process and receives one or two responses.
Here, the request is to order a product online. If the product is delayed, the service sends a message letting the customer know. In any case, the service always sends a notification when the item ships.
Here, the request is to order a product online. If the product is delayed, the service sends a message letting the customer know. In any case, the service always sends a notification when the item ships.
The Client BPEL Service needs a scope activity containing the invoke activity to send the request, and a receive activity to accept the mandatory reply. For the optional message, the onMessage handler of the scope activity is set along with the instructions on what to do if the optional message is received (for example, notify you that the product has been delayed). The Client BPEL Process waits to receive the mandatory reply. If the mandatory reply is received first, the BPEL Process continues without waiting for the optional reply.
The Client BPEL Service needs a scope activity containing the invoke activity to send the request, and a receive activity to accept the mandatory reply. For the optional message, the onMessage handler of the scope activity is set along with the instructions on what to do if the optional message is received (for example, notify you that the product has been delayed). The Client BPEL Process waits to receive the mandatory reply. If the mandatory reply is received first, the BPEL Process continues without waiting for the optional reply.
The Service BPEL Process needs a scope activity containing the receive activity and an invoke activity to send the mandatory shipping message, and the scope's onAlarm handler to send the optional delayed message if a timer expires (for example, send the delayed message if the item is not shipped in 24 hours).
The Service BPEL Process needs a scope activity containing the receive activity and an invoke activity to send the mandatory shipping message, and the scope's onAlarm handler to send the optional delayed message if a timer expires (for example, send the delayed message if the item is not shipped in 24 hours).
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
Now, we will learn the concept of partial processing in BPEL.
The Client BPEL Process sends a request to the Service BPEL Process and receives an immediate response, but processing continues on the service side.
The Client BPEL Process sends a request to the Service BPEL Process and receives an immediate response, but processing continues on the service side.
This pattern can also include multiple shot callbacks, followed by longer-term processing.
This pattern can also include multiple shot callbacks, followed by longer-term processing.
For example, the client sends a request to purchase a vacation package, and the service sends an immediate reply confirming the purchase, then continues to book the hotel, the flight, the rental car, and so on.
For example, the client sends a request to purchase a vacation package, and the service sends an immediate reply confirming the purchase, then continues to book the hotel, the flight, the rental car, and so on.
The Client BPEL Process needs an invoke activity for each request and a receive activity for each reply for asynchronous transactions, or just an invoke activity for each synchronous transaction.
The Client BPEL Process needs an invoke activity for each request and a receive activity for each reply for asynchronous transactions, or just an invoke activity for each synchronous transaction.
The Service BPEL Process needs a receive activity for each request from the client, and an invoke activity for each response. Once the responses are finished, the Service BPEL Process as the service can continue with its processing, using the information gathered in the transaction to perform the necessary tasks without any further input from the client.
The Service BPEL Process needs a receive activity for each request from the client, and an invoke activity for each response. Once the responses are finished, the Service BPEL Process as the service can continue with its processing, using the information gathered in the transaction to perform the necessary tasks without any further input from the client.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction.
We will learn about the multiple application interactions with BPEL in this chapter.
When there are more than two applications involved in a transaction.
When there are more than two applications involved in a transaction.
This A-to-B-to-C-to-A transaction pattern can handle many transactions at the same time. Therefore, a mechanism is required for keeping track of which message goes where.
This A-to-B-to-C-to-A transaction pattern can handle many transactions at the same time. Therefore, a mechanism is required for keeping track of which message goes where.
This can be handled using WS-Addressing or correlation sets.
This can be handled using WS-Addressing or correlation sets.
We have discussed in one of the previous chapters that Synchronous Web Service is one, which provides an immediate response to an invocation.
In the screenshot shown below, we have created a Synchronous BPEL Process which has a receive activity to accept the request from the user. The reply activity simultaneously sends the response back.
As discussed before Asynchronous Web Service is one which sends a request to other web service and waits for the response.
In the screenshot shown below, we have created the Asynchronous BPEL Process which has a receive activity to accept the request from the user. The assign activity further assigns values to the different elements in the request.
Next, the invoke activity invokes the HelloWorld Application which sends the response simultaneously and that is captured in receive activity.
Further, we have the callback activity which finally generates output and sends response asynchronously.
If you double-click the receiveInput or callbackClient, you will see each of them has only one variable.
receiveInput → inputVariable
callbackClient → outputVariable
In this chapter, we will understand how parallel flow works in BPEL.
A flow activity typically contains many sequence activities, and each sequence is performed in parallel. A flow activity can also contain other activities.
For example, two asynchronous callbacks execute in parallel, so that one callback does not have to wait for the other to complete first. Each response is stored in a different global variable.
In the flow activity, the BPEL code determines the number of parallel branches. However, often the number of branches required is different depending on the available information.
The flowN activity creates multiple flows equal to the value of N, which is defined at the run time based on the data available and logic within the process. There is an Index variable increment each time a new branch is created, until the index variable reaches the value of N.
The flowN activity performs activities on an arbitrary number of data elements. As the number of elements changes, the BPEL process adjusts accordingly.
The branches created by flowN perform the same activities, but use different data. Each branch uses the index variable to look up input variables. The index variable can be used in the XPath expression to acquire the data specific for that branch.
BPEL applies logic to make choices through conditional branching. The two different actions based on conditional branching are shown below −
In this method, you set up two or more branches, with each branch in the form of an XPath expression. If the expression is true, then the branch is executed. If the expression is false, then the BPEL process moves to the next branch condition, until it either finds a valid branch condition, encounters an otherwise branch, or runs out of branches. If more than one branch condition is true, then BPEL executes the first true branch.
You can use a while activity to create a while loop to select between two actions.
To understand how to use fault handling, we need to learn the basic architecture of a Service Composite in Oracle SOA Suite.
Service components − BPEL Processes, Business Rule, Human Task, Mediator. These are used to construct a SOA composite application.
Service components − BPEL Processes, Business Rule, Human Task, Mediator. These are used to construct a SOA composite application.
Binding components − Establish connection between a SOA composite and external world.
Binding components − Establish connection between a SOA composite and external world.
Services − Provides an entry point to SOA composite application.
Services − Provides an entry point to SOA composite application.
Binding − Defines the protocols that communicate with the service like SOAP/HTTP, JCA adapter, etc.
Binding − Defines the protocols that communicate with the service like SOAP/HTTP, JCA adapter, etc.
WSDL − Defines the service definition of a web service.
WSDL − Defines the service definition of a web service.
References − Enables a SOA composite application to send messages to external services
References − Enables a SOA composite application to send messages to external services
Wires − Enables connection between service components.
Wires − Enables connection between service components.
Let us now see the different types of faults.
Occurs when application executes THROW activity or an INVOKE receives fault as response. Fault name is specified by the BPEL process service component. The fault handler using Fault name and Fault variable catches this fault.
This is thrown by the system. These faults are associated with RunTimeFaultMessage and are included in
http://schemas.oracle.com/bpel/extensionnamespace.
In this section, we will learn about the different ways of fault handling.
Throw activity explicitly throws the fault. The catch block catches this fault and the corresponding actions get executed thereby.
Using throw activity, you can throw business faults & within the created scope, you can catch this fault and redirect to the caller (consumer) to take action.
Using throw activity, you can throw business faults & within the created scope, you can catch this fault and redirect to the caller (consumer) to take action.
Instead of the above approach, you throw the same fault caught in catch activity of the created scope. In the main scope, you can catch this fault using the catchall activity.
Instead of the above approach, you throw the same fault caught in catch activity of the created scope. In the main scope, you can catch this fault using the catchall activity.
The 2 main files used in EHF are −
Fault-Policy.xml
Fault-Bindings.xml
Whenever the BPEL process throws an error, the EHF will check whether the error exists in Fault-Bindings.xml files. If so, the action in the Fault-Policy.xml file will be taken. If the action is not found, the fault will the thrown and it will be handled in the catch block.
Fault management framework (Fault-Policy.xml and Fault-Bindings.xml) is kept inside a SOA Composite.
Fault-handlers like catch and catchall are inside a BPEL to catch all faults, but fault policies will only be executed when an invoke activity fails.
In this chapter, we will see different scenarios related to the resubmitting of a faulted process.
The BPEL code uses a fault-policy and a fault is handled using the “ora-human-intervention” activity. The fault is then marked as Recoverable and the instance state is set to “Running”.
The BPEL code uses a fault-policy and a fault is caught and re-thrown using the “ora-rethrow-fault” action. The fault is then marked as Recoverable and the instance state is set to “Faulted”; provided the fault is a recoverable one (like URL was not available).
There are several methods for incorporating Java and Java EE code in BPEL processes. Following are a few important methods −
Wrap as a Simple Object Access Protocol (SOAP) service
Wrap as a Simple Object Access Protocol (SOAP) service
Embed Java code snippets into a BPEL process with the bpelx − exec tag
Embed Java code snippets into a BPEL process with the bpelx − exec tag
Use an XML facade to simplify DOM manipulation
Use an XML facade to simplify DOM manipulation
Use bpelx − exec built-in methods
Use bpelx − exec built-in methods
Use Java code wrapped in a service interface
Use Java code wrapped in a service interface
The Java Embedding activity allows us to add activities in a BPEL process. We can write a Java snippet using standard JDK libraries, the BPEL APIs, custom and 3rd party Java Classes included in JAR files in deployed SCA composites (in SCA-INF/lib directory) and Java Classes and libraries available on the Classpath for the SOA Suite run time.
Java Embedding means functionality hidden inside, in a not very decoupled way. The Java code is hard to maintain. By embedding Java in BPEL (XML driven), we start mixing technology, that require different skills as well as expensive XML to Java Object marshalling and unmarshalling.
The best use cases for Java Embedding seems to be for advanced logging/tracing or for special validations/transformations. However, not to replace built in capabilities of the BPEL engine as well as the other components in SOA Suite 11g and the adapters that come with it.
XPath is mainly used to manipulate XMLs in the BPEL process. There are some valuable Xpath functions that can be used for manipulating XML. Let us see the functions below.
This can be used to extract a set of elements from a variable, using a XPath expression.
<bpel:copy>
<bpel:from>
<![CDATA[count(bpel:getVariableData(‘$Variable','$partName')/ns:return)]]>
</bpel:from>
<bpel:to variable = "itemNumber">
</bpel:to>
</bpel:copy>
You can assign boolean values with the XPath boolean function.
<assign>
<!-- copy from boolean expression function to the variable -->
<copy>
<from expression = "true()"/>
<to variable = "output" part = "payload" query="/result/approved"/>
</copy>
</assign>
You can assign the current value of a date or time field by using the Oracle BPEL XPath function getCurrentDate, getCurrentTime, or getCurrentDateTime, respectively.
<!-- execute the XPath extension function getCurrentDate() -->
<assign>
<copy>
<from expression = "xpath20:getCurrentDate()"/>
<to variable = "output" part = "payload"
query = "/invoice/invoiceDate"/>
</copy>
</assign>
Rather than copying the value of one string variable (or variable part or field) to another, you can first perform string manipulation, such as concatenating several strings.
<assign>
<!-- copy from XPath expression to the variable -->
<copy>
<from expression = "concat('Hello ',
bpws:getVariableData('input', 'payload', '/p:name'))"/>
<to variable = "output" part = "payload" query = "/p:result/p:message"/>
</copy>
</assign>
You can assign string literals to a variable in BPEL.
<assign>
<!-- copy from string expression to the variable -->
<copy>
<from expression = "'GE'"/>
<to variable = "output" part = "payload" query = "/p:result/p:symbol"/>
</copy>
</assign>
You can assign numeric values in XPath expressions.
<assign>
<!-- copy from integer expression to the variable -->
<copy>
<from expression = "100"/>
<to variable = "output" part = "payload" query = "/p:result/p:quantity"/>
</copy>
</assign>
Note − A few XSLT functions were used to transform an XML document.
BPEL correlation matches inbound messages with a specific process instance. When you need to associate specific data to a specific instance of a business process, you use correlation.
For example, while creating a process that verifies an account number and checks the account’s credit limit. When verified, the process makes a call to another system to check inventory and, if the item is in stock, generates a purchase order. How does the purchase order know which account is to be debited? The answer to this question is correlation.
Correlation sets are used to uniquely identify process instances. You provide each correlation set with a unique name and then define it by one or more properties. Each property has a name and a type (for example, string or integer).
The property alias for each property in the correlation set needs to be defined. A property alias is a mapping that binds the property with the input or output values.
Consider the following important points related to the Correlation Sets and Message Aggregation −
A process that contains more than one receive or pick activity must have a correlation set.
A process that contains more than one receive or pick activity must have a correlation set.
Correlation sets are initialized with values from process inbound or outbound messages.
Correlation sets are initialized with values from process inbound or outbound messages.
If you have groups of messages that are associated together with one specific process, you can set up one or more correlation sets to handle.
If you have groups of messages that are associated together with one specific process, you can set up one or more correlation sets to handle.
Asynchronous web services usually take a long time to return a response and as such, a BPEL process service component must be able to time out, or give up waiting, and continue with the rest of the flow after a certain amount of time. You can use the pick activity to configure a BPEL flow either to wait over a specified amount of time or to continue performing its duties. To set an expiration period for the time, you can use the wait activity. To manage message, events can be used particularly when the business process is waiting for callbacks from partner Web services.
BPEL supports two types of events −
These events are triggered by incoming messages through operation invocation on port types.
These events are time-related and are triggered either after a certain duration or at a specific time.
Often, however, it is more useful to wait for more than one message, of which only one will occur.
Often, however, it is more useful to wait for more than one message, of which only one will occur.
Alarm events are useful when you want the process to wait for a callback for a certain period of time, such as 15 minutes.
Alarm events are useful when you want the process to wait for a callback for a certain period of time, such as 15 minutes.
If no callback is received, the process flow continues as designed.
If no callback is received, the process flow continues as designed.
Useful in loosely coupled service-oriented architectures, where you cannot rely on Web services being available all the time.
Useful in loosely coupled service-oriented architectures, where you cannot rely on Web services being available all the time.
The pick activity has 2 branches −
onMessage − the code on this branch is equal to the code for receiving a response before a timeout was added.
onMessage − the code on this branch is equal to the code for receiving a response before a timeout was added.
onAlarm − this condition has code for a timeout of one minute.
onAlarm − this condition has code for a timeout of one minute.
The wait activity allows a process to wait for a given time period or until a time limit has been reached. Exactly one of the expiration criteria must be specified.
The BPEL process can be made use of for notification service. The process can be designed to send the following −
email
voice message
instant messaging (IM), or
short message service (SMS) notifications
For the services mentioned above, you can configure the channel for the incoming and outgoing message.
Composite sensors within a SOA application provides the ability to define trackable fields on messages and enables you to find a specific composite instance by searching for a field or fields within a message. For example, a sensor could be defined for an order number within a message, thus allowing us to find the instance where the order number in question is found.
Composite sensors can be defined within a SOA application in several components −
Service component (exposed service)
Service component (exposed service)
Reference component (external reference)
Reference component (external reference)
Mediator or BPEL component that have subscribed to a business event (publishing an event cannot have a sensor)
Mediator or BPEL component that have subscribed to a business event (publishing an event cannot have a sensor)
There are different ways to define a composite sensor −
By specifying an existing variable as the sensor.
By an expression with the help of the expression builder.
By using properties (e.g. message header properties).
Defining a sensor allows for a quick search for data within a composite instance in the EM Console.
In the EM Console dashboard, a user can search for instances by sensor name and value.
In the “Flow Instances” tab, you can select sensors from the dropdowns and can use wildcard-like values for the sensor value.
New Activities have been added in 2.0 which have replaced the ones in 1.1.
This activity helps repeat the set of activities. The activity replaces the FlowN activity in BPEL 1.1 version.
This activity comes of use if the body of an activity must be performed at least once. The XPath expression condition in the repeatUntil activity is evaluated after the body of the activity completes.
This activity replaces the switch activity in BPEL 2.0. The activity enables you to define conditional behavior for specific activities to decide between two or more branches. Only one activity is selected for execution from a set of branches.
This activity helps compensate the specified child scope.
This activity has been added to fault handlers. It enables you to rethrow a fault originally captured by the immediately enclosing fault handler.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2614,
"s": 2461,
"text": "SOA or the Service Oriented Architecture is an architectural approach, which makes use of technology to present business processes as reusable services."
},
{
"code": null,
"e": 2754,
"s": 2614,
"text": "It is focused on the business and enables process transformation to new levels of integration, visualization, monitoring, and optimization."
},
{
"code": null,
"e": 2894,
"s": 2754,
"text": "It is focused on the business and enables process transformation to new levels of integration, visualization, monitoring, and optimization."
},
{
"code": null,
"e": 3012,
"s": 2894,
"text": "It is not a technology, it is a concept and a strategy for using technologies to build business automation solutions."
},
{
"code": null,
"e": 3130,
"s": 3012,
"text": "It is not a technology, it is a concept and a strategy for using technologies to build business automation solutions."
},
{
"code": null,
"e": 3188,
"s": 3130,
"text": "We will now see what BPEL is and how it helps in the SOA."
},
{
"code": null,
"e": 3286,
"s": 3188,
"text": "Business Process Engineering Language is a technology used to build programs in SOA architecture."
},
{
"code": null,
"e": 3347,
"s": 3286,
"text": "Follow these steps to add a BPEL Process Service Component −"
},
{
"code": null,
"e": 3431,
"s": 3347,
"text": "From the Application Navigator, select File > New > Applications > SOA Application."
},
{
"code": null,
"e": 3515,
"s": 3431,
"text": "From the Application Navigator, select File > New > Applications > SOA Application."
},
{
"code": null,
"e": 3562,
"s": 3515,
"text": "This starts the Create SOA Application wizard."
},
{
"code": null,
"e": 3609,
"s": 3562,
"text": "This starts the Create SOA Application wizard."
},
{
"code": null,
"e": 3698,
"s": 3609,
"text": "In the Application Name dialog, enter an application name in the Application Name field."
},
{
"code": null,
"e": 3787,
"s": 3698,
"text": "In the Application Name dialog, enter an application name in the Application Name field."
},
{
"code": null,
"e": 3896,
"s": 3787,
"text": "In the Directory field, enter a directory path in which to create the SOA composite application and project."
},
{
"code": null,
"e": 4005,
"s": 3896,
"text": "In the Directory field, enter a directory path in which to create the SOA composite application and project."
},
{
"code": null,
"e": 4017,
"s": 4005,
"text": "Click Next."
},
{
"code": null,
"e": 4029,
"s": 4017,
"text": "Click Next."
},
{
"code": null,
"e": 4097,
"s": 4029,
"text": "In the Project Name dialog, enter a name in the Project Name field."
},
{
"code": null,
"e": 4165,
"s": 4097,
"text": "In the Project Name dialog, enter a name in the Project Name field."
},
{
"code": null,
"e": 4177,
"s": 4165,
"text": "Click Next."
},
{
"code": null,
"e": 4189,
"s": 4177,
"text": "Click Next."
},
{
"code": null,
"e": 4265,
"s": 4189,
"text": "In the Project SOA Settings dialog, select Composite with the BPEL Process."
},
{
"code": null,
"e": 4341,
"s": 4265,
"text": "In the Project SOA Settings dialog, select Composite with the BPEL Process."
},
{
"code": null,
"e": 4355,
"s": 4341,
"text": "Click Finish."
},
{
"code": null,
"e": 4369,
"s": 4355,
"text": "Click Finish."
},
{
"code": null,
"e": 4419,
"s": 4369,
"text": "The BPEL composite contains the following files −"
},
{
"code": null,
"e": 4541,
"s": 4419,
"text": "composite.xml − This file describes the entire composite assembly of services, service components, references, and wires."
},
{
"code": null,
"e": 4663,
"s": 4541,
"text": "composite.xml − This file describes the entire composite assembly of services, service components, references, and wires."
},
{
"code": null,
"e": 4734,
"s": 4663,
"text": ".bpel − This file contains the set of activities added to the process."
},
{
"code": null,
"e": 4805,
"s": 4734,
"text": ".bpel − This file contains the set of activities added to the process."
},
{
"code": null,
"e": 4910,
"s": 4805,
"text": ".componentType − This file describes the services and references for the BPEL process service component."
},
{
"code": null,
"e": 5015,
"s": 4910,
"text": ".componentType − This file describes the services and references for the BPEL process service component."
},
{
"code": null,
"e": 5166,
"s": 5015,
"text": ".wsdl − This file defines the input and output messages for this BPEL process flow, the supported client interface and operations, and other features."
},
{
"code": null,
"e": 5317,
"s": 5166,
"text": ".wsdl − This file defines the input and output messages for this BPEL process flow, the supported client interface and operations, and other features."
},
{
"code": null,
"e": 5400,
"s": 5317,
"text": "In this section, we will learn the different concepts involved in the BPL process."
},
{
"code": null,
"e": 5497,
"s": 5400,
"text": "A central process (which can be another Web service) takes control of the involved Web services."
},
{
"code": null,
"e": 5594,
"s": 5497,
"text": "A central process (which can be another Web service) takes control of the involved Web services."
},
{
"code": null,
"e": 5691,
"s": 5594,
"text": "Coordinates the execution of different operations on the web services involved in the operation."
},
{
"code": null,
"e": 5788,
"s": 5691,
"text": "Coordinates the execution of different operations on the web services involved in the operation."
},
{
"code": null,
"e": 5968,
"s": 5788,
"text": "The involved Web services do not \"know\" (and do not need to know) that they are involved in a composition process and that they are taking part in a higher-level business process."
},
{
"code": null,
"e": 6162,
"s": 5968,
"text": "Only the central coordinator of the orchestration is aware of this goal, so the orchestration is centralized with explicit definitions of operations and the order of invocation of Web services."
},
{
"code": null,
"e": 6356,
"s": 6162,
"text": "Only the central coordinator of the orchestration is aware of this goal, so the orchestration is centralized with explicit definitions of operations and the order of invocation of Web services."
},
{
"code": null,
"e": 6396,
"s": 6356,
"text": "Does not rely on a central coordinator."
},
{
"code": null,
"e": 6436,
"s": 6396,
"text": "Does not rely on a central coordinator."
},
{
"code": null,
"e": 6554,
"s": 6436,
"text": "Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact."
},
{
"code": null,
"e": 6672,
"s": 6554,
"text": "Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact."
},
{
"code": null,
"e": 6790,
"s": 6672,
"text": "Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact."
},
{
"code": null,
"e": 6908,
"s": 6790,
"text": "Each Web service involved in the choreography knows exactly when to execute its operations and with whom to interact."
},
{
"code": null,
"e": 7069,
"s": 6908,
"text": "All participants in the choreography need to be aware of the business process, operations to execute, messages to exchange, and the timing of message exchanges."
},
{
"code": null,
"e": 7230,
"s": 7069,
"text": "All participants in the choreography need to be aware of the business process, operations to execute, messages to exchange, and the timing of message exchanges."
},
{
"code": null,
"e": 7382,
"s": 7230,
"text": "In this chapter, we will learn about the different activities that make up the building blocks The building blocks of a BPEL process service component."
},
{
"code": null,
"e": 7559,
"s": 7382,
"text": "Oracle BPEL Designer includes a set of activities that you drag into a BPEL process service component and double-click an activity to define its attributes and property values."
},
{
"code": null,
"e": 7664,
"s": 7559,
"text": " An assign activity enables to manipulate data, such as copying the contents of one variable to another."
},
{
"code": null,
"e": 7803,
"s": 7664,
"text": " An invoke activity enables you to invoke a service (identified by its partner link) and specify an operation for this service to perform."
},
{
"code": null,
"e": 7892,
"s": 7803,
"text": " A receive activity waits for an asynchronous callback response message from a service."
},
{
"code": null,
"e": 7963,
"s": 7892,
"text": "Let us learn more about the Invoke activity in our subsequent section."
},
{
"code": null,
"e": 8324,
"s": 7963,
"text": "The invoke activity enables to specify an operation that is to be invoked for the service (identified by its partner link). The operation can be one-way or request-response on a port provided by the service. Variables can be automatically created in an invoke activity. An invoke activity invokes a synchronous service or initiates an asynchronous web service."
},
{
"code": null,
"e": 8572,
"s": 8324,
"text": "The invoke activity opens a port in the process to send and receive data. This port can be further used to submit required data and receive a response. For synchronous callbacks, only one port is needed for both the send and the receive functions."
},
{
"code": null,
"e": 8688,
"s": 8572,
"text": "Partner Links are defined as communication exchanges between all the parties with which the BPEL Process interacts."
},
{
"code": null,
"e": 8809,
"s": 8688,
"text": "They are the references to the actual implementations, through which the BPEL process interacts with the external world."
},
{
"code": null,
"e": 8875,
"s": 8809,
"text": "These are links to services that are invoked by the BPEL process."
},
{
"code": null,
"e": 8935,
"s": 8875,
"text": "These are links to services that can invoke a BPEL process."
},
{
"code": null,
"e": 9102,
"s": 8935,
"text": "The Partner Link Property Editor allows you to establish partner links for your BPEL processes. With the Partner Link Property Editor, you can specify the following −"
},
{
"code": null,
"e": 9151,
"s": 9102,
"text": "Name − Specifies the name of the Invoke element."
},
{
"code": null,
"e": 9200,
"s": 9151,
"text": "Name − Specifies the name of the Invoke element."
},
{
"code": null,
"e": 9270,
"s": 9200,
"text": "WSDL File − Indicates the WSDL file associated with the Partner Link."
},
{
"code": null,
"e": 9340,
"s": 9270,
"text": "WSDL File − Indicates the WSDL file associated with the Partner Link."
},
{
"code": null,
"e": 9413,
"s": 9340,
"text": "Partner Link Type − Indicates the Partner Link type defined in the WSDL."
},
{
"code": null,
"e": 9486,
"s": 9413,
"text": "Partner Link Type − Indicates the Partner Link type defined in the WSDL."
},
{
"code": null,
"e": 9547,
"s": 9486,
"text": "My Role − Indicates the role of the business process itself."
},
{
"code": null,
"e": 9608,
"s": 9547,
"text": "My Role − Indicates the role of the business process itself."
},
{
"code": null,
"e": 9658,
"s": 9608,
"text": "Partner Pole − Indicates the role of the partner."
},
{
"code": null,
"e": 9708,
"s": 9658,
"text": "Partner Pole − Indicates the role of the partner."
},
{
"code": null,
"e": 9759,
"s": 9708,
"text": "Documentation − Accessed on the Properties window."
},
{
"code": null,
"e": 9810,
"s": 9759,
"text": "Documentation − Accessed on the Properties window."
},
{
"code": null,
"e": 9855,
"s": 9810,
"text": "Partner Links are defined in the .bpel file."
},
{
"code": null,
"e": 9923,
"s": 9855,
"text": "A BPEL can interact with the services in the following three ways −"
},
{
"code": null,
"e": 9959,
"s": 9923,
"text": "Services that invoke a BPEL process"
},
{
"code": null,
"e": 10005,
"s": 9959,
"text": "Services that are invoked by the BPEL process"
},
{
"code": null,
"e": 10033,
"s": 10005,
"text": "Services that act both ways"
},
{
"code": null,
"e": 10094,
"s": 10033,
"text": "In this chapter, we will learn how to create a partner link."
},
{
"code": null,
"e": 10150,
"s": 10094,
"text": "Follow the steps shown below to create a partner link −"
},
{
"code": null,
"e": 10228,
"s": 10150,
"text": "In the SOA Composite Editor, double-click the BPEL process service component."
},
{
"code": null,
"e": 10306,
"s": 10228,
"text": "In the SOA Composite Editor, double-click the BPEL process service component."
},
{
"code": null,
"e": 10382,
"s": 10306,
"text": "Upon clicking the service component, the Oracle BPEL Designer is displayed."
},
{
"code": null,
"e": 10458,
"s": 10382,
"text": "Upon clicking the service component, the Oracle BPEL Designer is displayed."
},
{
"code": null,
"e": 10506,
"s": 10458,
"text": "In the Component Palette, expand BPEL Services."
},
{
"code": null,
"e": 10554,
"s": 10506,
"text": "In the Component Palette, expand BPEL Services."
},
{
"code": null,
"e": 10619,
"s": 10554,
"text": "Drag a Partner Link into the appropriate Partner Links swimlane."
},
{
"code": null,
"e": 10684,
"s": 10619,
"text": "Drag a Partner Link into the appropriate Partner Links swimlane."
},
{
"code": null,
"e": 10771,
"s": 10684,
"text": "Complete the fields for this dialog as mentioned above in the Partner Link Properties."
},
{
"code": null,
"e": 10858,
"s": 10771,
"text": "Complete the fields for this dialog as mentioned above in the Partner Link Properties."
},
{
"code": null,
"e": 11196,
"s": 10858,
"text": "Adapters enable to integrate the BPEL process service component with access to file systems, FTP servers, database tables, database queues, sockets, Java Message Services (JMS), MQ, and Oracle E-Business Suite. This wizard enables to configure the types of adapters shown in below figure for use with the BPEL process service component −"
},
{
"code": null,
"e": 11252,
"s": 11196,
"text": "The following image shows the different adapter types −"
},
{
"code": null,
"e": 11397,
"s": 11252,
"text": "For interaction with a queue. AQ provides a flexible mechanism for bidirectional, asynchronous communication between participating applications."
},
{
"code": null,
"e": 11458,
"s": 11397,
"text": "For publishing data to data objects in an Oracle BAM Server."
},
{
"code": null,
"e": 11596,
"s": 11458,
"text": "For interaction with Oracle and non-Oracle databases through JDBC and Oracle Business Intelligence (which is a special data source type)."
},
{
"code": null,
"e": 11728,
"s": 11596,
"text": "For file exchange (read and write) on local file systems and remote file systems (through use of the file transfer protocol (FTP))."
},
{
"code": null,
"e": 11843,
"s": 11728,
"text": "For interaction with JMS. The JMS architecture uses a one client interface to many messaging servers architecture."
},
{
"code": null,
"e": 11899,
"s": 11843,
"text": "For message exchange with WebSphere MQ queuing systems."
},
{
"code": null,
"e": 11982,
"s": 11899,
"text": "For interaction with Oracle Application's set of integrated business applications."
},
{
"code": null,
"e": 12085,
"s": 11982,
"text": "For browsing B2B metadata in the metadata service (MDS) repository and selecting document definitions."
},
{
"code": null,
"e": 12171,
"s": 12085,
"text": "For modeling standard or nonstandard protocols for communication over TCP/IP sockets."
},
{
"code": null,
"e": 12798,
"s": 12171,
"text": "The Service Name window prompts to enter a name, when the adapter type is selected from the pallet. For this example, File Adapter was selected. When the wizard completes, a WSDL file by this service name appears in the Application Navigator for the BPEL process service component (for this example, named ReadFile.wsdl). The service name must be unique within the project. This configuration file includes the adapter configuration settings specified with this wizard. Other configuration files (such as header files and files specific to the adapter) are also created. These files are displayed in the Application Navigator."
},
{
"code": null,
"e": 12919,
"s": 12798,
"text": "BPEL process monitors in Oracle BPEL Designer can be configured by selecting Monitor at the top of Oracle BPEL Designer."
},
{
"code": null,
"e": 12981,
"s": 12919,
"text": "At this stage, the Oracle BAM Adapter needs to be configured."
},
{
"code": null,
"e": 13130,
"s": 12981,
"text": "The Client BPEL Process sends a message to Service BPEL Process and the Service BPEL Process is not required to reply as shown in the figure below −"
},
{
"code": null,
"e": 13205,
"s": 13130,
"text": "The Client BPEL Process needs a valid partner link and an invoke activity."
},
{
"code": null,
"e": 13280,
"s": 13205,
"text": "The Client BPEL Process needs a valid partner link and an invoke activity."
},
{
"code": null,
"e": 13331,
"s": 13280,
"text": "The Service BPEL Process needs a receive activity."
},
{
"code": null,
"e": 13382,
"s": 13331,
"text": "The Service BPEL Process needs a receive activity."
},
{
"code": null,
"e": 13522,
"s": 13382,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 13662,
"s": 13522,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 13907,
"s": 13662,
"text": "<wsdl:portType name = \"BPELProcess\">\n <wsdl:operation name = \"process\">\n <wsdl:input message = \"client:BPELProcessRequestMessage\" />\n <wsdl:output message = \"client:BPELProcessResponseMessage\"/>\n </wsdl:operation>\n</wsdl:portType>"
},
{
"code": null,
"e": 14242,
"s": 13907,
"text": "The Client BPEL Process sends a request to the Service BPEL Process (d1 in the below figure), and receives an immediate reply (d2 in the below figure). For example, a user requests a subscription to an online application form for admission to a college and immediately receives email confirmation that their request has been accepted."
},
{
"code": null,
"e": 14362,
"s": 14242,
"text": "The Client BPEL Process needs an invoke activity. The port on the client side sends the request and receives the reply."
},
{
"code": null,
"e": 14482,
"s": 14362,
"text": "The Client BPEL Process needs an invoke activity. The port on the client side sends the request and receives the reply."
},
{
"code": null,
"e": 14703,
"s": 14482,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request, and a reply activity to return either the requested information or an error message (a fault; f1 in the below figure) defined in the WSDL."
},
{
"code": null,
"e": 14924,
"s": 14703,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request, and a reply activity to return either the requested information or an error message (a fault; f1 in the below figure) defined in the WSDL."
},
{
"code": null,
"e": 15064,
"s": 14924,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 15204,
"s": 15064,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 15214,
"s": 15204,
"text": "WSDL File"
},
{
"code": null,
"e": 15459,
"s": 15214,
"text": "<wsdl:portType name = \"BPELProcess\">\n <wsdl:operation name = \"process\">\n <wsdl:input message = \"client:BPELProcessRequestMessage\" />\n <wsdl:output message = \"client:BPELProcessResponseMessage\"/>\n </wsdl:operation>\n</wsdl:portType>"
},
{
"code": null,
"e": 15627,
"s": 15459,
"text": "The Client BPEL Process sends a request to the Service BPEL Process (d1 in the figure given below), and waits until the service replies (d2 in the figure given below)."
},
{
"code": null,
"e": 15811,
"s": 15627,
"text": "For example, a user requests a subscription to an online application form for admission to a college and the request cannot be confirmed unless it is accepted at the admission office."
},
{
"code": null,
"e": 15925,
"s": 15811,
"text": "The Client BPEL Process needs an invoke activity to send the request and a receive activity to receive the reply."
},
{
"code": null,
"e": 16039,
"s": 15925,
"text": "The Client BPEL Process needs an invoke activity to send the request and a receive activity to receive the reply."
},
{
"code": null,
"e": 16421,
"s": 16039,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault.\nNote − The difference between responding from a synchronous and asynchronous BPEL process is that the synchronous service uses a reply activity to respond to the client and an asynchronous service uses an invoke activity.\n"
},
{
"code": null,
"e": 16580,
"s": 16421,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault."
},
{
"code": null,
"e": 16802,
"s": 16580,
"text": "Note − The difference between responding from a synchronous and asynchronous BPEL process is that the synchronous service uses a reply activity to respond to the client and an asynchronous service uses an invoke activity."
},
{
"code": null,
"e": 16942,
"s": 16802,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 17082,
"s": 16942,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction. The WSDL file is as shown below."
},
{
"code": null,
"e": 17092,
"s": 17082,
"text": "WSDL File"
},
{
"code": null,
"e": 17464,
"s": 17092,
"text": "<wsdl:portType name = \"BPELProcess\">\n <wsdl:operation name = \"process\">\n <wsdl:input message = \"client:BPELProcessRequestMessage\"/>\n </wsdl:operation>\n</wsdl:portType>\n\n<wsdl:portType name = \"BPELProcessCallback\">\n <wsdl:operation name = \"processResponse\">\n <wsdl:input message = \"client:BPELProcessResponseMessage\"/>\n </wsdl:operation>\n</wsdl:portType>"
},
{
"code": null,
"e": 17685,
"s": 17464,
"text": "The Client BPEL Process sends a request to the Service BPEL Process (d1 in the below figure), and waits until the service replies or until a certain time limit is reached, whichever comes first. (d2 in the below figure)."
},
{
"code": null,
"e": 17900,
"s": 17685,
"text": "For example, a user requests a subscription to an online application form for admission to a college and the request is cancelled if the user does not receive a confirmation reply within a specified amount of time."
},
{
"code": null,
"e": 18148,
"s": 17900,
"text": "The Client BPEL Process needs an invoke activity to send the request and a pick activity with two branches - an onMessage branch and an onAlarm branch. If the reply comes after the time limit has expired, the message goes to the dead letter queue."
},
{
"code": null,
"e": 18307,
"s": 18148,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault."
},
{
"code": null,
"e": 18414,
"s": 18307,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 18577,
"s": 18414,
"text": "In this chapter, we will learn about asynchronous interactions with a notification timer. Consider the following points related to the asynchronous interactions −"
},
{
"code": null,
"e": 18723,
"s": 18577,
"text": "The Client BPEL Process sends a request to the Service BPEL Process and waits for a reply, although a notification is sent after a timer expires."
},
{
"code": null,
"e": 18869,
"s": 18723,
"text": "The Client BPEL Process sends a request to the Service BPEL Process and waits for a reply, although a notification is sent after a timer expires."
},
{
"code": null,
"e": 18989,
"s": 18869,
"text": "The Client BPEL Process continues to wait for the reply from the Service BPEL Process even after the timer has expired."
},
{
"code": null,
"e": 19109,
"s": 18989,
"text": "The Client BPEL Process continues to wait for the reply from the Service BPEL Process even after the timer has expired."
},
{
"code": null,
"e": 19365,
"s": 19109,
"text": "The Client BPEL Process needs a scope activity containing an invoke activity to send the request, and a receive activity to accept the reply. The onAlarm handler of the scope activity has a time limit and instructions on what to do when the timer expires."
},
{
"code": null,
"e": 19621,
"s": 19365,
"text": "The Client BPEL Process needs a scope activity containing an invoke activity to send the request, and a receive activity to accept the reply. The onAlarm handler of the scope activity has a time limit and instructions on what to do when the timer expires."
},
{
"code": null,
"e": 19731,
"s": 19621,
"text": "For example, wait 60 seconds, then send a warning indicating that the process is taking longer than expected."
},
{
"code": null,
"e": 19841,
"s": 19731,
"text": "For example, wait 60 seconds, then send a warning indicating that the process is taking longer than expected."
},
{
"code": null,
"e": 20000,
"s": 19841,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault."
},
{
"code": null,
"e": 20159,
"s": 20000,
"text": "The Service BPEL Process needs a receive activity to accept the incoming request and an invoke activity to return either the requested information or a fault."
},
{
"code": null,
"e": 20266,
"s": 20159,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 20373,
"s": 20266,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 20461,
"s": 20373,
"text": "In this chapter, we will learn about the concept of One Request and Multiple Responses."
},
{
"code": null,
"e": 20875,
"s": 20461,
"text": "The Client BPEL Process sends a single request to the Service BPEL Process and receives multiple responses in return.\nFor example, the request can be to order a product online, and the first response can be the estimated delivery time, the second response a payment confirmation, and the third response a notification that the product has shipped. In this example, the number and types of responses are expected.\n"
},
{
"code": null,
"e": 20993,
"s": 20875,
"text": "The Client BPEL Process sends a single request to the Service BPEL Process and receives multiple responses in return."
},
{
"code": null,
"e": 21288,
"s": 20993,
"text": "For example, the request can be to order a product online, and the first response can be the estimated delivery time, the second response a payment confirmation, and the third response a notification that the product has shipped. In this example, the number and types of responses are expected."
},
{
"code": null,
"e": 21413,
"s": 21288,
"text": "The Client BPEL Process needs an invoke activity to send the request, and a sequence activity with three receive activities."
},
{
"code": null,
"e": 21538,
"s": 21413,
"text": "The Client BPEL Process needs an invoke activity to send the request, and a sequence activity with three receive activities."
},
{
"code": null,
"e": 21702,
"s": 21538,
"text": "The Service BPEL Process needs a receive activity to accept the message from the client, and a sequence attribute with three invoke activities, one for each reply."
},
{
"code": null,
"e": 21866,
"s": 21702,
"text": "The Service BPEL Process needs a receive activity to accept the message from the client, and a sequence attribute with three invoke activities, one for each reply."
},
{
"code": null,
"e": 21973,
"s": 21866,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 22080,
"s": 21973,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 22179,
"s": 22080,
"text": "In this chapter, we will learn about the concept of one request and one of two possible responses."
},
{
"code": null,
"e": 22443,
"s": 22179,
"text": "The Client BPEL Process sends a single request to the Service BPEL Process and receives one of two possible responses.\nFor example, the request can be to order a product online, and the first response can be either an in-stock message, or an out-of-stock message."
},
{
"code": null,
"e": 22562,
"s": 22443,
"text": "The Client BPEL Process sends a single request to the Service BPEL Process and receives one of two possible responses."
},
{
"code": null,
"e": 22707,
"s": 22562,
"text": "For example, the request can be to order a product online, and the first response can be either an in-stock message, or an out-of-stock message."
},
{
"code": null,
"e": 22753,
"s": 22707,
"text": "The Client BPEL Process needs the following −"
},
{
"code": null,
"e": 22799,
"s": 22753,
"text": "The Client BPEL Process needs the following −"
},
{
"code": null,
"e": 22839,
"s": 22799,
"text": "An invoke activity to send the request."
},
{
"code": null,
"e": 22879,
"s": 22839,
"text": "An invoke activity to send the request."
},
{
"code": null,
"e": 23021,
"s": 22879,
"text": "A pick activity with two branches: one onMessage for the in-stock response and instructions on what to do if an in-stock message is received."
},
{
"code": null,
"e": 23163,
"s": 23021,
"text": "A pick activity with two branches: one onMessage for the in-stock response and instructions on what to do if an in-stock message is received."
},
{
"code": null,
"e": 23283,
"s": 23163,
"text": "A second onMessage for the out-of-stock response and instructions on what to do if an out-of-stock message is received."
},
{
"code": null,
"e": 23403,
"s": 23283,
"text": "A second onMessage for the out-of-stock response and instructions on what to do if an out-of-stock message is received."
},
{
"code": null,
"e": 23723,
"s": 23403,
"text": "The Service BPEL Process needs a receive activity to accept the message from the client, and a switch activity with two branches, one with an invoke activity sending the in-stock message if the item is available, and a second branch with an invoke activity sending the out-of-stock message if the item is not available."
},
{
"code": null,
"e": 24043,
"s": 23723,
"text": "The Service BPEL Process needs a receive activity to accept the message from the client, and a switch activity with two branches, one with an invoke activity sending the in-stock message if the item is available, and a second branch with an invoke activity sending the out-of-stock message if the item is not available."
},
{
"code": null,
"e": 24150,
"s": 24043,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 24262,
"s": 24150,
"text": "In this chapter, we will understand the concept of one request, a mandatory response, and an optional response."
},
{
"code": null,
"e": 24372,
"s": 24262,
"text": "The Client BPEL Service sends a single request to the Service BPEL Process and receives one or two responses."
},
{
"code": null,
"e": 24482,
"s": 24372,
"text": "The Client BPEL Service sends a single request to the Service BPEL Process and receives one or two responses."
},
{
"code": null,
"e": 24686,
"s": 24482,
"text": "Here, the request is to order a product online. If the product is delayed, the service sends a message letting the customer know. In any case, the service always sends a notification when the item ships."
},
{
"code": null,
"e": 24890,
"s": 24686,
"text": "Here, the request is to order a product online. If the product is delayed, the service sends a message letting the customer know. In any case, the service always sends a notification when the item ships."
},
{
"code": null,
"e": 25430,
"s": 24890,
"text": "The Client BPEL Service needs a scope activity containing the invoke activity to send the request, and a receive activity to accept the mandatory reply. For the optional message, the onMessage handler of the scope activity is set along with the instructions on what to do if the optional message is received (for example, notify you that the product has been delayed). The Client BPEL Process waits to receive the mandatory reply. If the mandatory reply is received first, the BPEL Process continues without waiting for the optional reply."
},
{
"code": null,
"e": 25970,
"s": 25430,
"text": "The Client BPEL Service needs a scope activity containing the invoke activity to send the request, and a receive activity to accept the mandatory reply. For the optional message, the onMessage handler of the scope activity is set along with the instructions on what to do if the optional message is received (for example, notify you that the product has been delayed). The Client BPEL Process waits to receive the mandatory reply. If the mandatory reply is received first, the BPEL Process continues without waiting for the optional reply."
},
{
"code": null,
"e": 26281,
"s": 25970,
"text": "The Service BPEL Process needs a scope activity containing the receive activity and an invoke activity to send the mandatory shipping message, and the scope's onAlarm handler to send the optional delayed message if a timer expires (for example, send the delayed message if the item is not shipped in 24 hours)."
},
{
"code": null,
"e": 26592,
"s": 26281,
"text": "The Service BPEL Process needs a scope activity containing the receive activity and an invoke activity to send the mandatory shipping message, and the scope's onAlarm handler to send the optional delayed message if a timer expires (for example, send the delayed message if the item is not shipped in 24 hours)."
},
{
"code": null,
"e": 26699,
"s": 26592,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 26806,
"s": 26699,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 26868,
"s": 26806,
"text": "Now, we will learn the concept of partial processing in BPEL."
},
{
"code": null,
"e": 27018,
"s": 26868,
"text": "The Client BPEL Process sends a request to the Service BPEL Process and receives an immediate response, but processing continues on the service side."
},
{
"code": null,
"e": 27168,
"s": 27018,
"text": "The Client BPEL Process sends a request to the Service BPEL Process and receives an immediate response, but processing continues on the service side."
},
{
"code": null,
"e": 27259,
"s": 27168,
"text": "This pattern can also include multiple shot callbacks, followed by longer-term processing."
},
{
"code": null,
"e": 27350,
"s": 27259,
"text": "This pattern can also include multiple shot callbacks, followed by longer-term processing."
},
{
"code": null,
"e": 27561,
"s": 27350,
"text": "For example, the client sends a request to purchase a vacation package, and the service sends an immediate reply confirming the purchase, then continues to book the hotel, the flight, the rental car, and so on."
},
{
"code": null,
"e": 27772,
"s": 27561,
"text": "For example, the client sends a request to purchase a vacation package, and the service sends an immediate reply confirming the purchase, then continues to book the hotel, the flight, the rental car, and so on."
},
{
"code": null,
"e": 27968,
"s": 27772,
"text": "The Client BPEL Process needs an invoke activity for each request and a receive activity for each reply for asynchronous transactions, or just an invoke activity for each synchronous transaction."
},
{
"code": null,
"e": 28164,
"s": 27968,
"text": "The Client BPEL Process needs an invoke activity for each request and a receive activity for each reply for asynchronous transactions, or just an invoke activity for each synchronous transaction."
},
{
"code": null,
"e": 28521,
"s": 28164,
"text": "The Service BPEL Process needs a receive activity for each request from the client, and an invoke activity for each response. Once the responses are finished, the Service BPEL Process as the service can continue with its processing, using the information gathered in the transaction to perform the necessary tasks without any further input from the client."
},
{
"code": null,
"e": 28878,
"s": 28521,
"text": "The Service BPEL Process needs a receive activity for each request from the client, and an invoke activity for each response. Once the responses are finished, the Service BPEL Process as the service can continue with its processing, using the information gathered in the transaction to perform the necessary tasks without any further input from the client."
},
{
"code": null,
"e": 28985,
"s": 28878,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 29092,
"s": 28985,
"text": "As with all partner activities, the Web Services Description Language (WSDL) file defines the interaction."
},
{
"code": null,
"e": 29177,
"s": 29092,
"text": "We will learn about the multiple application interactions with BPEL in this chapter."
},
{
"code": null,
"e": 29246,
"s": 29177,
"text": "When there are more than two applications involved in a transaction."
},
{
"code": null,
"e": 29315,
"s": 29246,
"text": "When there are more than two applications involved in a transaction."
},
{
"code": null,
"e": 29486,
"s": 29315,
"text": "This A-to-B-to-C-to-A transaction pattern can handle many transactions at the same time. Therefore, a mechanism is required for keeping track of which message goes where."
},
{
"code": null,
"e": 29657,
"s": 29486,
"text": "This A-to-B-to-C-to-A transaction pattern can handle many transactions at the same time. Therefore, a mechanism is required for keeping track of which message goes where."
},
{
"code": null,
"e": 29718,
"s": 29657,
"text": "This can be handled using WS-Addressing or correlation sets."
},
{
"code": null,
"e": 29779,
"s": 29718,
"text": "This can be handled using WS-Addressing or correlation sets."
},
{
"code": null,
"e": 29921,
"s": 29779,
"text": "We have discussed in one of the previous chapters that Synchronous Web Service is one, which provides an immediate response to an invocation."
},
{
"code": null,
"e": 30120,
"s": 29921,
"text": "In the screenshot shown below, we have created a Synchronous BPEL Process which has a receive activity to accept the request from the user. The reply activity simultaneously sends the response back."
},
{
"code": null,
"e": 30243,
"s": 30120,
"text": "As discussed before Asynchronous Web Service is one which sends a request to other web service and waits for the response."
},
{
"code": null,
"e": 30471,
"s": 30243,
"text": "In the screenshot shown below, we have created the Asynchronous BPEL Process which has a receive activity to accept the request from the user. The assign activity further assigns values to the different elements in the request."
},
{
"code": null,
"e": 30614,
"s": 30471,
"text": "Next, the invoke activity invokes the HelloWorld Application which sends the response simultaneously and that is captured in receive activity."
},
{
"code": null,
"e": 30719,
"s": 30614,
"text": "Further, we have the callback activity which finally generates output and sends response asynchronously."
},
{
"code": null,
"e": 30824,
"s": 30719,
"text": "If you double-click the receiveInput or callbackClient, you will see each of them has only one variable."
},
{
"code": null,
"e": 30887,
"s": 30824,
"text": "receiveInput → inputVariable\ncallbackClient → outputVariable \n"
},
{
"code": null,
"e": 30956,
"s": 30887,
"text": "In this chapter, we will understand how parallel flow works in BPEL."
},
{
"code": null,
"e": 31112,
"s": 30956,
"text": "A flow activity typically contains many sequence activities, and each sequence is performed in parallel. A flow activity can also contain other activities."
},
{
"code": null,
"e": 31305,
"s": 31112,
"text": "For example, two asynchronous callbacks execute in parallel, so that one callback does not have to wait for the other to complete first. Each response is stored in a different global variable."
},
{
"code": null,
"e": 31485,
"s": 31305,
"text": "In the flow activity, the BPEL code determines the number of parallel branches. However, often the number of branches required is different depending on the available information."
},
{
"code": null,
"e": 31764,
"s": 31485,
"text": "The flowN activity creates multiple flows equal to the value of N, which is defined at the run time based on the data available and logic within the process. There is an Index variable increment each time a new branch is created, until the index variable reaches the value of N."
},
{
"code": null,
"e": 31917,
"s": 31764,
"text": "The flowN activity performs activities on an arbitrary number of data elements. As the number of elements changes, the BPEL process adjusts accordingly."
},
{
"code": null,
"e": 32165,
"s": 31917,
"text": "The branches created by flowN perform the same activities, but use different data. Each branch uses the index variable to look up input variables. The index variable can be used in the XPath expression to acquire the data specific for that branch."
},
{
"code": null,
"e": 32306,
"s": 32165,
"text": "BPEL applies logic to make choices through conditional branching. The two different actions based on conditional branching are shown below −"
},
{
"code": null,
"e": 32740,
"s": 32306,
"text": "In this method, you set up two or more branches, with each branch in the form of an XPath expression. If the expression is true, then the branch is executed. If the expression is false, then the BPEL process moves to the next branch condition, until it either finds a valid branch condition, encounters an otherwise branch, or runs out of branches. If more than one branch condition is true, then BPEL executes the first true branch."
},
{
"code": null,
"e": 32823,
"s": 32740,
"text": "You can use a while activity to create a while loop to select between two actions."
},
{
"code": null,
"e": 32948,
"s": 32823,
"text": "To understand how to use fault handling, we need to learn the basic architecture of a Service Composite in Oracle SOA Suite."
},
{
"code": null,
"e": 33079,
"s": 32948,
"text": "Service components − BPEL Processes, Business Rule, Human Task, Mediator. These are used to construct a SOA composite application."
},
{
"code": null,
"e": 33210,
"s": 33079,
"text": "Service components − BPEL Processes, Business Rule, Human Task, Mediator. These are used to construct a SOA composite application."
},
{
"code": null,
"e": 33296,
"s": 33210,
"text": "Binding components − Establish connection between a SOA composite and external world."
},
{
"code": null,
"e": 33382,
"s": 33296,
"text": "Binding components − Establish connection between a SOA composite and external world."
},
{
"code": null,
"e": 33447,
"s": 33382,
"text": "Services − Provides an entry point to SOA composite application."
},
{
"code": null,
"e": 33512,
"s": 33447,
"text": "Services − Provides an entry point to SOA composite application."
},
{
"code": null,
"e": 33612,
"s": 33512,
"text": "Binding − Defines the protocols that communicate with the service like SOAP/HTTP, JCA adapter, etc."
},
{
"code": null,
"e": 33712,
"s": 33612,
"text": "Binding − Defines the protocols that communicate with the service like SOAP/HTTP, JCA adapter, etc."
},
{
"code": null,
"e": 33768,
"s": 33712,
"text": "WSDL − Defines the service definition of a web service."
},
{
"code": null,
"e": 33824,
"s": 33768,
"text": "WSDL − Defines the service definition of a web service."
},
{
"code": null,
"e": 33911,
"s": 33824,
"text": "References − Enables a SOA composite application to send messages to external services"
},
{
"code": null,
"e": 33998,
"s": 33911,
"text": "References − Enables a SOA composite application to send messages to external services"
},
{
"code": null,
"e": 34053,
"s": 33998,
"text": "Wires − Enables connection between service components."
},
{
"code": null,
"e": 34108,
"s": 34053,
"text": "Wires − Enables connection between service components."
},
{
"code": null,
"e": 34154,
"s": 34108,
"text": "Let us now see the different types of faults."
},
{
"code": null,
"e": 34380,
"s": 34154,
"text": "Occurs when application executes THROW activity or an INVOKE receives fault as response. Fault name is specified by the BPEL process service component. The fault handler using Fault name and Fault variable catches this fault."
},
{
"code": null,
"e": 34483,
"s": 34380,
"text": "This is thrown by the system. These faults are associated with RunTimeFaultMessage and are included in"
},
{
"code": null,
"e": 34534,
"s": 34483,
"text": "http://schemas.oracle.com/bpel/extensionnamespace."
},
{
"code": null,
"e": 34609,
"s": 34534,
"text": "In this section, we will learn about the different ways of fault handling."
},
{
"code": null,
"e": 34740,
"s": 34609,
"text": "Throw activity explicitly throws the fault. The catch block catches this fault and the corresponding actions get executed thereby."
},
{
"code": null,
"e": 34899,
"s": 34740,
"text": "Using throw activity, you can throw business faults & within the created scope, you can catch this fault and redirect to the caller (consumer) to take action."
},
{
"code": null,
"e": 35058,
"s": 34899,
"text": "Using throw activity, you can throw business faults & within the created scope, you can catch this fault and redirect to the caller (consumer) to take action."
},
{
"code": null,
"e": 35234,
"s": 35058,
"text": "Instead of the above approach, you throw the same fault caught in catch activity of the created scope. In the main scope, you can catch this fault using the catchall activity."
},
{
"code": null,
"e": 35410,
"s": 35234,
"text": "Instead of the above approach, you throw the same fault caught in catch activity of the created scope. In the main scope, you can catch this fault using the catchall activity."
},
{
"code": null,
"e": 35445,
"s": 35410,
"text": "The 2 main files used in EHF are −"
},
{
"code": null,
"e": 35462,
"s": 35445,
"text": "Fault-Policy.xml"
},
{
"code": null,
"e": 35481,
"s": 35462,
"text": "Fault-Bindings.xml"
},
{
"code": null,
"e": 35756,
"s": 35481,
"text": "Whenever the BPEL process throws an error, the EHF will check whether the error exists in Fault-Bindings.xml files. If so, the action in the Fault-Policy.xml file will be taken. If the action is not found, the fault will the thrown and it will be handled in the catch block."
},
{
"code": null,
"e": 35857,
"s": 35756,
"text": "Fault management framework (Fault-Policy.xml and Fault-Bindings.xml) is kept inside a SOA Composite."
},
{
"code": null,
"e": 36007,
"s": 35857,
"text": "Fault-handlers like catch and catchall are inside a BPEL to catch all faults, but fault policies will only be executed when an invoke activity fails."
},
{
"code": null,
"e": 36106,
"s": 36007,
"text": "In this chapter, we will see different scenarios related to the resubmitting of a faulted process."
},
{
"code": null,
"e": 36292,
"s": 36106,
"text": "The BPEL code uses a fault-policy and a fault is handled using the “ora-human-intervention” activity. The fault is then marked as Recoverable and the instance state is set to “Running”."
},
{
"code": null,
"e": 36554,
"s": 36292,
"text": "The BPEL code uses a fault-policy and a fault is caught and re-thrown using the “ora-rethrow-fault” action. The fault is then marked as Recoverable and the instance state is set to “Faulted”; provided the fault is a recoverable one (like URL was not available)."
},
{
"code": null,
"e": 36679,
"s": 36554,
"text": "There are several methods for incorporating Java and Java EE code in BPEL processes. Following are a few important methods −"
},
{
"code": null,
"e": 36734,
"s": 36679,
"text": "Wrap as a Simple Object Access Protocol (SOAP) service"
},
{
"code": null,
"e": 36789,
"s": 36734,
"text": "Wrap as a Simple Object Access Protocol (SOAP) service"
},
{
"code": null,
"e": 36860,
"s": 36789,
"text": "Embed Java code snippets into a BPEL process with the bpelx − exec tag"
},
{
"code": null,
"e": 36931,
"s": 36860,
"text": "Embed Java code snippets into a BPEL process with the bpelx − exec tag"
},
{
"code": null,
"e": 36978,
"s": 36931,
"text": "Use an XML facade to simplify DOM manipulation"
},
{
"code": null,
"e": 37025,
"s": 36978,
"text": "Use an XML facade to simplify DOM manipulation"
},
{
"code": null,
"e": 37059,
"s": 37025,
"text": "Use bpelx − exec built-in methods"
},
{
"code": null,
"e": 37093,
"s": 37059,
"text": "Use bpelx − exec built-in methods"
},
{
"code": null,
"e": 37138,
"s": 37093,
"text": "Use Java code wrapped in a service interface"
},
{
"code": null,
"e": 37183,
"s": 37138,
"text": "Use Java code wrapped in a service interface"
},
{
"code": null,
"e": 37527,
"s": 37183,
"text": "The Java Embedding activity allows us to add activities in a BPEL process. We can write a Java snippet using standard JDK libraries, the BPEL APIs, custom and 3rd party Java Classes included in JAR files in deployed SCA composites (in SCA-INF/lib directory) and Java Classes and libraries available on the Classpath for the SOA Suite run time."
},
{
"code": null,
"e": 37810,
"s": 37527,
"text": "Java Embedding means functionality hidden inside, in a not very decoupled way. The Java code is hard to maintain. By embedding Java in BPEL (XML driven), we start mixing technology, that require different skills as well as expensive XML to Java Object marshalling and unmarshalling."
},
{
"code": null,
"e": 38083,
"s": 37810,
"text": "The best use cases for Java Embedding seems to be for advanced logging/tracing or for special validations/transformations. However, not to replace built in capabilities of the BPEL engine as well as the other components in SOA Suite 11g and the adapters that come with it."
},
{
"code": null,
"e": 38255,
"s": 38083,
"text": "XPath is mainly used to manipulate XMLs in the BPEL process. There are some valuable Xpath functions that can be used for manipulating XML. Let us see the functions below."
},
{
"code": null,
"e": 38344,
"s": 38255,
"text": "This can be used to extract a set of elements from a variable, using a XPath expression."
},
{
"code": null,
"e": 38532,
"s": 38344,
"text": "<bpel:copy>\n <bpel:from>\n <![CDATA[count(bpel:getVariableData(‘$Variable','$partName')/ns:return)]]>\n </bpel:from>\n <bpel:to variable = \"itemNumber\">\n </bpel:to>\n</bpel:copy>"
},
{
"code": null,
"e": 38595,
"s": 38532,
"text": "You can assign boolean values with the XPath boolean function."
},
{
"code": null,
"e": 38811,
"s": 38595,
"text": "<assign>\n <!-- copy from boolean expression function to the variable -->\n <copy>\n <from expression = \"true()\"/>\n <to variable = \"output\" part = \"payload\" query=\"/result/approved\"/>\n </copy>\n</assign>"
},
{
"code": null,
"e": 38977,
"s": 38811,
"text": "You can assign the current value of a date or time field by using the Oracle BPEL XPath function getCurrentDate, getCurrentTime, or getCurrentDateTime, respectively."
},
{
"code": null,
"e": 39220,
"s": 38977,
"text": "<!-- execute the XPath extension function getCurrentDate() -->\n<assign>\n <copy>\n <from expression = \"xpath20:getCurrentDate()\"/>\n <to variable = \"output\" part = \"payload\"\n query = \"/invoice/invoiceDate\"/>\n </copy>\n</assign>"
},
{
"code": null,
"e": 39395,
"s": 39220,
"text": "Rather than copying the value of one string variable (or variable part or field) to another, you can first perform string manipulation, such as concatenating several strings."
},
{
"code": null,
"e": 39674,
"s": 39395,
"text": "<assign>\n <!-- copy from XPath expression to the variable -->\n <copy>\n <from expression = \"concat('Hello ',\n bpws:getVariableData('input', 'payload', '/p:name'))\"/>\n <to variable = \"output\" part = \"payload\" query = \"/p:result/p:message\"/>\n </copy>\n</assign>"
},
{
"code": null,
"e": 39728,
"s": 39674,
"text": "You can assign string literals to a variable in BPEL."
},
{
"code": null,
"e": 39936,
"s": 39728,
"text": "<assign>\n <!-- copy from string expression to the variable -->\n <copy>\n <from expression = \"'GE'\"/>\n <to variable = \"output\" part = \"payload\" query = \"/p:result/p:symbol\"/>\n </copy>\n</assign>"
},
{
"code": null,
"e": 39988,
"s": 39936,
"text": "You can assign numeric values in XPath expressions."
},
{
"code": null,
"e": 40198,
"s": 39988,
"text": "<assign>\n <!-- copy from integer expression to the variable -->\n <copy>\n <from expression = \"100\"/>\n <to variable = \"output\" part = \"payload\" query = \"/p:result/p:quantity\"/>\n </copy>\n</assign>"
},
{
"code": null,
"e": 40266,
"s": 40198,
"text": "Note − A few XSLT functions were used to transform an XML document."
},
{
"code": null,
"e": 40450,
"s": 40266,
"text": "BPEL correlation matches inbound messages with a specific process instance. When you need to associate specific data to a specific instance of a business process, you use correlation."
},
{
"code": null,
"e": 40803,
"s": 40450,
"text": "For example, while creating a process that verifies an account number and checks the account’s credit limit. When verified, the process makes a call to another system to check inventory and, if the item is in stock, generates a purchase order. How does the purchase order know which account is to be debited? The answer to this question is correlation."
},
{
"code": null,
"e": 41037,
"s": 40803,
"text": "Correlation sets are used to uniquely identify process instances. You provide each correlation set with a unique name and then define it by one or more properties. Each property has a name and a type (for example, string or integer)."
},
{
"code": null,
"e": 41205,
"s": 41037,
"text": "The property alias for each property in the correlation set needs to be defined. A property alias is a mapping that binds the property with the input or output values."
},
{
"code": null,
"e": 41303,
"s": 41205,
"text": "Consider the following important points related to the Correlation Sets and Message Aggregation −"
},
{
"code": null,
"e": 41395,
"s": 41303,
"text": "A process that contains more than one receive or pick activity must have a correlation set."
},
{
"code": null,
"e": 41487,
"s": 41395,
"text": "A process that contains more than one receive or pick activity must have a correlation set."
},
{
"code": null,
"e": 41575,
"s": 41487,
"text": "Correlation sets are initialized with values from process inbound or outbound messages."
},
{
"code": null,
"e": 41663,
"s": 41575,
"text": "Correlation sets are initialized with values from process inbound or outbound messages."
},
{
"code": null,
"e": 41805,
"s": 41663,
"text": "If you have groups of messages that are associated together with one specific process, you can set up one or more correlation sets to handle."
},
{
"code": null,
"e": 41947,
"s": 41805,
"text": "If you have groups of messages that are associated together with one specific process, you can set up one or more correlation sets to handle."
},
{
"code": null,
"e": 42524,
"s": 41947,
"text": "Asynchronous web services usually take a long time to return a response and as such, a BPEL process service component must be able to time out, or give up waiting, and continue with the rest of the flow after a certain amount of time. You can use the pick activity to configure a BPEL flow either to wait over a specified amount of time or to continue performing its duties. To set an expiration period for the time, you can use the wait activity. To manage message, events can be used particularly when the business process is waiting for callbacks from partner Web services."
},
{
"code": null,
"e": 42560,
"s": 42524,
"text": "BPEL supports two types of events −"
},
{
"code": null,
"e": 42652,
"s": 42560,
"text": "These events are triggered by incoming messages through operation invocation on port types."
},
{
"code": null,
"e": 42755,
"s": 42652,
"text": "These events are time-related and are triggered either after a certain duration or at a specific time."
},
{
"code": null,
"e": 42854,
"s": 42755,
"text": "Often, however, it is more useful to wait for more than one message, of which only one will occur."
},
{
"code": null,
"e": 42953,
"s": 42854,
"text": "Often, however, it is more useful to wait for more than one message, of which only one will occur."
},
{
"code": null,
"e": 43076,
"s": 42953,
"text": "Alarm events are useful when you want the process to wait for a callback for a certain period of time, such as 15 minutes."
},
{
"code": null,
"e": 43199,
"s": 43076,
"text": "Alarm events are useful when you want the process to wait for a callback for a certain period of time, such as 15 minutes."
},
{
"code": null,
"e": 43267,
"s": 43199,
"text": "If no callback is received, the process flow continues as designed."
},
{
"code": null,
"e": 43335,
"s": 43267,
"text": "If no callback is received, the process flow continues as designed."
},
{
"code": null,
"e": 43461,
"s": 43335,
"text": "Useful in loosely coupled service-oriented architectures, where you cannot rely on Web services being available all the time."
},
{
"code": null,
"e": 43587,
"s": 43461,
"text": "Useful in loosely coupled service-oriented architectures, where you cannot rely on Web services being available all the time."
},
{
"code": null,
"e": 43622,
"s": 43587,
"text": "The pick activity has 2 branches −"
},
{
"code": null,
"e": 43732,
"s": 43622,
"text": "onMessage − the code on this branch is equal to the code for receiving a response before a timeout was added."
},
{
"code": null,
"e": 43842,
"s": 43732,
"text": "onMessage − the code on this branch is equal to the code for receiving a response before a timeout was added."
},
{
"code": null,
"e": 43905,
"s": 43842,
"text": "onAlarm − this condition has code for a timeout of one minute."
},
{
"code": null,
"e": 43968,
"s": 43905,
"text": "onAlarm − this condition has code for a timeout of one minute."
},
{
"code": null,
"e": 44133,
"s": 43968,
"text": "The wait activity allows a process to wait for a given time period or until a time limit has been reached. Exactly one of the expiration criteria must be specified."
},
{
"code": null,
"e": 44247,
"s": 44133,
"text": "The BPEL process can be made use of for notification service. The process can be designed to send the following −"
},
{
"code": null,
"e": 44253,
"s": 44247,
"text": "email"
},
{
"code": null,
"e": 44267,
"s": 44253,
"text": "voice message"
},
{
"code": null,
"e": 44294,
"s": 44267,
"text": "instant messaging (IM), or"
},
{
"code": null,
"e": 44336,
"s": 44294,
"text": "short message service (SMS) notifications"
},
{
"code": null,
"e": 44439,
"s": 44336,
"text": "For the services mentioned above, you can configure the channel for the incoming and outgoing message."
},
{
"code": null,
"e": 44809,
"s": 44439,
"text": "Composite sensors within a SOA application provides the ability to define trackable fields on messages and enables you to find a specific composite instance by searching for a field or fields within a message. For example, a sensor could be defined for an order number within a message, thus allowing us to find the instance where the order number in question is found."
},
{
"code": null,
"e": 44891,
"s": 44809,
"text": "Composite sensors can be defined within a SOA application in several components −"
},
{
"code": null,
"e": 44927,
"s": 44891,
"text": "Service component (exposed service)"
},
{
"code": null,
"e": 44963,
"s": 44927,
"text": "Service component (exposed service)"
},
{
"code": null,
"e": 45004,
"s": 44963,
"text": "Reference component (external reference)"
},
{
"code": null,
"e": 45045,
"s": 45004,
"text": "Reference component (external reference)"
},
{
"code": null,
"e": 45156,
"s": 45045,
"text": "Mediator or BPEL component that have subscribed to a business event (publishing an event cannot have a sensor)"
},
{
"code": null,
"e": 45267,
"s": 45156,
"text": "Mediator or BPEL component that have subscribed to a business event (publishing an event cannot have a sensor)"
},
{
"code": null,
"e": 45323,
"s": 45267,
"text": "There are different ways to define a composite sensor −"
},
{
"code": null,
"e": 45373,
"s": 45323,
"text": "By specifying an existing variable as the sensor."
},
{
"code": null,
"e": 45431,
"s": 45373,
"text": "By an expression with the help of the expression builder."
},
{
"code": null,
"e": 45485,
"s": 45431,
"text": "By using properties (e.g. message header properties)."
},
{
"code": null,
"e": 45585,
"s": 45485,
"text": "Defining a sensor allows for a quick search for data within a composite instance in the EM Console."
},
{
"code": null,
"e": 45672,
"s": 45585,
"text": "In the EM Console dashboard, a user can search for instances by sensor name and value."
},
{
"code": null,
"e": 45798,
"s": 45672,
"text": "In the “Flow Instances” tab, you can select sensors from the dropdowns and can use wildcard-like values for the sensor value."
},
{
"code": null,
"e": 45873,
"s": 45798,
"text": "New Activities have been added in 2.0 which have replaced the ones in 1.1."
},
{
"code": null,
"e": 45985,
"s": 45873,
"text": "This activity helps repeat the set of activities. The activity replaces the FlowN activity in BPEL 1.1 version."
},
{
"code": null,
"e": 46186,
"s": 45985,
"text": "This activity comes of use if the body of an activity must be performed at least once. The XPath expression condition in the repeatUntil activity is evaluated after the body of the activity completes."
},
{
"code": null,
"e": 46430,
"s": 46186,
"text": "This activity replaces the switch activity in BPEL 2.0. The activity enables you to define conditional behavior for specific activities to decide between two or more branches. Only one activity is selected for execution from a set of branches."
},
{
"code": null,
"e": 46488,
"s": 46430,
"text": "This activity helps compensate the specified child scope."
},
{
"code": null,
"e": 46634,
"s": 46488,
"text": "This activity has been added to fault handlers. It enables you to rethrow a fault originally captured by the immediately enclosing fault handler."
},
{
"code": null,
"e": 46641,
"s": 46634,
"text": " Print"
},
{
"code": null,
"e": 46652,
"s": 46641,
"text": " Add Notes"
}
] |
Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1 - GeeksforGeeks
|
11 May, 2021
Given a number n, the task is to print all the numbers less than or equal to n which are perfect cubes as well as the eventual sum of their digits is 1.Examples:
Input: n = 100 Output: 1 64 64 = 6 + 4 = 10 = 1 + 0 = 1 Input: n = 1000 Output: 1 64 343 1000
Approach: For every perfect cube less than or equal to n keep on calculating the sum of its digits until the number is reduced to a single digit ( O(1) approach here ), if this digit is 1 then print the perfect cube else skip to the next perfect cube below n until all the perfect cubes have been considered.Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of the approach#include <cmath>#include <iostream>using namespace std; // Function that returns true if the eventual// digit sum of number nm is 1bool isDigitSumOne(int nm){ //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false;} // Function to print the required numbers// less than nvoid printValidNums(int n){ int cbrt_n = (int)cbrt(n); for (int i = 1; i <= cbrt_n; i++) { int cube = pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) cout << cube << " "; }} // Driver codeint main(){ int n = 1000; printValidNums(n); return 0;}
// Java implementation of the approachclass GFG { // Function that returns true if the eventual // digit sum of number nm is 1 static boolean isDigitSumOne(int nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required numbers // less than n static void printValidNums(int n) { int cbrt_n = (int)Math.cbrt(n); for (int i = 1; i <= cbrt_n; i++) { int cube = (int)Math.pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) System.out.print(cube + " "); } } // Driver code public static void main(String args[]) { int n = 1000; printValidNums(n); }}
# Python3 implementation of the approachimport math # Function that returns true if the eventual# digit sum of number nm is 1def isDigitSumOne(nm) : #if reminder will 1 #then eventual sum is 1 if(nm % 9 == 1): return True else: return False # Function to print the required numbers# less than ndef printValidNums(n): cbrt_n = math.ceil(n**(1./3.)) for i in range(1, cbrt_n + 1): cube = i * i * i if (cube >= 1 and cube <= n and isDigitSumOne(cube)): print(cube, end = " ") # Driver coden = 1000printValidNums(n)
// C# implementation of the approachusing System; class GFG{ // Function that returns true if the // eventual digit sum of number nm is 1 static bool isDigitSumOne(int nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required // numbers less than n static void printValidNums(int n) { int cbrt_n = (int)Math.Ceiling(Math.Pow(n, (double) 1 / 3)); for (int i = 1; i <= cbrt_n; i++) { int cube = (int)Math.Pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) Console.Write(cube + " "); } } // Driver code static public void Main () { int n = 1000; printValidNums(n); }} // This code is contributed by akt_mit
<?php// PHP implementation of the approach // Function that returns true if the// eventual digit sum of number nm is 1function isDigitSumOne($nm){ //if reminder will 1 //then eventual sum is 1 if ($nm % 9 == 1) return true; else return false;} // Function to print the required numbers// less than nfunction printValidNums($n){ $cbrt_n = ceil(pow($n,1/3)); for ($i = 1; $i <= $cbrt_n; $i++) { $cube = pow($i, 3); // If it is the required perfect cube if ($cube >= 1 && $cube <= $n && isDigitSumOne($cube)) echo $cube, " "; }} // Driver code$n = 1000;printValidNums($n); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the approach // Function that returns true if the // eventual digit sum of number nm is 1 function isDigitSumOne(nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required // numbers less than n function printValidNums(n) { let cbrt_n = Math.ceil(Math.pow(n, 1 / 3)); for (let i = 1; i <= cbrt_n; i++) { let cube = Math.pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) document.write(cube + " "); } } let n = 1000; printValidNums(n); </script>
1 64 343 1000
jit_t
ankthon
Chandan_Agrawal
Akanksha_Rai
suresh07
maths-perfect-cube
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Count ways to reach the n'th stair
Add two numbers without using arithmetic operators
Program to add two binary strings
Program to convert a given number to words
Modular multiplicative inverse
|
[
{
"code": null,
"e": 24327,
"s": 24299,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 24491,
"s": 24327,
"text": "Given a number n, the task is to print all the numbers less than or equal to n which are perfect cubes as well as the eventual sum of their digits is 1.Examples: "
},
{
"code": null,
"e": 24587,
"s": 24491,
"text": "Input: n = 100 Output: 1 64 64 = 6 + 4 = 10 = 1 + 0 = 1 Input: n = 1000 Output: 1 64 343 1000 "
},
{
"code": null,
"e": 24949,
"s": 24589,
"text": "Approach: For every perfect cube less than or equal to n keep on calculating the sum of its digits until the number is reduced to a single digit ( O(1) approach here ), if this digit is 1 then print the perfect cube else skip to the next perfect cube below n until all the perfect cubes have been considered.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24953,
"s": 24949,
"text": "C++"
},
{
"code": null,
"e": 24958,
"s": 24953,
"text": "Java"
},
{
"code": null,
"e": 24965,
"s": 24958,
"text": "Python"
},
{
"code": null,
"e": 24968,
"s": 24965,
"text": "C#"
},
{
"code": null,
"e": 24972,
"s": 24968,
"text": "PHP"
},
{
"code": null,
"e": 24983,
"s": 24972,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <cmath>#include <iostream>using namespace std; // Function that returns true if the eventual// digit sum of number nm is 1bool isDigitSumOne(int nm){ //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false;} // Function to print the required numbers// less than nvoid printValidNums(int n){ int cbrt_n = (int)cbrt(n); for (int i = 1; i <= cbrt_n; i++) { int cube = pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) cout << cube << \" \"; }} // Driver codeint main(){ int n = 1000; printValidNums(n); return 0;}",
"e": 25701,
"s": 24983,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function that returns true if the eventual // digit sum of number nm is 1 static boolean isDigitSumOne(int nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required numbers // less than n static void printValidNums(int n) { int cbrt_n = (int)Math.cbrt(n); for (int i = 1; i <= cbrt_n; i++) { int cube = (int)Math.pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) System.out.print(cube + \" \"); } } // Driver code public static void main(String args[]) { int n = 1000; printValidNums(n); }}",
"e": 26536,
"s": 25701,
"text": null
},
{
"code": "# Python3 implementation of the approachimport math # Function that returns true if the eventual# digit sum of number nm is 1def isDigitSumOne(nm) : #if reminder will 1 #then eventual sum is 1 if(nm % 9 == 1): return True else: return False # Function to print the required numbers# less than ndef printValidNums(n): cbrt_n = math.ceil(n**(1./3.)) for i in range(1, cbrt_n + 1): cube = i * i * i if (cube >= 1 and cube <= n and isDigitSumOne(cube)): print(cube, end = \" \") # Driver coden = 1000printValidNums(n)",
"e": 27116,
"s": 26536,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if the // eventual digit sum of number nm is 1 static bool isDigitSumOne(int nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required // numbers less than n static void printValidNums(int n) { int cbrt_n = (int)Math.Ceiling(Math.Pow(n, (double) 1 / 3)); for (int i = 1; i <= cbrt_n; i++) { int cube = (int)Math.Pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) Console.Write(cube + \" \"); } } // Driver code static public void Main () { int n = 1000; printValidNums(n); }} // This code is contributed by akt_mit",
"e": 28083,
"s": 27116,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function that returns true if the// eventual digit sum of number nm is 1function isDigitSumOne($nm){ //if reminder will 1 //then eventual sum is 1 if ($nm % 9 == 1) return true; else return false;} // Function to print the required numbers// less than nfunction printValidNums($n){ $cbrt_n = ceil(pow($n,1/3)); for ($i = 1; $i <= $cbrt_n; $i++) { $cube = pow($i, 3); // If it is the required perfect cube if ($cube >= 1 && $cube <= $n && isDigitSumOne($cube)) echo $cube, \" \"; }} // Driver code$n = 1000;printValidNums($n); // This code is contributed by Ryuga?>",
"e": 28783,
"s": 28083,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns true if the // eventual digit sum of number nm is 1 function isDigitSumOne(nm) { //if reminder will 1 //then eventual sum is 1 if (nm % 9 == 1) return true; else return false; } // Function to print the required // numbers less than n function printValidNums(n) { let cbrt_n = Math.ceil(Math.pow(n, 1 / 3)); for (let i = 1; i <= cbrt_n; i++) { let cube = Math.pow(i, 3); // If it is the required perfect cube if (cube >= 1 && cube <= n && isDigitSumOne(cube)) document.write(cube + \" \"); } } let n = 1000; printValidNums(n); </script>",
"e": 29571,
"s": 28783,
"text": null
},
{
"code": null,
"e": 29585,
"s": 29571,
"text": "1 64 343 1000"
},
{
"code": null,
"e": 29593,
"s": 29587,
"text": "jit_t"
},
{
"code": null,
"e": 29601,
"s": 29593,
"text": "ankthon"
},
{
"code": null,
"e": 29617,
"s": 29601,
"text": "Chandan_Agrawal"
},
{
"code": null,
"e": 29630,
"s": 29617,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29639,
"s": 29630,
"text": "suresh07"
},
{
"code": null,
"e": 29658,
"s": 29639,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 29672,
"s": 29658,
"text": "number-theory"
},
{
"code": null,
"e": 29685,
"s": 29672,
"text": "Mathematical"
},
{
"code": null,
"e": 29699,
"s": 29685,
"text": "number-theory"
},
{
"code": null,
"e": 29712,
"s": 29699,
"text": "Mathematical"
},
{
"code": null,
"e": 29810,
"s": 29712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29819,
"s": 29810,
"text": "Comments"
},
{
"code": null,
"e": 29832,
"s": 29819,
"text": "Old Comments"
},
{
"code": null,
"e": 29877,
"s": 29832,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 29909,
"s": 29877,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29953,
"s": 29909,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29978,
"s": 29953,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30011,
"s": 29978,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30046,
"s": 30011,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30097,
"s": 30046,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 30131,
"s": 30097,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 30174,
"s": 30131,
"text": "Program to convert a given number to words"
}
] |
Computer Programming - Operators
|
An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python.
Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming.
Take a look at the following two examples −
2 + 3
P(x) = x4 + 7x3 - 5x + 9.
These two statements are called arithmetic expressions in a programming language and plus, minus used in these expressions are called arithmetic operators and the values used in these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions produce numerical results.
Similarly, a programming language provides various arithmetic operators. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Following is a simple example of C Programming to understand the above mathematical operators −
#include <stdio.h>
int main() {
int a, b, c;
a = 10;
b = 20;
c = a + b;
printf( "Value of c = %d\n", c);
c = a - b;
printf( "Value of c = %d\n", c);
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
}
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
Consider a situation where we create two variables and assign them some values as follows −
A = 20
B = 10
Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −
(A > B)
Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Here, we will show you one example of C Programming which makes use of if conditional statement. Though this statement will be discussed later in a separate chapter, but in short, we use if statement to check a condition and if the condition is true, then the body of if statement is executed, otherwise the body of if statement is skipped.
#include <stdio.h>
int main() {
int a, b;
a = 10;
b = 20;
/* Here we check whether a is equal to 10 or not */
if( a == 10 ) {
/* if a is equal to 10 then this body will be executed */
printf( "a is equal to 10\n");
}
/* Here we check whether b is equal to 10 or not */
if( b == 10 ) {
/* if b is equal to 10 then this body will be executed */
printf( "b is equal to 10\n");
}
/* Here we check if a is less b than or not */
if( a < b ) {
/* if a is less than b then this body will be executed */
printf( "a is less than b\n");
}
/* Here we check whether a and b are not equal */
if( a != b ) {
/* if a is not equal to b then this body will be executed */
printf( "a is not equal to b\n");
}
}
When the above program is executed, it produces the following result −
a is equal to 10
a is less than b
a is not equal to b
Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result.
The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −
Try the following example to understand all the logical operators available in C programming language −
#include <stdio.h>
int main() {
int a = 1;
int b = 0;
if ( a && b ) {
printf("This will never print because condition is false\n" );
}
if ( a || b ) {
printf("This will be printed print because condition is true\n" );
}
if ( !(a && b) ) {
printf("This will be printed print because condition is true\n" );
}
}
When you compile and execute the above program, it produces the following result −
This will be printed print because condition is true
This will be printed print because condition is true
Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
public class DemoJava {
public static void main(String []args) {
int a, b, c;
a = 10;
b = 20;
c = a + b;
System.out.println("Value of c = " + c );
c = a - b;
System.out.println("Value of c = " + c );
c = a * b;
System.out.println("Value of c = " + c );
c = b / a;
System.out.println("Value of c = " + c );
c = b % a;
System.out.println("Value of c = " + c );
if( a == 10 ) {
System.out.println("a is equal to 10" );
}
}
}
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
a is equal to 10
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators.
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
a = 10
b = 20
c = a + b
print "Value of c = ", c
c = a - b
print "Value of c = ", c
c = a * b
print "Value of c = ", c
c = a / b
print "Value of c = ", c
c = a % b
print "Value of c = ", c
if( a == 10 ):
print "a is equal to 10"
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 0
Value of c = 10
a is equal to 10
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2485,
"s": 2140,
"text": "An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python."
},
{
"code": null,
"e": 2917,
"s": 2485,
"text": "Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming."
},
{
"code": null,
"e": 2961,
"s": 2917,
"text": "Take a look at the following two examples −"
},
{
"code": null,
"e": 2996,
"s": 2961,
"text": "2 + 3\n\nP(x) = x4 + 7x3 - 5x + 9. \n"
},
{
"code": null,
"e": 3304,
"s": 2996,
"text": "These two statements are called arithmetic expressions in a programming language and plus, minus used in these expressions are called arithmetic operators and the values used in these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such expressions produce numerical results."
},
{
"code": null,
"e": 3548,
"s": 3304,
"text": "Similarly, a programming language provides various arithmetic operators. The following table lists down a few of the important arithmetic operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 3644,
"s": 3548,
"text": "Following is a simple example of C Programming to understand the above mathematical operators −"
},
{
"code": null,
"e": 4006,
"s": 3644,
"text": "#include <stdio.h>\n\nint main() {\n int a, b, c;\n \n a = 10;\n b = 20;\n \n c = a + b; \n printf( \"Value of c = %d\\n\", c);\n \n c = a - b; \n printf( \"Value of c = %d\\n\", c);\n \n c = a * b; \n printf( \"Value of c = %d\\n\", c);\n \n c = b / a; \n printf( \"Value of c = %d\\n\", c);\n \n c = b % a; \n printf( \"Value of c = %d\\n\", c);\n}"
},
{
"code": null,
"e": 4077,
"s": 4006,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4158,
"s": 4077,
"text": "Value of c = 30\nValue of c = -10\nValue of c = 200\nValue of c = 2\nValue of c = 0\n"
},
{
"code": null,
"e": 4250,
"s": 4158,
"text": "Consider a situation where we create two variables and assign them some values as follows −"
},
{
"code": null,
"e": 4265,
"s": 4250,
"text": "A = 20\nB = 10\n"
},
{
"code": null,
"e": 4505,
"s": 4265,
"text": "Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −"
},
{
"code": null,
"e": 4514,
"s": 4505,
"text": "(A > B)\n"
},
{
"code": null,
"e": 4932,
"s": 4514,
"text": "Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 5273,
"s": 4932,
"text": "Here, we will show you one example of C Programming which makes use of if conditional statement. Though this statement will be discussed later in a separate chapter, but in short, we use if statement to check a condition and if the condition is true, then the body of if statement is executed, otherwise the body of if statement is skipped."
},
{
"code": null,
"e": 6090,
"s": 5273,
"text": "#include <stdio.h>\n\nint main() {\n int a, b;\n \n a = 10;\n b = 20;\n \n /* Here we check whether a is equal to 10 or not */\n if( a == 10 ) {\n\t \n /* if a is equal to 10 then this body will be executed */\n printf( \"a is equal to 10\\n\");\n }\n \n /* Here we check whether b is equal to 10 or not */\n if( b == 10 ) {\n\t\n /* if b is equal to 10 then this body will be executed */\n printf( \"b is equal to 10\\n\");\n }\n \n /* Here we check if a is less b than or not */\n if( a < b ) {\n\t\n /* if a is less than b then this body will be executed */\n printf( \"a is less than b\\n\");\n }\n \n /* Here we check whether a and b are not equal */\n if( a != b ) {\n\t\n /* if a is not equal to b then this body will be executed */\n printf( \"a is not equal to b\\n\");\n }\n}"
},
{
"code": null,
"e": 6161,
"s": 6090,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 6216,
"s": 6161,
"text": "a is equal to 10\na is less than b\na is not equal to b\n"
},
{
"code": null,
"e": 6480,
"s": 6216,
"text": "Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result."
},
{
"code": null,
"e": 6618,
"s": 6480,
"text": "The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −"
},
{
"code": null,
"e": 6722,
"s": 6618,
"text": "Try the following example to understand all the logical operators available in C programming language −"
},
{
"code": null,
"e": 7082,
"s": 6722,
"text": "#include <stdio.h>\n\nint main() {\n int a = 1;\n int b = 0;\n\n if ( a && b ) {\n\t\n printf(\"This will never print because condition is false\\n\" );\n }\n if ( a || b ) {\n\t\n printf(\"This will be printed print because condition is true\\n\" );\n }\n if ( !(a && b) ) {\n\t\n printf(\"This will be printed print because condition is true\\n\" );\n }\n}"
},
{
"code": null,
"e": 7165,
"s": 7082,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 7272,
"s": 7165,
"text": "This will be printed print because condition is true\nThis will be printed print because condition is true\n"
},
{
"code": null,
"e": 7614,
"s": 7272,
"text": "Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −"
},
{
"code": null,
"e": 7748,
"s": 7614,
"text": "You can try to execute the following program to see the output, which must be identical to the result generated by the above example."
},
{
"code": null,
"e": 8321,
"s": 7748,
"text": "public class DemoJava {\n public static void main(String []args) {\n int a, b, c;\n \n a = 10;\n b = 20;\n \n c = a + b; \n System.out.println(\"Value of c = \" + c );\n \n c = a - b;\n System.out.println(\"Value of c = \" + c );\n \n c = a * b; \n System.out.println(\"Value of c = \" + c );\n \n c = b / a; \n System.out.println(\"Value of c = \" + c );\n \n c = b % a; \n System.out.println(\"Value of c = \" + c );\n \n if( a == 10 ) {\n\t\t\n System.out.println(\"a is equal to 10\" );\n }\n }\n}"
},
{
"code": null,
"e": 8392,
"s": 8321,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 8490,
"s": 8392,
"text": "Value of c = 30\nValue of c = -10\nValue of c = 200\nValue of c = 2\nValue of c = 0\na is equal to 10\n"
},
{
"code": null,
"e": 8949,
"s": 8490,
"text": "Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators."
},
{
"code": null,
"e": 9083,
"s": 8949,
"text": "You can try to execute the following program to see the output, which must be identical to the result generated by the above example."
},
{
"code": null,
"e": 9339,
"s": 9083,
"text": "a = 10\nb = 20\n \nc = a + b \nprint \"Value of c = \", c\n\nc = a - b \nprint \"Value of c = \", c\n\nc = a * b \nprint \"Value of c = \", c\n\nc = a / b \nprint \"Value of c = \", c\n\nc = a % b \nprint \"Value of c = \", c\n\nif( a == 10 ):\n print \"a is equal to 10\""
},
{
"code": null,
"e": 9410,
"s": 9339,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 9514,
"s": 9410,
"text": "Value of c = 30\nValue of c = -10\nValue of c = 200\nValue of c = 0\nValue of c = 10\na is equal to 10\n"
},
{
"code": null,
"e": 9551,
"s": 9514,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 9570,
"s": 9551,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9604,
"s": 9570,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 9623,
"s": 9604,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9656,
"s": 9623,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9675,
"s": 9656,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9710,
"s": 9675,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9718,
"s": 9710,
"text": " Shweta"
},
{
"code": null,
"e": 9751,
"s": 9718,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 9768,
"s": 9751,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9801,
"s": 9768,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9823,
"s": 9801,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 9830,
"s": 9823,
"text": " Print"
},
{
"code": null,
"e": 9841,
"s": 9830,
"text": " Add Notes"
}
] |
Validate the ZIP code with Java Regular expressions
|
In order to match the ZIP code using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression.
Declaration − The java.lang.String.matches() method is declared as follows −
public boolean matches(String regex)
Let us see a program which validates the ZIP code with Java Regular Expressions −
Live Demo
public class Example {
public static void main( String[] args ) {
System.out.println(zipIndia("400709"));
System.out.println(zipUS("10060"));
}
// validate zip
public static boolean zipIndia( String z ) {
return z.matches( "\\d{6}" );
}
public static boolean zipUS( String z ) {
return z.matches( "\\d{5}" );
}
}
true
true
|
[
{
"code": null,
"e": 1289,
"s": 1062,
"text": "In order to match the ZIP code using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression."
},
{
"code": null,
"e": 1366,
"s": 1289,
"text": "Declaration − The java.lang.String.matches() method is declared as follows −"
},
{
"code": null,
"e": 1403,
"s": 1366,
"text": "public boolean matches(String regex)"
},
{
"code": null,
"e": 1485,
"s": 1403,
"text": "Let us see a program which validates the ZIP code with Java Regular Expressions −"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": " Live Demo"
},
{
"code": null,
"e": 1854,
"s": 1496,
"text": "public class Example {\n public static void main( String[] args ) {\n System.out.println(zipIndia(\"400709\"));\n System.out.println(zipUS(\"10060\"));\n }\n // validate zip\n public static boolean zipIndia( String z ) {\n return z.matches( \"\\\\d{6}\" );\n }\n public static boolean zipUS( String z ) {\n return z.matches( \"\\\\d{5}\" );\n }\n}"
},
{
"code": null,
"e": 1864,
"s": 1854,
"text": "true\ntrue"
}
] |
How to use XMLPullParser to parse XML in Android using Kotlin?
|
This example demonstrates how to use XMLPullParser to parse XML in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>
Step 3 − Create a Layout resource file (row.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvDesignation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tvName"
android:layout_marginTop="7dp"
android:textColor="#343434"
android:textSize="12sp" />
<TextView
android:id="@+id/tvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tvDesignation"
android:layout_alignBottom="@+id/tvDesignation"
android:layout_alignParentEnd="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp" />
</RelativeLayout>
Step 5 − Create a new asset folder, and inside the asset folder create a Android resource file (model.xml) and add the following code −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<users>
<user>
<name>Sehwag</name>
<designation>Vice Captain</designation>
<loation>Delhi</loation>
</user>
<user>
<name>Ashwin</name>
<designation>Off Spin Bowler</designation>
<loation>Chennai</loation>
</user>
<user>
<name>Dhoni</name>
<designation>Captain</designation>
<loation>Ranchi</loation>
</user>
</users>
</resources>
Step 6 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.io.IOException
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
try {
val userList = ArrayList<java.util.HashMap<String?, String?>>()
var user: HashMap<String?, String?>? = HashMap()
val lv: ListView = findViewById(R.id.listView)
val inputStream = assets.open("model.xml")
val parserFactory: XmlPullParserFactory = XmlPullParserFactory.newInstance()
val parser: XmlPullParser = parserFactory.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true)
parser.setInput(inputStream, null)
var tag: String?
var text = ""
var event = parser.eventType
while (event != XmlPullParser.END_DOCUMENT) {
tag = parser.name
when (event) {
XmlPullParser.START_TAG -> if (tag == "user") user = HashMap()
XmlPullParser.TEXT −> text = parser.text
XmlPullParser.END_TAG −> when (tag) {
"name" −> user!!["name"] = text
"designation" −> user!!["designation"] = text
"location" −> user!!["location"] = text
"user" −> if (user != null) userList.add(user)
}
}
event = parser.next()
}
val adapter: ListAdapter = SimpleAdapter(this@MainActivity, userList, R.layout.row,
arrayOf("name", "designation", "location"), intArrayOf(R.id.tvName,
R.id.tvDesignation, R.id.tvLocation))
lv.adapter = adapter
} catch (e: IOException) {
e.printStackTrace()
} catch (e: XmlPullParserException) {
e.printStackTrace()
}
}
}
Step 6 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "This example demonstrates how to use XMLPullParser to parse XML in Android using Kotlin."
},
{
"code": null,
"e": 1280,
"s": 1151,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1345,
"s": 1280,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1752,
"s": 1345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:dividerHeight=\"1dp\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1830,
"s": 1752,
"text": "Step 3 − Create a Layout resource file (row.xml) and add the following code −"
},
{
"code": null,
"e": 2973,
"s": 1830,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\">\n <TextView\n android:id=\"@+id/tvName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/tvDesignation\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/tvName\"\n android:layout_marginTop=\"7dp\"\n android:textColor=\"#343434\"\n android:textSize=\"12sp\" />\n <TextView\n android:id=\"@+id/tvLocation\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBaseline=\"@+id/tvDesignation\"\n android:layout_alignBottom=\"@+id/tvDesignation\"\n android:layout_alignParentEnd=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3109,
"s": 2973,
"text": "Step 5 − Create a new asset folder, and inside the asset folder create a Android resource file (model.xml) and add the following code −"
},
{
"code": null,
"e": 3562,
"s": 3109,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n<users>\n <user>\n <name>Sehwag</name>\n <designation>Vice Captain</designation>\n <loation>Delhi</loation>\n </user>\n <user>\n <name>Ashwin</name>\n <designation>Off Spin Bowler</designation>\n <loation>Chennai</loation>\n </user>\n <user>\n <name>Dhoni</name>\n <designation>Captain</designation>\n <loation>Ranchi</loation>\n </user>\n</users>\n</resources>"
},
{
"code": null,
"e": 3617,
"s": 3562,
"text": "Step 6 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 5772,
"s": 3617,
"text": "import android.os.Bundle\nimport android.widget.ListAdapter\nimport android.widget.ListView\nimport android.widget.SimpleAdapter\nimport androidx.appcompat.app.AppCompatActivity\nimport org.xmlpull.v1.XmlPullParser\nimport org.xmlpull.v1.XmlPullParserException\nimport org.xmlpull.v1.XmlPullParserFactory\nimport java.io.IOException\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n try {\n val userList = ArrayList<java.util.HashMap<String?, String?>>()\n var user: HashMap<String?, String?>? = HashMap()\n val lv: ListView = findViewById(R.id.listView)\n val inputStream = assets.open(\"model.xml\")\n val parserFactory: XmlPullParserFactory = XmlPullParserFactory.newInstance()\n val parser: XmlPullParser = parserFactory.newPullParser()\n parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true)\n parser.setInput(inputStream, null)\n var tag: String?\n var text = \"\"\n var event = parser.eventType\n while (event != XmlPullParser.END_DOCUMENT) {\n tag = parser.name\n when (event) {\n XmlPullParser.START_TAG -> if (tag == \"user\") user = HashMap()\n XmlPullParser.TEXT −> text = parser.text\n XmlPullParser.END_TAG −> when (tag) {\n \"name\" −> user!![\"name\"] = text\n \"designation\" −> user!![\"designation\"] = text\n \"location\" −> user!![\"location\"] = text\n \"user\" −> if (user != null) userList.add(user)\n }\n }\n event = parser.next()\n }\n val adapter: ListAdapter = SimpleAdapter(this@MainActivity, userList, R.layout.row,\n arrayOf(\"name\", \"designation\", \"location\"), intArrayOf(R.id.tvName,\n R.id.tvDesignation, R.id.tvLocation))\n lv.adapter = adapter\n } catch (e: IOException) {\n e.printStackTrace()\n } catch (e: XmlPullParserException) {\n e.printStackTrace()\n }\n }\n}"
},
{
"code": null,
"e": 5827,
"s": 5772,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6498,
"s": 5827,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6846,
"s": 6498,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Quickly Transfer a Kaggle dataset into a Google bucket | by Alex Federation | Towards Data Science
|
15 days. I was shocked at how long it was going to take to upload a relatively small (20GB) image dataset from my local machine to a Google Cloud Platform (GCP) bucket.
In this article, I’ll go through the alternative approach that shortened this process to a 2-hour operation using a GCP Virtual Machine (VM). The key is creating a VM in the same zone as your bucket, downloading the file there and then transferring it to the bucket.
If you don’t have a bucket, go set that up first, and remember what zone you decide to use. You can use all the standard settings without issue.
The next step was to create a VM. I went with 4 cores, so we could take advantage of the multiprocessing option during the image transfer. Other than that, it was a pretty standard set-up, keeping all the defaults. The exceptions were expanding startup disk to 100 GB to accommodate the unzipped data and using Ubuntu 18 LTS, just a personal preference.
Once the VM spun up, I connected with the ssh tool provided by the Google CLI (which you may need to install on your local machine)
gcloud compute ssh --project [NAME OF YOUR PROJECT] --zone [ZONE NAME] [NAME OF VM]
Once on the VM, I installed pip and the kaggle API.
## Install pip> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py> sudo apt-get install python3-distutils> sudo python3 get-pip.py## Install kaggle API> pip install kaggle
In order to download files from Kaggle, you need an API token saved on the VM. You can go into your Kaggle account, download a new token and scp it onto the VM. Once on the VM, create a hidden folder called “.kaggle” and move the key there
On your local machine:
> gcloud compute scp Downloads/kaggle.json kaggle-download:~
On the VM:
> mkdir .kaggle> mv kaggle.json .kaggle
At this point, the Kaggle API should be good to go! Navigate to the competition or dataset you’re interested in and copy the API command into the VM and the download should start. Many of the datasets are zipped, so you’ll need to install the unzip tool and extract the data.
> sudo apt-get install unzip> unzip [DATASET].zip
Then all that’s left is to authenticate your google account on the VM and transfer the data! The -m flag allows us to use multithread processing and the -r recursively transfers everything in the data folder. For me, it took ~2h to run this whole process for ~20GB of data.
> gcloud auth login> gsutil -m cp -r [DATA FOLDER] gs://[BUCKET NAME]
Remember to kill the VM when you finish. I just delete it and spin up a new one whenever I need to download something new. Happy Kaggling!
|
[
{
"code": null,
"e": 341,
"s": 172,
"text": "15 days. I was shocked at how long it was going to take to upload a relatively small (20GB) image dataset from my local machine to a Google Cloud Platform (GCP) bucket."
},
{
"code": null,
"e": 608,
"s": 341,
"text": "In this article, I’ll go through the alternative approach that shortened this process to a 2-hour operation using a GCP Virtual Machine (VM). The key is creating a VM in the same zone as your bucket, downloading the file there and then transferring it to the bucket."
},
{
"code": null,
"e": 753,
"s": 608,
"text": "If you don’t have a bucket, go set that up first, and remember what zone you decide to use. You can use all the standard settings without issue."
},
{
"code": null,
"e": 1107,
"s": 753,
"text": "The next step was to create a VM. I went with 4 cores, so we could take advantage of the multiprocessing option during the image transfer. Other than that, it was a pretty standard set-up, keeping all the defaults. The exceptions were expanding startup disk to 100 GB to accommodate the unzipped data and using Ubuntu 18 LTS, just a personal preference."
},
{
"code": null,
"e": 1239,
"s": 1107,
"text": "Once the VM spun up, I connected with the ssh tool provided by the Google CLI (which you may need to install on your local machine)"
},
{
"code": null,
"e": 1323,
"s": 1239,
"text": "gcloud compute ssh --project [NAME OF YOUR PROJECT] --zone [ZONE NAME] [NAME OF VM]"
},
{
"code": null,
"e": 1375,
"s": 1323,
"text": "Once on the VM, I installed pip and the kaggle API."
},
{
"code": null,
"e": 1553,
"s": 1375,
"text": "## Install pip> curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py> sudo apt-get install python3-distutils> sudo python3 get-pip.py## Install kaggle API> pip install kaggle"
},
{
"code": null,
"e": 1793,
"s": 1553,
"text": "In order to download files from Kaggle, you need an API token saved on the VM. You can go into your Kaggle account, download a new token and scp it onto the VM. Once on the VM, create a hidden folder called “.kaggle” and move the key there"
},
{
"code": null,
"e": 1816,
"s": 1793,
"text": "On your local machine:"
},
{
"code": null,
"e": 1877,
"s": 1816,
"text": "> gcloud compute scp Downloads/kaggle.json kaggle-download:~"
},
{
"code": null,
"e": 1888,
"s": 1877,
"text": "On the VM:"
},
{
"code": null,
"e": 1928,
"s": 1888,
"text": "> mkdir .kaggle> mv kaggle.json .kaggle"
},
{
"code": null,
"e": 2204,
"s": 1928,
"text": "At this point, the Kaggle API should be good to go! Navigate to the competition or dataset you’re interested in and copy the API command into the VM and the download should start. Many of the datasets are zipped, so you’ll need to install the unzip tool and extract the data."
},
{
"code": null,
"e": 2254,
"s": 2204,
"text": "> sudo apt-get install unzip> unzip [DATASET].zip"
},
{
"code": null,
"e": 2528,
"s": 2254,
"text": "Then all that’s left is to authenticate your google account on the VM and transfer the data! The -m flag allows us to use multithread processing and the -r recursively transfers everything in the data folder. For me, it took ~2h to run this whole process for ~20GB of data."
},
{
"code": null,
"e": 2598,
"s": 2528,
"text": "> gcloud auth login> gsutil -m cp -r [DATA FOLDER] gs://[BUCKET NAME]"
}
] |
Bootstrap 4 .card-footer class
|
Use the card-footer class in Bootstrap 4 to set the footer of a Bootstrap card.
Add it using the class −
<div class="card-footer">
Add footer message here
</div>
The card-footer class comes after the card-header and card-body class −
<div class="card">
<div class="card-header">Details</div>
<div class="card-body">Timings: 4PM - 8PM</div>
<div class="card-footer">Reach before 4PM</div>
</div>
You can try to run the following code to implement the card-footer class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Conference</h2>
<div class="card">
<div class="card-header">Details</div>
<div class="card-body">Timings: 4PM - 8PM</div>
<div class="card-footer">Reach before 4PM</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Use the card-footer class in Bootstrap 4 to set the footer of a Bootstrap card."
},
{
"code": null,
"e": 1167,
"s": 1142,
"text": "Add it using the class −"
},
{
"code": null,
"e": 1226,
"s": 1167,
"text": "<div class=\"card-footer\">\n Add footer message here\n</div>"
},
{
"code": null,
"e": 1298,
"s": 1226,
"text": "The card-footer class comes after the card-header and card-body class −"
},
{
"code": null,
"e": 1465,
"s": 1298,
"text": "<div class=\"card\">\n <div class=\"card-header\">Details</div>\n <div class=\"card-body\">Timings: 4PM - 8PM</div>\n <div class=\"card-footer\">Reach before 4PM</div>\n</div>"
},
{
"code": null,
"e": 1540,
"s": 1465,
"text": "You can try to run the following code to implement the card-footer class −"
},
{
"code": null,
"e": 1550,
"s": 1540,
"text": "Live Demo"
},
{
"code": null,
"e": 2304,
"s": 1550,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h2>Conference</h2>\n <div class=\"card\">\n <div class=\"card-header\">Details</div>\n <div class=\"card-body\">Timings: 4PM - 8PM</div>\n <div class=\"card-footer\">Reach before 4PM</div>\n </div>\n </div>\n\n</body>\n</html>"
}
] |
XQuery - Environment Setup
|
This chapter elaborates how to set up XQuery library in a local development environment.
We are using an open source standalone XQuery processor Saxon Home Edition (Saxon-HE) which is widely used. This processor supports XSLT 2.0, XQuery 3.0, and XPath 3.0 and is highly optimized for performance. Saxon XQuery processor can be used without having any XML database. We'll use a simple XML document as our database in our examples.
In order to use Saxon XQuery processor, you should have saxon9he.jar, saxon9-test.jar, saxon9-unpack, saxon9-xqj.jar in your application's classpath. These jar files are available in the download file SaxonHE9-6-0-1J.zip Download SaxonHE9-6-0-1J.zip.
We'll use the Java-based Saxon XQuery processor to test books.xqy, a file containing XQuery expression against our sample XML document, i.e., books.xml.
In this example, we'll see how to write and process a query to get the title elements of the books whose price is greater than 30.
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
package com.tutorialspoint.xquery;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import com.saxonica.xqj.SaxonXQDataSource;
public class XQueryTester {
public static void main(String[] args){
try {
execute();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (XQException e) {
e.printStackTrace();
}
}
private static void execute() throws FileNotFoundException, XQException{
InputStream inputStream = new FileInputStream(new File("books.xqy"));
XQDataSource ds = new SaxonXQDataSource();
XQConnection conn = ds.getConnection();
XQPreparedExpression exp = conn.prepareExpression(inputStream);
XQResultSequence result = exp.executeQuery();
while (result.next()) {
System.out.println(result.getItemAsString(null));
}
}
}
Step 1 − Copy XQueryTester.java to any location, say, E: > java
Step 1 − Copy XQueryTester.java to any location, say, E: > java
Step 2 − Copy books.xml to the same location, E: > java
Step 2 − Copy books.xml to the same location, E: > java
Step 3 − Copy books.xqy to the same location, E: > java
Step 3 − Copy books.xqy to the same location, E: > java
Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial
Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial
E:\java\javac XQueryTester.java
Step 5 − Execute XQueryTester
Step 5 − Execute XQueryTester
E:\java\java XQueryTester
You'll get the following result −
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
books.xml represents the sample data.
books.xml represents the sample data.
books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter.
books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter.
XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed.
XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1961,
"s": 1872,
"text": "This chapter elaborates how to set up XQuery library in a local development environment."
},
{
"code": null,
"e": 2303,
"s": 1961,
"text": "We are using an open source standalone XQuery processor Saxon Home Edition (Saxon-HE) which is widely used. This processor supports XSLT 2.0, XQuery 3.0, and XPath 3.0 and is highly optimized for performance. Saxon XQuery processor can be used without having any XML database. We'll use a simple XML document as our database in our examples."
},
{
"code": null,
"e": 2554,
"s": 2303,
"text": "In order to use Saxon XQuery processor, you should have saxon9he.jar, saxon9-test.jar, saxon9-unpack, saxon9-xqj.jar in your application's classpath. These jar files are available in the download file SaxonHE9-6-0-1J.zip Download SaxonHE9-6-0-1J.zip."
},
{
"code": null,
"e": 2707,
"s": 2554,
"text": "We'll use the Java-based Saxon XQuery processor to test books.xqy, a file containing XQuery expression against our sample XML document, i.e., books.xml."
},
{
"code": null,
"e": 2838,
"s": 2707,
"text": "In this example, we'll see how to write and process a query to get the title elements of the books whose price is greater than 30."
},
{
"code": null,
"e": 3635,
"s": 2838,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>40.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>"
},
{
"code": null,
"e": 3707,
"s": 3635,
"text": "for $x in doc(\"books.xml\")/books/book\nwhere $x/price>30\nreturn $x/title"
},
{
"code": null,
"e": 4867,
"s": 3707,
"text": "package com.tutorialspoint.xquery;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\n\nimport javax.xml.xquery.XQConnection;\nimport javax.xml.xquery.XQDataSource;\nimport javax.xml.xquery.XQException;\nimport javax.xml.xquery.XQPreparedExpression;\nimport javax.xml.xquery.XQResultSequence;\n\nimport com.saxonica.xqj.SaxonXQDataSource;\n\npublic class XQueryTester {\n public static void main(String[] args){\n try {\n execute();\n }\n \n catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n \n catch (XQException e) {\n e.printStackTrace();\n }\n }\n\n private static void execute() throws FileNotFoundException, XQException{\n InputStream inputStream = new FileInputStream(new File(\"books.xqy\"));\n XQDataSource ds = new SaxonXQDataSource();\n XQConnection conn = ds.getConnection();\n XQPreparedExpression exp = conn.prepareExpression(inputStream);\n XQResultSequence result = exp.executeQuery();\n \n while (result.next()) {\n System.out.println(result.getItemAsString(null));\n }\n }\t\n}"
},
{
"code": null,
"e": 4933,
"s": 4867,
"text": "Step 1 − Copy XQueryTester.java to any location, say, E: > java "
},
{
"code": null,
"e": 4999,
"s": 4933,
"text": "Step 1 − Copy XQueryTester.java to any location, say, E: > java "
},
{
"code": null,
"e": 5057,
"s": 4999,
"text": "Step 2 − Copy books.xml to the same location, E: > java "
},
{
"code": null,
"e": 5115,
"s": 5057,
"text": "Step 2 − Copy books.xml to the same location, E: > java "
},
{
"code": null,
"e": 5173,
"s": 5115,
"text": "Step 3 − Copy books.xqy to the same location, E: > java "
},
{
"code": null,
"e": 5231,
"s": 5173,
"text": "Step 3 − Copy books.xqy to the same location, E: > java "
},
{
"code": null,
"e": 5429,
"s": 5231,
"text": "Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial\n"
},
{
"code": null,
"e": 5626,
"s": 5429,
"text": "Step 4 − Compile XQueryTester.java using console. Make sure you have JDK 1.5 or later installed on your machine and classpaths are configured. For details on how to use JAVA, see our JAVA Tutorial"
},
{
"code": null,
"e": 5659,
"s": 5626,
"text": "E:\\java\\javac XQueryTester.java\n"
},
{
"code": null,
"e": 5690,
"s": 5659,
"text": "Step 5 − Execute XQueryTester\n"
},
{
"code": null,
"e": 5720,
"s": 5690,
"text": "Step 5 − Execute XQueryTester"
},
{
"code": null,
"e": 5747,
"s": 5720,
"text": "E:\\java\\java XQueryTester\n"
},
{
"code": null,
"e": 5781,
"s": 5747,
"text": "You'll get the following result −"
},
{
"code": null,
"e": 5880,
"s": 5781,
"text": "<title lang=\"en\">Learn .Net in 24 hours</title>\n<title lang=\"en\">Learn XQuery in 24 hours</title>\n"
},
{
"code": null,
"e": 5918,
"s": 5880,
"text": "books.xml represents the sample data."
},
{
"code": null,
"e": 5956,
"s": 5918,
"text": "books.xml represents the sample data."
},
{
"code": null,
"e": 6097,
"s": 5956,
"text": "books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter."
},
{
"code": null,
"e": 6238,
"s": 6097,
"text": "books.xqy represents the XQuery expression which is to be executed on books.xml. We'll understand the expression in details in next chapter."
},
{
"code": null,
"e": 6414,
"s": 6238,
"text": "XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed."
},
{
"code": null,
"e": 6590,
"s": 6414,
"text": "XQueryTester, a Java-based XQuery executor program, reads the books.xqy, passes it to the XQuery expression processor, and executes the expression. Then the result is printed."
},
{
"code": null,
"e": 6597,
"s": 6590,
"text": " Print"
},
{
"code": null,
"e": 6608,
"s": 6597,
"text": " Add Notes"
}
] |
Java Program to fill an array with random numbers
|
Let us first crate an array −
double[] arr = new double[5];
Now, create Random class object −
Random randNum = new Random();
Now, fill the above array with random numbers −
for (int i = 0; i < 5; i++) {
arr[i] = randNum.nextInt();
}
Live Demo
import java.util.Arrays;
import java.util.Random;
public class Demo {
public static void main(String args[]) {
double[] arr = new double[5];
Random randNum = new Random();
for (int i = 0; i < 5; i++) {
arr[i] = randNum.nextInt();
}
System.out.println("Random numbers = "+Arrays.toString(arr));
}
}
Random numbers = [-6.59888981E8, 1.141160731E9, -9.931249E8, 1.335266582E9, 8.27918412E8]
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first crate an array −"
},
{
"code": null,
"e": 1122,
"s": 1092,
"text": "double[] arr = new double[5];"
},
{
"code": null,
"e": 1156,
"s": 1122,
"text": "Now, create Random class object −"
},
{
"code": null,
"e": 1187,
"s": 1156,
"text": "Random randNum = new Random();"
},
{
"code": null,
"e": 1235,
"s": 1187,
"text": "Now, fill the above array with random numbers −"
},
{
"code": null,
"e": 1295,
"s": 1235,
"text": "for (int i = 0; i < 5; i++) {\narr[i] = randNum.nextInt();\n}"
},
{
"code": null,
"e": 1306,
"s": 1295,
"text": " Live Demo"
},
{
"code": null,
"e": 1649,
"s": 1306,
"text": "import java.util.Arrays;\nimport java.util.Random;\npublic class Demo {\n public static void main(String args[]) {\n double[] arr = new double[5];\n Random randNum = new Random();\n for (int i = 0; i < 5; i++) {\n arr[i] = randNum.nextInt();\n }\n System.out.println(\"Random numbers = \"+Arrays.toString(arr));\n }\n}"
},
{
"code": null,
"e": 1739,
"s": 1649,
"text": "Random numbers = [-6.59888981E8, 1.141160731E9, -9.931249E8, 1.335266582E9, 8.27918412E8]"
}
] |
Introduction to Statistics in Python | by Donald Le | Towards Data Science
|
Statistics is the discipline that concerns the collection, organization, analysis, interpretation and presentation of data. In applying statistics to a scientific, industrial, or social problem, it is conventional to begin with a statistical population or a statistical model to be studied.
is a central or typical value for a probability distribution. It may also be called a center or location of the distribution. Colloquially, measures of central tendency are often called averages.
is the extent to which a distribution is stretched or squeezed. Common examples of measures of statistical dispersion are the variance, standard deviation, and interquartile range.
or dependence is any statistical relationship, whether causal or not, between two random variables or bivariate data. In the broadest sense correlation is any statistical association, though it commonly refers to the degree to which a pair of variables are linearly related.
which goes by several names, is a phenomenon in probability and statistics, in which a trend appears in several different groups of data but disappears or reverses when these groups are combined.
Data Analytics solutions offer a convenient way to leverage business data. But the number of solutions on the market can be daunting — and many may seem to cover a different category of analytics. How can organizations make sense of it all? Start by understanding the different types of analytics, including descriptive, diagnostic, predictive, and prescriptive analytics.
Descriptive Analytics tells you what happened in the past.
Diagnostic Analytics helps you understand why something happened in the past.
Predictive Analytics predicts what is most likely to happen in the future.
Prescriptive Analytics recommends actions you can take to affect those outcomes.
Imagine we have to do some data analysis with the number of friends for each member of our staffs in the work has. The number of friends will be described in a Python list like below :
num_friends = [100, 49, 41, 40, 25, 100, 100, 100, 41, 41, 49, 59, 25, 25, 4, 4, 4, 4, 4, 4, 10, 10, 10, 10,]
We will display the num_friends in Histogram with matplotlib :
Seeing the histogram would be
mean
We would like to get the mean of number of friends
def mean(x): return sum(x) / len(x)
Apply this method will get the value for number of friends like
35.791666666666664
median
The median is a simple measure of central tendency. To find the median, we arrange the observations in order from smallest to largest value. If there is an odd number of observations, the median is the middle value. If there is an even number of observations, the median is the average of the two middle values.
Apply this method will give us the result
25.0
quantile
A generalization of the median is the quantile, which represents the value less than which a certain percentile of the data lies. (The median represents the value less than which 50% of the data lies.)
def quantile(x, p): """returns the pth-percentile value in x""" p_index = int(p * len(x)) return sorted(x)[p_index]
Apply quantile method with num_friends for the percentile is 0.8 would have result
59
mode (or most common values)
Apply mode method for num_friends will return
[4]
Studying about statistics help us know more about the fundamentals concept of Data Analysis or Data Science in general. There’s a lot more about statistics like Hypothesis testing, Correlation, or Estimation which I have not went over. So feel free to learn more about them.
Data Science from Scratch book — by Joel Grus
|
[
{
"code": null,
"e": 463,
"s": 172,
"text": "Statistics is the discipline that concerns the collection, organization, analysis, interpretation and presentation of data. In applying statistics to a scientific, industrial, or social problem, it is conventional to begin with a statistical population or a statistical model to be studied."
},
{
"code": null,
"e": 659,
"s": 463,
"text": "is a central or typical value for a probability distribution. It may also be called a center or location of the distribution. Colloquially, measures of central tendency are often called averages."
},
{
"code": null,
"e": 840,
"s": 659,
"text": "is the extent to which a distribution is stretched or squeezed. Common examples of measures of statistical dispersion are the variance, standard deviation, and interquartile range."
},
{
"code": null,
"e": 1115,
"s": 840,
"text": "or dependence is any statistical relationship, whether causal or not, between two random variables or bivariate data. In the broadest sense correlation is any statistical association, though it commonly refers to the degree to which a pair of variables are linearly related."
},
{
"code": null,
"e": 1311,
"s": 1115,
"text": "which goes by several names, is a phenomenon in probability and statistics, in which a trend appears in several different groups of data but disappears or reverses when these groups are combined."
},
{
"code": null,
"e": 1684,
"s": 1311,
"text": "Data Analytics solutions offer a convenient way to leverage business data. But the number of solutions on the market can be daunting — and many may seem to cover a different category of analytics. How can organizations make sense of it all? Start by understanding the different types of analytics, including descriptive, diagnostic, predictive, and prescriptive analytics."
},
{
"code": null,
"e": 1743,
"s": 1684,
"text": "Descriptive Analytics tells you what happened in the past."
},
{
"code": null,
"e": 1821,
"s": 1743,
"text": "Diagnostic Analytics helps you understand why something happened in the past."
},
{
"code": null,
"e": 1896,
"s": 1821,
"text": "Predictive Analytics predicts what is most likely to happen in the future."
},
{
"code": null,
"e": 1977,
"s": 1896,
"text": "Prescriptive Analytics recommends actions you can take to affect those outcomes."
},
{
"code": null,
"e": 2162,
"s": 1977,
"text": "Imagine we have to do some data analysis with the number of friends for each member of our staffs in the work has. The number of friends will be described in a Python list like below :"
},
{
"code": null,
"e": 2272,
"s": 2162,
"text": "num_friends = [100, 49, 41, 40, 25, 100, 100, 100, 41, 41, 49, 59, 25, 25, 4, 4, 4, 4, 4, 4, 10, 10, 10, 10,]"
},
{
"code": null,
"e": 2335,
"s": 2272,
"text": "We will display the num_friends in Histogram with matplotlib :"
},
{
"code": null,
"e": 2365,
"s": 2335,
"text": "Seeing the histogram would be"
},
{
"code": null,
"e": 2370,
"s": 2365,
"text": "mean"
},
{
"code": null,
"e": 2421,
"s": 2370,
"text": "We would like to get the mean of number of friends"
},
{
"code": null,
"e": 2460,
"s": 2421,
"text": "def mean(x): return sum(x) / len(x)"
},
{
"code": null,
"e": 2524,
"s": 2460,
"text": "Apply this method will get the value for number of friends like"
},
{
"code": null,
"e": 2543,
"s": 2524,
"text": "35.791666666666664"
},
{
"code": null,
"e": 2550,
"s": 2543,
"text": "median"
},
{
"code": null,
"e": 2862,
"s": 2550,
"text": "The median is a simple measure of central tendency. To find the median, we arrange the observations in order from smallest to largest value. If there is an odd number of observations, the median is the middle value. If there is an even number of observations, the median is the average of the two middle values."
},
{
"code": null,
"e": 2904,
"s": 2862,
"text": "Apply this method will give us the result"
},
{
"code": null,
"e": 2909,
"s": 2904,
"text": "25.0"
},
{
"code": null,
"e": 2918,
"s": 2909,
"text": "quantile"
},
{
"code": null,
"e": 3120,
"s": 2918,
"text": "A generalization of the median is the quantile, which represents the value less than which a certain percentile of the data lies. (The median represents the value less than which 50% of the data lies.)"
},
{
"code": null,
"e": 3245,
"s": 3120,
"text": "def quantile(x, p): \"\"\"returns the pth-percentile value in x\"\"\" p_index = int(p * len(x)) return sorted(x)[p_index]"
},
{
"code": null,
"e": 3328,
"s": 3245,
"text": "Apply quantile method with num_friends for the percentile is 0.8 would have result"
},
{
"code": null,
"e": 3331,
"s": 3328,
"text": "59"
},
{
"code": null,
"e": 3360,
"s": 3331,
"text": "mode (or most common values)"
},
{
"code": null,
"e": 3406,
"s": 3360,
"text": "Apply mode method for num_friends will return"
},
{
"code": null,
"e": 3410,
"s": 3406,
"text": "[4]"
},
{
"code": null,
"e": 3685,
"s": 3410,
"text": "Studying about statistics help us know more about the fundamentals concept of Data Analysis or Data Science in general. There’s a lot more about statistics like Hypothesis testing, Correlation, or Estimation which I have not went over. So feel free to learn more about them."
}
] |
Minimum Increment / decrement to make array elements equal - GeeksforGeeks
|
26 Apr, 2021
Given an array of integers where . In one operation you can either Increment/Decrement any element by 1. The task is to find the minimum operations needed to be performed on the array elements to make all array elements equal.Examples:
Input : A[] = { 1, 5, 7, 10 }
Output : 11
Increment 1 by 4, 5 by 0.
Decrement 7 by 2, 10 by 5.
New array A = { 5, 5, 5, 5 } with
cost of operations = 4 + 0 + 2 + 5 = 11.
Input : A = { 10, 2, 20 }
Output : 18
Approach:
Sort the array of Integers in increasing order.Now, to make all elements equal with min cost. We will have to make the elements equal to the middle element of this sorted array. So, select the middle value, Let it be K. Note: In case of even numbers of element, we will have to check for the costs of both middle elements and take minimum.If A[i] < K, Increment the element by K – A[i].If A[i] > K, Decrement the element by A[i] – K.Update cost of each operation performed.
Sort the array of Integers in increasing order.
Now, to make all elements equal with min cost. We will have to make the elements equal to the middle element of this sorted array. So, select the middle value, Let it be K. Note: In case of even numbers of element, we will have to check for the costs of both middle elements and take minimum.
If A[i] < K, Increment the element by K – A[i].
If A[i] > K, Decrement the element by A[i] – K.
Update cost of each operation performed.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum Increment or// decrement to make array elements equal#include <bits/stdc++.h>using namespace std; // Function to return minimum operations need// to be make each element of array equalint minCost(int A[], int n){ // Initialize cost to 0 int cost = 0; // Sort the array sort(A, A + n); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += abs(A[i] - K); // Take minimum of two cost cost = min(cost, tempCost); } // Return total cost return cost;} // Driver Codeint main(){ int A[] = { 1, 6, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); cout << minCost(A, n); return 0;}
// Java program to find minimum Increment or// decrement to make array elements equalimport java.util.*;class GfG { // Function to return minimum operations need// to be make each element of array equalstatic int minCost(int A[], int n){ // Initialize cost to 0 int cost = 0; // Sort the array Arrays.sort(A); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += Math.abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += Math.abs(A[i] - K); // Take minimum of two cost cost = Math.min(cost, tempCost); } // Return total cost return cost;} // Driver Codepublic static void main(String[] args){ int A[] = { 1, 6, 7, 10 }; int n = A.length; System.out.println(minCost(A, n));}}
# Python3 program to find minimum Increment or# decrement to make array elements equal # Function to return minimum operations need# to be make each element of array equaldef minCost(A, n): # Initialize cost to 0 cost = 0 # Sort the array A.sort(); # Middle element K = A[int(n / 2)] #Find Cost for i in range(0, n): cost = cost + abs(A[i] - K) # If n, is even. Take minimum of the # Cost obtained by considering both # middle elements if n % 2 == 0: tempCost = 0 K = A[int(n / 2) - 1] # FInd cost again for i in range(0, n): tempCost = tempCost + abs(A[i] - K) # Take minimum of two cost cost = min(cost, tempCost) # Return total cost return cost # Driver codeA = [1, 6, 7, 10]n = len(A) print(minCost(A, n)) # This code is contributed# by Shashank_Sharma
// C# program to find minimum Increment or// decrement to make array elements equalusing System; class GFG { // Function to return minimum operations need// to be make each element of array equalstatic int minCost(int []A, int n){ // Initialize cost to 0 int cost = 0; // Sort the array Array.Sort(A); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += Math.Abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += Math.Abs(A[i] - K); // Take minimum of two cost cost = Math.Min(cost, tempCost); } // Return total cost return cost;} // Driver Codepublic static void Main(String[] args){ int []A = new int []{ 1, 6, 7, 10 }; int n = A.Length; Console.WriteLine(minCost(A, n));}}
<?php// PHP program to find minimum Increment or// decrement to make array elements equal // Function to return minimum operations need// to be make each element of array equalfunction minCost($A, $n){ // Initialize cost to 0 $cost = 0; // Sort the array sort($A); // Middle element $K = $A[$n / 2]; // Find Cost for ($i = 0; $i < $n; ++$i) $cost += abs($A[$i] - $K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if ($n % 2 == 0) { $tempCost = 0; $K = $A[($n / 2) - 1]; // Find cost again for ($i = 0; $i < $n; ++$i) $tempCost += abs($A[$i] - $K); // Take minimum of two cost $cost = min($cost, $tempCost); } // Return total cost return $cost;} // Driver Code$A = array( 1, 6, 7, 10 );$n = sizeof($A);echo minCost($A, $n); // This code is contributed// by Sach_Code?>
<script> // Javascript program to find minimum Increment or// decrement to make array elements equal // Function to return minimum operations need// to be make each element of array equalfunction minCost(A,n){ // Initialize cost to 0 var cost = 0; // Sort the array A.sort(); // Middle element var K = A[parseInt(n/2)]; var i; // Find Cost for (i = 0; i < n; ++i) cost += Math.abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { var tempCost = 0; K = A[parseInt(n / 2) - 1]; // Find cost again for (i = 0; i < n; ++i) tempCost += Math.abs(A[i] - K); // Take minimum of two cost cost = Math.min(cost, tempCost); } // Return total cost return cost;} // Driver Code var A = [1, 6, 7, 10]; var n = A.length; document.write(minCost(A, n)); </script>
10
Time Complexity: O(N*log(N))Further Optimization We can find median in linear time and reduce time complexity to O(N)
Shashank_Sharma
ankita_saini
prerna saini
Sach_Code
bgangwar59
median-finding
Greedy
Mathematical
Sorting
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Coin Change | DP-7
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 25121,
"s": 25093,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 25359,
"s": 25121,
"text": "Given an array of integers where . In one operation you can either Increment/Decrement any element by 1. The task is to find the minimum operations needed to be performed on the array elements to make all array elements equal.Examples: "
},
{
"code": null,
"e": 25569,
"s": 25359,
"text": "Input : A[] = { 1, 5, 7, 10 }\nOutput : 11\nIncrement 1 by 4, 5 by 0.\nDecrement 7 by 2, 10 by 5.\nNew array A = { 5, 5, 5, 5 } with \ncost of operations = 4 + 0 + 2 + 5 = 11.\n\nInput : A = { 10, 2, 20 }\nOutput : 18"
},
{
"code": null,
"e": 25583,
"s": 25571,
"text": "Approach: "
},
{
"code": null,
"e": 26057,
"s": 25583,
"text": "Sort the array of Integers in increasing order.Now, to make all elements equal with min cost. We will have to make the elements equal to the middle element of this sorted array. So, select the middle value, Let it be K. Note: In case of even numbers of element, we will have to check for the costs of both middle elements and take minimum.If A[i] < K, Increment the element by K – A[i].If A[i] > K, Decrement the element by A[i] – K.Update cost of each operation performed."
},
{
"code": null,
"e": 26105,
"s": 26057,
"text": "Sort the array of Integers in increasing order."
},
{
"code": null,
"e": 26398,
"s": 26105,
"text": "Now, to make all elements equal with min cost. We will have to make the elements equal to the middle element of this sorted array. So, select the middle value, Let it be K. Note: In case of even numbers of element, we will have to check for the costs of both middle elements and take minimum."
},
{
"code": null,
"e": 26446,
"s": 26398,
"text": "If A[i] < K, Increment the element by K – A[i]."
},
{
"code": null,
"e": 26494,
"s": 26446,
"text": "If A[i] > K, Decrement the element by A[i] – K."
},
{
"code": null,
"e": 26535,
"s": 26494,
"text": "Update cost of each operation performed."
},
{
"code": null,
"e": 26584,
"s": 26535,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26588,
"s": 26584,
"text": "C++"
},
{
"code": null,
"e": 26593,
"s": 26588,
"text": "Java"
},
{
"code": null,
"e": 26601,
"s": 26593,
"text": "Python3"
},
{
"code": null,
"e": 26604,
"s": 26601,
"text": "C#"
},
{
"code": null,
"e": 26608,
"s": 26604,
"text": "PHP"
},
{
"code": null,
"e": 26619,
"s": 26608,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum Increment or// decrement to make array elements equal#include <bits/stdc++.h>using namespace std; // Function to return minimum operations need// to be make each element of array equalint minCost(int A[], int n){ // Initialize cost to 0 int cost = 0; // Sort the array sort(A, A + n); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += abs(A[i] - K); // Take minimum of two cost cost = min(cost, tempCost); } // Return total cost return cost;} // Driver Codeint main(){ int A[] = { 1, 6, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); cout << minCost(A, n); return 0;}",
"e": 27601,
"s": 26619,
"text": null
},
{
"code": "// Java program to find minimum Increment or// decrement to make array elements equalimport java.util.*;class GfG { // Function to return minimum operations need// to be make each element of array equalstatic int minCost(int A[], int n){ // Initialize cost to 0 int cost = 0; // Sort the array Arrays.sort(A); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += Math.abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += Math.abs(A[i] - K); // Take minimum of two cost cost = Math.min(cost, tempCost); } // Return total cost return cost;} // Driver Codepublic static void main(String[] args){ int A[] = { 1, 6, 7, 10 }; int n = A.length; System.out.println(minCost(A, n));}}",
"e": 28603,
"s": 27601,
"text": null
},
{
"code": "# Python3 program to find minimum Increment or# decrement to make array elements equal # Function to return minimum operations need# to be make each element of array equaldef minCost(A, n): # Initialize cost to 0 cost = 0 # Sort the array A.sort(); # Middle element K = A[int(n / 2)] #Find Cost for i in range(0, n): cost = cost + abs(A[i] - K) # If n, is even. Take minimum of the # Cost obtained by considering both # middle elements if n % 2 == 0: tempCost = 0 K = A[int(n / 2) - 1] # FInd cost again for i in range(0, n): tempCost = tempCost + abs(A[i] - K) # Take minimum of two cost cost = min(cost, tempCost) # Return total cost return cost # Driver codeA = [1, 6, 7, 10]n = len(A) print(minCost(A, n)) # This code is contributed# by Shashank_Sharma",
"e": 29530,
"s": 28603,
"text": null
},
{
"code": "// C# program to find minimum Increment or// decrement to make array elements equalusing System; class GFG { // Function to return minimum operations need// to be make each element of array equalstatic int minCost(int []A, int n){ // Initialize cost to 0 int cost = 0; // Sort the array Array.Sort(A); // Middle element int K = A[n / 2]; // Find Cost for (int i = 0; i < n; ++i) cost += Math.Abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { int tempCost = 0; K = A[(n / 2) - 1]; // Find cost again for (int i = 0; i < n; ++i) tempCost += Math.Abs(A[i] - K); // Take minimum of two cost cost = Math.Min(cost, tempCost); } // Return total cost return cost;} // Driver Codepublic static void Main(String[] args){ int []A = new int []{ 1, 6, 7, 10 }; int n = A.Length; Console.WriteLine(minCost(A, n));}}",
"e": 30537,
"s": 29530,
"text": null
},
{
"code": "<?php// PHP program to find minimum Increment or// decrement to make array elements equal // Function to return minimum operations need// to be make each element of array equalfunction minCost($A, $n){ // Initialize cost to 0 $cost = 0; // Sort the array sort($A); // Middle element $K = $A[$n / 2]; // Find Cost for ($i = 0; $i < $n; ++$i) $cost += abs($A[$i] - $K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if ($n % 2 == 0) { $tempCost = 0; $K = $A[($n / 2) - 1]; // Find cost again for ($i = 0; $i < $n; ++$i) $tempCost += abs($A[$i] - $K); // Take minimum of two cost $cost = min($cost, $tempCost); } // Return total cost return $cost;} // Driver Code$A = array( 1, 6, 7, 10 );$n = sizeof($A);echo minCost($A, $n); // This code is contributed// by Sach_Code?>",
"e": 31469,
"s": 30537,
"text": null
},
{
"code": "<script> // Javascript program to find minimum Increment or// decrement to make array elements equal // Function to return minimum operations need// to be make each element of array equalfunction minCost(A,n){ // Initialize cost to 0 var cost = 0; // Sort the array A.sort(); // Middle element var K = A[parseInt(n/2)]; var i; // Find Cost for (i = 0; i < n; ++i) cost += Math.abs(A[i] - K); // If n, is even. Take minimum of the // Cost obtained by considering both // middle elements if (n % 2 == 0) { var tempCost = 0; K = A[parseInt(n / 2) - 1]; // Find cost again for (i = 0; i < n; ++i) tempCost += Math.abs(A[i] - K); // Take minimum of two cost cost = Math.min(cost, tempCost); } // Return total cost return cost;} // Driver Code var A = [1, 6, 7, 10]; var n = A.length; document.write(minCost(A, n)); </script>",
"e": 32419,
"s": 31469,
"text": null
},
{
"code": null,
"e": 32422,
"s": 32419,
"text": "10"
},
{
"code": null,
"e": 32543,
"s": 32424,
"text": "Time Complexity: O(N*log(N))Further Optimization We can find median in linear time and reduce time complexity to O(N) "
},
{
"code": null,
"e": 32559,
"s": 32543,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 32572,
"s": 32559,
"text": "ankita_saini"
},
{
"code": null,
"e": 32585,
"s": 32572,
"text": "prerna saini"
},
{
"code": null,
"e": 32595,
"s": 32585,
"text": "Sach_Code"
},
{
"code": null,
"e": 32606,
"s": 32595,
"text": "bgangwar59"
},
{
"code": null,
"e": 32621,
"s": 32606,
"text": "median-finding"
},
{
"code": null,
"e": 32628,
"s": 32621,
"text": "Greedy"
},
{
"code": null,
"e": 32641,
"s": 32628,
"text": "Mathematical"
},
{
"code": null,
"e": 32649,
"s": 32641,
"text": "Sorting"
},
{
"code": null,
"e": 32656,
"s": 32649,
"text": "Greedy"
},
{
"code": null,
"e": 32669,
"s": 32656,
"text": "Mathematical"
},
{
"code": null,
"e": 32677,
"s": 32669,
"text": "Sorting"
},
{
"code": null,
"e": 32775,
"s": 32677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32784,
"s": 32775,
"text": "Comments"
},
{
"code": null,
"e": 32797,
"s": 32784,
"text": "Old Comments"
},
{
"code": null,
"e": 32828,
"s": 32797,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 32871,
"s": 32828,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 32890,
"s": 32871,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 32918,
"s": 32890,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 32999,
"s": 32918,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 33029,
"s": 32999,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33044,
"s": 33029,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33087,
"s": 33044,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33106,
"s": 33087,
"text": "Coin Change | DP-7"
}
] |
Java Arrays compare() Method with Examples - GeeksforGeeks
|
29 Dec, 2021
Arrays compare() method in Java comes under the Arrays class and java.util package. This method compares two arrays lexicographically (Dictionary order). There are two different versions of different overloads for Boolean, byte, char, double, float, int, long, short, and Object arrays. This method returns values as per the below-mentioned cases.
It returns 0 if the array is equal to the other array.
It returns a value less than 0 is returned if the array is lexicographically less than the other array in
It returns a value greater than 0 if the array is lexicographically greater than the other array (more characters).
A null array is lexicographically less than a non-null array, and the two arrays are considered equal if both are null so that it will print 0 in this case.
Syntax:
Arrays.compare(array1,array2);
// array1 and array2 are two arrays
Parameters and Return Type: The method compare() accepts an array as parameters with different data types example: string, integer, float, double, long, etc. The return type of this method is an integer. It returns a positive value if the array is lexicographically greater, negative if it is lesser, and 0 if equal.
Exceptions: It usually throws NullPointerException and ClassCastException, and both of these exceptions have different means too.
NullPointerException: The NullPointerException is a runtime exception that refers to null and occurs when a variable is accessed that does not point to any object.
ClassCastException: This exception occurs when we’re trying to convert one class object into another class-type object.
If we want to invoke this method, First import the “Arrays” class from JavaJava. util packages just by adding the “import java.util.Arrays” command. then invoke method by “Arrays” follow “.compare(parameter1,parameter2);” by this you can invoke compare() method easily.
Example 1: Let’s take an example, First import java.util.Arrays, create a public class named CompareExample, then Initialize two integer arrays with elements, compare them using the compare() method, and finally print the result from the compare method.
Java
import java.util.Arrays; public class CompareExample{ public static void main(String[] args) { //Initialized two integer array int[] array1 ={6, 7, 8, 11, 18, 8, 2, 5}; int[] array2 ={3, 5, 9, 13, 28, 6, 8, 9}; //compare both integer array using compare method and finally print result System.out.println("Result is "+ Arrays.compare(array1,array2)); }}
Result is 1
Hence the desired output is 1 because array1 is lexicographically greater than array2.
Example 2: Let’s take another example, In this example, we’ll take an array of different data types, and that is float, and do the same as we did in the example as mentioned above, first import class, create a new class named “CompareExample” then initialize two floating type array with elements then compare them using compare method of array class and finally print the result we got.
Java
// import Arrays class from java.util packageimport java.util.Arrays; public class CompareExample{ public static void main(String[] args) { // Initialize two float array with element float[] floatArray1={5.12f, 8.3f, 9.17f, 2.5f, 8.8f, 5.17f, 4.2f, 7.37f}; float[] floatArray2={7.12f, 9.3f, 6.17f, 7.5f, 5.8f, 7.17f, 3.2f, 6.37f}; // compare two float array using compare method and finally print result System.out.println("Result is " + Arrays.compare(floatArray1, floatArray2)); }}
Result is -1
The result is -1 in output because floatArray1 is lexicographically less than floatArray2.
Example 3: Let’s take an example. In this, we’ll initialize an array with the same numbers and size. Then compare array1 and array2 and finally prints the result we got from compare method.
Java
import java.util.Arrays; public class CompareExample { public static void main(String[] args) { // Initialize two integer array with same elements int[] array1 = { 1, 2, 3, 4 }; int[] array2 = { 1, 2, 3, 4 }; // compare array1 and array2 using compare() method // and print the result System.out.println( "Result is " + Arrays.compare(array1, array2)); }}
Result is 0
The desired output is 0 because we are given two integer arrays with the same numbers and size.
In this article, we’ve learned how to use the compare() method. If array1 is lexicographically greater than array2, it will return a positive(-ve) value. If array1 is lexicographically less than array2, it will return a negative(-ve) value. If both the array is lexicographically equal or null, then it will return 0.
surindertarika1234
Java-Arrays
Java-Functions
Picked
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
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java
|
[
{
"code": null,
"e": 23894,
"s": 23866,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 24243,
"s": 23894,
"text": "Arrays compare() method in Java comes under the Arrays class and java.util package. This method compares two arrays lexicographically (Dictionary order). There are two different versions of different overloads for Boolean, byte, char, double, float, int, long, short, and Object arrays. This method returns values as per the below-mentioned cases. "
},
{
"code": null,
"e": 24298,
"s": 24243,
"text": "It returns 0 if the array is equal to the other array."
},
{
"code": null,
"e": 24405,
"s": 24298,
"text": "It returns a value less than 0 is returned if the array is lexicographically less than the other array in"
},
{
"code": null,
"e": 24521,
"s": 24405,
"text": "It returns a value greater than 0 if the array is lexicographically greater than the other array (more characters)."
},
{
"code": null,
"e": 24678,
"s": 24521,
"text": "A null array is lexicographically less than a non-null array, and the two arrays are considered equal if both are null so that it will print 0 in this case."
},
{
"code": null,
"e": 24686,
"s": 24678,
"text": "Syntax:"
},
{
"code": null,
"e": 24753,
"s": 24686,
"text": "Arrays.compare(array1,array2);\n// array1 and array2 are two arrays"
},
{
"code": null,
"e": 25071,
"s": 24753,
"text": "Parameters and Return Type: The method compare() accepts an array as parameters with different data types example: string, integer, float, double, long, etc. The return type of this method is an integer. It returns a positive value if the array is lexicographically greater, negative if it is lesser, and 0 if equal. "
},
{
"code": null,
"e": 25201,
"s": 25071,
"text": "Exceptions: It usually throws NullPointerException and ClassCastException, and both of these exceptions have different means too."
},
{
"code": null,
"e": 25365,
"s": 25201,
"text": "NullPointerException: The NullPointerException is a runtime exception that refers to null and occurs when a variable is accessed that does not point to any object."
},
{
"code": null,
"e": 25485,
"s": 25365,
"text": "ClassCastException: This exception occurs when we’re trying to convert one class object into another class-type object."
},
{
"code": null,
"e": 25757,
"s": 25485,
"text": "If we want to invoke this method, First import the “Arrays” class from JavaJava. util packages just by adding the “import java.util.Arrays” command. then invoke method by “Arrays” follow “.compare(parameter1,parameter2);” by this you can invoke compare() method easily. "
},
{
"code": null,
"e": 26012,
"s": 25757,
"text": "Example 1: Let’s take an example, First import java.util.Arrays, create a public class named CompareExample, then Initialize two integer arrays with elements, compare them using the compare() method, and finally print the result from the compare method. "
},
{
"code": null,
"e": 26017,
"s": 26012,
"text": "Java"
},
{
"code": "import java.util.Arrays; public class CompareExample{ public static void main(String[] args) { //Initialized two integer array int[] array1 ={6, 7, 8, 11, 18, 8, 2, 5}; int[] array2 ={3, 5, 9, 13, 28, 6, 8, 9}; //compare both integer array using compare method and finally print result System.out.println(\"Result is \"+ Arrays.compare(array1,array2)); }}",
"e": 26429,
"s": 26017,
"text": null
},
{
"code": null,
"e": 26441,
"s": 26429,
"text": "Result is 1"
},
{
"code": null,
"e": 26528,
"s": 26441,
"text": "Hence the desired output is 1 because array1 is lexicographically greater than array2."
},
{
"code": null,
"e": 26916,
"s": 26528,
"text": "Example 2: Let’s take another example, In this example, we’ll take an array of different data types, and that is float, and do the same as we did in the example as mentioned above, first import class, create a new class named “CompareExample” then initialize two floating type array with elements then compare them using compare method of array class and finally print the result we got."
},
{
"code": null,
"e": 26921,
"s": 26916,
"text": "Java"
},
{
"code": "// import Arrays class from java.util packageimport java.util.Arrays; public class CompareExample{ public static void main(String[] args) { // Initialize two float array with element float[] floatArray1={5.12f, 8.3f, 9.17f, 2.5f, 8.8f, 5.17f, 4.2f, 7.37f}; float[] floatArray2={7.12f, 9.3f, 6.17f, 7.5f, 5.8f, 7.17f, 3.2f, 6.37f}; // compare two float array using compare method and finally print result System.out.println(\"Result is \" + Arrays.compare(floatArray1, floatArray2)); }}",
"e": 27460,
"s": 26921,
"text": null
},
{
"code": null,
"e": 27473,
"s": 27460,
"text": "Result is -1"
},
{
"code": null,
"e": 27564,
"s": 27473,
"text": "The result is -1 in output because floatArray1 is lexicographically less than floatArray2."
},
{
"code": null,
"e": 27755,
"s": 27564,
"text": "Example 3: Let’s take an example. In this, we’ll initialize an array with the same numbers and size. Then compare array1 and array2 and finally prints the result we got from compare method. "
},
{
"code": null,
"e": 27760,
"s": 27755,
"text": "Java"
},
{
"code": "import java.util.Arrays; public class CompareExample { public static void main(String[] args) { // Initialize two integer array with same elements int[] array1 = { 1, 2, 3, 4 }; int[] array2 = { 1, 2, 3, 4 }; // compare array1 and array2 using compare() method // and print the result System.out.println( \"Result is \" + Arrays.compare(array1, array2)); }}",
"e": 28186,
"s": 27760,
"text": null
},
{
"code": null,
"e": 28198,
"s": 28186,
"text": "Result is 0"
},
{
"code": null,
"e": 28294,
"s": 28198,
"text": "The desired output is 0 because we are given two integer arrays with the same numbers and size."
},
{
"code": null,
"e": 28612,
"s": 28294,
"text": "In this article, we’ve learned how to use the compare() method. If array1 is lexicographically greater than array2, it will return a positive(-ve) value. If array1 is lexicographically less than array2, it will return a negative(-ve) value. If both the array is lexicographically equal or null, then it will return 0."
},
{
"code": null,
"e": 28631,
"s": 28612,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28643,
"s": 28631,
"text": "Java-Arrays"
},
{
"code": null,
"e": 28658,
"s": 28643,
"text": "Java-Functions"
},
{
"code": null,
"e": 28665,
"s": 28658,
"text": "Picked"
},
{
"code": null,
"e": 28670,
"s": 28665,
"text": "Java"
},
{
"code": null,
"e": 28675,
"s": 28670,
"text": "Java"
},
{
"code": null,
"e": 28773,
"s": 28675,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28782,
"s": 28773,
"text": "Comments"
},
{
"code": null,
"e": 28795,
"s": 28782,
"text": "Old Comments"
},
{
"code": null,
"e": 28841,
"s": 28795,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28862,
"s": 28841,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28877,
"s": 28862,
"text": "Stream In Java"
},
{
"code": null,
"e": 28896,
"s": 28877,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28913,
"s": 28896,
"text": "Generics in Java"
},
{
"code": null,
"e": 28956,
"s": 28913,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28998,
"s": 28956,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 29027,
"s": 28998,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 29057,
"s": 29027,
"text": "Functional Interfaces in Java"
}
] |
CBSE Class 12 | Computer Science - Python Syllabus - GeeksforGeeks
|
04 Sep, 2018
Computer ScienceCLASS-XII (Code No. 083)Optional for the academic year 2019-20 and mandatory for the academic year 2020-21 onwards
1. Prerequisites: Computer Science- Class XI
2. Learning Outcomes:
Understand the concept of functions and recursion.Learn how to create and use Python libraries.Learn file handling.Learn about the concept of efficiency in algorithms and computing in general.Learn basic data structures: lists, stacks, and queues.Get a basic understanding of computer networks: network stack, basic network hardware, basic protocols, and basic tools.Connect a Python program with an SQL database, and learn aggregation functions in SQL.Have a clear understanding of cyber ethics and cybercrime. Understand the value of technology in societies, gender and disability issues, and the technology behind biometric ids.
Understand the concept of functions and recursion.
Learn how to create and use Python libraries.
Learn file handling.
Learn about the concept of efficiency in algorithms and computing in general.
Learn basic data structures: lists, stacks, and queues.
Get a basic understanding of computer networks: network stack, basic network hardware, basic protocols, and basic tools.
Connect a Python program with an SQL database, and learn aggregation functions in SQL.
Have a clear understanding of cyber ethics and cybercrime. Understand the value of technology in societies, gender and disability issues, and the technology behind biometric ids.
3. Distribution of Marks
UnitNo. Unit Name Marks
1. Programming and Computational Thinking–2 30
2. Computer Networks 15
3. Data Management–2 15
4. Society, Law and Ethics–2 10
5. Practicals 30
Total 100
4.1 Unit 1: Programming and Computational Thinking (PCT-2) (80 Theory + 70 Practical)Revision of the basics of PythonFunctions: scope, parameter passing, mutable/immutable properties of data objects, pass arrays to functions, return values, functions using libraries: mathematical, and string functions.File handling: open and close a file, read, write, and append to a file, standard input, output, and error streams, relative and absolute paths.Using Python libraries: create and import Python librariesRecursion: simple algorithms with recursion: factorial, Fibonacci numbers; recursion on arrays: binary searchIdea of efficiency: performance defined as inversely proportional to the wall clock time, count the number of operations a piece of code is performing, and measure the time taken by a program. Example: take two different programs for the same problem, and understand how the efficient one takes less time.Data visualization using Pyplot: line chart, pie chart, and bar chart.Data-structures: lists, stacks, queue.
4.2 Unit 2: Computer Networks (CN) (30 Theory + 10 Practical)Structure of a network: Types of networks: local area and wide area (web and internet), new technologies such as cloud and IoT, public vs. private cloud, wired and wireless networks; concept of a client and server.Network devices such as a NIC, switch, hub, router, and access point.Network stack: amplitude and frequency modulation, collision in wireless networks, error checking, and the notion of a MAC address, main idea of routing. IP addresses: (v4 and v6), DNS, and web URLs, TCP: basic idea of retransmission, and rate modulation when there is congestion (analogy to a road network), Protocols: 2G, 3G, 4G, WiFi What makes a protocol have a higher bandwidth?Basic network tools: traceroute, ping, ipconfig, nslookup, whois, speed-test.Application layer: HTTP (basic idea), working of email, secure communication: encryption and certificates (HTTPS), network applications: remote desktop, remote login, FTP, SCP, SSH, POP/IMAP, SMTP, VoIP, NFC.
4.3 Unit 3: Data Management (DM-2) (20 Theory + 20 Practical)Write a minimal Django based web application that parses a GET and POST request, and writes the fields to a file – flat file and CSV file.Interface Python with an SQL databaseSQL commands: aggregation functions – group by, having, , order by.
4.4. Unit 4: Society, Law and Ethics (SLE-2) (10 Theory)Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL and Apache), open source, open data, privacy.Privacy laws, fraud; cyber-crime- phishing, illegal downloads, child pornography, scams; cyber forensics, IT Act, 2000.Technology and society: understanding of societal issues and cultural changes induced by technology.E-waste management: proper disposal of used electronic gadgets.Identity theft, unique ids, and biometrics.Gender and disability issues while teaching and using computers.
5. Practical
Some sample lab assignments are as follows:
5.1. Programming in Python:
Recursively find the factorial of a natural number.Read a file line by line and print it.Remove all the lines that contain the character `a’ in a file and write it to another file.Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series expansion up to n terms. Compare the values of sin(x) for different values of n with the correct valueWrite a random number generator that generates random numbers between 1 and 6 (simulates a dice).Write a recursive code to find the sum of all elements of a list.Write a recursive code to compute the nth Fibonacci number.Write a Python program to implement a stack and queue using a list data-structure.Write a recursive Python program to test if a string is a palindrome or not.Write a Python program to plot the function y = x2 using the pyplot or matplotlib libraries.Create a graphical application that accepts user inputs, performs some operation on them, and then writes the output on the screen. For example, write a small calculator. Use the tkinter library.Open a webpage using the urllib library.Compute EMIs for a loan using the numpy or scipy libraries.Take a sample of 10 phishing e-mails and find the most common words.
Recursively find the factorial of a natural number.
Read a file line by line and print it.
Remove all the lines that contain the character `a’ in a file and write it to another file.
Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series expansion up to n terms. Compare the values of sin(x) for different values of n with the correct value
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Write a recursive code to find the sum of all elements of a list.
Write a recursive code to compute the nth Fibonacci number.
Write a Python program to implement a stack and queue using a list data-structure.
Write a recursive Python program to test if a string is a palindrome or not.
Write a Python program to plot the function y = x2 using the pyplot or matplotlib libraries.
Create a graphical application that accepts user inputs, performs some operation on them, and then writes the output on the screen. For example, write a small calculator. Use the tkinter library.
Open a webpage using the urllib library.
Compute EMIs for a loan using the numpy or scipy libraries.
Take a sample of 10 phishing e-mails and find the most common words.
5.2. Data Management: SQL and web-server
Find the min, max, sum, and average of the marks in a student marks table.Find the total number of customers from each country in the table (customer ID, customer name, country) using group by.Write a SQL query to order the (student ID, marks) table in descending order of the marks.Integrate SQL with Python by importing the MySQL moduleWrite a Django based web server to parse a user request (POST), and write it to a CSV file.
Find the min, max, sum, and average of the marks in a student marks table.
Find the total number of customers from each country in the table (customer ID, customer name, country) using group by.
Write a SQL query to order the (student ID, marks) table in descending order of the marks.
Integrate SQL with Python by importing the MySQL module
Write a Django based web server to parse a user request (POST), and write it to a CSV file.
6. ProjectThe aim of the class project is to create something that is tangible and useful. This should be done in groups of 2 to 3 students, and should be started by students at least 6 months before the submission deadline. The aim here is to find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, Of course to do some of this projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. If three people work on a project for 6 months, at least 500 lines of code is expected. The committee has also been made aware about the degree of plagiarism in such projects. Teachers should take a very strict look at this situation, and take very strict disciplinary action against students who are cheating on lab assignments, or projects, or using pirated software to do the same. Everything that is proposed can be achieved using absolutely free, and legitimate open source software.
CBSE - Class 12
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 25062,
"s": 25034,
"text": "\n04 Sep, 2018"
},
{
"code": null,
"e": 25193,
"s": 25062,
"text": "Computer ScienceCLASS-XII (Code No. 083)Optional for the academic year 2019-20 and mandatory for the academic year 2020-21 onwards"
},
{
"code": null,
"e": 25238,
"s": 25193,
"text": "1. Prerequisites: Computer Science- Class XI"
},
{
"code": null,
"e": 25260,
"s": 25238,
"text": "2. Learning Outcomes:"
},
{
"code": null,
"e": 25892,
"s": 25260,
"text": "Understand the concept of functions and recursion.Learn how to create and use Python libraries.Learn file handling.Learn about the concept of efficiency in algorithms and computing in general.Learn basic data structures: lists, stacks, and queues.Get a basic understanding of computer networks: network stack, basic network hardware, basic protocols, and basic tools.Connect a Python program with an SQL database, and learn aggregation functions in SQL.Have a clear understanding of cyber ethics and cybercrime. Understand the value of technology in societies, gender and disability issues, and the technology behind biometric ids."
},
{
"code": null,
"e": 25943,
"s": 25892,
"text": "Understand the concept of functions and recursion."
},
{
"code": null,
"e": 25989,
"s": 25943,
"text": "Learn how to create and use Python libraries."
},
{
"code": null,
"e": 26010,
"s": 25989,
"text": "Learn file handling."
},
{
"code": null,
"e": 26088,
"s": 26010,
"text": "Learn about the concept of efficiency in algorithms and computing in general."
},
{
"code": null,
"e": 26144,
"s": 26088,
"text": "Learn basic data structures: lists, stacks, and queues."
},
{
"code": null,
"e": 26265,
"s": 26144,
"text": "Get a basic understanding of computer networks: network stack, basic network hardware, basic protocols, and basic tools."
},
{
"code": null,
"e": 26352,
"s": 26265,
"text": "Connect a Python program with an SQL database, and learn aggregation functions in SQL."
},
{
"code": null,
"e": 26531,
"s": 26352,
"text": "Have a clear understanding of cyber ethics and cybercrime. Understand the value of technology in societies, gender and disability issues, and the technology behind biometric ids."
},
{
"code": null,
"e": 26556,
"s": 26531,
"text": "3. Distribution of Marks"
},
{
"code": null,
"e": 26909,
"s": 26556,
"text": "UnitNo. Unit Name Marks\n1. Programming and Computational Thinking–2 30\n2. Computer Networks 15\n3. Data Management–2 15\n4. Society, Law and Ethics–2 10\n5. Practicals 30\nTotal 100"
},
{
"code": null,
"e": 27937,
"s": 26909,
"text": "4.1 Unit 1: Programming and Computational Thinking (PCT-2) (80 Theory + 70 Practical)Revision of the basics of PythonFunctions: scope, parameter passing, mutable/immutable properties of data objects, pass arrays to functions, return values, functions using libraries: mathematical, and string functions.File handling: open and close a file, read, write, and append to a file, standard input, output, and error streams, relative and absolute paths.Using Python libraries: create and import Python librariesRecursion: simple algorithms with recursion: factorial, Fibonacci numbers; recursion on arrays: binary searchIdea of efficiency: performance defined as inversely proportional to the wall clock time, count the number of operations a piece of code is performing, and measure the time taken by a program. Example: take two different programs for the same problem, and understand how the efficient one takes less time.Data visualization using Pyplot: line chart, pie chart, and bar chart.Data-structures: lists, stacks, queue."
},
{
"code": null,
"e": 28950,
"s": 27937,
"text": "4.2 Unit 2: Computer Networks (CN) (30 Theory + 10 Practical)Structure of a network: Types of networks: local area and wide area (web and internet), new technologies such as cloud and IoT, public vs. private cloud, wired and wireless networks; concept of a client and server.Network devices such as a NIC, switch, hub, router, and access point.Network stack: amplitude and frequency modulation, collision in wireless networks, error checking, and the notion of a MAC address, main idea of routing. IP addresses: (v4 and v6), DNS, and web URLs, TCP: basic idea of retransmission, and rate modulation when there is congestion (analogy to a road network), Protocols: 2G, 3G, 4G, WiFi What makes a protocol have a higher bandwidth?Basic network tools: traceroute, ping, ipconfig, nslookup, whois, speed-test.Application layer: HTTP (basic idea), working of email, secure communication: encryption and certificates (HTTPS), network applications: remote desktop, remote login, FTP, SCP, SSH, POP/IMAP, SMTP, VoIP, NFC."
},
{
"code": null,
"e": 29254,
"s": 28950,
"text": "4.3 Unit 3: Data Management (DM-2) (20 Theory + 20 Practical)Write a minimal Django based web application that parses a GET and POST request, and writes the fields to a file – flat file and CSV file.Interface Python with an SQL databaseSQL commands: aggregation functions – group by, having, , order by."
},
{
"code": null,
"e": 29851,
"s": 29254,
"text": "4.4. Unit 4: Society, Law and Ethics (SLE-2) (10 Theory)Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL and Apache), open source, open data, privacy.Privacy laws, fraud; cyber-crime- phishing, illegal downloads, child pornography, scams; cyber forensics, IT Act, 2000.Technology and society: understanding of societal issues and cultural changes induced by technology.E-waste management: proper disposal of used electronic gadgets.Identity theft, unique ids, and biometrics.Gender and disability issues while teaching and using computers."
},
{
"code": null,
"e": 29864,
"s": 29851,
"text": "5. Practical"
},
{
"code": null,
"e": 29908,
"s": 29864,
"text": "Some sample lab assignments are as follows:"
},
{
"code": null,
"e": 29936,
"s": 29908,
"text": "5.1. Programming in Python:"
},
{
"code": null,
"e": 31143,
"s": 29936,
"text": "Recursively find the factorial of a natural number.Read a file line by line and print it.Remove all the lines that contain the character `a’ in a file and write it to another file.Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series expansion up to n terms. Compare the values of sin(x) for different values of n with the correct valueWrite a random number generator that generates random numbers between 1 and 6 (simulates a dice).Write a recursive code to find the sum of all elements of a list.Write a recursive code to compute the nth Fibonacci number.Write a Python program to implement a stack and queue using a list data-structure.Write a recursive Python program to test if a string is a palindrome or not.Write a Python program to plot the function y = x2 using the pyplot or matplotlib libraries.Create a graphical application that accepts user inputs, performs some operation on them, and then writes the output on the screen. For example, write a small calculator. Use the tkinter library.Open a webpage using the urllib library.Compute EMIs for a loan using the numpy or scipy libraries.Take a sample of 10 phishing e-mails and find the most common words."
},
{
"code": null,
"e": 31195,
"s": 31143,
"text": "Recursively find the factorial of a natural number."
},
{
"code": null,
"e": 31234,
"s": 31195,
"text": "Read a file line by line and print it."
},
{
"code": null,
"e": 31326,
"s": 31234,
"text": "Remove all the lines that contain the character `a’ in a file and write it to another file."
},
{
"code": null,
"e": 31520,
"s": 31326,
"text": "Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series expansion up to n terms. Compare the values of sin(x) for different values of n with the correct value"
},
{
"code": null,
"e": 31618,
"s": 31520,
"text": "Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)."
},
{
"code": null,
"e": 31684,
"s": 31618,
"text": "Write a recursive code to find the sum of all elements of a list."
},
{
"code": null,
"e": 31744,
"s": 31684,
"text": "Write a recursive code to compute the nth Fibonacci number."
},
{
"code": null,
"e": 31827,
"s": 31744,
"text": "Write a Python program to implement a stack and queue using a list data-structure."
},
{
"code": null,
"e": 31904,
"s": 31827,
"text": "Write a recursive Python program to test if a string is a palindrome or not."
},
{
"code": null,
"e": 31997,
"s": 31904,
"text": "Write a Python program to plot the function y = x2 using the pyplot or matplotlib libraries."
},
{
"code": null,
"e": 32193,
"s": 31997,
"text": "Create a graphical application that accepts user inputs, performs some operation on them, and then writes the output on the screen. For example, write a small calculator. Use the tkinter library."
},
{
"code": null,
"e": 32234,
"s": 32193,
"text": "Open a webpage using the urllib library."
},
{
"code": null,
"e": 32294,
"s": 32234,
"text": "Compute EMIs for a loan using the numpy or scipy libraries."
},
{
"code": null,
"e": 32363,
"s": 32294,
"text": "Take a sample of 10 phishing e-mails and find the most common words."
},
{
"code": null,
"e": 32404,
"s": 32363,
"text": "5.2. Data Management: SQL and web-server"
},
{
"code": null,
"e": 32834,
"s": 32404,
"text": "Find the min, max, sum, and average of the marks in a student marks table.Find the total number of customers from each country in the table (customer ID, customer name, country) using group by.Write a SQL query to order the (student ID, marks) table in descending order of the marks.Integrate SQL with Python by importing the MySQL moduleWrite a Django based web server to parse a user request (POST), and write it to a CSV file."
},
{
"code": null,
"e": 32909,
"s": 32834,
"text": "Find the min, max, sum, and average of the marks in a student marks table."
},
{
"code": null,
"e": 33029,
"s": 32909,
"text": "Find the total number of customers from each country in the table (customer ID, customer name, country) using group by."
},
{
"code": null,
"e": 33120,
"s": 33029,
"text": "Write a SQL query to order the (student ID, marks) table in descending order of the marks."
},
{
"code": null,
"e": 33176,
"s": 33120,
"text": "Integrate SQL with Python by importing the MySQL module"
},
{
"code": null,
"e": 33268,
"s": 33176,
"text": "Write a Django based web server to parse a user request (POST), and write it to a CSV file."
},
{
"code": null,
"e": 34832,
"s": 33268,
"text": "6. ProjectThe aim of the class project is to create something that is tangible and useful. This should be done in groups of 2 to 3 students, and should be started by students at least 6 months before the submission deadline. The aim here is to find a real world problem that is worthwhile to solve. Students are encouraged to visit local businesses and ask them about the problems that they are facing. For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a wide variety of Python libraries to create user friendly applications such as games, software for their school, software for their disabled fellow students, and mobile applications, Of course to do some of this projects, some additional learning is required; this should be encouraged. Students should know how to teach themselves. If three people work on a project for 6 months, at least 500 lines of code is expected. The committee has also been made aware about the degree of plagiarism in such projects. Teachers should take a very strict look at this situation, and take very strict disciplinary action against students who are cheating on lab assignments, or projects, or using pirated software to do the same. Everything that is proposed can be achieved using absolutely free, and legitimate open source software."
},
{
"code": null,
"e": 34848,
"s": 34832,
"text": "CBSE - Class 12"
},
{
"code": null,
"e": 34855,
"s": 34848,
"text": "Python"
},
{
"code": null,
"e": 34874,
"s": 34855,
"text": "School Programming"
},
{
"code": null,
"e": 34972,
"s": 34874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34981,
"s": 34972,
"text": "Comments"
},
{
"code": null,
"e": 34994,
"s": 34981,
"text": "Old Comments"
},
{
"code": null,
"e": 35012,
"s": 34994,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35034,
"s": 35012,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 35066,
"s": 35034,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 35108,
"s": 35066,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 35134,
"s": 35108,
"text": "Python String | replace()"
},
{
"code": null,
"e": 35152,
"s": 35134,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35168,
"s": 35152,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35187,
"s": 35168,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 35212,
"s": 35187,
"text": "Reverse a string in Java"
}
] |
Google AMP - Caching
|
Google amp provides caching facility which is a proxy based content delivery network to serve pure amp pages. Amp cache is available by default to all the valid amp pages. It helps in rendering the pages faster in comparison to non amp pages.
Currently, there are 2 amp cache providers Google AMP Cache and Cloudflare AMP Cache. As said earlier, amp caching is made available to all valid amp pages. Incase if the user does not want to use amp cache feature, you need to make your amp page invalid. Amp cache is not applied for invalid amp pages.
The moment Google search crawls and finds amp () for the html content, it considers for caching.
In this section, we will discuss various components of Google amp cache URL.
Google AMP adds a subdomain to the url requested. There are some rules followed for amp cache subdomain url. They are shown here −
Converting the AMP document domain from IDN (Punycode) to UTF-8.
Converting the AMP document domain from IDN (Punycode) to UTF-8.
The dash (-) in the url is replaced with two dashes (--)
The dash (-) in the url is replaced with two dashes (--)
The dot (.) in the url is replaced with dash(-).
The dot (.) in the url is replaced with dash(-).
Converting back to IDN (Punycode).
Converting back to IDN (Punycode).
For example pub.mypage will be replaced with pub-mypage.cdn.ampproject.com. Here cdn.ampproject.com is the subdomain added by google amp. Now the cached url is Pub-mypage.cdn.ampproject.com.
The content type available are c for AMP HTML Document, i for image and r for resource like for example font. You will get 404 error if the content type does not match with the ones specified.
If s is present, the content will be fetched from the origin https:// ; else, it will fetch from http://
An example for the request made to cached image from https and http is shown here −
https://pub-mypage-com.cdn.ampproject.org/i/s/examples/images/testimage.png
So, in the above example the url is having i which means image and s for https −
http://pub-mypage-com.cdn.ampproject.org/i/examples/images/testimage.png
Thus, in the above example the url is having i which means image and there is no s, so the url will be fetched from http.
For a font cached file, the url will be as follows −
https://pub-mypage-com.cdn.ampproject.org/r/s/examples/themes/lemon/fonts/Genericons.ttf
Content type r is used for resources like fonts and s for secure url.
For html document the url is as follows −
https://pub-mypage-com.cdn.ampproject.org/c/s/trends/main.html
It has c in the url is for HTML document, followed by s which is for https://
Google AMP cache uses http headers like Max-age to decide whether the content cache is stale or fresh and automatically sends fresh requests and updates the contents so that next user gets the contents updated.
20 Lectures
2.5 hours
Asif Hussain
7 Lectures
1 hours
Aditya Kulkarni
33 Lectures
2.5 hours
Sasha Miller
22 Lectures
1.5 hours
Zach Miller
16 Lectures
1.5 hours
Sasha Miller
23 Lectures
2.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2663,
"s": 2420,
"text": "Google amp provides caching facility which is a proxy based content delivery network to serve pure amp pages. Amp cache is available by default to all the valid amp pages. It helps in rendering the pages faster in comparison to non amp pages."
},
{
"code": null,
"e": 2967,
"s": 2663,
"text": "Currently, there are 2 amp cache providers Google AMP Cache and Cloudflare AMP Cache. As said earlier, amp caching is made available to all valid amp pages. Incase if the user does not want to use amp cache feature, you need to make your amp page invalid. Amp cache is not applied for invalid amp pages."
},
{
"code": null,
"e": 3064,
"s": 2967,
"text": "The moment Google search crawls and finds amp () for the html content, it considers for caching."
},
{
"code": null,
"e": 3141,
"s": 3064,
"text": "In this section, we will discuss various components of Google amp cache URL."
},
{
"code": null,
"e": 3272,
"s": 3141,
"text": "Google AMP adds a subdomain to the url requested. There are some rules followed for amp cache subdomain url. They are shown here −"
},
{
"code": null,
"e": 3337,
"s": 3272,
"text": "Converting the AMP document domain from IDN (Punycode) to UTF-8."
},
{
"code": null,
"e": 3402,
"s": 3337,
"text": "Converting the AMP document domain from IDN (Punycode) to UTF-8."
},
{
"code": null,
"e": 3459,
"s": 3402,
"text": "The dash (-) in the url is replaced with two dashes (--)"
},
{
"code": null,
"e": 3516,
"s": 3459,
"text": "The dash (-) in the url is replaced with two dashes (--)"
},
{
"code": null,
"e": 3565,
"s": 3516,
"text": "The dot (.) in the url is replaced with dash(-)."
},
{
"code": null,
"e": 3614,
"s": 3565,
"text": "The dot (.) in the url is replaced with dash(-)."
},
{
"code": null,
"e": 3649,
"s": 3614,
"text": "Converting back to IDN (Punycode)."
},
{
"code": null,
"e": 3684,
"s": 3649,
"text": "Converting back to IDN (Punycode)."
},
{
"code": null,
"e": 3875,
"s": 3684,
"text": "For example pub.mypage will be replaced with pub-mypage.cdn.ampproject.com. Here cdn.ampproject.com is the subdomain added by google amp. Now the cached url is Pub-mypage.cdn.ampproject.com."
},
{
"code": null,
"e": 4068,
"s": 3875,
"text": "The content type available are c for AMP HTML Document, i for image and r for resource like for example font. You will get 404 error if the content type does not match with the ones specified."
},
{
"code": null,
"e": 4173,
"s": 4068,
"text": "If s is present, the content will be fetched from the origin https:// ; else, it will fetch from http://"
},
{
"code": null,
"e": 4257,
"s": 4173,
"text": "An example for the request made to cached image from https and http is shown here −"
},
{
"code": null,
"e": 4333,
"s": 4257,
"text": "https://pub-mypage-com.cdn.ampproject.org/i/s/examples/images/testimage.png"
},
{
"code": null,
"e": 4414,
"s": 4333,
"text": "So, in the above example the url is having i which means image and s for https −"
},
{
"code": null,
"e": 4487,
"s": 4414,
"text": "http://pub-mypage-com.cdn.ampproject.org/i/examples/images/testimage.png"
},
{
"code": null,
"e": 4609,
"s": 4487,
"text": "Thus, in the above example the url is having i which means image and there is no s, so the url will be fetched from http."
},
{
"code": null,
"e": 4662,
"s": 4609,
"text": "For a font cached file, the url will be as follows −"
},
{
"code": null,
"e": 4751,
"s": 4662,
"text": "https://pub-mypage-com.cdn.ampproject.org/r/s/examples/themes/lemon/fonts/Genericons.ttf"
},
{
"code": null,
"e": 4821,
"s": 4751,
"text": "Content type r is used for resources like fonts and s for secure url."
},
{
"code": null,
"e": 4863,
"s": 4821,
"text": "For html document the url is as follows −"
},
{
"code": null,
"e": 4926,
"s": 4863,
"text": "https://pub-mypage-com.cdn.ampproject.org/c/s/trends/main.html"
},
{
"code": null,
"e": 5004,
"s": 4926,
"text": "It has c in the url is for HTML document, followed by s which is for https://"
},
{
"code": null,
"e": 5215,
"s": 5004,
"text": "Google AMP cache uses http headers like Max-age to decide whether the content cache is stale or fresh and automatically sends fresh requests and updates the contents so that next user gets the contents updated."
},
{
"code": null,
"e": 5250,
"s": 5215,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5264,
"s": 5250,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5296,
"s": 5264,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5313,
"s": 5296,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 5348,
"s": 5313,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5362,
"s": 5348,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5397,
"s": 5362,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5410,
"s": 5397,
"text": " Zach Miller"
},
{
"code": null,
"e": 5445,
"s": 5410,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5459,
"s": 5445,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5494,
"s": 5459,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5508,
"s": 5494,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5515,
"s": 5508,
"text": " Print"
},
{
"code": null,
"e": 5526,
"s": 5515,
"text": " Add Notes"
}
] |
Check if a string is a scrambled form of another string - GeeksforGeeks
|
16 Dec, 2021
Given two strings S1 and S2 of equal length, the task is to determine if S2 is a scrambled form of S1.Scrambled string: Given string str, we can represent it as a binary tree by partitioning it into two non-empty substrings recursively.Note: Scrambled string is not same as an AnagramBelow is one possible representation of str = “coder”:
coder
/ \
co der
/ \ / \
c o d er
/ \
e r
To scramble the string, we may choose any non-leaf node and swap its two children. Suppose, we choose the node “co” and swap its two children, it produces a scrambled string “ocder”.
ocder
/ \
oc der
/ \ / \
o c d er
/ \
e r
Thus, “ocder” is a scrambled string of “coder”.Similarly, if we continue to swap the children of nodes “der” and “er”, it produces a scrambled string “ocred”.
ocred
/ \
oc red
/ \ / \
o c re d
/ \
r e
Thus, “ocred” is a scrambled string of “coder”.Examples:
Input: S1=”coder”, S2=”ocder” Output: Yes Explanation: “ocder” is a scrambled form of “coder”Input: S1=”abcde”, S2=”caebd” Output: No Explanation: “caebd” is not a scrambled form of “abcde”
Approach In order to solve this problem, we are using Divide and Conquer approach. Given two strings of equal length (say n+1), S1[0...n] and S2[0...n]. If S2 is a scrambled form of S1, then there must exist an index i such that at least one of the following conditions is true:
S2[0...i] is a scrambled string of S1[0...i] and S2[i+1...n] is a scrambled string of S1[i+1...n].
S2[0...i] is a scrambled string of S1[n-i...n] and S2[i+1...n] is a scrambled string of S1[0...n-i-1].
Note: An optimization step to consider here is to check beforehand if the two strings are anagrams of each other. If not, it indicates that the strings contain different characters and can’t be a scrambled form of each other.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to check if a// given string is a scrambled// form of another string #include <bits/stdc++.h>using namespace std; bool isScramble(string S1, string S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; sort(copy_S1.begin(), copy_S1.end()); sort(copy_S2.begin(), copy_S2.end()); if (copy_S1 != copy_S2) { return false; } for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substr(0, i), S2.substr(0, i)) && isScramble(S1.substr(i, n - i), S2.substr(i, n - i))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substr(0, i), S2.substr(n - i, i)) && isScramble(S1.substr(i, n - i), S2.substr(0, n - i))) { return true; } } // If none of the above // conditions are satisfied return false;} // Driver Codeint main(){ string S1 = "coder"; string S2 = "ocred"; if (isScramble(S1, S2)) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java program to check if a// given string is a scrambled// form of another stringimport java.util.*; class GFG{ static boolean isScramble(String S1, String S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1.equals(S2)) { return true; } // Converting string to // character array char[] tempArray1 = S1.toCharArray(); char[] tempArray2 = S2.toCharArray(); // Checking condition for Anagram Arrays.sort(tempArray1); Arrays.sort(tempArray2); String copy_S1 = new String(tempArray1); String copy_S2 = new String(tempArray2); if (!copy_S1.equals(copy_S2)) { return false; } for(int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(n - i, n), S2.substring(0, i)) && isScramble(S1.substring(0, n - i), S2.substring(i, n))) { return true; } } // If none of the above // conditions are satisfied return false;} // Driver Codepublic static void main(String[] args){ String S1 = "coder"; String S2 = "ocred"; if (isScramble(S1, S2)) { System.out.println("Yes"); } else { System.out.println("No"); }}} // This code is contributed by dadi madhav
# Python3 program to check if a# given string is a scrambled# form of another stringdef isScramble(S1: str, S2: str): # Strings of non-equal length # cant' be scramble strings if len(S1) != len(S2): return False n = len(S1) # Empty strings are scramble strings if not n: return True # Equal strings are scramble strings if S1 == S2: return True # Check for the condition of anagram if sorted(S1) != sorted(S2): return False for i in range(1, n): # Check if S2[0...i] is a scrambled # string of S1[0...i] and if S2[i+1...n] # is a scrambled string of S1[i+1...n] if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])): return True # Check if S2[0...i] is a scrambled # string of S1[n-i...n] and S2[i+1...n] # is a scramble string of S1[0...n-i-1] if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])): return True # If none of the above # conditions are satisfied return False # Driver Codeif __name__ == "__main__": S1 = "coder" S2 = "ocred" if (isScramble(S1, S2)): print("Yes") else: print("No") # This code is contributed by sgshah2
// C# program to check if a// given string is a scrambled// form of another stringusing System;using System.Collections.Generic;class GFG { static bool isScramble(string S1, string S2) { // Strings of non-equal length // cant' be scramble strings if (S1.Length != S2.Length) { return false; } int n = S1.Length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1.Equals(S2)) { return true; } // Converting string to // character array char[] tempArray1 = S1.ToCharArray(); char[] tempArray2 = S2.ToCharArray(); // Checking condition for Anagram Array.Sort(tempArray1); Array.Sort(tempArray2); string copy_S1 = new string(tempArray1); string copy_S2 = new string(tempArray2); if (!copy_S1.Equals(copy_S2)) { return false; } for(int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.Substring(0, i), S2.Substring(0, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(i, n - i))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.Substring(0, i), S2.Substring(n - i, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(0, n - i))) { return true; } } // If none of the above // conditions are satisfied return false; } // Driver code static void Main() { string S1 = "coder"; string S2 = "ocred"; if (isScramble(S1, S2)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by divyeshrabadiya07
<script> // Javascript program to check if a // given string is a scrambled // form of another string function isScramble(S1, S2) { // Strings of non-equal length // can't be scramble strings if (S1.length != S2.length) { return false; } let n = S1.length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Converting string to // character array let tempArray1 = S1.split(''); let tempArray2 = S2.split(''); // Checking condition for Anagram tempArray1.sort(); tempArray2.sort(); let copy_S1 = tempArray1.join(""); let copy_S2 = tempArray2.join(""); if (copy_S1 != copy_S2) { return false; } for(let i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, i + n), S2.substring(i, i + n))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(n - i, n - i + n), S2.substring(0, i)) && isScramble(S1.substring(0, n - i), S2.substring(i, i + n))) { return true; } } // If none of the above // conditions are satisfied return false; } let S1 = "coder"; let S2 = "ocred"; if (isScramble(S1, S2)) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by decode2207.</script>
Yes
Time Complexity: O(2^k + 2^(n-k)), where k and n-k are the length of the two substrings.
Auxiliary Space: O(2^N), recursion stack.
Dynamic Programming Solution: The above recursive Code can be optimized by storing Boolean values of substrings in an unordered map, so if the same substrings have to be checked again we can easily just get value from the map instead of performing function calls.
Memoized Code:
C++
Java
Python3
C#
Javascript
// C++ Program to check if a// given string is a scrambled// form of another string #include <bits/stdc++.h>using namespace std; // map declaration for storing key value pair// means for storing subproblem resultunordered_map<string, bool> mp; bool isScramble(string S1, string S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; sort(copy_S1.begin(), copy_S1.end()); sort(copy_S2.begin(), copy_S2.end()); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map string key = (S1 + " " + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.find(key) != mp.end()) { return mp[key]; } // declaring flag variable to store result bool flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substr(0, i), S2.substr(0, i)) && isScramble(S1.substr(i, n - i), S2.substr(i, n - i))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substr(0, i), S2.substr(n - i, i)) && isScramble(S1.substr(i, n - i), S2.substr(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false;} // Driver Codeint main(){ string S1 = "coder"; string S2 = "ocred"; if (isScramble(S1, S2)) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java Program to check if a// given string is a scrambled// form of another stringimport java.util.*;public class Main{ // map declaration for storing key value pair // means for storing subproblem result static HashMap<String, Boolean> mp = new HashMap<String, Boolean>(); static boolean isScramble(String S1, String S2) { // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n != 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram String copy_S1 = S1, copy_S2 = S2; char[] t1 = copy_S1.toCharArray(); char[] t2 = copy_S2.toCharArray(); Arrays.sort(t1); Arrays.sort(t2); copy_S1 = new String(t1); copy_S2 = new String(t2); if (!copy_S1.equals(copy_S2)) { return false; } // make key of type string for search in map String key = (S1 + " " + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.containsKey(key)) { return mp.get(key); } // declaring flag variable to store result boolean flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(0, i), S2.substring(n - i, n)) && isScramble(S1.substring(i, n), S2.substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp.put(key, flag); // If none of the above conditions are satisfied return false; } public static void main(String[] args) { String S1 = "coder"; String S2 = "ocred"; if (isScramble(S1, S2)) { System.out.print("Yes"); } else { System.out.print("No"); } }} // This code is contributed by divyesh072019.
# Declaring unordered map globallymap={}# Python3 program to check if a# given string is a scrambled# form of another stringdef isScramble(S1: str, S2: str): # Strings of non-equal length # cant' be scramble strings if len(S1) != len(S2): return False n = len(S1) # Empty strings are scramble strings if not n: return True # Equal strings are scramble strings if S1 == S2: return True # Check for the condition of anagram if sorted(S1) != sorted(S2): return False # Checking if both Substrings are in # map or are already calculated or not if(S1+' '+S2 in map): return map[S1+' '+S2] # Declaring a flag variable flag = False for i in range(1, n): # Check if S2[0...i] is a scrambled # string of S1[0...i] and if S2[i+1...n] # is a scrambled string of S1[i+1...n] if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])): flag = True return True # Check if S2[0...i] is a scrambled # string of S1[n-i...n] and S2[i+1...n] # is a scramble string of S1[0...n-i-1] if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])): flag = True return True # Storing calculated value to map map[S1+" "+S2] = flag # If none of the above # conditions are satisfied return False # Driver Codeif __name__ == "__main__": S1 = "great" S2 = "rgate" if (isScramble(S1, S2)): print("Yes") else: print("No")
// C# Program to check if a// given string is a scrambled// form of another stringusing System;using System.Collections.Generic;class GFG { // map declaration for storing key value pair // means for storing subproblem result static Dictionary<string, bool> mp = new Dictionary<string, bool>(); static bool isScramble(string S1, string S2) { // Strings of non-equal length // cant' be scramble strings if (S1.Length != S2.Length) { return false; } int n = S1.Length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; char[] t1 = copy_S1.ToCharArray(); char[] t2 = copy_S2.ToCharArray(); Array.Sort(t1); Array.Sort(t2); copy_S1 = new string(t1); copy_S2 = new string(t2); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map string key = (S1 + " " + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.ContainsKey(key)) { return mp[key]; } // declaring flag variable to store result bool flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.Substring(0, i), S2.Substring(0, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(i, n - i))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.Substring(0, i), S2.Substring(n - i, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false; } static void Main() { string S1 = "coder"; string S2 = "ocred"; if (isScramble(S1, S2)) { Console.Write("Yes"); } else { Console.Write("No"); } }} // This code is contributed by rameshtravel07.
<script> // Javascript Program to check if a // given string is a scrambled // form of another string // map declaration for storing key value pair // means for storing subproblem result let mp = new Map(); function isScramble(S1, S2) { // Strings of non-equal length // cant' be scramble strings if (S1.length != S2.length) { return false; } let n = S1.length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram let copy_S1 = S1, copy_S2 = S2; let t1 = copy_S1.split('') let t2 = copy_S2.split('') t1.sort(); t2.sort(); copy_S1 = t1.join(""); copy_S2 = t2.join(""); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map let key = (S1 + " " + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.has(key)) { return mp[key]; } // declaring flag variable to store result let flag = false; for (let i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(0, i), S2.substring(n - i, n)) && isScramble(S1.substring(i, n), S2.substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false; } let S1 = "coder"; let S2 = "ocred"; if (isScramble(S1, S2)) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by suresh07.</script>
Yes
Time Complexity: O(N^2), where N is the length of the given strings.Auxiliary Space: O(N^2), As we need to store O(N^2) string in our mp map.
amarjeet_singh
sgshah2
dadimadhav
divyeshrabadiya07
decode2207
taran910
ajaymakvana
bunnyram19
pankajsharmagfg
suresh07
rameshtravel07
divyesh072019
arpitdadhich045
Algorithms
Divide and Conquer
Recursion
Strings
Tree
Strings
Recursion
Divide and Conquer
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to Start Learning DSA?
Understanding Time Complexity with Simple Examples
How to write a Pseudo Code?
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
|
[
{
"code": null,
"e": 26049,
"s": 26021,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 26389,
"s": 26049,
"text": "Given two strings S1 and S2 of equal length, the task is to determine if S2 is a scrambled form of S1.Scrambled string: Given string str, we can represent it as a binary tree by partitioning it into two non-empty substrings recursively.Note: Scrambled string is not same as an AnagramBelow is one possible representation of str = “coder”: "
},
{
"code": null,
"e": 26479,
"s": 26389,
"text": " coder\n / \\\n co der\n / \\ / \\\nc o d er\n / \\\n e r"
},
{
"code": null,
"e": 26663,
"s": 26479,
"text": "To scramble the string, we may choose any non-leaf node and swap its two children. Suppose, we choose the node “co” and swap its two children, it produces a scrambled string “ocder”. "
},
{
"code": null,
"e": 26753,
"s": 26663,
"text": " ocder\n / \\\n oc der\n / \\ / \\\no c d er\n / \\\n e r"
},
{
"code": null,
"e": 26913,
"s": 26753,
"text": "Thus, “ocder” is a scrambled string of “coder”.Similarly, if we continue to swap the children of nodes “der” and “er”, it produces a scrambled string “ocred”. "
},
{
"code": null,
"e": 26994,
"s": 26913,
"text": " ocred\n / \\\n oc red\n / \\ / \\\no c re d\n / \\\n r e"
},
{
"code": null,
"e": 27051,
"s": 26994,
"text": "Thus, “ocred” is a scrambled string of “coder”.Examples:"
},
{
"code": null,
"e": 27241,
"s": 27051,
"text": "Input: S1=”coder”, S2=”ocder” Output: Yes Explanation: “ocder” is a scrambled form of “coder”Input: S1=”abcde”, S2=”caebd” Output: No Explanation: “caebd” is not a scrambled form of “abcde”"
},
{
"code": null,
"e": 27522,
"s": 27241,
"text": "Approach In order to solve this problem, we are using Divide and Conquer approach. Given two strings of equal length (say n+1), S1[0...n] and S2[0...n]. If S2 is a scrambled form of S1, then there must exist an index i such that at least one of the following conditions is true: "
},
{
"code": null,
"e": 27621,
"s": 27522,
"text": "S2[0...i] is a scrambled string of S1[0...i] and S2[i+1...n] is a scrambled string of S1[i+1...n]."
},
{
"code": null,
"e": 27724,
"s": 27621,
"text": "S2[0...i] is a scrambled string of S1[n-i...n] and S2[i+1...n] is a scrambled string of S1[0...n-i-1]."
},
{
"code": null,
"e": 28001,
"s": 27724,
"text": "Note: An optimization step to consider here is to check beforehand if the two strings are anagrams of each other. If not, it indicates that the strings contain different characters and can’t be a scrambled form of each other.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28005,
"s": 28001,
"text": "C++"
},
{
"code": null,
"e": 28010,
"s": 28005,
"text": "Java"
},
{
"code": null,
"e": 28018,
"s": 28010,
"text": "Python3"
},
{
"code": null,
"e": 28021,
"s": 28018,
"text": "C#"
},
{
"code": null,
"e": 28032,
"s": 28021,
"text": "Javascript"
},
{
"code": "// C++ Program to check if a// given string is a scrambled// form of another string #include <bits/stdc++.h>using namespace std; bool isScramble(string S1, string S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; sort(copy_S1.begin(), copy_S1.end()); sort(copy_S2.begin(), copy_S2.end()); if (copy_S1 != copy_S2) { return false; } for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substr(0, i), S2.substr(0, i)) && isScramble(S1.substr(i, n - i), S2.substr(i, n - i))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substr(0, i), S2.substr(n - i, i)) && isScramble(S1.substr(i, n - i), S2.substr(0, n - i))) { return true; } } // If none of the above // conditions are satisfied return false;} // Driver Codeint main(){ string S1 = \"coder\"; string S2 = \"ocred\"; if (isScramble(S1, S2)) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 29717,
"s": 28032,
"text": null
},
{
"code": "// Java program to check if a// given string is a scrambled// form of another stringimport java.util.*; class GFG{ static boolean isScramble(String S1, String S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1.equals(S2)) { return true; } // Converting string to // character array char[] tempArray1 = S1.toCharArray(); char[] tempArray2 = S2.toCharArray(); // Checking condition for Anagram Arrays.sort(tempArray1); Arrays.sort(tempArray2); String copy_S1 = new String(tempArray1); String copy_S2 = new String(tempArray2); if (!copy_S1.equals(copy_S2)) { return false; } for(int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(n - i, n), S2.substring(0, i)) && isScramble(S1.substring(0, n - i), S2.substring(i, n))) { return true; } } // If none of the above // conditions are satisfied return false;} // Driver Codepublic static void main(String[] args){ String S1 = \"coder\"; String S2 = \"ocred\"; if (isScramble(S1, S2)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); }}} // This code is contributed by dadi madhav",
"e": 31787,
"s": 29717,
"text": null
},
{
"code": "# Python3 program to check if a# given string is a scrambled# form of another stringdef isScramble(S1: str, S2: str): # Strings of non-equal length # cant' be scramble strings if len(S1) != len(S2): return False n = len(S1) # Empty strings are scramble strings if not n: return True # Equal strings are scramble strings if S1 == S2: return True # Check for the condition of anagram if sorted(S1) != sorted(S2): return False for i in range(1, n): # Check if S2[0...i] is a scrambled # string of S1[0...i] and if S2[i+1...n] # is a scrambled string of S1[i+1...n] if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])): return True # Check if S2[0...i] is a scrambled # string of S1[n-i...n] and S2[i+1...n] # is a scramble string of S1[0...n-i-1] if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])): return True # If none of the above # conditions are satisfied return False # Driver Codeif __name__ == \"__main__\": S1 = \"coder\" S2 = \"ocred\" if (isScramble(S1, S2)): print(\"Yes\") else: print(\"No\") # This code is contributed by sgshah2",
"e": 33069,
"s": 31787,
"text": null
},
{
"code": "// C# program to check if a// given string is a scrambled// form of another stringusing System;using System.Collections.Generic;class GFG { static bool isScramble(string S1, string S2) { // Strings of non-equal length // cant' be scramble strings if (S1.Length != S2.Length) { return false; } int n = S1.Length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1.Equals(S2)) { return true; } // Converting string to // character array char[] tempArray1 = S1.ToCharArray(); char[] tempArray2 = S2.ToCharArray(); // Checking condition for Anagram Array.Sort(tempArray1); Array.Sort(tempArray2); string copy_S1 = new string(tempArray1); string copy_S2 = new string(tempArray2); if (!copy_S1.Equals(copy_S2)) { return false; } for(int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.Substring(0, i), S2.Substring(0, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(i, n - i))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.Substring(0, i), S2.Substring(n - i, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(0, n - i))) { return true; } } // If none of the above // conditions are satisfied return false; } // Driver code static void Main() { string S1 = \"coder\"; string S2 = \"ocred\"; if (isScramble(S1, S2)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by divyeshrabadiya07",
"e": 35497,
"s": 33069,
"text": null
},
{
"code": "<script> // Javascript program to check if a // given string is a scrambled // form of another string function isScramble(S1, S2) { // Strings of non-equal length // can't be scramble strings if (S1.length != S2.length) { return false; } let n = S1.length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Converting string to // character array let tempArray1 = S1.split(''); let tempArray2 = S2.split(''); // Checking condition for Anagram tempArray1.sort(); tempArray2.sort(); let copy_S1 = tempArray1.join(\"\"); let copy_S2 = tempArray2.join(\"\"); if (copy_S1 != copy_S2) { return false; } for(let i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, i + n), S2.substring(i, i + n))) { return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(n - i, n - i + n), S2.substring(0, i)) && isScramble(S1.substring(0, n - i), S2.substring(i, i + n))) { return true; } } // If none of the above // conditions are satisfied return false; } let S1 = \"coder\"; let S2 = \"ocred\"; if (isScramble(S1, S2)) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code is contributed by decode2207.</script>",
"e": 37616,
"s": 35497,
"text": null
},
{
"code": null,
"e": 37620,
"s": 37616,
"text": "Yes"
},
{
"code": null,
"e": 37709,
"s": 37620,
"text": "Time Complexity: O(2^k + 2^(n-k)), where k and n-k are the length of the two substrings."
},
{
"code": null,
"e": 37751,
"s": 37709,
"text": "Auxiliary Space: O(2^N), recursion stack."
},
{
"code": null,
"e": 38015,
"s": 37751,
"text": "Dynamic Programming Solution: The above recursive Code can be optimized by storing Boolean values of substrings in an unordered map, so if the same substrings have to be checked again we can easily just get value from the map instead of performing function calls."
},
{
"code": null,
"e": 38031,
"s": 38015,
"text": "Memoized Code: "
},
{
"code": null,
"e": 38035,
"s": 38031,
"text": "C++"
},
{
"code": null,
"e": 38040,
"s": 38035,
"text": "Java"
},
{
"code": null,
"e": 38048,
"s": 38040,
"text": "Python3"
},
{
"code": null,
"e": 38051,
"s": 38048,
"text": "C#"
},
{
"code": null,
"e": 38062,
"s": 38051,
"text": "Javascript"
},
{
"code": "// C++ Program to check if a// given string is a scrambled// form of another string #include <bits/stdc++.h>using namespace std; // map declaration for storing key value pair// means for storing subproblem resultunordered_map<string, bool> mp; bool isScramble(string S1, string S2){ // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; sort(copy_S1.begin(), copy_S1.end()); sort(copy_S2.begin(), copy_S2.end()); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map string key = (S1 + \" \" + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.find(key) != mp.end()) { return mp[key]; } // declaring flag variable to store result bool flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substr(0, i), S2.substr(0, i)) && isScramble(S1.substr(i, n - i), S2.substr(i, n - i))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substr(0, i), S2.substr(n - i, i)) && isScramble(S1.substr(i, n - i), S2.substr(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false;} // Driver Codeint main(){ string S1 = \"coder\"; string S2 = \"ocred\"; if (isScramble(S1, S2)) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 40351,
"s": 38062,
"text": null
},
{
"code": "// Java Program to check if a// given string is a scrambled// form of another stringimport java.util.*;public class Main{ // map declaration for storing key value pair // means for storing subproblem result static HashMap<String, Boolean> mp = new HashMap<String, Boolean>(); static boolean isScramble(String S1, String S2) { // Strings of non-equal length // cant' be scramble strings if (S1.length() != S2.length()) { return false; } int n = S1.length(); // Empty strings are scramble strings if (n != 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram String copy_S1 = S1, copy_S2 = S2; char[] t1 = copy_S1.toCharArray(); char[] t2 = copy_S2.toCharArray(); Arrays.sort(t1); Arrays.sort(t2); copy_S1 = new String(t1); copy_S2 = new String(t2); if (!copy_S1.equals(copy_S2)) { return false; } // make key of type string for search in map String key = (S1 + \" \" + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.containsKey(key)) { return mp.get(key); } // declaring flag variable to store result boolean flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(0, i), S2.substring(n - i, n)) && isScramble(S1.substring(i, n), S2.substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp.put(key, flag); // If none of the above conditions are satisfied return false; } public static void main(String[] args) { String S1 = \"coder\"; String S2 = \"ocred\"; if (isScramble(S1, S2)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); } }} // This code is contributed by divyesh072019.",
"e": 43179,
"s": 40351,
"text": null
},
{
"code": "# Declaring unordered map globallymap={}# Python3 program to check if a# given string is a scrambled# form of another stringdef isScramble(S1: str, S2: str): # Strings of non-equal length # cant' be scramble strings if len(S1) != len(S2): return False n = len(S1) # Empty strings are scramble strings if not n: return True # Equal strings are scramble strings if S1 == S2: return True # Check for the condition of anagram if sorted(S1) != sorted(S2): return False # Checking if both Substrings are in # map or are already calculated or not if(S1+' '+S2 in map): return map[S1+' '+S2] # Declaring a flag variable flag = False for i in range(1, n): # Check if S2[0...i] is a scrambled # string of S1[0...i] and if S2[i+1...n] # is a scrambled string of S1[i+1...n] if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])): flag = True return True # Check if S2[0...i] is a scrambled # string of S1[n-i...n] and S2[i+1...n] # is a scramble string of S1[0...n-i-1] if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])): flag = True return True # Storing calculated value to map map[S1+\" \"+S2] = flag # If none of the above # conditions are satisfied return False # Driver Codeif __name__ == \"__main__\": S1 = \"great\" S2 = \"rgate\" if (isScramble(S1, S2)): print(\"Yes\") else: print(\"No\")",
"e": 44773,
"s": 43179,
"text": null
},
{
"code": "// C# Program to check if a// given string is a scrambled// form of another stringusing System;using System.Collections.Generic;class GFG { // map declaration for storing key value pair // means for storing subproblem result static Dictionary<string, bool> mp = new Dictionary<string, bool>(); static bool isScramble(string S1, string S2) { // Strings of non-equal length // cant' be scramble strings if (S1.Length != S2.Length) { return false; } int n = S1.Length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram string copy_S1 = S1, copy_S2 = S2; char[] t1 = copy_S1.ToCharArray(); char[] t2 = copy_S2.ToCharArray(); Array.Sort(t1); Array.Sort(t2); copy_S1 = new string(t1); copy_S2 = new string(t2); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map string key = (S1 + \" \" + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.ContainsKey(key)) { return mp[key]; } // declaring flag variable to store result bool flag = false; for (int i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.Substring(0, i), S2.Substring(0, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(i, n - i))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.Substring(0, i), S2.Substring(n - i, i)) && isScramble(S1.Substring(i, n - i), S2.Substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false; } static void Main() { string S1 = \"coder\"; string S2 = \"ocred\"; if (isScramble(S1, S2)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); } }} // This code is contributed by rameshtravel07.",
"e": 47530,
"s": 44773,
"text": null
},
{
"code": "<script> // Javascript Program to check if a // given string is a scrambled // form of another string // map declaration for storing key value pair // means for storing subproblem result let mp = new Map(); function isScramble(S1, S2) { // Strings of non-equal length // cant' be scramble strings if (S1.length != S2.length) { return false; } let n = S1.length; // Empty strings are scramble strings if (n == 0) { return true; } // Equal strings are scramble strings if (S1 == S2) { return true; } // Check for the condition of anagram let copy_S1 = S1, copy_S2 = S2; let t1 = copy_S1.split('') let t2 = copy_S2.split('') t1.sort(); t2.sort(); copy_S1 = t1.join(\"\"); copy_S2 = t2.join(\"\"); if (copy_S1 != copy_S2) { return false; } // make key of type string for search in map let key = (S1 + \" \" + S2); // checking if both string are before calculated or not // if calculated means find in map then return it's // value if (mp.has(key)) { return mp[key]; } // declaring flag variable to store result let flag = false; for (let i = 1; i < n; i++) { // Check if S2[0...i] is a scrambled // string of S1[0...i] and if S2[i+1...n] // is a scrambled string of S1[i+1...n] if (isScramble(S1.substring(0, i), S2.substring(0, i)) && isScramble(S1.substring(i, n), S2.substring(i, n))) { flag = true; return true; } // Check if S2[0...i] is a scrambled // string of S1[n-i...n] and S2[i+1...n] // is a scramble string of S1[0...n-i-1] if (isScramble(S1.substring(0, i), S2.substring(n - i, n)) && isScramble(S1.substring(i, n), S2.substring(0, n - i))) { flag = true; return true; } } // add key & flag value to map (store for future use) // so next time no required to calculate it again mp[key] = flag; // If none of the above conditions are satisfied return false; } let S1 = \"coder\"; let S2 = \"ocred\"; if (isScramble(S1, S2)) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code is contributed by suresh07.</script>",
"e": 50115,
"s": 47530,
"text": null
},
{
"code": null,
"e": 50119,
"s": 50115,
"text": "Yes"
},
{
"code": null,
"e": 50261,
"s": 50119,
"text": "Time Complexity: O(N^2), where N is the length of the given strings.Auxiliary Space: O(N^2), As we need to store O(N^2) string in our mp map."
},
{
"code": null,
"e": 50276,
"s": 50261,
"text": "amarjeet_singh"
},
{
"code": null,
"e": 50284,
"s": 50276,
"text": "sgshah2"
},
{
"code": null,
"e": 50295,
"s": 50284,
"text": "dadimadhav"
},
{
"code": null,
"e": 50313,
"s": 50295,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 50324,
"s": 50313,
"text": "decode2207"
},
{
"code": null,
"e": 50333,
"s": 50324,
"text": "taran910"
},
{
"code": null,
"e": 50345,
"s": 50333,
"text": "ajaymakvana"
},
{
"code": null,
"e": 50356,
"s": 50345,
"text": "bunnyram19"
},
{
"code": null,
"e": 50372,
"s": 50356,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 50381,
"s": 50372,
"text": "suresh07"
},
{
"code": null,
"e": 50396,
"s": 50381,
"text": "rameshtravel07"
},
{
"code": null,
"e": 50410,
"s": 50396,
"text": "divyesh072019"
},
{
"code": null,
"e": 50426,
"s": 50410,
"text": "arpitdadhich045"
},
{
"code": null,
"e": 50437,
"s": 50426,
"text": "Algorithms"
},
{
"code": null,
"e": 50456,
"s": 50437,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 50466,
"s": 50456,
"text": "Recursion"
},
{
"code": null,
"e": 50474,
"s": 50466,
"text": "Strings"
},
{
"code": null,
"e": 50479,
"s": 50474,
"text": "Tree"
},
{
"code": null,
"e": 50487,
"s": 50479,
"text": "Strings"
},
{
"code": null,
"e": 50497,
"s": 50487,
"text": "Recursion"
},
{
"code": null,
"e": 50516,
"s": 50497,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 50521,
"s": 50516,
"text": "Tree"
},
{
"code": null,
"e": 50532,
"s": 50521,
"text": "Algorithms"
},
{
"code": null,
"e": 50630,
"s": 50532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50679,
"s": 50630,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 50704,
"s": 50679,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 50731,
"s": 50704,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 50782,
"s": 50731,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 50810,
"s": 50782,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 50821,
"s": 50810,
"text": "Merge Sort"
},
{
"code": null,
"e": 50831,
"s": 50821,
"text": "QuickSort"
},
{
"code": null,
"e": 50845,
"s": 50831,
"text": "Binary Search"
},
{
"code": null,
"e": 50913,
"s": 50845,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Date setTime() method in Java with Examples
|
07 Nov, 2019
The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT.Syntax:
public void setTime(long time)
Parameters: The function accepts a single parameter time which specifies the number of milliseconds.
Return Value: It method has no return value.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
Program 1:
// Java code to demonstrate// setTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a date object with specified time. Date dateOne = new Date(); System.out.println("Date initially: " + dateOne); // Sets the time dateOne.setTime(1000); // Prints the time System.out.println("Date after setting" + " the time: " + dateOne); }}
Date initially: Wed Jan 02 09:34:03 UTC 2019
Date after setting the time: Thu Jan 01 00:00:01 UTC 1970
Program 2:
// Java code to demonstrate// setTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println("Date initially: " + dateOne); // Sets the time dateOne.setTime(1000999); // Prints the time System.out.println("Date after setting" + " the time: " + dateOne); }}
Date initially: Thu Dec 05 09:32:53 UTC 1996
Date after setting the time: Thu Jan 01 00:16:40 UTC 1970
ManasChhabra2
Java - util package
Java-Functions
Java-util-Date
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
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 182,
"s": 28,
"text": "The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT.Syntax:"
},
{
"code": null,
"e": 214,
"s": 182,
"text": "public void setTime(long time)\n"
},
{
"code": null,
"e": 315,
"s": 214,
"text": "Parameters: The function accepts a single parameter time which specifies the number of milliseconds."
},
{
"code": null,
"e": 360,
"s": 315,
"text": "Return Value: It method has no return value."
},
{
"code": null,
"e": 415,
"s": 360,
"text": "Exception: The function does not throws any exception."
},
{
"code": null,
"e": 472,
"s": 415,
"text": "Program below demonstrates the above mentioned function:"
},
{
"code": null,
"e": 483,
"s": 472,
"text": "Program 1:"
},
{
"code": "// Java code to demonstrate// setTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a date object with specified time. Date dateOne = new Date(); System.out.println(\"Date initially: \" + dateOne); // Sets the time dateOne.setTime(1000); // Prints the time System.out.println(\"Date after setting\" + \" the time: \" + dateOne); }}",
"e": 1071,
"s": 483,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1071,
"text": "Date initially: Wed Jan 02 09:34:03 UTC 2019\nDate after setting the time: Thu Jan 01 00:00:01 UTC 1970\n"
},
{
"code": null,
"e": 1186,
"s": 1175,
"text": "Program 2:"
},
{
"code": "// Java code to demonstrate// setTime() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println(\"Date initially: \" + dateOne); // Sets the time dateOne.setTime(1000999); // Prints the time System.out.println(\"Date after setting\" + \" the time: \" + dateOne); }}",
"e": 2078,
"s": 1186,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2078,
"text": "Date initially: Thu Dec 05 09:32:53 UTC 1996\nDate after setting the time: Thu Jan 01 00:16:40 UTC 1970\n"
},
{
"code": null,
"e": 2196,
"s": 2182,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2216,
"s": 2196,
"text": "Java - util package"
},
{
"code": null,
"e": 2231,
"s": 2216,
"text": "Java-Functions"
},
{
"code": null,
"e": 2246,
"s": 2231,
"text": "Java-util-Date"
},
{
"code": null,
"e": 2251,
"s": 2246,
"text": "Java"
},
{
"code": null,
"e": 2256,
"s": 2251,
"text": "Java"
},
{
"code": null,
"e": 2354,
"s": 2256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2405,
"s": 2354,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2436,
"s": 2405,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2455,
"s": 2436,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2485,
"s": 2455,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2500,
"s": 2485,
"text": "Stream In Java"
},
{
"code": null,
"e": 2518,
"s": 2500,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2538,
"s": 2518,
"text": "Collections in Java"
},
{
"code": null,
"e": 2562,
"s": 2538,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2594,
"s": 2562,
"text": "Multidimensional Arrays in Java"
}
] |
Find the lexicographically smallest string which satisfies the given condition
|
09 Jun, 2022
Given an array, arr[] of N integers, where arr[i] represents the number of distinct characters in the prefix of length (i + 1) of a string S. The task is to find the lexicographically smallest string (if any exists) that satisfies the given prefix array. The string should be of lowercase English alphabets [a-z]. If no such string exists then print -1.
Examples:
Input: arr[] = {1, 1, 2, 3} Output: aabc prefix[0] has 1 distinct character prefix[1] has 1 distinct character prefix[2] has 2 distinct characters prefix[3] has 3 distinct characters And the string is the smallest possible.
Input: arr[] = {1, 2, 2, 3, 3, 4} Output: abacad
Input: arr[] = {1, 1, 3, 3} Output: -1
Approach: The first character of every string will always be ‘a’. Since we have to find the lexicographically smallest string. Therefore, if the number of different characters in the prefix of length i and i + 1 is same, then (i+1)th character will be ‘a’ otherwise it will be a different character from all characters in length i and it will be one greater than the greatest character in the prefix of length i.
For example, if prefix array is {1, 2, 2, 3, 4} then the first character will be ‘a’, the second character will be ‘b’ since number of different character is 2 (it can also be ‘c’ or ‘d’ etc but we have to take lexicographically smallest). Third character will be either ‘a’ or ‘b’ but we take ‘a’ since “aba” is smaller than “abb”. Similarly, fourth and fifth character will be ‘c’ and ‘d’ respectively. Therefore, the resultant string that satisfies the given prefix array will be “abacd”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the required stringstring smallestString(int N, int A[]){ // First character will always be 'a' char ch = 'a'; // To store the resultant string string S = ""; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = "-1"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = "-1"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << smallestString(n, arr); return 0;}
// Java implementation of the above approachclass GFG{ // Function to return the required string static String smallestString(int N, int []A) { // First character will always be 'a' char ch = 'a'; // To store the resultant string String S = ""; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = "-1"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = "-1"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S; } // Driver code public static void main(String args[]) { int []arr = { 1, 1, 2, 3, 3 }; int n = arr.length; System.out.println(smallestString(n, arr)); }} // This code is contributed by Ryuga
# Function to return the required stringdef smallestString(N, A): # First character will always be 'a' ch = 'a' # To store the resultant string S = "" # Since length of the string should be # greater than 0 and first element # of array should be 1 if (N < 1 or A[0] != 1): S = "-1" return S S += str(ch) ch = chr(ord(ch) + 1) # Check one by one all element of # given prefix array for i in range(1, N): diff = A[i] - A[i - 1] # If the difference between any two # consecutive elements of the prefix # array is greater than 1 then there # will be no such string possible that # satisfies the given array. # Also, string cannot have more than # 26 distinct characters if (diff > 1 or diff < 0 or A[i] > 26): S = "-1" return S # If difference is 0 then the # (i + 1)th character will be # same as the ith character elif (diff == 0): S += 'a' # If difference is 1 then the # (i + 1)th character will be # different from the ith character else: S += ch ch = chr(ord(ch) + 1) # Return the resultant string return S # Driver codearr = [1, 1, 2, 3, 3]n = len(arr)print(smallestString(n, arr)) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the required stringstatic string smallestString(int N, int []A){ // First character will always be 'a' char ch = 'a'; // To store the resultant string string S = ""; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = "-1"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = "-1"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S;} // Driver codestatic void Main(){ int []arr = { 1, 1, 2, 3, 3 }; int n = arr.Length; Console.WriteLine(smallestString(n, arr));}} // This code is contributed by mits
<?PHP// PHP implementation of the above approach// Function to return the required stringfunction smallestString($N, $A){ // First character will always be 'a' $ch = 'a'; // To store the resultant string $S = ""; // Since length of the string should be // greater than 0 and first element // of array should be 1 if ($N < 1 || $A[0] != 1) { $S = "-1"; return $S; } $S .= $ch; $ch++; // Check one by one all element of given prefix array for ($i = 1; $i < $N; $i++) { $diff = $A[$i] - $A[$i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if ($diff > 1 || $diff < 0 || $A[$i] > 26) { $S = "-1"; return $S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if ($diff == 0) $S .= 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { $S .= $ch; $ch++; } } // Return the resultant string return $S;} // Driver code$arr = array( 1, 1, 2, 3, 3 );$n = sizeof($arr);echo(smallestString($n, $arr)); // This code is contributed by Code_Mech?>
<script> // Javascript implementation of the approach // Function to return the required stringfunction smallestString(N, A){ // First character will always be 'a' let ch = 'a'; // To store the resultant string let S = ""; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = "-1"; return S; } S += ch; ch = String.fromCharCode(ch.charCodeAt(0) + 1); // Check one by one all element of // given prefix array for(let i = 1; i < N; i++) { let diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix // array is greater than 1 then there // will be no such string possible that // satisfies the given array. Also, // string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = "-1"; return S; } // If difference is 0 then the (i + 1)th // character will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th // character will be different from the // ith character else { S += ch; ch = String.fromCharCode( ch.charCodeAt(0) + 1); } } // Return the resultant string return S;} // Driver codelet arr = [ 1, 1, 2, 3, 3 ];let n = arr.length; document.write(smallestString(n, arr)); // This code is contributed by souravmahato348 </script>
aabca
Time Complexity: O(n)Auxiliary Space: O(1)
mohit kumar 29
Mithun Kumar
ankthon
Code_Mech
souravmahato348
rishavnitro
Greedy
Mathematical
Strings
Strings
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 408,
"s": 53,
"text": "Given an array, arr[] of N integers, where arr[i] represents the number of distinct characters in the prefix of length (i + 1) of a string S. The task is to find the lexicographically smallest string (if any exists) that satisfies the given prefix array. The string should be of lowercase English alphabets [a-z]. If no such string exists then print -1. "
},
{
"code": null,
"e": 419,
"s": 408,
"text": "Examples: "
},
{
"code": null,
"e": 643,
"s": 419,
"text": "Input: arr[] = {1, 1, 2, 3} Output: aabc prefix[0] has 1 distinct character prefix[1] has 1 distinct character prefix[2] has 2 distinct characters prefix[3] has 3 distinct characters And the string is the smallest possible."
},
{
"code": null,
"e": 692,
"s": 643,
"text": "Input: arr[] = {1, 2, 2, 3, 3, 4} Output: abacad"
},
{
"code": null,
"e": 733,
"s": 692,
"text": "Input: arr[] = {1, 1, 3, 3} Output: -1 "
},
{
"code": null,
"e": 1147,
"s": 733,
"text": "Approach: The first character of every string will always be ‘a’. Since we have to find the lexicographically smallest string. Therefore, if the number of different characters in the prefix of length i and i + 1 is same, then (i+1)th character will be ‘a’ otherwise it will be a different character from all characters in length i and it will be one greater than the greatest character in the prefix of length i. "
},
{
"code": null,
"e": 1639,
"s": 1147,
"text": "For example, if prefix array is {1, 2, 2, 3, 4} then the first character will be ‘a’, the second character will be ‘b’ since number of different character is 2 (it can also be ‘c’ or ‘d’ etc but we have to take lexicographically smallest). Third character will be either ‘a’ or ‘b’ but we take ‘a’ since “aba” is smaller than “abb”. Similarly, fourth and fifth character will be ‘c’ and ‘d’ respectively. Therefore, the resultant string that satisfies the given prefix array will be “abacd”."
},
{
"code": null,
"e": 1692,
"s": 1639,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1696,
"s": 1692,
"text": "C++"
},
{
"code": null,
"e": 1701,
"s": 1696,
"text": "Java"
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Python3"
},
{
"code": null,
"e": 1712,
"s": 1709,
"text": "C#"
},
{
"code": null,
"e": 1716,
"s": 1712,
"text": "PHP"
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the required stringstring smallestString(int N, int A[]){ // First character will always be 'a' char ch = 'a'; // To store the resultant string string S = \"\"; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = \"-1\"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = \"-1\"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S;} // Driver codeint main(){ int arr[] = { 1, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << smallestString(n, arr); return 0;}",
"e": 3235,
"s": 1727,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Function to return the required string static String smallestString(int N, int []A) { // First character will always be 'a' char ch = 'a'; // To store the resultant string String S = \"\"; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = \"-1\"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = \"-1\"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S; } // Driver code public static void main(String args[]) { int []arr = { 1, 1, 2, 3, 3 }; int n = arr.length; System.out.println(smallestString(n, arr)); }} // This code is contributed by Ryuga",
"e": 5050,
"s": 3235,
"text": null
},
{
"code": "# Function to return the required stringdef smallestString(N, A): # First character will always be 'a' ch = 'a' # To store the resultant string S = \"\" # Since length of the string should be # greater than 0 and first element # of array should be 1 if (N < 1 or A[0] != 1): S = \"-1\" return S S += str(ch) ch = chr(ord(ch) + 1) # Check one by one all element of # given prefix array for i in range(1, N): diff = A[i] - A[i - 1] # If the difference between any two # consecutive elements of the prefix # array is greater than 1 then there # will be no such string possible that # satisfies the given array. # Also, string cannot have more than # 26 distinct characters if (diff > 1 or diff < 0 or A[i] > 26): S = \"-1\" return S # If difference is 0 then the # (i + 1)th character will be # same as the ith character elif (diff == 0): S += 'a' # If difference is 1 then the # (i + 1)th character will be # different from the ith character else: S += ch ch = chr(ord(ch) + 1) # Return the resultant string return S # Driver codearr = [1, 1, 2, 3, 3]n = len(arr)print(smallestString(n, arr)) # This code is contributed# by mohit kumar",
"e": 6424,
"s": 5050,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the required stringstatic string smallestString(int N, int []A){ // First character will always be 'a' char ch = 'a'; // To store the resultant string string S = \"\"; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = \"-1\"; return S; } S += ch; ch++; // Check one by one all element of given prefix array for (int i = 1; i < N; i++) { int diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = \"-1\"; return S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { S += ch; ch++; } } // Return the resultant string return S;} // Driver codestatic void Main(){ int []arr = { 1, 1, 2, 3, 3 }; int n = arr.Length; Console.WriteLine(smallestString(n, arr));}} // This code is contributed by mits",
"e": 7971,
"s": 6424,
"text": null
},
{
"code": "<?PHP// PHP implementation of the above approach// Function to return the required stringfunction smallestString($N, $A){ // First character will always be 'a' $ch = 'a'; // To store the resultant string $S = \"\"; // Since length of the string should be // greater than 0 and first element // of array should be 1 if ($N < 1 || $A[0] != 1) { $S = \"-1\"; return $S; } $S .= $ch; $ch++; // Check one by one all element of given prefix array for ($i = 1; $i < $N; $i++) { $diff = $A[$i] - $A[$i - 1]; // If the difference between any two // consecutive elements of the prefix array // is greater than 1 then there will be no such // string possible that satisfies the given array // Also, string cannot have more than // 26 distinct characters if ($diff > 1 || $diff < 0 || $A[$i] > 26) { $S = \"-1\"; return $S; } // If difference is 0 then the (i + 1)th character // will be same as the ith character else if ($diff == 0) $S .= 'a'; // If difference is 1 then the (i + 1)th character // will be different from the ith character else { $S .= $ch; $ch++; } } // Return the resultant string return $S;} // Driver code$arr = array( 1, 1, 2, 3, 3 );$n = sizeof($arr);echo(smallestString($n, $arr)); // This code is contributed by Code_Mech?>",
"e": 9460,
"s": 7971,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the required stringfunction smallestString(N, A){ // First character will always be 'a' let ch = 'a'; // To store the resultant string let S = \"\"; // Since length of the string should be // greater than 0 and first element // of array should be 1 if (N < 1 || A[0] != 1) { S = \"-1\"; return S; } S += ch; ch = String.fromCharCode(ch.charCodeAt(0) + 1); // Check one by one all element of // given prefix array for(let i = 1; i < N; i++) { let diff = A[i] - A[i - 1]; // If the difference between any two // consecutive elements of the prefix // array is greater than 1 then there // will be no such string possible that // satisfies the given array. Also, // string cannot have more than // 26 distinct characters if (diff > 1 || diff < 0 || A[i] > 26) { S = \"-1\"; return S; } // If difference is 0 then the (i + 1)th // character will be same as the ith character else if (diff == 0) S += 'a'; // If difference is 1 then the (i + 1)th // character will be different from the // ith character else { S += ch; ch = String.fromCharCode( ch.charCodeAt(0) + 1); } } // Return the resultant string return S;} // Driver codelet arr = [ 1, 1, 2, 3, 3 ];let n = arr.length; document.write(smallestString(n, arr)); // This code is contributed by souravmahato348 </script>",
"e": 11092,
"s": 9460,
"text": null
},
{
"code": null,
"e": 11098,
"s": 11092,
"text": "aabca"
},
{
"code": null,
"e": 11143,
"s": 11100,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11158,
"s": 11143,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11171,
"s": 11158,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11179,
"s": 11171,
"text": "ankthon"
},
{
"code": null,
"e": 11189,
"s": 11179,
"text": "Code_Mech"
},
{
"code": null,
"e": 11205,
"s": 11189,
"text": "souravmahato348"
},
{
"code": null,
"e": 11217,
"s": 11205,
"text": "rishavnitro"
},
{
"code": null,
"e": 11224,
"s": 11217,
"text": "Greedy"
},
{
"code": null,
"e": 11237,
"s": 11224,
"text": "Mathematical"
},
{
"code": null,
"e": 11245,
"s": 11237,
"text": "Strings"
},
{
"code": null,
"e": 11253,
"s": 11245,
"text": "Strings"
},
{
"code": null,
"e": 11260,
"s": 11253,
"text": "Greedy"
},
{
"code": null,
"e": 11273,
"s": 11260,
"text": "Mathematical"
},
{
"code": null,
"e": 11371,
"s": 11273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11402,
"s": 11371,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 11421,
"s": 11402,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 11464,
"s": 11421,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 11492,
"s": 11464,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 11515,
"s": 11492,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 11545,
"s": 11515,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11588,
"s": 11545,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 11603,
"s": 11588,
"text": "C++ Data Types"
},
{
"code": null,
"e": 11627,
"s": 11603,
"text": "Merge two sorted arrays"
}
] |
Use of COALESCE() function in SQL Server
|
10 Dec, 2020
Introduction :The SQL Server COALESCE() function is useful to handle NULL values. The NULL values are replaced with the user-given value during the expression value evaluation process. The SQL Server Coalesce function evaluates the expression in a definite order and always results first not null value from the defined expression list.
Syntax :
COALESCE ( exv1, exv2..., exvN )
Where –exv1, exv2..., exvN are expression values.
Properties of the Syntax of SQL Server Coalesce function :
All expressions must be have same data-type.
It could have multiple expressions.
Example-1 :
SELECT COALESCE (NULL, 'X', 'Y')
AS RESULT ;
Output :
Example-2 :
SELECT COALESCE (NULL, 13, 24, 35, 46)
AS RESULT ;
Output :
Example-3 :
SELECT COALESCE (NULL, NULL, 45, NULL, NULL)
AS RESULT ;
Output :
Example-4 :
SELECT COALESCE (NULL, NULL, NULL, NULL, NULL, 'GFG')
AS RESULT ;
Output :
Example-5 :
SELECT COALESCE (NULL, NULL, NULL, NULL, 5, ‘GFG’) AS RESULT ;
Output :when the queries are run in SQL Server Management Studio.
Example-6 :
SELECT COALESCE
(NULL, NULL, NULL, NULL, NULL, 'GFG', 1)
Output :
Using SQL Server Coalesce function in a string concatenation operation :Let us suppose we have below table name “GeekName”.
Example-7 :Output :
Select * from GeekName;
Example-8 :
SELECT F_Name + ' ' +M_Name+ ' '
+ L_Name FullName FROM GeekName ;
Output :
Using SQL server function called COALESCE to handle the NULL values :The SQL statement will concatenate all three names, but no NULL values will appear in the output.
Example-9 :
SELECT F_Name +' '+COALESCE(M_Name, '') +' '
+ L_Name FullName FROM GeekName ;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2020"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "Introduction :The SQL Server COALESCE() function is useful to handle NULL values. The NULL values are replaced with the user-given value during the expression value evaluation process. The SQL Server Coalesce function evaluates the expression in a definite order and always results first not null value from the defined expression list."
},
{
"code": null,
"e": 374,
"s": 365,
"text": "Syntax :"
},
{
"code": null,
"e": 408,
"s": 374,
"text": "COALESCE ( exv1, exv2..., exvN )\n"
},
{
"code": null,
"e": 458,
"s": 408,
"text": "Where –exv1, exv2..., exvN are expression values."
},
{
"code": null,
"e": 517,
"s": 458,
"text": "Properties of the Syntax of SQL Server Coalesce function :"
},
{
"code": null,
"e": 562,
"s": 517,
"text": "All expressions must be have same data-type."
},
{
"code": null,
"e": 598,
"s": 562,
"text": "It could have multiple expressions."
},
{
"code": null,
"e": 610,
"s": 598,
"text": "Example-1 :"
},
{
"code": null,
"e": 656,
"s": 610,
"text": "SELECT COALESCE (NULL, 'X', 'Y') \nAS RESULT ;"
},
{
"code": null,
"e": 665,
"s": 656,
"text": "Output :"
},
{
"code": null,
"e": 677,
"s": 665,
"text": "Example-2 :"
},
{
"code": null,
"e": 729,
"s": 677,
"text": "SELECT COALESCE (NULL, 13, 24, 35, 46) \nAS RESULT ;"
},
{
"code": null,
"e": 738,
"s": 729,
"text": "Output :"
},
{
"code": null,
"e": 750,
"s": 738,
"text": "Example-3 :"
},
{
"code": null,
"e": 808,
"s": 750,
"text": "SELECT COALESCE (NULL, NULL, 45, NULL, NULL) \nAS RESULT ;"
},
{
"code": null,
"e": 817,
"s": 808,
"text": "Output :"
},
{
"code": null,
"e": 829,
"s": 817,
"text": "Example-4 :"
},
{
"code": null,
"e": 896,
"s": 829,
"text": "SELECT COALESCE (NULL, NULL, NULL, NULL, NULL, 'GFG') \nAS RESULT ;"
},
{
"code": null,
"e": 905,
"s": 896,
"text": "Output :"
},
{
"code": null,
"e": 917,
"s": 905,
"text": "Example-5 :"
},
{
"code": null,
"e": 980,
"s": 917,
"text": "SELECT COALESCE (NULL, NULL, NULL, NULL, 5, ‘GFG’) AS RESULT ;"
},
{
"code": null,
"e": 1046,
"s": 980,
"text": "Output :when the queries are run in SQL Server Management Studio."
},
{
"code": null,
"e": 1058,
"s": 1046,
"text": "Example-6 :"
},
{
"code": null,
"e": 1116,
"s": 1058,
"text": "SELECT COALESCE \n(NULL, NULL, NULL, NULL, NULL, 'GFG', 1)"
},
{
"code": null,
"e": 1125,
"s": 1116,
"text": "Output :"
},
{
"code": null,
"e": 1249,
"s": 1125,
"text": "Using SQL Server Coalesce function in a string concatenation operation :Let us suppose we have below table name “GeekName”."
},
{
"code": null,
"e": 1269,
"s": 1249,
"text": "Example-7 :Output :"
},
{
"code": null,
"e": 1293,
"s": 1269,
"text": "Select * from GeekName;"
},
{
"code": null,
"e": 1305,
"s": 1293,
"text": "Example-8 :"
},
{
"code": null,
"e": 1373,
"s": 1305,
"text": "SELECT F_Name + ' ' +M_Name+ ' ' \n+ L_Name FullName FROM GeekName ;"
},
{
"code": null,
"e": 1382,
"s": 1373,
"text": "Output :"
},
{
"code": null,
"e": 1549,
"s": 1382,
"text": "Using SQL server function called COALESCE to handle the NULL values :The SQL statement will concatenate all three names, but no NULL values will appear in the output."
},
{
"code": null,
"e": 1561,
"s": 1549,
"text": "Example-9 :"
},
{
"code": null,
"e": 1643,
"s": 1561,
"text": "SELECT F_Name +' '+COALESCE(M_Name, '') +' '\n+ L_Name FullName FROM GeekName ;"
},
{
"code": null,
"e": 1652,
"s": 1643,
"text": "Output :"
},
{
"code": null,
"e": 1661,
"s": 1652,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1672,
"s": 1661,
"text": "SQL-Server"
},
{
"code": null,
"e": 1676,
"s": 1672,
"text": "SQL"
},
{
"code": null,
"e": 1680,
"s": 1676,
"text": "SQL"
},
{
"code": null,
"e": 1778,
"s": 1680,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1789,
"s": 1778,
"text": "CTE in SQL"
},
{
"code": null,
"e": 1855,
"s": 1789,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1886,
"s": 1855,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 1910,
"s": 1886,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1922,
"s": 1910,
"text": "SQL | Views"
},
{
"code": null,
"e": 1967,
"s": 1922,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2000,
"s": 1967,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 2024,
"s": 2000,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2056,
"s": 2024,
"text": "MySQL | Group_CONCAT() Function"
}
] |
Java Program for Longest Common Subsequence
|
04 Dec, 2018
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program that outputs the differences between two files), and has applications in bioinformatics.
Examples:LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).
If last characters of both sequences match (or X[m-1] == Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
If last characters of both sequences do not match (or X[m-1] != Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])
/* A Naive recursive implementation of LCS problem in java*/public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGTAB"; String s2 = "GXTXAYB"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs(X, Y, m, n)); }} // This Code is Contributed by Saket Kumar
Length of LCS is 4
Following is a tabulated implementation for the LCS problem.
/* Dynamic Programming Java implementation of LCS problem */public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { int L[][] = new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } return L[m][n]; } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = "AGGTAB"; String s2 = "GXTXAYB"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println("Length of LCS is" + " " + lcs.lcs(X, Y, m, n)); }} // This Code is Contributed by Saket Kumar
Length of LCS is 4
Please refer complete article on Dynamic Programming | Set 4 (Longest Common Subsequence) for more details!
LCS
Dynamic Programming
Java Programs
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 415,
"s": 52,
"text": "LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences."
},
{
"code": null,
"e": 591,
"s": 415,
"text": "It is a classic computer science problem, the basis of diff (a file comparison program that outputs the differences between two files), and has applications in bioinformatics."
},
{
"code": null,
"e": 737,
"s": 591,
"text": "Examples:LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4."
},
{
"code": null,
"e": 970,
"s": 737,
"text": "Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0..m-1], Y[0..n-1])."
},
{
"code": null,
"e": 1093,
"s": 970,
"text": "If last characters of both sequences match (or X[m-1] == Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])"
},
{
"code": null,
"e": 1250,
"s": 1093,
"text": "If last characters of both sequences do not match (or X[m-1] != Y[n-1]) thenL(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])"
},
{
"code": "/* A Naive recursive implementation of LCS problem in java*/public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = \"AGGTAB\"; String s2 = \"GXTXAYB\"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println(\"Length of LCS is\" + \" \" + lcs.lcs(X, Y, m, n)); }} // This Code is Contributed by Saket Kumar",
"e": 2244,
"s": 1250,
"text": null
},
{
"code": null,
"e": 2264,
"s": 2244,
"text": "Length of LCS is 4\n"
},
{
"code": null,
"e": 2325,
"s": 2264,
"text": "Following is a tabulated implementation for the LCS problem."
},
{
"code": "/* Dynamic Programming Java implementation of LCS problem */public class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char[] X, char[] Y, int m, int n) { int L[][] = new int[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } return L[m][n]; } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); String s1 = \"AGGTAB\"; String s2 = \"GXTXAYB\"; char[] X = s1.toCharArray(); char[] Y = s2.toCharArray(); int m = X.length; int n = Y.length; System.out.println(\"Length of LCS is\" + \" \" + lcs.lcs(X, Y, m, n)); }} // This Code is Contributed by Saket Kumar",
"e": 3671,
"s": 2325,
"text": null
},
{
"code": null,
"e": 3691,
"s": 3671,
"text": "Length of LCS is 4\n"
},
{
"code": null,
"e": 3799,
"s": 3691,
"text": "Please refer complete article on Dynamic Programming | Set 4 (Longest Common Subsequence) for more details!"
},
{
"code": null,
"e": 3803,
"s": 3799,
"text": "LCS"
},
{
"code": null,
"e": 3823,
"s": 3803,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 3837,
"s": 3823,
"text": "Java Programs"
},
{
"code": null,
"e": 3857,
"s": 3837,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 3861,
"s": 3857,
"text": "LCS"
},
{
"code": null,
"e": 3959,
"s": 3861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3986,
"s": 3959,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 4024,
"s": 3986,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 4057,
"s": 4024,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 4076,
"s": 4057,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 4111,
"s": 4076,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 4139,
"s": 4111,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 4165,
"s": 4139,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4209,
"s": 4165,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 4243,
"s": 4209,
"text": "Convert Double to Integer in Java"
}
] |
What is a modulo operator (%) in Python?
|
28 Jul, 2020
When we see a ‘%’ the first thing that comes to our mind is the “Percentage-sign”, but when we think of it from the perspective of computer language, this sign has, in fact, another name and meaning. In computing, the modulo operation(%) finds the remainder or signed remainder after the division of one number by another (called the modulus of the operation).
Given two positive numbers, a and n, a modulo n (a % n, abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
Basically, Python modulo operation is used to get the remainder of a division. The modulo operator(%) is considered an arithmetic operation, along with +, –, /, *, **, //. In most languages, both operands of this modulo operator have to be an integer. But Python Modulo is versatile in this case. The operands can be either integer or float.
Syntax:
a % b
Here, a is divided by b, and the remainder of that division is returned.
Code:
Python3
# inputsa = 13b = 5 # Stores the remainder obtained # when dividing a by b, in cc = a % b print(a, "mod", b, "=", c, sep = " ") # inputsd = 15.0e = 7.0 # Stores the remainder obtained # when dividing d by e, in ff = d % eprint(d, "mod", e, "=", f, sep = " ")
Output:
13 mod 5 = 3
15.0 mod 7.0 = 1.0
This was a simple example showing the use of the syntax, and a basic operation performed by the modulo operator. Suppose, we want to calculate the remainder of every number from 1 to n when divided by a fixed number k.
Python3
# function is defined for finding out # the remainder of every number from 1 to ndef findRemainder(n, k): for i in range(1, n + 1): # rem will store the remainder # when i is divided by k. rem = i % k print(i, "mod", k, "=", rem, sep = " ") # Driver codeif __name__ == "__main__" : # inputs n = 5 k = 3 # function calling findRemainder(n, k)
Output:
1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
5 mod 3 = 2
The only Exception you get with python modulo operation is ZeroDivisionError. This happens if the divider operand of the modulo operator becomes zero. That means the right operand can’t be zero. Let’s see the following code to know about this python exception.
Python3
# inputsa = 14b = 0 # exception handlingtry: print(a, 'mod', b, '=', a % b, sep = " ") except ZeroDivisionError as err: print('Cannot divide by zero!' + 'Change the value of the right operand.')
Output:
Cannot divide by zero! Change the value of the right operand.
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 413,
"s": 52,
"text": "When we see a ‘%’ the first thing that comes to our mind is the “Percentage-sign”, but when we think of it from the perspective of computer language, this sign has, in fact, another name and meaning. In computing, the modulo operation(%) finds the remainder or signed remainder after the division of one number by another (called the modulus of the operation)."
},
{
"code": null,
"e": 593,
"s": 413,
"text": "Given two positive numbers, a and n, a modulo n (a % n, abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor."
},
{
"code": null,
"e": 935,
"s": 593,
"text": "Basically, Python modulo operation is used to get the remainder of a division. The modulo operator(%) is considered an arithmetic operation, along with +, –, /, *, **, //. In most languages, both operands of this modulo operator have to be an integer. But Python Modulo is versatile in this case. The operands can be either integer or float."
},
{
"code": null,
"e": 943,
"s": 935,
"text": "Syntax:"
},
{
"code": null,
"e": 951,
"s": 943,
"text": "a % b\n\n"
},
{
"code": null,
"e": 1024,
"s": 951,
"text": "Here, a is divided by b, and the remainder of that division is returned."
},
{
"code": null,
"e": 1031,
"s": 1024,
"text": "Code: "
},
{
"code": null,
"e": 1039,
"s": 1031,
"text": "Python3"
},
{
"code": "# inputsa = 13b = 5 # Stores the remainder obtained # when dividing a by b, in cc = a % b print(a, \"mod\", b, \"=\", c, sep = \" \") # inputsd = 15.0e = 7.0 # Stores the remainder obtained # when dividing d by e, in ff = d % eprint(d, \"mod\", e, \"=\", f, sep = \" \")",
"e": 1317,
"s": 1039,
"text": null
},
{
"code": null,
"e": 1325,
"s": 1317,
"text": "Output:"
},
{
"code": null,
"e": 1358,
"s": 1325,
"text": "13 mod 5 = 3\n15.0 mod 7.0 = 1.0\n"
},
{
"code": null,
"e": 1577,
"s": 1358,
"text": "This was a simple example showing the use of the syntax, and a basic operation performed by the modulo operator. Suppose, we want to calculate the remainder of every number from 1 to n when divided by a fixed number k."
},
{
"code": null,
"e": 1585,
"s": 1577,
"text": "Python3"
},
{
"code": "# function is defined for finding out # the remainder of every number from 1 to ndef findRemainder(n, k): for i in range(1, n + 1): # rem will store the remainder # when i is divided by k. rem = i % k print(i, \"mod\", k, \"=\", rem, sep = \" \") # Driver codeif __name__ == \"__main__\" : # inputs n = 5 k = 3 # function calling findRemainder(n, k)",
"e": 1977,
"s": 1585,
"text": null
},
{
"code": null,
"e": 1986,
"s": 1977,
"text": " Output:"
},
{
"code": null,
"e": 2047,
"s": 1986,
"text": "1 mod 3 = 1\n2 mod 3 = 2\n3 mod 3 = 0\n4 mod 3 = 1\n5 mod 3 = 2\n"
},
{
"code": null,
"e": 2308,
"s": 2047,
"text": "The only Exception you get with python modulo operation is ZeroDivisionError. This happens if the divider operand of the modulo operator becomes zero. That means the right operand can’t be zero. Let’s see the following code to know about this python exception."
},
{
"code": null,
"e": 2316,
"s": 2308,
"text": "Python3"
},
{
"code": "# inputsa = 14b = 0 # exception handlingtry: print(a, 'mod', b, '=', a % b, sep = \" \") except ZeroDivisionError as err: print('Cannot divide by zero!' + 'Change the value of the right operand.')",
"e": 2541,
"s": 2316,
"text": null
},
{
"code": null,
"e": 2550,
"s": 2541,
"text": " Output:"
},
{
"code": null,
"e": 2613,
"s": 2550,
"text": "Cannot divide by zero! Change the value of the right operand.\n"
},
{
"code": null,
"e": 2630,
"s": 2613,
"text": "Python-Operators"
},
{
"code": null,
"e": 2637,
"s": 2630,
"text": "Python"
}
] |
RadioGroup in Kotlin
|
19 Feb, 2021
RadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. The RadioGroup class is beneficial for placing a set of radio buttons inside it because this class adds multiple-exclusion scope feature to the radio buttons. This feature assures that the user will be able to check only one of the radio buttons among all which belongs to a RadioGroup class. If the user checks another radio button, the RadioGroup class unchecks the previously checked radio button. This feature is very important when the developer wants to have only one answer to be selected such as asking the gender of a user.
In this example step by step demonstration of creating a RadioGroup will be covered, it consists of 5 RadioButton children which ask the user to choose a course offered by GeeksforGeeks. When the user checks one of the RadioButtons and clicks the Submit button a toast message appears which displays the selected option.
Note: Following steps are performed on Android Studio version 4.0
Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need.
Click on File, then New => New Project.
Choose “Empty Activity” for the project template.
Select language as Kotlin.
Select the minimum SDK as per your need.
Below is the code for activity_main.xml file to add a RadioGroup and its 5 RadioButton children. A normal submit button is also added to accept and display the response selected by the user.
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/Heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="36sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.19" /> <RadioGroup android:id="@+id/radioGroup1" android:layout_width="0dp" android:layout_height="wrap_content" android:background="#024CAF50" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.24000001"> <RadioButton android:id="@+id/radioButton1" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/RadioButton1" android:textSize="24sp" /> <RadioButton android:id="@+id/radioButton2" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/radioButton2" android:textSize="24sp" /> <RadioButton android:id="@+id/radioButton3" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/radioButton3" android:textSize="24sp" /> <RadioButton android:id="@+id/radioButton4" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/radioButton4" android:textSize="24sp" /> <RadioButton android:id="@+id/radioButton5" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/radioButton5" android:textSize="24sp" /> </RadioGroup> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#AB4CAF50" android:text="@string/submit_Button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/radioGroup1" app:layout_constraintVertical_bias="0.17000002" /></androidx.constraintlayout.widget.ConstraintLayout>
Below is the code for MainActivity.kt file to access RadioGroup widget in kotlin file and show a proper message whenever a radio button is selected by the user.
package com.example.sampleproject import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.RadioButtonimport android.widget.RadioGroupimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { var radioGroup: RadioGroup? = null lateinit var radioButton: RadioButton private lateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Display name of the Application title = "RadioGroup in Kotlin" // Assigning id of RadioGroup radioGroup = findViewById(R.id.radioGroup1) // Assigning id of Submit button button = findViewById(R.id.submitButton) // Actions to be performed // when Submit button is clicked button.setOnClickListener { // Getting the checked radio button id // from the radio group val selectedOption: Int = radioGroup!!.checkedRadioButtonId // Assigning id of the checked radio button radioButton = findViewById(selectedOption) // Displaying text of the checked radio button in the form of toast Toast.makeText(baseContext, radioButton.text, Toast.LENGTH_SHORT).show() } }}
All the strings which are used in the activity, from the application name to the option of various RadioButtons are listed in this file.
<resources> <string name="app_name">RadioGroup in Kotlin</string> <string name="Heading">Choose a GfG course</string> <string name="RadioButton1">Amazon SDE Test Series</string> <string name="radioButton2">Placement 100</string> <string name="radioButton3">C++ STL</string> <string name="radioButton4">CS Core Subjects</string> <string name="radioButton5">DSA Self paced</string> <string name="submit_Button">Submit</string></resources>
Android-Button
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Navigation Drawer in Android
Android Project folder Structure
Flutter - Custom Bottom Navigation Bar
Android RecyclerView in Kotlin
Android UI Layouts
Kotlin constructor
Retrofit with Kotlin Coroutine in Android
Content Providers in Android with Example
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 700,
"s": 54,
"text": "RadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. The RadioGroup class is beneficial for placing a set of radio buttons inside it because this class adds multiple-exclusion scope feature to the radio buttons. This feature assures that the user will be able to check only one of the radio buttons among all which belongs to a RadioGroup class. If the user checks another radio button, the RadioGroup class unchecks the previously checked radio button. This feature is very important when the developer wants to have only one answer to be selected such as asking the gender of a user."
},
{
"code": null,
"e": 1021,
"s": 700,
"text": "In this example step by step demonstration of creating a RadioGroup will be covered, it consists of 5 RadioButton children which ask the user to choose a course offered by GeeksforGeeks. When the user checks one of the RadioButtons and clicks the Submit button a toast message appears which displays the selected option."
},
{
"code": null,
"e": 1087,
"s": 1021,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 1242,
"s": 1087,
"text": "Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need."
},
{
"code": null,
"e": 1282,
"s": 1242,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 1332,
"s": 1282,
"text": "Choose “Empty Activity” for the project template."
},
{
"code": null,
"e": 1359,
"s": 1332,
"text": "Select language as Kotlin."
},
{
"code": null,
"e": 1400,
"s": 1359,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 1591,
"s": 1400,
"text": "Below is the code for activity_main.xml file to add a RadioGroup and its 5 RadioButton children. A normal submit button is also added to accept and display the response selected by the user."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/Heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"36sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.19\" /> <RadioGroup android:id=\"@+id/radioGroup1\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:background=\"#024CAF50\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView\" app:layout_constraintVertical_bias=\"0.24000001\"> <RadioButton android:id=\"@+id/radioButton1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/RadioButton1\" android:textSize=\"24sp\" /> <RadioButton android:id=\"@+id/radioButton2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/radioButton2\" android:textSize=\"24sp\" /> <RadioButton android:id=\"@+id/radioButton3\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/radioButton3\" android:textSize=\"24sp\" /> <RadioButton android:id=\"@+id/radioButton4\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/radioButton4\" android:textSize=\"24sp\" /> <RadioButton android:id=\"@+id/radioButton5\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/radioButton5\" android:textSize=\"24sp\" /> </RadioGroup> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#AB4CAF50\" android:text=\"@string/submit_Button\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/radioGroup1\" app:layout_constraintVertical_bias=\"0.17000002\" /></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 5080,
"s": 1591,
"text": null
},
{
"code": null,
"e": 5241,
"s": 5080,
"text": "Below is the code for MainActivity.kt file to access RadioGroup widget in kotlin file and show a proper message whenever a radio button is selected by the user."
},
{
"code": "package com.example.sampleproject import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.RadioButtonimport android.widget.RadioGroupimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { var radioGroup: RadioGroup? = null lateinit var radioButton: RadioButton private lateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Display name of the Application title = \"RadioGroup in Kotlin\" // Assigning id of RadioGroup radioGroup = findViewById(R.id.radioGroup1) // Assigning id of Submit button button = findViewById(R.id.submitButton) // Actions to be performed // when Submit button is clicked button.setOnClickListener { // Getting the checked radio button id // from the radio group val selectedOption: Int = radioGroup!!.checkedRadioButtonId // Assigning id of the checked radio button radioButton = findViewById(selectedOption) // Displaying text of the checked radio button in the form of toast Toast.makeText(baseContext, radioButton.text, Toast.LENGTH_SHORT).show() } }}",
"e": 6677,
"s": 5241,
"text": null
},
{
"code": null,
"e": 6814,
"s": 6677,
"text": "All the strings which are used in the activity, from the application name to the option of various RadioButtons are listed in this file."
},
{
"code": "<resources> <string name=\"app_name\">RadioGroup in Kotlin</string> <string name=\"Heading\">Choose a GfG course</string> <string name=\"RadioButton1\">Amazon SDE Test Series</string> <string name=\"radioButton2\">Placement 100</string> <string name=\"radioButton3\">C++ STL</string> <string name=\"radioButton4\">CS Core Subjects</string> <string name=\"radioButton5\">DSA Self paced</string> <string name=\"submit_Button\">Submit</string></resources>",
"e": 7275,
"s": 6814,
"text": null
},
{
"code": null,
"e": 7290,
"s": 7275,
"text": "Android-Button"
},
{
"code": null,
"e": 7305,
"s": 7290,
"text": "Kotlin Android"
},
{
"code": null,
"e": 7312,
"s": 7305,
"text": "Picked"
},
{
"code": null,
"e": 7320,
"s": 7312,
"text": "Android"
},
{
"code": null,
"e": 7327,
"s": 7320,
"text": "Kotlin"
},
{
"code": null,
"e": 7335,
"s": 7327,
"text": "Android"
},
{
"code": null,
"e": 7433,
"s": 7335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7465,
"s": 7433,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7496,
"s": 7465,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 7525,
"s": 7496,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 7558,
"s": 7525,
"text": "Android Project folder Structure"
},
{
"code": null,
"e": 7597,
"s": 7558,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7628,
"s": 7597,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 7647,
"s": 7628,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 7666,
"s": 7647,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 7708,
"s": 7666,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
Update two columns with a single MySQL query
|
For this, you need to use SET command only once. Let us first create a table −
mysql> create table DemoTable1909
(
Id int NOT NULL,
FirstName varchar(20),
LastName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1909 values(101,'John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(102,'John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(103,'Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1909 values(104,'David','Miller');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1909;
This will produce the following output −
+-----+-----------+----------+
| Id | FirstName | LastName |
+-----+-----------+----------+
| 101 | John | Smith |
| 102 | John | Doe |
| 103 | Adam | Smith |
| 104 | David | Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)
Here is the query to update two column values −
mysql> update DemoTable1909
set FirstName='Carol',LastName='Taylor'
where Id=103;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1909;
This will produce the following output −
+-----+-----------+----------+
| Id | FirstName | LastName |
+-----+-----------+----------+
| 101 | John | Smith |
| 102 | John | Doe |
| 103 | Carol | Taylor |
| 104 | David | Miller |
+-----+-----------+----------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1266,
"s": 1187,
"text": "For this, you need to use SET command only once. Let us first create a table −"
},
{
"code": null,
"e": 1418,
"s": 1266,
"text": "mysql> create table DemoTable1909\n (\n Id int NOT NULL,\n FirstName varchar(20),\n LastName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1474,
"s": 1418,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1862,
"s": 1474,
"text": "mysql> insert into DemoTable1909 values(101,'John','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1909 values(102,'John','Doe');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1909 values(103,'Adam','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1909 values(104,'David','Miller');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1922,
"s": 1862,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1958,
"s": 1922,
"text": "mysql> select * from DemoTable1909;"
},
{
"code": null,
"e": 1999,
"s": 1958,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2272,
"s": 1999,
"text": "+-----+-----------+----------+\n| Id | FirstName | LastName |\n+-----+-----------+----------+\n| 101 | John | Smith |\n| 102 | John | Doe |\n| 103 | Adam | Smith |\n| 104 | David | Miller |\n+-----+-----------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2320,
"s": 2272,
"text": "Here is the query to update two column values −"
},
{
"code": null,
"e": 2488,
"s": 2320,
"text": "mysql> update DemoTable1909\n set FirstName='Carol',LastName='Taylor'\n where Id=103;\nQuery OK, 1 row affected (0.00 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2532,
"s": 2488,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2568,
"s": 2532,
"text": "mysql> select * from DemoTable1909;"
},
{
"code": null,
"e": 2609,
"s": 2568,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2882,
"s": 2609,
"text": "+-----+-----------+----------+\n| Id | FirstName | LastName |\n+-----+-----------+----------+\n| 101 | John | Smith |\n| 102 | John | Doe |\n| 103 | Carol | Taylor |\n| 104 | David | Miller |\n+-----+-----------+----------+\n4 rows in set (0.00 sec)"
}
] |
Maximum sum subarray having sum less than or equal to given sum using Set
|
14 Jun, 2022
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.
Note: If K is less than the minimum element, then return INT_MIN.
Examples:
Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum sum = 4, but it is not less than 4.
Input: arr[] = {5, -2, 6, 3, -5}, K =15 Output: 12 Explanation: The subarray with maximum sum which is less than 15 is {5, -2, 6, 3}.
Efficient Approach: Sum of subarray [i, j] is given by cumulative sum till j – cumulative sum till i of the array. Now the problem reduces to finding two indexes i and j, such that i < j and cum[j] – cum[i] are as close to K but lesser than it.To solve this, iterate the array from left to right. Put the cumulative sum of i values that you have encountered till now into a set. When you are processing cum[j] what you need to retrieve from the set is the smallest number in the set which is bigger than or equal to cum[j] – K. This can be done in O(logN) using upper_bound on the set.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find maximum sum// subarray less than K #include <bits/stdc++.h>using namespace std; // Function to maximum required sum < Kint maxSubarraySum(int arr[], int N, int K){ // Hash to lookup for value (cum_sum - K) set<int> cum_set; cum_set.insert(0); int max_sum = INT_MIN, cSum = 0; for (int i = 0; i < N; i++) { // getting cumulative sum from [0 to i] cSum += arr[i]; // lookup for upperbound // of (cSum-K) in hash set<int>::iterator sit = cum_set.lower_bound(cSum - K); // check if upper_bound // of (cSum-K) exists // then update max sum if (sit != cum_set.end()) max_sum = max(max_sum, cSum - *sit); // insert cumulative value in hash cum_set.insert(cSum); } // return maximum sum // lesser than K return max_sum;} // Driver codeint main(){ // initialise the array int arr[] = { 5, -2, 6, 3, -5 }; // initialise the value of K int K = 15; // size of array int N = sizeof(arr) / sizeof(arr[0]); cout << maxSubarraySum(arr, N, K); return 0;}
// Java program to find maximum sum// subarray less than Kimport java.util.*;import java.io.*; class GFG{ // Function to maximum required sum < Kstatic int maxSubarraySum(int arr[], int N, int K){ // Hash to lookup for value (cum_sum - K) Set<Integer> cum_set = new HashSet<>(); cum_set.add(0); int max_sum =Integer.MIN_VALUE, cSum = 0; for(int i = 0; i < N; i++) { // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash ArrayList<Integer> al = new ArrayList<>(); Iterator<Integer> it = cum_set.iterator(); int end = 0; while (it.hasNext()) { end = it.next(); al.add(end); } Collections.sort(al); int sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.add(cSum); } // Return maximum sum // lesser than K return max_sum;} static int lower_bound(ArrayList<Integer> al, int x){ // x is the target value or key int l = -1, r = al.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (al.get(m) >= x) r = m; else l = m; } return r;} // Driver codepublic static void main(String args[]){ // Initialise the array int arr[] = { 5, -2, 6, 3, -5 }; // Initialise the value of K int K = 15; // Size of array int N = arr.length; System.out.println(maxSubarraySum(arr, N, K));}} // This code is contributed by jyoti369
# Python3 program to find maximum sum# subarray less than Kimport sysimport bisect # Function to maximum required sum < K def maxSubarraySum(arr, N, K): # Hash to lookup for value (cum_sum - K) cum_set = set() cum_set.add(0) max_sum = 12 cSum = 0 for i in range(N): # getting cumulative sum from [0 to i] cSum += arr[i] # check if upper_bound # of (cSum-K) exists # then update max sum x = bisect.bisect_left(arr, cSum - K, lo=0, hi=len(arr)) if x: max_sum = max(max_sum,x ) # insert cumulative value in hash cum_set.add(cSum) # return maximum sum # lesser than K return max_sum # Driver codeif __name__ == '__main__': # initialise the array arr = [5, -2, 6, 3, -5] # initialise the value of K K = 15 # size of array N = len(arr) print(maxSubarraySum(arr, N, K)) # This code is contributed by Surendra_Gangwar
// Java program to find maximum sum// subarray less than Kusing System;using System.Collections.Generic;class GFG { // Function to maximum required sum < K static int maxSubarraySum(int[] arr, int N, int K) { // Hash to lookup for value (cum_sum - K) HashSet<int> cum_set = new HashSet<int>(); cum_set.Add(0); int max_sum = Int32.MinValue, cSum = 0; for (int i = 0; i < N; i++) { // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash List<int> al = new List<int>(); int end = 0; foreach(int it in cum_set) { end = it; al.Add(it); } al.Sort(); int sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.Max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.Add(cSum); } // Return maximum sum // lesser than K return max_sum; } static int lower_bound(List<int> al, int x) { // x is the target value or key int l = -1, r = al.Count; while (l + 1 < r) { int m = (l + r) >> 1; if (al[m] >= x) r = m; else l = m; } return r; } // Driver code public static void Main(string[] args) { // Initialise the array int[] arr = { 5, -2, 6, 3, -5 }; // Initialise the value of K int K = 15; // Size of array int N = arr.Length; Console.Write(maxSubarraySum(arr, N, K)); }} // This code is contributed by chitranayal.
<script> // JavaScript program to find maximum sum// subarray less than K // Function to maximum required sum < K function maxSubarraySum(arr, N, K) { // Hash to lookup for value (cum_sum - K) let cum_set = new Set(); cum_set.add(0); let max_sum = Number.MIN_SAFE_INTEGER; let cSum = 0; for(let i = 0; i < N; i++){ // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash let al = []; let end = 0; for(let it of cum_set) { end = it; al.push(it); } al.sort((a, b) => a - b); let sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.add(cSum); } // Return maximum sum // lesser than K return max_sum; } let lower_bound = (al, x) => al.filter((item) => item > x )[0] // Driver code // Initialise the array let arr = [ 5, -2, 6, 3, -5 ]; // Initialise the value of K let K = 15; // Size of array let N = arr.length; document.write(maxSubarraySum(arr, N, K)); // This code is contributed by _saurabh_jaiswal </script>
12
Time Complexity: O(N*Log(N)), where N represents the size of the given array.
Auxiliary Space: O(N), where N represents the size of the given array.
Similar article: Maximum sum subarray having sum less than or equal to given sum using Sliding Window
SURENDRA_GANGWAR
____
jyoti369
ukasp
_saurabh_jaiswal
simranarora5sos
surindertarika1234
tamanna17122007
ashishkataria002
subarray
subarray-sum
Arrays
Dynamic Programming
Hash
Searching
Arrays
Searching
Hash
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 173,
"s": 52,
"text": "Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K."
},
{
"code": null,
"e": 239,
"s": 173,
"text": "Note: If K is less than the minimum element, then return INT_MIN."
},
{
"code": null,
"e": 250,
"s": 239,
"text": "Examples: "
},
{
"code": null,
"e": 441,
"s": 250,
"text": "Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum sum = 4, but it is not less than 4. "
},
{
"code": null,
"e": 576,
"s": 441,
"text": "Input: arr[] = {5, -2, 6, 3, -5}, K =15 Output: 12 Explanation: The subarray with maximum sum which is less than 15 is {5, -2, 6, 3}. "
},
{
"code": null,
"e": 1163,
"s": 576,
"text": "Efficient Approach: Sum of subarray [i, j] is given by cumulative sum till j – cumulative sum till i of the array. Now the problem reduces to finding two indexes i and j, such that i < j and cum[j] – cum[i] are as close to K but lesser than it.To solve this, iterate the array from left to right. Put the cumulative sum of i values that you have encountered till now into a set. When you are processing cum[j] what you need to retrieve from the set is the smallest number in the set which is bigger than or equal to cum[j] – K. This can be done in O(logN) using upper_bound on the set. "
},
{
"code": null,
"e": 1215,
"s": 1163,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1219,
"s": 1215,
"text": "C++"
},
{
"code": null,
"e": 1224,
"s": 1219,
"text": "Java"
},
{
"code": null,
"e": 1232,
"s": 1224,
"text": "Python3"
},
{
"code": null,
"e": 1235,
"s": 1232,
"text": "C#"
},
{
"code": null,
"e": 1246,
"s": 1235,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum sum// subarray less than K #include <bits/stdc++.h>using namespace std; // Function to maximum required sum < Kint maxSubarraySum(int arr[], int N, int K){ // Hash to lookup for value (cum_sum - K) set<int> cum_set; cum_set.insert(0); int max_sum = INT_MIN, cSum = 0; for (int i = 0; i < N; i++) { // getting cumulative sum from [0 to i] cSum += arr[i]; // lookup for upperbound // of (cSum-K) in hash set<int>::iterator sit = cum_set.lower_bound(cSum - K); // check if upper_bound // of (cSum-K) exists // then update max sum if (sit != cum_set.end()) max_sum = max(max_sum, cSum - *sit); // insert cumulative value in hash cum_set.insert(cSum); } // return maximum sum // lesser than K return max_sum;} // Driver codeint main(){ // initialise the array int arr[] = { 5, -2, 6, 3, -5 }; // initialise the value of K int K = 15; // size of array int N = sizeof(arr) / sizeof(arr[0]); cout << maxSubarraySum(arr, N, K); return 0;}",
"e": 2371,
"s": 1246,
"text": null
},
{
"code": "// Java program to find maximum sum// subarray less than Kimport java.util.*;import java.io.*; class GFG{ // Function to maximum required sum < Kstatic int maxSubarraySum(int arr[], int N, int K){ // Hash to lookup for value (cum_sum - K) Set<Integer> cum_set = new HashSet<>(); cum_set.add(0); int max_sum =Integer.MIN_VALUE, cSum = 0; for(int i = 0; i < N; i++) { // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash ArrayList<Integer> al = new ArrayList<>(); Iterator<Integer> it = cum_set.iterator(); int end = 0; while (it.hasNext()) { end = it.next(); al.add(end); } Collections.sort(al); int sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.add(cSum); } // Return maximum sum // lesser than K return max_sum;} static int lower_bound(ArrayList<Integer> al, int x){ // x is the target value or key int l = -1, r = al.size(); while (l + 1 < r) { int m = (l + r) >>> 1; if (al.get(m) >= x) r = m; else l = m; } return r;} // Driver codepublic static void main(String args[]){ // Initialise the array int arr[] = { 5, -2, 6, 3, -5 }; // Initialise the value of K int K = 15; // Size of array int N = arr.length; System.out.println(maxSubarraySum(arr, N, K));}} // This code is contributed by jyoti369",
"e": 4194,
"s": 2371,
"text": null
},
{
"code": "# Python3 program to find maximum sum# subarray less than Kimport sysimport bisect # Function to maximum required sum < K def maxSubarraySum(arr, N, K): # Hash to lookup for value (cum_sum - K) cum_set = set() cum_set.add(0) max_sum = 12 cSum = 0 for i in range(N): # getting cumulative sum from [0 to i] cSum += arr[i] # check if upper_bound # of (cSum-K) exists # then update max sum x = bisect.bisect_left(arr, cSum - K, lo=0, hi=len(arr)) if x: max_sum = max(max_sum,x ) # insert cumulative value in hash cum_set.add(cSum) # return maximum sum # lesser than K return max_sum # Driver codeif __name__ == '__main__': # initialise the array arr = [5, -2, 6, 3, -5] # initialise the value of K K = 15 # size of array N = len(arr) print(maxSubarraySum(arr, N, K)) # This code is contributed by Surendra_Gangwar",
"e": 5145,
"s": 4194,
"text": null
},
{
"code": "// Java program to find maximum sum// subarray less than Kusing System;using System.Collections.Generic;class GFG { // Function to maximum required sum < K static int maxSubarraySum(int[] arr, int N, int K) { // Hash to lookup for value (cum_sum - K) HashSet<int> cum_set = new HashSet<int>(); cum_set.Add(0); int max_sum = Int32.MinValue, cSum = 0; for (int i = 0; i < N; i++) { // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash List<int> al = new List<int>(); int end = 0; foreach(int it in cum_set) { end = it; al.Add(it); } al.Sort(); int sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.Max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.Add(cSum); } // Return maximum sum // lesser than K return max_sum; } static int lower_bound(List<int> al, int x) { // x is the target value or key int l = -1, r = al.Count; while (l + 1 < r) { int m = (l + r) >> 1; if (al[m] >= x) r = m; else l = m; } return r; } // Driver code public static void Main(string[] args) { // Initialise the array int[] arr = { 5, -2, 6, 3, -5 }; // Initialise the value of K int K = 15; // Size of array int N = arr.Length; Console.Write(maxSubarraySum(arr, N, K)); }} // This code is contributed by chitranayal.",
"e": 6977,
"s": 5145,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum sum// subarray less than K // Function to maximum required sum < K function maxSubarraySum(arr, N, K) { // Hash to lookup for value (cum_sum - K) let cum_set = new Set(); cum_set.add(0); let max_sum = Number.MIN_SAFE_INTEGER; let cSum = 0; for(let i = 0; i < N; i++){ // Getting cumulative sum from [0 to i] cSum += arr[i]; // Lookup for upperbound // of (cSum-K) in hash let al = []; let end = 0; for(let it of cum_set) { end = it; al.push(it); } al.sort((a, b) => a - b); let sit = lower_bound(al, cSum - K); // Check if upper_bound // of (cSum-K) exists // then update max sum if (sit != end) max_sum = Math.max(max_sum, cSum - sit); // Insert cumulative value in hash cum_set.add(cSum); } // Return maximum sum // lesser than K return max_sum; } let lower_bound = (al, x) => al.filter((item) => item > x )[0] // Driver code // Initialise the array let arr = [ 5, -2, 6, 3, -5 ]; // Initialise the value of K let K = 15; // Size of array let N = arr.length; document.write(maxSubarraySum(arr, N, K)); // This code is contributed by _saurabh_jaiswal </script>",
"e": 8484,
"s": 6977,
"text": null
},
{
"code": null,
"e": 8487,
"s": 8484,
"text": "12"
},
{
"code": null,
"e": 8565,
"s": 8487,
"text": "Time Complexity: O(N*Log(N)), where N represents the size of the given array."
},
{
"code": null,
"e": 8636,
"s": 8565,
"text": "Auxiliary Space: O(N), where N represents the size of the given array."
},
{
"code": null,
"e": 8739,
"s": 8636,
"text": "Similar article: Maximum sum subarray having sum less than or equal to given sum using Sliding Window "
},
{
"code": null,
"e": 8756,
"s": 8739,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8761,
"s": 8756,
"text": "____"
},
{
"code": null,
"e": 8770,
"s": 8761,
"text": "jyoti369"
},
{
"code": null,
"e": 8776,
"s": 8770,
"text": "ukasp"
},
{
"code": null,
"e": 8793,
"s": 8776,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 8809,
"s": 8793,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8828,
"s": 8809,
"text": "surindertarika1234"
},
{
"code": null,
"e": 8844,
"s": 8828,
"text": "tamanna17122007"
},
{
"code": null,
"e": 8861,
"s": 8844,
"text": "ashishkataria002"
},
{
"code": null,
"e": 8870,
"s": 8861,
"text": "subarray"
},
{
"code": null,
"e": 8883,
"s": 8870,
"text": "subarray-sum"
},
{
"code": null,
"e": 8890,
"s": 8883,
"text": "Arrays"
},
{
"code": null,
"e": 8910,
"s": 8890,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8915,
"s": 8910,
"text": "Hash"
},
{
"code": null,
"e": 8925,
"s": 8915,
"text": "Searching"
},
{
"code": null,
"e": 8932,
"s": 8925,
"text": "Arrays"
},
{
"code": null,
"e": 8942,
"s": 8932,
"text": "Searching"
},
{
"code": null,
"e": 8947,
"s": 8942,
"text": "Hash"
},
{
"code": null,
"e": 8967,
"s": 8947,
"text": "Dynamic Programming"
}
] |
InsertionSort - GeeksforGeeks
|
28 Jun, 2021
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Algorithm// Sort an arr[] of size ninsertionSort(arr, n)Loop from i = 1 to n-1 ... More on Insertion Sort
Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above.
Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while doing insertion sort in the array.
4 5 3 2 1
3 4 5 2 1
2 3 4 5 1
1 2 3 4 5
5 4 3 1 2
5 4 1 2 3
5 1 2 3 4
1 2 3 4 5
4 3 2 1 5
3 2 1 5 4
2 1 5 4 3
1 5 4 3 2
4 5 3 2 1
2 3 4 5 1
3 4 5 2 1
1 2 3 4 5
In the insertion sort , just imagine that the first element is already sorted and all the right side Elements are unsorted, we need to insert all elements one by one from left to right in the sorted Array. Sorted : 5
unsorted : 4 3 2 1 Insert all elements less than 5 on the left (Considering 5 as the key ) Now key value is 4 and array will look like this Sorted : 4 5
unsorted : 3 2 1 Similarly for all the cases the key will always be the newly inserted value and all the values will be compared to that key and inserted in to proper position.
In best case,
Quick sort: O (nlogn)
Merge sort: O (nlogn)
Insertion sort: O (n)
Selection sort: O (n^2)
*Online - can sort a list at runtime
*Stable - doesn't change the relative
order of elements with equal keys.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Software Testing - Boundary Value Analysis
TCS NQT Coding Sheet
A Freshers Guide To Programming
Difference Between @Controller and @RestController Annotation in Spring
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29784,
"s": 29577,
"text": "Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Algorithm// Sort an arr[] of size ninsertionSort(arr, n)Loop from i = 1 to n-1 ... More on Insertion Sort "
},
{
"code": null,
"e": 29879,
"s": 29784,
"text": "Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above."
},
{
"code": null,
"e": 30012,
"s": 29879,
"text": "Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done while doing insertion sort in the array. "
},
{
"code": null,
"e": 30022,
"s": 30012,
"text": "4 5 3 2 1"
},
{
"code": null,
"e": 30032,
"s": 30022,
"text": "3 4 5 2 1"
},
{
"code": null,
"e": 30042,
"s": 30032,
"text": "2 3 4 5 1"
},
{
"code": null,
"e": 30052,
"s": 30042,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 30062,
"s": 30052,
"text": "5 4 3 1 2"
},
{
"code": null,
"e": 30072,
"s": 30062,
"text": "5 4 1 2 3"
},
{
"code": null,
"e": 30082,
"s": 30072,
"text": "5 1 2 3 4"
},
{
"code": null,
"e": 30092,
"s": 30082,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 30102,
"s": 30092,
"text": "4 3 2 1 5"
},
{
"code": null,
"e": 30112,
"s": 30102,
"text": "3 2 1 5 4"
},
{
"code": null,
"e": 30122,
"s": 30112,
"text": "2 1 5 4 3"
},
{
"code": null,
"e": 30132,
"s": 30122,
"text": "1 5 4 3 2"
},
{
"code": null,
"e": 30142,
"s": 30132,
"text": "4 5 3 2 1"
},
{
"code": null,
"e": 30152,
"s": 30142,
"text": "2 3 4 5 1"
},
{
"code": null,
"e": 30162,
"s": 30152,
"text": "3 4 5 2 1"
},
{
"code": null,
"e": 30172,
"s": 30162,
"text": "1 2 3 4 5"
},
{
"code": null,
"e": 30389,
"s": 30172,
"text": "In the insertion sort , just imagine that the first element is already sorted and all the right side Elements are unsorted, we need to insert all elements one by one from left to right in the sorted Array. Sorted : 5"
},
{
"code": null,
"e": 30543,
"s": 30389,
"text": " unsorted : 4 3 2 1 Insert all elements less than 5 on the left (Considering 5 as the key ) Now key value is 4 and array will look like this Sorted : 4 5"
},
{
"code": null,
"e": 30720,
"s": 30543,
"text": "unsorted : 3 2 1 Similarly for all the cases the key will always be the newly inserted value and all the values will be compared to that key and inserted in to proper position."
},
{
"code": null,
"e": 30829,
"s": 30720,
"text": "In best case, \n\nQuick sort: O (nlogn) \nMerge sort: O (nlogn)\nInsertion sort: O (n)\nSelection sort: O (n^2) "
},
{
"code": null,
"e": 30951,
"s": 30829,
"text": "*Online - can sort a list at runtime\n*Stable - doesn't change the relative \n order of elements with equal keys. "
},
{
"code": null,
"e": 31051,
"s": 30953,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 31125,
"s": 31051,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 31178,
"s": 31125,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 31227,
"s": 31178,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31252,
"s": 31227,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31265,
"s": 31252,
"text": "Java Threads"
},
{
"code": null,
"e": 31317,
"s": 31265,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 31360,
"s": 31317,
"text": "Software Testing - Boundary Value Analysis"
},
{
"code": null,
"e": 31381,
"s": 31360,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 31413,
"s": 31381,
"text": "A Freshers Guide To Programming"
}
] |
Inserting data using a CSV file in Cassandra
|
31 Mar, 2021
In this article, we will discuss how you can insert data into the table using a CSV file. And we will also cover the implementation with the help of examples. Let’s discuss it one by one.
Pre-requisite – Introduction to Cassandra
Introduction :If you want to store data in bulk then inserting data from a CSV file is one of the nice ways. If you have data in a file so, you can directly insert your data into the database by using the COPY command in Cassandra. It will be very useful when you have a very large database, and you want to store data quickly and your data is in a CSV file then you can directly insert your data.
Syntax – You can see the COPY command syntax for your reference as follows.
COPY table_name [( column_list )]
FROM 'file_name path'[, 'file2_name path', ...] | STDIN
[WITH option = 'value' [AND ...]]
Now, let’s create the sample data for implementing the approach.
Step-1 :Creating keyspace – dataHere, you can use the following cqlsh command to create the keyspace as follows.
CREATE KEYSPACE data
WITH REPLICATION = {
'class' : 'NetworkTopologyStrategy',
'datacenter1' : 1
} ;
Step-2 :Creating the Student_personal_data table –Here, you can use the following cqlsh command to create the Student_personal_data table as follows.
CREATE TABLE data.Student_personal_data (
S_id UUID PRIMARY KEY,
S_firstname text,
S_lastname text,
);
Step-3 :Creating the CSV file –Consider the following given table as a CSV file namely as personal_data.csv. But, in actual you can insert data in CSV file and save it in your computer drive.
Step-4 :Inserting data from the CSV file –In this, you will see how you can insert data into the database from existed CSV file you have, and you can use the following cqlsh command as follows.
COPY data.Student_personal_data (S_id, S_firstname, S_lastname)
FROM 'personal_data.csv'
WITH HEADER = TRUE;
Step-5 :Verifying the result –Once you will execute the above command, then you will get the following result as follows.
Using 7 child processes
Starting copy of data.Student_personal_data with columns [S_id, S_firstname, S_lastname].
Processed: 6 rows; Rate: 10 rows/s; Avg. rate: 14 rows/s
6 rows imported from 1 files in 0.422 seconds (0 skipped).
You can use the following command to see the output as follows.
select * from data.Student_personal_data;
Output :
Apache
NoSQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
Difference between Star Schema and Snowflake Schema
What is Cursor in SQL ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "In this article, we will discuss how you can insert data into the table using a CSV file. And we will also cover the implementation with the help of examples. Let’s discuss it one by one."
},
{
"code": null,
"e": 258,
"s": 216,
"text": "Pre-requisite – Introduction to Cassandra"
},
{
"code": null,
"e": 657,
"s": 258,
"text": "Introduction :If you want to store data in bulk then inserting data from a CSV file is one of the nice ways. If you have data in a file so, you can directly insert your data into the database by using the COPY command in Cassandra. It will be very useful when you have a very large database, and you want to store data quickly and your data is in a CSV file then you can directly insert your data. "
},
{
"code": null,
"e": 733,
"s": 657,
"text": "Syntax – You can see the COPY command syntax for your reference as follows."
},
{
"code": null,
"e": 857,
"s": 733,
"text": "COPY table_name [( column_list )]\nFROM 'file_name path'[, 'file2_name path', ...] | STDIN\n[WITH option = 'value' [AND ...]]"
},
{
"code": null,
"e": 923,
"s": 857,
"text": "Now, let’s create the sample data for implementing the approach. "
},
{
"code": null,
"e": 1036,
"s": 923,
"text": "Step-1 :Creating keyspace – dataHere, you can use the following cqlsh command to create the keyspace as follows."
},
{
"code": null,
"e": 1150,
"s": 1036,
"text": "CREATE KEYSPACE data\n WITH REPLICATION = { \n 'class' : 'NetworkTopologyStrategy', \n 'datacenter1' : 1 \n } ;"
},
{
"code": null,
"e": 1300,
"s": 1150,
"text": "Step-2 :Creating the Student_personal_data table –Here, you can use the following cqlsh command to create the Student_personal_data table as follows."
},
{
"code": null,
"e": 1414,
"s": 1300,
"text": "CREATE TABLE data.Student_personal_data ( \n S_id UUID PRIMARY KEY, \nS_firstname text, \nS_lastname text, \n);"
},
{
"code": null,
"e": 1607,
"s": 1414,
"text": "Step-3 :Creating the CSV file –Consider the following given table as a CSV file namely as personal_data.csv. But, in actual you can insert data in CSV file and save it in your computer drive. "
},
{
"code": null,
"e": 1803,
"s": 1607,
"text": "Step-4 :Inserting data from the CSV file –In this, you will see how you can insert data into the database from existed CSV file you have, and you can use the following cqlsh command as follows. "
},
{
"code": null,
"e": 1914,
"s": 1803,
"text": "COPY data.Student_personal_data (S_id, S_firstname, S_lastname) \nFROM 'personal_data.csv' \nWITH HEADER = TRUE;"
},
{
"code": null,
"e": 2036,
"s": 1914,
"text": "Step-5 :Verifying the result –Once you will execute the above command, then you will get the following result as follows."
},
{
"code": null,
"e": 2277,
"s": 2036,
"text": "Using 7 child processes\n\nStarting copy of data.Student_personal_data with columns [S_id, S_firstname, S_lastname].\nProcessed: 6 rows; Rate: 10 rows/s; Avg. rate: 14 rows/s\n6 rows imported from 1 files in 0.422 seconds (0 skipped)."
},
{
"code": null,
"e": 2341,
"s": 2277,
"text": "You can use the following command to see the output as follows."
},
{
"code": null,
"e": 2383,
"s": 2341,
"text": "select * from data.Student_personal_data;"
},
{
"code": null,
"e": 2392,
"s": 2383,
"text": "Output :"
},
{
"code": null,
"e": 2399,
"s": 2392,
"text": "Apache"
},
{
"code": null,
"e": 2405,
"s": 2399,
"text": "NoSQL"
},
{
"code": null,
"e": 2410,
"s": 2405,
"text": "DBMS"
},
{
"code": null,
"e": 2415,
"s": 2410,
"text": "DBMS"
},
{
"code": null,
"e": 2513,
"s": 2415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2554,
"s": 2513,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 2591,
"s": 2554,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 2632,
"s": 2591,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 2664,
"s": 2632,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2714,
"s": 2664,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 2742,
"s": 2714,
"text": "SQL | DDL, DML, TCL and DCL"
},
{
"code": null,
"e": 2785,
"s": 2742,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 2810,
"s": 2785,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 2862,
"s": 2810,
"text": "Difference between Star Schema and Snowflake Schema"
}
] |
Language Translator Using Google API in Python
|
24 Sep, 2021
API stands for Application Programming Interface. It acts as an intermediate between two applications or software. In simple terms, API acts as a messenger that takes your request to destinations and then brings back its response for you. Google API is developed by Google to allow communications with their servers and use their API keys to develop projects.
In this tutorial, we are going to use Google API to build a Language Translator which can translate one language to another language. On the internet, we can see lots of projects on Speech Recognitions, Speech to text, text to speech, etc. but here in this project we are going to build something more advance than that.
Let’s assume a scenario, we are traveling in Spain and we don’t know how to speak Spanish or we are in any other country and we don’t know their native language, then we can use this tool to overcome the problem. We can translate between all those languages which are present in google translator.
Now to Check what languages it supports we have to use google trans library. We can use pip to install it.
pip install googletrans
Now to check which languages it supports to run the following code.
Python3
# To Print all the languages that google# translator supportsimport googletrans print(googletrans.LANGUAGES)
Output:
Now let’s start building Language Translator. To begin with the coding part, we need to install some dependencies. While installing Pyaudio you might get an error of portaudio. For details of installation of pyaudio click here.
pip install pyaudio
pip install SpeechRecognition
pip install gtts
Below is the implementation.
Python3
# Importing necessary modules requiredimport speech_recognition as sprfrom googletrans import Translatorfrom gtts import gTTSimport os # Creating Recogniser() class objectrecog1 = spr.Recognizer() # Creating microphone instancemc = spr.Microphone() # Capture Voicewith mc as source: print("Speak 'hello' to initiate the Translation !") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") recog1.adjust_for_ambient_noise(source, duration=0.2) audio = recog1.listen(source) MyText = recog1.recognize_google(audio) MyText = MyText.lower() # Here initialising the recorder with# hello, whatever after that hello it# will recognise it.if 'hello' in MyText: # Translator method for translation translator = Translator() # short form of english in which # you will speak from_lang = 'en' # In which we want to convert, short # form of hindi to_lang = 'hi' with mc as source: print("Speak a stentence...") recog1.adjust_for_ambient_noise(source, duration=0.2) # Storing the speech into audio variable audio = recog1.listen(source) # Using recognize.google() method to # convert audio into text get_sentence = recog1.recognize_google(audio) # Using try and except block to improve # its efficiency. try: # Printing Speech which need to # be translated. print("Phase to be Translated :"+ get_sentence) # Using translate() method which requires # three arguments, 1st the sentence which # needs to be translated 2nd source language # and 3rd to which we need to translate in text_to_translate = translator.translate(get_sentence, src= from_lang, dest= to_lang) # Storing the translated text in text # variable text = text_to_translate.text # Using Google-Text-to-Speech ie, gTTS() method # to speak the translated text into the # destination language which is stored in to_lang. # Also, we have given 3rd argument as False because # by default it speaks very slowly speak = gTTS(text=text, lang=to_lang, slow= False) # Using save() method to save the translated # speech in capture_voice.mp3 speak.save("captured_voice.mp3") # Using OS module to run the translated voice. os.system("start captured_voice.mp3") # Here we are using except block for UnknownValue # and Request Error and printing the same to # provide better service to the user. except spr.UnknownValueError: print("Unable to Understand the Input") except spr.RequestError as e: print("Unable to provide Required Output".format(e))
Output:
Speak 'hello' to initiate the Translation !
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Speak a stentence...
Phase to be Translated :what are you doing
sweetyty
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 414,
"s": 54,
"text": "API stands for Application Programming Interface. It acts as an intermediate between two applications or software. In simple terms, API acts as a messenger that takes your request to destinations and then brings back its response for you. Google API is developed by Google to allow communications with their servers and use their API keys to develop projects."
},
{
"code": null,
"e": 736,
"s": 414,
"text": "In this tutorial, we are going to use Google API to build a Language Translator which can translate one language to another language. On the internet, we can see lots of projects on Speech Recognitions, Speech to text, text to speech, etc. but here in this project we are going to build something more advance than that. "
},
{
"code": null,
"e": 1035,
"s": 736,
"text": "Let’s assume a scenario, we are traveling in Spain and we don’t know how to speak Spanish or we are in any other country and we don’t know their native language, then we can use this tool to overcome the problem. We can translate between all those languages which are present in google translator. "
},
{
"code": null,
"e": 1144,
"s": 1035,
"text": "Now to Check what languages it supports we have to use google trans library. We can use pip to install it. "
},
{
"code": null,
"e": 1168,
"s": 1144,
"text": "pip install googletrans"
},
{
"code": null,
"e": 1237,
"s": 1168,
"text": "Now to check which languages it supports to run the following code. "
},
{
"code": null,
"e": 1245,
"s": 1237,
"text": "Python3"
},
{
"code": "# To Print all the languages that google# translator supportsimport googletrans print(googletrans.LANGUAGES)",
"e": 1355,
"s": 1245,
"text": null
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "Output:"
},
{
"code": null,
"e": 1592,
"s": 1363,
"text": "Now let’s start building Language Translator. To begin with the coding part, we need to install some dependencies. While installing Pyaudio you might get an error of portaudio. For details of installation of pyaudio click here. "
},
{
"code": null,
"e": 1659,
"s": 1592,
"text": "pip install pyaudio\npip install SpeechRecognition\npip install gtts"
},
{
"code": null,
"e": 1689,
"s": 1659,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1697,
"s": 1689,
"text": "Python3"
},
{
"code": "# Importing necessary modules requiredimport speech_recognition as sprfrom googletrans import Translatorfrom gtts import gTTSimport os # Creating Recogniser() class objectrecog1 = spr.Recognizer() # Creating microphone instancemc = spr.Microphone() # Capture Voicewith mc as source: print(\"Speak 'hello' to initiate the Translation !\") print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\") recog1.adjust_for_ambient_noise(source, duration=0.2) audio = recog1.listen(source) MyText = recog1.recognize_google(audio) MyText = MyText.lower() # Here initialising the recorder with# hello, whatever after that hello it# will recognise it.if 'hello' in MyText: # Translator method for translation translator = Translator() # short form of english in which # you will speak from_lang = 'en' # In which we want to convert, short # form of hindi to_lang = 'hi' with mc as source: print(\"Speak a stentence...\") recog1.adjust_for_ambient_noise(source, duration=0.2) # Storing the speech into audio variable audio = recog1.listen(source) # Using recognize.google() method to # convert audio into text get_sentence = recog1.recognize_google(audio) # Using try and except block to improve # its efficiency. try: # Printing Speech which need to # be translated. print(\"Phase to be Translated :\"+ get_sentence) # Using translate() method which requires # three arguments, 1st the sentence which # needs to be translated 2nd source language # and 3rd to which we need to translate in text_to_translate = translator.translate(get_sentence, src= from_lang, dest= to_lang) # Storing the translated text in text # variable text = text_to_translate.text # Using Google-Text-to-Speech ie, gTTS() method # to speak the translated text into the # destination language which is stored in to_lang. # Also, we have given 3rd argument as False because # by default it speaks very slowly speak = gTTS(text=text, lang=to_lang, slow= False) # Using save() method to save the translated # speech in capture_voice.mp3 speak.save(\"captured_voice.mp3\") # Using OS module to run the translated voice. os.system(\"start captured_voice.mp3\") # Here we are using except block for UnknownValue # and Request Error and printing the same to # provide better service to the user. except spr.UnknownValueError: print(\"Unable to Understand the Input\") except spr.RequestError as e: print(\"Unable to provide Required Output\".format(e))",
"e": 4712,
"s": 1697,
"text": null
},
{
"code": null,
"e": 4720,
"s": 4712,
"text": "Output:"
},
{
"code": null,
"e": 4873,
"s": 4720,
"text": "Speak 'hello' to initiate the Translation !\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nSpeak a stentence...\nPhase to be Translated :what are you doing"
},
{
"code": null,
"e": 4884,
"s": 4875,
"text": "sweetyty"
},
{
"code": null,
"e": 4900,
"s": 4884,
"text": "Python-projects"
},
{
"code": null,
"e": 4915,
"s": 4900,
"text": "python-utility"
},
{
"code": null,
"e": 4922,
"s": 4915,
"text": "Python"
}
] |
Learn R Programming
|
22 Aug, 2021
R is a Programming Language that is mostly used for machine learning, data analysis, and statistical computing. It is an interpreted language and is platform independent that means it can be used on platforms like Windows, Linux, and macOS.
In this R Language tutorial, we will Learn R Programming Language from scratch to advance and this tutorial is suitable for both beginners and experienced developers).
R programming is used as a leading tool for machine learning, statistics, and data analysis.
R is an open-source language that means it is free of cost and anyone from any organization can install it without purchasing a license.
It is available across widely used platforms like windows, Linux, and macOS.
R programming language is not only a statistic package but also allows us to integrate with other languages (C, C++). Thus, you can easily interact with many data sources and statistical packages.
Its user base is growing day by day and has vast community support.
R Programming Language is currently one of the most requested programming languages in the Data Science job market that makes it the hottest trend nowadays.
Some key features of R that make the R one of the most demanding job in data science market are:
Basic Statistics: The most common basic statistics terms are the mean, mode, and median. These are all known as “Measures of Central Tendency.” So using the R language we can measure central tendency very easily.
Static graphics: R is rich with facilities for creating and developing various kinds of static graphics including graphic maps, mosaic plots, biplots, and the list goes on.
Probability distributions: Using R we can easily handle various types of probability distribution such as Binomial Distribution, Normal Distribution, Chi-squared Distribution, and many more.
R Packages: One of the major features of R is it has a wide availability of libraries. R has CRAN(Comprehensive R Archive Network), which is a repository holding more than 10,0000 packages.
Distributed Computing: Distributed computing is a model in which components of a software system are shared among multiple computers to improve efficiency and performance. Two new packages ddR and multidplyr used for distributed programming in R were released in November 2015.
There are many IDE’s available for using R in this article we will dealing with the installation of RStudio in R.
Refer to the below articles to get detailed information about RStudio and its installation.
How to Install R Studio on Windows and Linux?
Introduction to R Studio
Creation and Execution of R File in R Studio
R Program can be run in several ways. You can choose any of the following options to continue with this tutorial.
Using IDEs like RStudio, Eclipse, Jupyter, Notebook, etc.
Using R Command Prompt
Using RScripts
Now type the below code to print hello world on your console.
R
# R Program to print# Hello World print("HelloWorld")
Output:
[1] "HelloWorld"
Note: For more information, refer Hello World in R Programming
R is a dynamically typed language, i.e. the variables are not declared with a data type rather they take the data type of the R-object assigned to them. In R, the assignment can be denoted in three ways.
Using equal operator- data is copied from right to left.
variable_name = value
Using leftward operator- data is copied from right to left.
variable_name <- value
Using rightward operator- data is copied from left to right.
value -> variable_name
Example:
R
# R program to illustrate# Initialization of variables # using equal to operatorvar1 = "gfg"print(var1) # using leftward operatorvar2 <- "gfg"print(var2) # using rightward operator"gfg" -> var3print(var3)
Output:
[1] "gfg"
[1] "gfg"
[1] "gfg"
Note: For more information, refer R – Variables.
Comments are the english sentences that are used to add useful information to the source code to make it more understandable by the reader. It explains the logic part used in the code and will have no impact in the code during its execution. Any statement starting with “#” is a comment in R.
Example:
R
# all the lines starting with '#'# are comments and will be ignored# during the execution of the# program # Assigning values to variablesa <- 1b <- 2 # Printing sumprint(a + b)
Output:
[1] 3
Note: For more information, refer Comments in R
Operators are the symbols directing the various kinds of operations that can be performed between the operands. Operators simulate the various mathematical, logical and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. These are classified based on their functionality –
Arithmetic Operators: Arithmetic operations simulate various math operations, like addition, subtraction, multiplication, division and modulo.
Example:
R
# R program to illustrate# the use of Arithmetic operatorsa <- 12b <- 5 # Performing operations on Operandscat ("Addition :", a + b, "\n")cat ("Subtraction :", a - b, "\n")cat ("Multiplication :", a * b, "\n")cat ("Division :", a / b, "\n")cat ("Modulo :", a %% b, "\n")cat ("Power operator :", a ^ b)
Output:
Addition : 17
Subtraction : 7
Multiplication : 60
Division : 2.4
Modulo : 2
Power operator : 248832
Logical Operators: Logical operations simulate element-wise decision operations, based on the specified operator between the operands, which are then evaluated to either a True or False boolean value.
Example:
R
# R program to illustrate# the use of Logical operatorsvec1 <- c(FALSE, TRUE)vec2 <- c(TRUE,FALSE) # Performing operations on Operandscat ("Element wise AND :", vec1 & vec2, "\n")cat ("Element wise OR :", vec1 | vec2, "\n")cat ("Logical AND :", vec1 && vec2, "\n")cat ("Logical OR :", vec1 || vec2, "\n")cat ("Negation :", !vec1)
Output:
Element wise AND : FALSE FALSE
Element wise OR : TRUE TRUE
Logical AND : FALSE
Logical OR : TRUE
Negation : TRUE FALSE
Relational Operators: The relational operators carry out comparison operations between the corresponding elements of the operands.
Example:
R
# R program to illustrate# the use of Relational operatorsa <- 10b <- 14 # Performing operations on Operandscat ("a less than b :", a < b, "\n")cat ("a less than equal to b :", a <= b, "\n")cat ("a greater than b :", a > b, "\n")cat ("a greater than equal to b :", a >= b, "\n")cat ("a not equal to b :", a != b, "\n")
Output:
a less than b : TRUE
a less than equal to b : TRUE
a greater than b : FALSE
a greater than equal to b : FALSE
a not equal to b : TRUE
Assignment Operators: Assignment operators are used to assign values to various data objects in R.
Example:
R
# R program to illustrate# the use of Assignment operators # Left assignment operatorv1 <- "GeeksForGeeks"v2 <<- "GeeksForGeeks"v3 = "GeeksForGeeks" # Right Assignment operator"GeeksForGeeks" ->> v4"GeeksForGeeks" -> v5 # Performing operations on Operandscat("Value 1 :", v1, "\n")cat("Value 2 :", v2, "\n")cat("Value 3 :", v3, "\n")cat("Value 4 :", v4, "\n")cat("Value 5 :", v5)
Output:
Value 1 : GeeksForGeeks
Value 2 : GeeksForGeeks
Value 3 : GeeksForGeeks
Value 4 : GeeksForGeeks
Value 5 : GeeksForGeeks
Note: For more information, refer R – Operators
Keywords are specific reserved words in R, each of which has a specific feature associated with it. Here is the list of keywords in R:
Note: For more information, refer R – Keywords
Each variable in R has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. R supports 5 type of data types. These are –
Example:
R
# A simple R program# to illustrate data type print("Numberic type")# Assign a decimal value to xx = 12.25 # print the class name of variableprint(class(x)) # print the type of variableprint(typeof(x)) print("----------------------------")print("Integer Type")# Declare an integer by appending an# L suffix.y = 15L # print the class name of yprint(class(y)) # print the type of yprint(typeof(y)) print("----------------------------")print("Logical Type")# Sample valuesx = 1y = 2 # Comparing two valuesz = x > y # print the logical valueprint(z) # print the class name of zprint(class(z)) # print the type of zprint(typeof(z)) print("----------------------------")print("Complex Type")# Assign a complex value to xx = 12 + 13i # print the class name of xprint(class(x)) # print the type of xprint(typeof(x)) print("----------------------------")print("Character Type") # Assign a character value to charchar = "GFG" # print the class name of charprint(class(char)) # print the type of charprint(typeof(char))
Output:
[1] "Numberic type"
[1] "numeric"
[1] "double"
[1] "----------------------------"
[1] "Integer Type"
[1] "integer"
[1] "integer"
[1] "----------------------------"
[1] "Logical Type"
[1] TRUE
[1] "logical"
[1] "logical"
[1] "----------------------------"
[1] "Complex Type"
[1] "complex"
[1] "complex"
[1] "----------------------------"
[1] "Character Type"
[1] "character"
[1] "character"
Note: for more information, refer R – Data Types
R Language provides us with two inbuilt functions to read the input from the keyboard.
readline() method: It takes input in string format. If one inputs an integer then it is inputted as a string.
Example:
R
# R program to illustrate# taking input from the user # taking input using readline()# this command will prompt you# to input a desired valuevar = readline();
scan() method: This method reads data in the form of a vector or list. This method is a very handy method while inputs are needed to taken quickly for any mathematical calculation or for any dataset.
Example:
R
# R program to illustrate# taking input from the user # taking input using scan()x = scan()
Note: For more information, refer Taking Input from User in R Programming
R Provides various functions to write output to the screen, let’s see them –
print(): It is the most common method to print the output.
Example:
R
# R program to illustrate# printing output of an R program # print stringprint("Hello") # print variable# it will print 'GeeksforGeeks' on# the consolex <- "Welcome to GeeksforGeeks"print(x)
Output:
[1] "Hello"
[1] "Welcome to GeeksforGeeks"
cat(): cat() converts its arguments to character strings. This is useful for printing output in user defined functions.
Example:
R
# R program to illustrate# printing output of an R# program # print string with variable# "\n" for new linex = "Hello"cat(x, "\nwelcome") # print normal stringcat("\nto GeeksForGeeks")
Output:
Hello
welcome
to GeeksForGeeks
Note: For more information, refer Printing Output of an R Program
Decision making decides the flow of the execution of the program based on certain conditions. In decision making programmer needs to provide some condition which is evaluated by the program, along with it there also provided some statements which are executed if the condition is true and optionally other statements if the condition is evaluated to be false.
Decision-making statements in R Language:
if statement
if-else statement
if-else-if ladder
nested if-else statement
switch statement
Example 1: Demonstrating if and if-else
R
# R program to illustrate# decision making a <- 99b <- 12 # if statement to check whether# the number a is larger or notif(a > b){ print("A is Larger")} # if-else statement to check which# number is greaterif(b > a){ print("B is Larger")} else{ print("A is Larger")}
Output:
[1] "A is Larger"
[1] "A is Larger"
Example 2: Demonstrating if-else-if and nested if
R
# R program to demonstrate# decision making a <- 10 # is-elifif (a == 11){ print ("a is 11")} else if (a==10){ print ("a is 10")} else print ("a is not present") # Nested if to check whether a# number is divisible by both 2 and 5if (a %% 2 == 0){ if (a %% 5 == 0) print("Number is divisible by both 2 and 5")}
Output:
[1] "a is 10"
[1] "Number is divisible by both 2 and 5"
Example 3: Demonstrating switch
R
# R switch statement example # Expression in terms of the index valuex <- switch( 2, # Expression "Welcome", # case 1 "to", # case 2 "GFG" # case 3)print(x) # Expression in terms of the string valuey <- switch( "3", # Expression "0"="Welcome", # case 1 "1"="to", # case 2 "3"="GFG" # case 3)print(y) z <- switch( "GfG", # Expression "GfG0"="Welcome", # case 1 "GfG1"="to", # case 2 "GfG3"="GFG" # case 3)print(z)
Output:
[1] "to"
[1] "GFG"
NULL
Note: For more information, refer Decision Making in R Programming
Loops are used wherever we have to execute a block of statements repeatedly. For example, printing “hello world” 10 times. The different types of loops in R are –
For Loop
Example:
R
# R Program to demonstrate the use of# for loop along with concatenatefor (i in c(-8, 9, 11, 45)){ print(i)}
Output:
[1] -8
[1] 9
[1] 11
[1] 45
While Loop
Example:
R
# R program to demonstrate the# use of while loop val = 1 # using while loopwhile (val <= 5 ){ # statements print(val) val = val + 1}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Repeat Loop
Example:
R
# R program to demonstrate the use# of repeat loop val = 1 # using repeat looprepeat{ # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break }}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Note: For more information, refer Loops in R
Loop control statements change execution from its normal sequence. Following are the loop control statements provided by R Language:
Break Statement: The break keyword is a jump statement that is used to terminate the loop at a particular iteration.
Next Statement: The next statement is used to skip the current iteration in the loop and move to the next iteration without exiting from the loop itself.
R
# R program for break statementno <- 15:20 for (val in no){ if (val == 17) { break } print(paste("Values are: ", val))} print("------------------------------------") # R Next Statement Examplefor (val in no){ if (val == 17) { next } print(paste("Values are: ", val))}
Output:
[1] "Values are: 15"
[1] "Values are: 16"
[1] "------------------------------------"
[1] "Values are: 15"
[1] "Values are: 16"
[1] "Values are: 18"
[1] "Values are: 19"
[1] "Values are: 20"
Note: For more information, refer Break and Next statements in R
Functions are the block of code that given the user the ability to reuse the same code which saves the excessive use of memory and provides better readability to the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. Functions are created in R by using the command function() keyword
Example:
R
# A simple R program to# demonstrate functions ask_user = function(x){ print("GeeksforGeeks")} my_func = function(x){ a <- 1:5 b <- 0 for (i in a){ b = b +1 } return(b)} ask_user()res = my_func()print(res)
Output:
[1] "GeeksforGeeks"
[1] 5
Arguments to a function can be specified at the time of function definition, after the function name, inside the parenthesis.
Example:
R
# A simple R function to check# whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) # return even if the number # is even return("even") else # return odd if the number # is odd return("odd")} # Function definition# To check a is divisible by b or notdivisible <- function(a, b){ if(a %% b == 0) { cat(a, "is divisible by", b, "\n") } else { cat(a, "is not divisible by", b, "\n") }} # function with single argumentprint(evenOdd(4))print(evenOdd(3)) # function with multiple argumentsdivisible(7, 3)divisible(36, 6)divisible(9, 2)
Output:
[1] "even"
[1] "odd"
7 is not divisible by 3
36 is divisible by 6
9 is not divisible by 2
Default Arguments: Default value in a function is a value that is not required to specify each time the function is called.
Example:
R
# Function definition to check# a is divisible by b or not. # If b is not provided in function call,# Then divisibility of a is checked# with 3 as defaultisdivisible <- function(a, b = 9){ if(a %% b == 0) { cat(a, "is divisible by", b, "\n") } else { cat(a, "is not divisible by", b, "\n") }} # Function callisdivisible(20, 2)isdivisible(12)
Output:
20 is divisible by 2
12 is not divisible by 9
Variable length arguments: Dots argument (...) is also known as ellipsis which allows the function to take an undefined number of arguments.
Example:
R
# Function definition of dots operatorfun <- function(n, ...){ l <- c(n, ...) paste(l, collapse = " ")} # Function callfun(5, 1L, 6i, TRUE, "GFG", 1:2)
Output:
5 1 0+6i TRUE GFG 1 2
Refer to the below articles to get detailed information about functions in R
Functions in R Programming
Function Arguments in R Programming
Types of Functions in R Programming
A data structure is a particular way of organizing data in a computer so that it can be used effectively.
Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’.
Example:
R
# R program to illustrate Vector # Numeric VectorN = c(1, 3, 5, 7, 8) # Character vectorC = c('Geeks', 'For', 'Geeks') # Logical VectorL = c(TRUE, FALSE, FALSE, TRUE) # Printing vectorsprint(N)print(C)print(L)
Output:
[1] 1 3 5 7 8
[1] "Geeks" "For" "Geeks"
[1] TRUE FALSE FALSE TRUE
Accessing Vector Elements:
There are many ways through which we can access the elements of the vector. The most common is using the ‘[]’, symbol.
Example:
R
# Accessing elements using# the position number.X <- c(2, 9, 8, 0, 5)print('using Subscript operator')print(X[2]) # Accessing specific values by passing# a vector inside another vector.Y <- c(6, 2, 7, 4, 0)print('using c function')print(Y[c(4, 1)]) # Logical indexingZ <- c(1, 6, 9, 4, 6)print('Logical indexing')print(Z[Z>3])
Output:
[1] "using Subscript operator"
[1] 9
[1] "using c function"
[1] 4 6
[1] "Logical indexing"
[1] 6 9 4 6
Refer to the below articles to get detailed information about vectors in R.
R – Vector
Types of Vectors in R Programming
Operations on Vectors in R
A list is a generic object consisting of an ordered collection of objects. Lists are heterogeneous data structures.
Example:
R
# R program to create a List # The first attributes is a numeric vector# containing the employee IDs which is created# using the command hereempId = c(1, 2, 3, 4) # The second attribute is the employee name# which is created using this line of code here# which is the character vectorempName = c("Nisha", "Nikhil", "Akshu", "Sambha") # The third attribute is the number of employees# which is a single numeric variable.numberOfEmp = 4 # The fourth attribute is the name of organization# which is a single character variable.Organization = "GFG" # We can combine all these three different# data types into a list# containing the details of employees# which can be done using a list commandempList = list(empId, empName, numberOfEmp, Organization) print(empList)
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
[[3]]
[1] 4
[[4]]
[1] "GFG"
Accessing List Elements:
Access components by names: All the components of a list can be named and we can use those names to access the components of the list using the dollar command.
Access components by indices: We can also access the components of the list using indices. To access the top-level components of a list we have to use a double slicing operator “[[ ]]” which is two square brackets and if we want to access the lower or inner level components of a list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]“.
Example:
R
# R program to access# components of a list # Creating a list by naming all its componentsempId = c(1, 2, 3, 4)empName = c("Nisha", "Nikhil", "Akshu", "Sambha")numberOfEmp = 4empList = list("ID" = empId,"Names" = empName,"Total Staff" = numberOfEmp)print("Initial List")print(empList) # Accessing components by namescat("\nAccessing name components using $ command\n")print(empList$Names) # Accessing a top level components by indicescat("\nAccessing name components using indices\n")print(empList[[2]])print(empList[[1]][2])print(empList[[2]][4])
Output:
[1] "Initial List"
$ID
[1] 1 2 3 4
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 4
Accessing name components using $ command
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
Accessing name components using indices
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
[1] 2
[1] "Sambha"
Adding and Modifying list elements:
A list can also be modified by accessing the components and replacing them with the ones which you want.
List elements can be added simply by assigning new values using new tags.
Example:
R
# R program to access# components of a list # Creating a list by naming all its componentsempId = c(1, 2, 3, 4)empName = c("Nisha", "Nikhil", "Akshu", "Sambha")numberOfEmp = 4empList = list("ID" = empId,"Names" = empName,"Total Staff" = numberOfEmp)print("Initial List")print(empList) # Adding new elementempList[["organization"]] <- "GFG"cat("\nAfter adding new element\n")print(empList) # Modifying the top-level componentempList$"Total Staff" = 5 # Modifying inner level componentempList[[1]][5] = 7 cat("\nAfter modification\n")print(empList)
Output:
[1] "Initial List"
$ID
[1] 1 2 3 4
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 4
After adding new element
$ID
[1] 1 2 3 4
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 4
$organization
[1] "GFG"
After modification
$ID
[1] 1 2 3 4 7
$Names
[1] "Nisha" "Nikhil" "Akshu" "Sambha"
$`Total Staff`
[1] 5
$organization
[1] "GFG"
Refer to the below articles to get detailed information about lists in R
R – Lists
Operations on Lists in R Programming
Two Dimensional List in R Programming
Named List in R Programming
A matrix is a rectangular arrangement of numbers in rows and columns. Matrices are two-dimensional, homogeneous data structures.
Example:
R
# R program to illustrate a matrix A = matrix( # Taking sequence of elements c(1, 4, 5, 6, 3, 8), # No of rows and columns nrow = 2, ncol = 3, # By default matrices are # in column-wise order # So this parameter decides # how to arrange the matrix byrow = TRUE) print(A)
Output:
[,1] [,2] [,3]
[1,] 1 4 5
[2,] 6 3 8
Accessing Matrix Elements:
Matrix elements can be accessed using the matrix name followed by a square bracket with a comma in between the array. Value before the comma is used to access rows and value that is after the comma is used to access columns.
Example:
R
# R program to illustrate# access rows in metrics # Create a 3x3 matrixA = matrix(c(1, 4, 5, 6, 3, 8),nrow = 2, ncol = 3,byrow = TRUE )cat("The 2x3 matrix:\n")print(A) print(A[1, 1]) print(A[2, 2]) # Accessing first and second rowcat("Accessing first and second row\n")print(A[1:2, ]) # Accessing first and second columncat("\nAccessing first and second column\n")print(A[, 1:2])
Output:
The 2x3 matrix:
[,1] [,2] [,3]
[1,] 1 4 5
[2,] 6 3 8
[1] 1
[1] 3
Accessing first and second row
[,1] [,2] [,3]
[1,] 1 4 5
[2,] 6 3 8
Accessing first and second column
[,1] [,2]
[1,] 1 4
[2,] 6 3
Modifying Matrix Elements:
You can modify the elements of the matrices by a direct assignment.
Example:
R
# R program to illustrate# editing elements in metrics # Create a 3x3 matrixA = matrix( c(1, 4, 5, 6, 3, 8), nrow = 2, ncol = 3, byrow = TRUE)cat("The 2x3 matrix:\n")print(A) # Editing the 3rd rows and 3rd# column element from 9 to 30# by direct assignmentsA[2, 1] = 30 cat("After edited the matrix\n")print(A)
Output:
The 2x3 matrix:
[,1] [,2] [,3]
[1,] 1 4 5
[2,] 6 3 8
After edited the matrix
[,1] [,2] [,3]
[1,] 1 4 5
[2,] 30 3 8
Refer to the below articles to get detailed information about Matrices in R
R – Matrices
Operations on Matrices in R
Algebraic Operations on a Matrix in R
Matrix Transpose in R
Inverse of Matrix in R
Dataframes are generic data objects of R which are used to store the tabular data. They are two-dimensional, heterogeneous data structures. These are lists of vectors of equal lengths.
Example:
R
# R program to illustrate dataframe # A vector which is a character vectorName = c("Nisha", "Nikhil", "Raju") # A vector which is a character vectorLanguage = c("R", "Python", "C") # A vector which is a numeric vectorAge = c(40, 25, 10) # To create dataframe use data.frame command# and then pass each of the vectors# we have created as arguments# to the function data.frame()df = data.frame(Name, Language, Age) print(df)
Output:
Name Language Age
1 Nisha R 40
2 Nikhil Python 25
3 Raju C 10
Getting the structure and data from DataFrame:
One can get the structure of the data frame using str() function.
One can extract a specific column from a data frame using its column name.
Example:
R
# R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Aman", "Nisha", "Nikhil", "Raju", "Raj"), stringsAsFactors = FALSE)# using str()print(str(friend.data)) # Extracting friend_name columnresult <- data.frame(friend.data$friend_name)print(result)
Output:
'data.frame': 5 obs. of 2 variables:
$ friend_id : int 1 2 3 4 5
$ friend_name: chr "Aman" "Nisha" "Nikhil" "Raju" ...
NULL
friend.data.friend_name
1 Aman
2 Nisha
3 Nikhil
4 Raju
5 Raj
Summary of dataframe:
The statistical summary and nature of the data can be obtained by applying summary() function.
Example:
R
# R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Aman", "Nisha", "Nikhil", "Raju", "Raj"), stringsAsFactors = FALSE)# using summary()print(summary(friend.data))
Output:
friend_id friend_name
Min. :1 Length:5
1st Qu.:2 Class :character
Median :3 Mode :character
Mean :3
3rd Qu.:4
Max. :5
Refer to the below articles to get detailed information about DataFrames in R
R – Data Frames
DataFrame Operations
DataFrame Manipulation
Joining of Dataframes
Data Reshaping
Handling Missing Values
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures.
Example:
R
# R program to illustrate an array A = array( # Taking sequence of elements c(2, 4, 5, 7, 1, 8, 9, 2), # Creating two rectangular matrices # each with two rows and two columns dim = c(2, 2, 2)) print(A)
Output:
, , 1
[,1] [,2]
[1,] 2 5
[2,] 4 7
, , 2
[,1] [,2]
[1,] 1 9
[2,] 8 2
Accessing arrays:
The arrays can be accessed by using indices for different dimensions separated by commas. Different components can be specified by any combination of elements’ names or positions.
Example:
R
vec1 <- c(2, 4, 5, 7, 1, 8, 9, 2)vec2 <- c(12, 21, 34) row_names <- c("row1", "row2")col_names <- c("col1", "col2", "col3")mat_names <- c("Mat1", "Mat2") arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint ("Matrix 1")print (arr[,,1]) # accessing matrix 2 by its nameprint ("Matrix 2")print(arr[,,"Mat2"]) # accessing matrix 1 by index valueprint ("1st column of matrix 1")print (arr[, 1, 1]) # accessing matrix 2 by its nameprint ("2nd row of matrix 2")print(arr["row2",,"Mat2"]) # accessing matrix 1 by index valueprint ("2nd row 3rd column matrix 1 element")print (arr[2, "col3", 1]) # accessing matrix 2 by its nameprint ("2nd row 1st column element of matrix 2")print(arr["row2", "col1", "Mat2"]) # print elements of both the rows and columns# 2 and 3 of matrix 1print (arr[, c(2, 3), 1])
Output:
[1] "Matrix 1"
col1 col2 col3
row1 2 5 1
row2 4 7 8
[1] "Matrix 2"
col1 col2 col3
row1 9 12 34
row2 2 21 2
[1] "1st column of matrix 1"
row1 row2
2 4
[1] "2nd row of matrix 2"
col1 col2 col3
2 21 2
[1] "2nd row 3rd column matrix 1 element"
[1] 8
[1] "2nd row 1st column element of matrix 2"
[1] 2
col2 col3
row1 5 1
row2 7 8
Adding elements to array:
Elements can be appended at the different positions in the array. The sequence of elements is retained in order of their addition to the array. There are various in-built functions available in R to add new values:
c(vector, values)
append(vector, values):
Using the length function of the array
Example:
R
# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print ("Array after 1st modification ")print (x) # addition of element using append functionx <- append(x, 7)print ("Array after 2nd modification ")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print ("Array after 3rd modification ")print (x) # adding on length + 3 indexx[len + 3]<-9print ("Array after 4th modification ")print (x) # append a vector of values to the# array after length + 3 of arrayprint ("Array after 5th modification")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint ("Array after 6th modification")x <- append(x, c(-1, -1), after = 3)print (x)
Output:
[1] "Array after 1st modification "
[1] 1 2 3 4 5 6
[1] "Array after 2nd modification "
[1] 1 2 3 4 5 6 7
[1] "Array after 3rd modification "
[1] 1 2 3 4 5 6 7 8
[1] "Array after 4th modification "
[1] 1 2 3 4 5 6 7 8 NA 9
[1] "Array after 5th modification"
[1] 1 2 3 4 5 6 7 8 NA 9 10 11 12
[1] "Array after 6th modification"
[1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12
Removing Elements from Array:
Elements can be removed from arrays in R, either one at a time or multiple together. These elements are specified as indexes to the array, wherein the array values satisfying the conditions are retained and rest removed.
Another way to remove elements is by using %in% operator wherein the set of element values belonging to the TRUE values of the operator are displayed as result and the rest are removed.
Example:
R
# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print ("Original Array")print (m) # remove a single value element:3# from arraym <- m[m != 3]print ("After 1st modification")print (m) # removing elements based on condition# where either element should be# greater than 2 and less than equal# to 8m <- m[m>2 & m<= 8]print ("After 2nd modification")print (m) # remove sequence of elements using# another arrayremove <- c(4, 6, 8) # check which element satisfies the# remove propertyprint (m % in % remove)print ("After 3rd modification")print (m [! m % in % remove])
Output:
[1] "Original Array"
[1] 1 2 3 4 5 6 7 8 9
[1] "After 1st modification"
[1] 1 2 4 5 6 7 8 9
[1] "After 2nd modification"
[1] 4 5 6 7 8
[1] TRUE FALSE TRUE FALSE TRUE
[1] "After 3rd modification"
[1] 5 7
Refer to the below articles to get detailed information about arrays in R.
R – Array
Multidimensional Array
Array Operations
Factors are the data objects which are used to categorize the data and store it as levels. They are useful for storing categorical data.
Example:
R
# Creating a vectorx<-c("female", "male", "other", "female", "other") # Converting the vector x into# a factor named gendergender<-factor(x)print(gender)
Output:
[1] female male other female other
Levels: female male other
Accessing elements of a Factor:
Like we access elements of a vector, the same way we access the elements of a factor
Example:
R
x<-c("female", "male", "other", "female", "other")print(x[3])
Output:
[1] "other"
Modifying of a Factor:
After a factor is formed, its components can be modified but the new values which need to be assigned must be in the predefined level.
Example:
R
x<-c("female", "male", "other", "female", "other")x[1]<-"male"print(x)
Output:
[1] "male" "male" "other" "female" "other"
Refer to the below articles to get detailed information Factors.
R – Factors
Level Ordering of Factors
Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its execution. In R
The stop() function will generate errors
The stopifnot() function will take a logical expression and if any of the expressions is FALSE then it will generate the error specifying which expression is FALSE.
The warning() will create the warning but will not stop the execution.
Error handling can be done using tryCatch(). The first argument of this function is the expression which is followed by the condition specifying how to handle the conditions.
Syntax:
check = tryCatch({
expression
}, warning = function(w){
code that handles the warnings
}, error = function(e){
code that handles the errors
}, finally = function(f){
clean-up code
})
Example:
R
# R program illustrating error handling # Evaluation of tryCatchcheck <- function(expression){ tryCatch(expression, warning = function(w){ message("warning:\n", w) }, error = function(e){ message("error:\n", e) }, finally = { message("Completed") })} check({10/2})check({10/0})check({10/'noe'})
Output:
Refer to the below articles to get detailed information about error handling in R
Handling Errors in R Programming
Condition Handling
Debugging in R Programming
In a real-world scenario enormous amount of data is produced on daily basis, so, interpreting it can be somewhat hectic. Here data visualization comes into play because it is always better to visualize that data through charts and graphs, to gain meaningful insights instead of screening huge Excel sheets. Let’s see some basic plots in R Programming.
R uses the function barplot() to create bar charts. Here, both vertical and Horizontal bars can be drawn.
Example:
R
# Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chartbarplot(A, xlab = "X-axis", ylab = "Y-axis", main ="Bar-Chart")
Output:
Note: For more information, refer Bar Charts in R
R creates histogram using hist() function.
Example:
R
# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = "No.of Articles ", col = "green", border = "black")
Output:
Note: For more information, refer Histograms in R language
The simple scatterplot is created using the plot() function.
Example:
R
# Create the data for the chartA <- c(17, 32, 8, 53, 1)B <- c(12, 43, 17, 43, 10) # Plot the bar chartplot(x=A, y=B, xlab = "X-axis", ylab = "Y-axis", main ="Scatter Plot")
Output:
Note: For more information, refer Scatter plots in R Language
The plot() function in R is used to create the line graph.
Example:
R
# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = "l", xlab = "X-axis", ylab = "Y-axis", main ="Line-Chart")
Output:
Note: For more information, refer Line Graphs in R Language.
R uses the function pie() to create pie charts. It takes positive numbers as a vector input.
Example:
R
# Create data for the graph.geeks<- c(23, 56, 20, 63)labels <- c("Mumbai", "Pune", "Chennai", "Bangalore") # Plot the chart.pie(geeks, labels)
Output:
Note: For more information, refer Pie Charts in R Language
Boxplots are created in R by using the boxplot() function.
R
input <- mtcars[, c('mpg', 'cyl')] # Plot the chart.boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data")
Output:
Note: For more information, refer Boxplots in R Language
For more articles refer Data Visualization using R
Statistics simply means numerical data, and is field of math that generally deals with collection of data, tabulation, and interpretation of numerical data. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. Statistics deals with how data can be used to solve complex problems.
Mean: It is the sum of observation divided by the total number of observations.
Median: It is the middle value of the data set.
Mode: It is the value that has the highest frequency in the given data set. R does not have a standard in-built function to calculate mode.
Example:
R
# Create the dataA <- c(17, 12, 8, 53, 1, 12, 43, 17, 43, 10) print(mean(A))print(median(A)) mode <- function(x) { a <- unique(x) a[which.max(tabulate(match(x, a)))]} # Calculate the mode using# the user function.print(mode(A)
Output:
[1] 21.6
[1] 14.5
[1] 17
Note: For more information, refer Mean, Median and Mode in R Programming
Normal Distribution tells about how the data values are distributed. For example, the height of the population, shoe size, IQ level, rolling a dice, and many more. In R, there are 4 built-in functions to generate normal distribution:
dnorm() function in R programming measures density function of distribution.
dnorm(x, mean, sd)
pnorm() function is the cumulative distribution function which measures the probability that a random number X takes a value less than or equal to x
pnorm(x, mean, sd)
qnorm() function is the inverse of pnorm() function. It takes the probability value and gives output which corresponds to the probability value.
qnorm(p, mean, sd)
rnorm() function in R programming is used to generate a vector of random numbers which are normally distributed.
rnorm(n, mean, sd)
Example:
R
# creating a sequence of values# between -10 to 10 with a# difference of 0.1x <- seq(-10, 10, by=0.1) y = dnorm(x, mean(x), sd(x))plot(x, y, main='dnorm') y <- pnorm(x, mean(x), sd(x))plot(x, y, main='pnorm') y <- qnorm(x, mean(x), sd(x))plot(x, y, main='qnorm') x <- rnorm(x, mean(x), sd(x))hist(x, breaks=50, main='rnorm')
Output:
Note: For more information refer Normal Distribution in R
The binomial distribution is a discrete distribution and has only two outcomes i.e. success or failure. For example, determining whether a particular lottery ticket has won or not, whether a drug is able to cure a person or not, it can be used to determine the number of heads or tails in a finite number of tosses, for analyzing the outcome of a die, etc. We have four functions for handling binomial distribution in R namely:
dbinom()
dbinom(k, n, p)
pbinom()
pbinom(k, n, p)
where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out.
qbinom()
qbinom(P, n, p)
Where P is the probability, n is the total number of trials and p is the probability of success.
rbinom()
rbinom(n, N, p)
Where n is numbers of observations, N is the total number of trials, p is the probability of success.
Example:
R
probabilities <- dbinom(x = c(0:10), size = 10, prob = 1 / 6)plot(0:10, probabilities, type = "l", main='dbinom') probabilities <- pbinom(0:10, size = 10, prob = 1 / 6)plot(0:10, , type = "l", main='pbinom') x <- seq(0, 1, by = 0.1)y <- qbinom(x, size = 13, prob = 1 / 6)plot(x, y, type = 'l') probabilities <- rbinom(8, size = 13, prob = 1 / 6)hist(probabilities)
Output:
Note: For more information, refer Binomial Distribution in R Programming
Time Series in R is used to see how an object behaves over a period of time. In R, it can be easily done by ts() function.
Example: Let’s take the example of COVID-19 pandemic situation. Taking total number of positive cases of COVID-19 cases weekly from 22 January, 2020 to 15 April, 2020 of the world in data vector.
R
# Weekly data of COVID-19 positive cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd("2020-01-22")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab ="Weekly Data", ylab ="Total Positive Cases", main ="COVID-19 Pandemic", col.main ="darkgreen")
Output:
Note: For more information, refer Time Series Analysis in R
anikaseth98
sumitgumber28
clintra
arorakashish0911
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Aug, 2021"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "R is a Programming Language that is mostly used for machine learning, data analysis, and statistical computing. It is an interpreted language and is platform independent that means it can be used on platforms like Windows, Linux, and macOS."
},
{
"code": null,
"e": 437,
"s": 269,
"text": "In this R Language tutorial, we will Learn R Programming Language from scratch to advance and this tutorial is suitable for both beginners and experienced developers)."
},
{
"code": null,
"e": 530,
"s": 437,
"text": "R programming is used as a leading tool for machine learning, statistics, and data analysis."
},
{
"code": null,
"e": 667,
"s": 530,
"text": "R is an open-source language that means it is free of cost and anyone from any organization can install it without purchasing a license."
},
{
"code": null,
"e": 744,
"s": 667,
"text": "It is available across widely used platforms like windows, Linux, and macOS."
},
{
"code": null,
"e": 941,
"s": 744,
"text": "R programming language is not only a statistic package but also allows us to integrate with other languages (C, C++). Thus, you can easily interact with many data sources and statistical packages."
},
{
"code": null,
"e": 1009,
"s": 941,
"text": "Its user base is growing day by day and has vast community support."
},
{
"code": null,
"e": 1166,
"s": 1009,
"text": "R Programming Language is currently one of the most requested programming languages in the Data Science job market that makes it the hottest trend nowadays."
},
{
"code": null,
"e": 1263,
"s": 1166,
"text": "Some key features of R that make the R one of the most demanding job in data science market are:"
},
{
"code": null,
"e": 1476,
"s": 1263,
"text": "Basic Statistics: The most common basic statistics terms are the mean, mode, and median. These are all known as “Measures of Central Tendency.” So using the R language we can measure central tendency very easily."
},
{
"code": null,
"e": 1649,
"s": 1476,
"text": "Static graphics: R is rich with facilities for creating and developing various kinds of static graphics including graphic maps, mosaic plots, biplots, and the list goes on."
},
{
"code": null,
"e": 1840,
"s": 1649,
"text": "Probability distributions: Using R we can easily handle various types of probability distribution such as Binomial Distribution, Normal Distribution, Chi-squared Distribution, and many more."
},
{
"code": null,
"e": 2030,
"s": 1840,
"text": "R Packages: One of the major features of R is it has a wide availability of libraries. R has CRAN(Comprehensive R Archive Network), which is a repository holding more than 10,0000 packages."
},
{
"code": null,
"e": 2308,
"s": 2030,
"text": "Distributed Computing: Distributed computing is a model in which components of a software system are shared among multiple computers to improve efficiency and performance. Two new packages ddR and multidplyr used for distributed programming in R were released in November 2015."
},
{
"code": null,
"e": 2422,
"s": 2308,
"text": "There are many IDE’s available for using R in this article we will dealing with the installation of RStudio in R."
},
{
"code": null,
"e": 2514,
"s": 2422,
"text": "Refer to the below articles to get detailed information about RStudio and its installation."
},
{
"code": null,
"e": 2560,
"s": 2514,
"text": "How to Install R Studio on Windows and Linux?"
},
{
"code": null,
"e": 2585,
"s": 2560,
"text": "Introduction to R Studio"
},
{
"code": null,
"e": 2630,
"s": 2585,
"text": "Creation and Execution of R File in R Studio"
},
{
"code": null,
"e": 2744,
"s": 2630,
"text": "R Program can be run in several ways. You can choose any of the following options to continue with this tutorial."
},
{
"code": null,
"e": 2802,
"s": 2744,
"text": "Using IDEs like RStudio, Eclipse, Jupyter, Notebook, etc."
},
{
"code": null,
"e": 2825,
"s": 2802,
"text": "Using R Command Prompt"
},
{
"code": null,
"e": 2840,
"s": 2825,
"text": "Using RScripts"
},
{
"code": null,
"e": 2902,
"s": 2840,
"text": "Now type the below code to print hello world on your console."
},
{
"code": null,
"e": 2904,
"s": 2902,
"text": "R"
},
{
"code": "# R Program to print# Hello World print(\"HelloWorld\")",
"e": 2958,
"s": 2904,
"text": null
},
{
"code": null,
"e": 2967,
"s": 2958,
"text": " Output:"
},
{
"code": null,
"e": 2984,
"s": 2967,
"text": "[1] \"HelloWorld\""
},
{
"code": null,
"e": 3047,
"s": 2984,
"text": "Note: For more information, refer Hello World in R Programming"
},
{
"code": null,
"e": 3253,
"s": 3049,
"text": "R is a dynamically typed language, i.e. the variables are not declared with a data type rather they take the data type of the R-object assigned to them. In R, the assignment can be denoted in three ways."
},
{
"code": null,
"e": 3310,
"s": 3253,
"text": "Using equal operator- data is copied from right to left."
},
{
"code": null,
"e": 3332,
"s": 3310,
"text": "variable_name = value"
},
{
"code": null,
"e": 3392,
"s": 3332,
"text": "Using leftward operator- data is copied from right to left."
},
{
"code": null,
"e": 3415,
"s": 3392,
"text": "variable_name <- value"
},
{
"code": null,
"e": 3476,
"s": 3415,
"text": "Using rightward operator- data is copied from left to right."
},
{
"code": null,
"e": 3499,
"s": 3476,
"text": "value -> variable_name"
},
{
"code": null,
"e": 3508,
"s": 3499,
"text": "Example:"
},
{
"code": null,
"e": 3510,
"s": 3508,
"text": "R"
},
{
"code": "# R program to illustrate# Initialization of variables # using equal to operatorvar1 = \"gfg\"print(var1) # using leftward operatorvar2 <- \"gfg\"print(var2) # using rightward operator\"gfg\" -> var3print(var3)",
"e": 3715,
"s": 3510,
"text": null
},
{
"code": null,
"e": 3724,
"s": 3715,
"text": " Output:"
},
{
"code": null,
"e": 3754,
"s": 3724,
"text": "[1] \"gfg\"\n[1] \"gfg\"\n[1] \"gfg\""
},
{
"code": null,
"e": 3803,
"s": 3754,
"text": "Note: For more information, refer R – Variables."
},
{
"code": null,
"e": 4096,
"s": 3803,
"text": "Comments are the english sentences that are used to add useful information to the source code to make it more understandable by the reader. It explains the logic part used in the code and will have no impact in the code during its execution. Any statement starting with “#” is a comment in R."
},
{
"code": null,
"e": 4105,
"s": 4096,
"text": "Example:"
},
{
"code": null,
"e": 4107,
"s": 4105,
"text": "R"
},
{
"code": "# all the lines starting with '#'# are comments and will be ignored# during the execution of the# program # Assigning values to variablesa <- 1b <- 2 # Printing sumprint(a + b)",
"e": 4284,
"s": 4107,
"text": null
},
{
"code": null,
"e": 4292,
"s": 4284,
"text": "Output:"
},
{
"code": null,
"e": 4298,
"s": 4292,
"text": "[1] 3"
},
{
"code": null,
"e": 4346,
"s": 4298,
"text": "Note: For more information, refer Comments in R"
},
{
"code": null,
"e": 4670,
"s": 4346,
"text": "Operators are the symbols directing the various kinds of operations that can be performed between the operands. Operators simulate the various mathematical, logical and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. These are classified based on their functionality –"
},
{
"code": null,
"e": 4813,
"s": 4670,
"text": "Arithmetic Operators: Arithmetic operations simulate various math operations, like addition, subtraction, multiplication, division and modulo."
},
{
"code": null,
"e": 4822,
"s": 4813,
"text": "Example:"
},
{
"code": null,
"e": 4824,
"s": 4822,
"text": "R"
},
{
"code": "# R program to illustrate# the use of Arithmetic operatorsa <- 12b <- 5 # Performing operations on Operandscat (\"Addition :\", a + b, \"\\n\")cat (\"Subtraction :\", a - b, \"\\n\")cat (\"Multiplication :\", a * b, \"\\n\")cat (\"Division :\", a / b, \"\\n\")cat (\"Modulo :\", a %% b, \"\\n\")cat (\"Power operator :\", a ^ b)",
"e": 5126,
"s": 4824,
"text": null
},
{
"code": null,
"e": 5135,
"s": 5126,
"text": " Output:"
},
{
"code": null,
"e": 5240,
"s": 5135,
"text": "Addition : 17 \nSubtraction : 7 \nMultiplication : 60 \nDivision : 2.4 \nModulo : 2 \nPower operator : 248832"
},
{
"code": null,
"e": 5441,
"s": 5240,
"text": "Logical Operators: Logical operations simulate element-wise decision operations, based on the specified operator between the operands, which are then evaluated to either a True or False boolean value."
},
{
"code": null,
"e": 5450,
"s": 5441,
"text": "Example:"
},
{
"code": null,
"e": 5452,
"s": 5450,
"text": "R"
},
{
"code": "# R program to illustrate# the use of Logical operatorsvec1 <- c(FALSE, TRUE)vec2 <- c(TRUE,FALSE) # Performing operations on Operandscat (\"Element wise AND :\", vec1 & vec2, \"\\n\")cat (\"Element wise OR :\", vec1 | vec2, \"\\n\")cat (\"Logical AND :\", vec1 && vec2, \"\\n\")cat (\"Logical OR :\", vec1 || vec2, \"\\n\")cat (\"Negation :\", !vec1)",
"e": 5782,
"s": 5452,
"text": null
},
{
"code": null,
"e": 5791,
"s": 5782,
"text": " Output:"
},
{
"code": null,
"e": 5914,
"s": 5791,
"text": "Element wise AND : FALSE FALSE \nElement wise OR : TRUE TRUE \nLogical AND : FALSE \nLogical OR : TRUE \nNegation : TRUE FALSE"
},
{
"code": null,
"e": 6045,
"s": 5914,
"text": "Relational Operators: The relational operators carry out comparison operations between the corresponding elements of the operands."
},
{
"code": null,
"e": 6054,
"s": 6045,
"text": "Example:"
},
{
"code": null,
"e": 6056,
"s": 6054,
"text": "R"
},
{
"code": "# R program to illustrate# the use of Relational operatorsa <- 10b <- 14 # Performing operations on Operandscat (\"a less than b :\", a < b, \"\\n\")cat (\"a less than equal to b :\", a <= b, \"\\n\")cat (\"a greater than b :\", a > b, \"\\n\")cat (\"a greater than equal to b :\", a >= b, \"\\n\")cat (\"a not equal to b :\", a != b, \"\\n\")",
"e": 6375,
"s": 6056,
"text": null
},
{
"code": null,
"e": 6384,
"s": 6375,
"text": " Output:"
},
{
"code": null,
"e": 6523,
"s": 6384,
"text": "a less than b : TRUE \na less than equal to b : TRUE \na greater than b : FALSE \na greater than equal to b : FALSE \na not equal to b : TRUE "
},
{
"code": null,
"e": 6622,
"s": 6523,
"text": "Assignment Operators: Assignment operators are used to assign values to various data objects in R."
},
{
"code": null,
"e": 6631,
"s": 6622,
"text": "Example:"
},
{
"code": null,
"e": 6633,
"s": 6631,
"text": "R"
},
{
"code": "# R program to illustrate# the use of Assignment operators # Left assignment operatorv1 <- \"GeeksForGeeks\"v2 <<- \"GeeksForGeeks\"v3 = \"GeeksForGeeks\" # Right Assignment operator\"GeeksForGeeks\" ->> v4\"GeeksForGeeks\" -> v5 # Performing operations on Operandscat(\"Value 1 :\", v1, \"\\n\")cat(\"Value 2 :\", v2, \"\\n\")cat(\"Value 3 :\", v3, \"\\n\")cat(\"Value 4 :\", v4, \"\\n\")cat(\"Value 5 :\", v5)",
"e": 7013,
"s": 6633,
"text": null
},
{
"code": null,
"e": 7022,
"s": 7013,
"text": " Output:"
},
{
"code": null,
"e": 7146,
"s": 7022,
"text": "Value 1 : GeeksForGeeks \nValue 2 : GeeksForGeeks \nValue 3 : GeeksForGeeks \nValue 4 : GeeksForGeeks \nValue 5 : GeeksForGeeks"
},
{
"code": null,
"e": 7194,
"s": 7146,
"text": "Note: For more information, refer R – Operators"
},
{
"code": null,
"e": 7329,
"s": 7194,
"text": "Keywords are specific reserved words in R, each of which has a specific feature associated with it. Here is the list of keywords in R:"
},
{
"code": null,
"e": 7380,
"s": 7333,
"text": "Note: For more information, refer R – Keywords"
},
{
"code": null,
"e": 7590,
"s": 7380,
"text": "Each variable in R has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. R supports 5 type of data types. These are –"
},
{
"code": null,
"e": 7601,
"s": 7592,
"text": "Example:"
},
{
"code": null,
"e": 7603,
"s": 7601,
"text": "R"
},
{
"code": "# A simple R program# to illustrate data type print(\"Numberic type\")# Assign a decimal value to xx = 12.25 # print the class name of variableprint(class(x)) # print the type of variableprint(typeof(x)) print(\"----------------------------\")print(\"Integer Type\")# Declare an integer by appending an# L suffix.y = 15L # print the class name of yprint(class(y)) # print the type of yprint(typeof(y)) print(\"----------------------------\")print(\"Logical Type\")# Sample valuesx = 1y = 2 # Comparing two valuesz = x > y # print the logical valueprint(z) # print the class name of zprint(class(z)) # print the type of zprint(typeof(z)) print(\"----------------------------\")print(\"Complex Type\")# Assign a complex value to xx = 12 + 13i # print the class name of xprint(class(x)) # print the type of xprint(typeof(x)) print(\"----------------------------\")print(\"Character Type\") # Assign a character value to charchar = \"GFG\" # print the class name of charprint(class(char)) # print the type of charprint(typeof(char))",
"e": 8612,
"s": 7603,
"text": null
},
{
"code": null,
"e": 8622,
"s": 8612,
"text": " Output:"
},
{
"code": null,
"e": 9012,
"s": 8622,
"text": "[1] \"Numberic type\"\n[1] \"numeric\"\n[1] \"double\"\n[1] \"----------------------------\"\n[1] \"Integer Type\"\n[1] \"integer\"\n[1] \"integer\"\n[1] \"----------------------------\"\n[1] \"Logical Type\"\n[1] TRUE\n[1] \"logical\"\n[1] \"logical\"\n[1] \"----------------------------\"\n[1] \"Complex Type\"\n[1] \"complex\"\n[1] \"complex\"\n[1] \"----------------------------\"\n[1] \"Character Type\"\n[1] \"character\"\n[1] \"character\""
},
{
"code": null,
"e": 9063,
"s": 9014,
"text": "Note: for more information, refer R – Data Types"
},
{
"code": null,
"e": 9152,
"s": 9065,
"text": "R Language provides us with two inbuilt functions to read the input from the keyboard."
},
{
"code": null,
"e": 9262,
"s": 9152,
"text": "readline() method: It takes input in string format. If one inputs an integer then it is inputted as a string."
},
{
"code": null,
"e": 9271,
"s": 9262,
"text": "Example:"
},
{
"code": null,
"e": 9273,
"s": 9271,
"text": "R"
},
{
"code": "# R program to illustrate# taking input from the user # taking input using readline()# this command will prompt you# to input a desired valuevar = readline();",
"e": 9432,
"s": 9273,
"text": null
},
{
"code": null,
"e": 9632,
"s": 9432,
"text": "scan() method: This method reads data in the form of a vector or list. This method is a very handy method while inputs are needed to taken quickly for any mathematical calculation or for any dataset."
},
{
"code": null,
"e": 9641,
"s": 9632,
"text": "Example:"
},
{
"code": null,
"e": 9643,
"s": 9641,
"text": "R"
},
{
"code": "# R program to illustrate# taking input from the user # taking input using scan()x = scan()",
"e": 9735,
"s": 9643,
"text": null
},
{
"code": null,
"e": 9809,
"s": 9735,
"text": "Note: For more information, refer Taking Input from User in R Programming"
},
{
"code": null,
"e": 9886,
"s": 9809,
"text": "R Provides various functions to write output to the screen, let’s see them –"
},
{
"code": null,
"e": 9945,
"s": 9886,
"text": "print(): It is the most common method to print the output."
},
{
"code": null,
"e": 9955,
"s": 9945,
"text": "Example: "
},
{
"code": null,
"e": 9957,
"s": 9955,
"text": "R"
},
{
"code": "# R program to illustrate# printing output of an R program # print stringprint(\"Hello\") # print variable# it will print 'GeeksforGeeks' on# the consolex <- \"Welcome to GeeksforGeeks\"print(x)",
"e": 10148,
"s": 9957,
"text": null
},
{
"code": null,
"e": 10157,
"s": 10148,
"text": " Output:"
},
{
"code": null,
"e": 10200,
"s": 10157,
"text": "[1] \"Hello\"\n[1] \"Welcome to GeeksforGeeks\""
},
{
"code": null,
"e": 10321,
"s": 10200,
"text": "cat(): cat() converts its arguments to character strings. This is useful for printing output in user defined functions. "
},
{
"code": null,
"e": 10330,
"s": 10321,
"text": "Example:"
},
{
"code": null,
"e": 10332,
"s": 10330,
"text": "R"
},
{
"code": "# R program to illustrate# printing output of an R# program # print string with variable# \"\\n\" for new linex = \"Hello\"cat(x, \"\\nwelcome\") # print normal stringcat(\"\\nto GeeksForGeeks\")",
"e": 10517,
"s": 10332,
"text": null
},
{
"code": null,
"e": 10526,
"s": 10517,
"text": " Output:"
},
{
"code": null,
"e": 10558,
"s": 10526,
"text": "Hello \nwelcome\nto GeeksForGeeks"
},
{
"code": null,
"e": 10624,
"s": 10558,
"text": "Note: For more information, refer Printing Output of an R Program"
},
{
"code": null,
"e": 10984,
"s": 10624,
"text": "Decision making decides the flow of the execution of the program based on certain conditions. In decision making programmer needs to provide some condition which is evaluated by the program, along with it there also provided some statements which are executed if the condition is true and optionally other statements if the condition is evaluated to be false."
},
{
"code": null,
"e": 11028,
"s": 10986,
"text": "Decision-making statements in R Language:"
},
{
"code": null,
"e": 11041,
"s": 11028,
"text": "if statement"
},
{
"code": null,
"e": 11059,
"s": 11041,
"text": "if-else statement"
},
{
"code": null,
"e": 11077,
"s": 11059,
"text": "if-else-if ladder"
},
{
"code": null,
"e": 11102,
"s": 11077,
"text": "nested if-else statement"
},
{
"code": null,
"e": 11119,
"s": 11102,
"text": "switch statement"
},
{
"code": null,
"e": 11159,
"s": 11119,
"text": "Example 1: Demonstrating if and if-else"
},
{
"code": null,
"e": 11161,
"s": 11159,
"text": "R"
},
{
"code": "# R program to illustrate# decision making a <- 99b <- 12 # if statement to check whether# the number a is larger or notif(a > b){ print(\"A is Larger\")} # if-else statement to check which# number is greaterif(b > a){ print(\"B is Larger\")} else{ print(\"A is Larger\")}",
"e": 11438,
"s": 11161,
"text": null
},
{
"code": null,
"e": 11447,
"s": 11438,
"text": " Output:"
},
{
"code": null,
"e": 11483,
"s": 11447,
"text": "[1] \"A is Larger\"\n[1] \"A is Larger\""
},
{
"code": null,
"e": 11533,
"s": 11483,
"text": "Example 2: Demonstrating if-else-if and nested if"
},
{
"code": null,
"e": 11535,
"s": 11533,
"text": "R"
},
{
"code": "# R program to demonstrate# decision making a <- 10 # is-elifif (a == 11){ print (\"a is 11\")} else if (a==10){ print (\"a is 10\")} else print (\"a is not present\") # Nested if to check whether a# number is divisible by both 2 and 5if (a %% 2 == 0){ if (a %% 5 == 0) print(\"Number is divisible by both 2 and 5\")}",
"e": 11866,
"s": 11535,
"text": null
},
{
"code": null,
"e": 11875,
"s": 11866,
"text": " Output:"
},
{
"code": null,
"e": 11931,
"s": 11875,
"text": "[1] \"a is 10\"\n[1] \"Number is divisible by both 2 and 5\""
},
{
"code": null,
"e": 11963,
"s": 11931,
"text": "Example 3: Demonstrating switch"
},
{
"code": null,
"e": 11965,
"s": 11963,
"text": "R"
},
{
"code": "# R switch statement example # Expression in terms of the index valuex <- switch( 2, # Expression \"Welcome\", # case 1 \"to\", # case 2 \"GFG\" # case 3)print(x) # Expression in terms of the string valuey <- switch( \"3\", # Expression \"0\"=\"Welcome\", # case 1 \"1\"=\"to\", # case 2 \"3\"=\"GFG\" # case 3)print(y) z <- switch( \"GfG\", # Expression \"GfG0\"=\"Welcome\", # case 1 \"GfG1\"=\"to\", # case 2 \"GfG3\"=\"GFG\" # case 3)print(z)",
"e": 12518,
"s": 11965,
"text": null
},
{
"code": null,
"e": 12527,
"s": 12518,
"text": " Output:"
},
{
"code": null,
"e": 12552,
"s": 12527,
"text": "[1] \"to\"\n[1] \"GFG\"\nNULL "
},
{
"code": null,
"e": 12619,
"s": 12552,
"text": "Note: For more information, refer Decision Making in R Programming"
},
{
"code": null,
"e": 12782,
"s": 12619,
"text": "Loops are used wherever we have to execute a block of statements repeatedly. For example, printing “hello world” 10 times. The different types of loops in R are –"
},
{
"code": null,
"e": 12791,
"s": 12782,
"text": "For Loop"
},
{
"code": null,
"e": 12800,
"s": 12791,
"text": "Example:"
},
{
"code": null,
"e": 12802,
"s": 12800,
"text": "R"
},
{
"code": "# R Program to demonstrate the use of# for loop along with concatenatefor (i in c(-8, 9, 11, 45)){ print(i)}",
"e": 12914,
"s": 12802,
"text": null
},
{
"code": null,
"e": 12924,
"s": 12914,
"text": " Output:"
},
{
"code": null,
"e": 12951,
"s": 12924,
"text": "[1] -8\n[1] 9\n[1] 11\n[1] 45"
},
{
"code": null,
"e": 12962,
"s": 12951,
"text": "While Loop"
},
{
"code": null,
"e": 12971,
"s": 12962,
"text": "Example:"
},
{
"code": null,
"e": 12973,
"s": 12971,
"text": "R"
},
{
"code": "# R program to demonstrate the# use of while loop val = 1 # using while loopwhile (val <= 5 ){ # statements print(val) val = val + 1}",
"e": 13116,
"s": 12973,
"text": null
},
{
"code": null,
"e": 13125,
"s": 13116,
"text": " Output:"
},
{
"code": null,
"e": 13155,
"s": 13125,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5"
},
{
"code": null,
"e": 13167,
"s": 13155,
"text": "Repeat Loop"
},
{
"code": null,
"e": 13176,
"s": 13167,
"text": "Example:"
},
{
"code": null,
"e": 13178,
"s": 13176,
"text": "R"
},
{
"code": "# R program to demonstrate the use# of repeat loop val = 1 # using repeat looprepeat{ # statements print(val) val = val + 1 # checking stop condition if(val > 5) { # using break statement # to terminate the loop break }}",
"e": 13442,
"s": 13178,
"text": null
},
{
"code": null,
"e": 13451,
"s": 13442,
"text": " Output:"
},
{
"code": null,
"e": 13482,
"s": 13451,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5 "
},
{
"code": null,
"e": 13527,
"s": 13482,
"text": "Note: For more information, refer Loops in R"
},
{
"code": null,
"e": 13662,
"s": 13529,
"text": "Loop control statements change execution from its normal sequence. Following are the loop control statements provided by R Language:"
},
{
"code": null,
"e": 13779,
"s": 13662,
"text": "Break Statement: The break keyword is a jump statement that is used to terminate the loop at a particular iteration."
},
{
"code": null,
"e": 13933,
"s": 13779,
"text": "Next Statement: The next statement is used to skip the current iteration in the loop and move to the next iteration without exiting from the loop itself."
},
{
"code": null,
"e": 13935,
"s": 13933,
"text": "R"
},
{
"code": "# R program for break statementno <- 15:20 for (val in no){ if (val == 17) { break } print(paste(\"Values are: \", val))} print(\"------------------------------------\") # R Next Statement Examplefor (val in no){ if (val == 17) { next } print(paste(\"Values are: \", val))}",
"e": 14241,
"s": 13935,
"text": null
},
{
"code": null,
"e": 14250,
"s": 14241,
"text": " Output:"
},
{
"code": null,
"e": 14447,
"s": 14250,
"text": "[1] \"Values are: 15\"\n[1] \"Values are: 16\"\n[1] \"------------------------------------\"\n[1] \"Values are: 15\"\n[1] \"Values are: 16\"\n[1] \"Values are: 18\"\n[1] \"Values are: 19\"\n[1] \"Values are: 20\""
},
{
"code": null,
"e": 14512,
"s": 14447,
"text": "Note: For more information, refer Break and Next statements in R"
},
{
"code": null,
"e": 14875,
"s": 14512,
"text": "Functions are the block of code that given the user the ability to reuse the same code which saves the excessive use of memory and provides better readability to the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. Functions are created in R by using the command function() keyword"
},
{
"code": null,
"e": 14884,
"s": 14875,
"text": "Example:"
},
{
"code": null,
"e": 14886,
"s": 14884,
"text": "R"
},
{
"code": "# A simple R program to# demonstrate functions ask_user = function(x){ print(\"GeeksforGeeks\")} my_func = function(x){ a <- 1:5 b <- 0 for (i in a){ b = b +1 } return(b)} ask_user()res = my_func()print(res)",
"e": 15122,
"s": 14886,
"text": null
},
{
"code": null,
"e": 15132,
"s": 15122,
"text": " Output: "
},
{
"code": null,
"e": 15158,
"s": 15132,
"text": "[1] \"GeeksforGeeks\"\n[1] 5"
},
{
"code": null,
"e": 15284,
"s": 15158,
"text": "Arguments to a function can be specified at the time of function definition, after the function name, inside the parenthesis."
},
{
"code": null,
"e": 15293,
"s": 15284,
"text": "Example:"
},
{
"code": null,
"e": 15295,
"s": 15293,
"text": "R"
},
{
"code": "# A simple R function to check# whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) # return even if the number # is even return(\"even\") else # return odd if the number # is odd return(\"odd\")} # Function definition# To check a is divisible by b or notdivisible <- function(a, b){ if(a %% b == 0) { cat(a, \"is divisible by\", b, \"\\n\") } else { cat(a, \"is not divisible by\", b, \"\\n\") }} # function with single argumentprint(evenOdd(4))print(evenOdd(3)) # function with multiple argumentsdivisible(7, 3)divisible(36, 6)divisible(9, 2)",
"e": 15933,
"s": 15295,
"text": null
},
{
"code": null,
"e": 15942,
"s": 15933,
"text": " Output:"
},
{
"code": null,
"e": 16035,
"s": 15942,
"text": "[1] \"even\"\n[1] \"odd\"\n7 is not divisible by 3 \n36 is divisible by 6 \n9 is not divisible by 2 "
},
{
"code": null,
"e": 16159,
"s": 16035,
"text": "Default Arguments: Default value in a function is a value that is not required to specify each time the function is called."
},
{
"code": null,
"e": 16168,
"s": 16159,
"text": "Example:"
},
{
"code": null,
"e": 16170,
"s": 16168,
"text": "R"
},
{
"code": "# Function definition to check# a is divisible by b or not. # If b is not provided in function call,# Then divisibility of a is checked# with 3 as defaultisdivisible <- function(a, b = 9){ if(a %% b == 0) { cat(a, \"is divisible by\", b, \"\\n\") } else { cat(a, \"is not divisible by\", b, \"\\n\") }} # Function callisdivisible(20, 2)isdivisible(12)",
"e": 16541,
"s": 16170,
"text": null
},
{
"code": null,
"e": 16550,
"s": 16541,
"text": " Output:"
},
{
"code": null,
"e": 16598,
"s": 16550,
"text": "20 is divisible by 2 \n12 is not divisible by 9 "
},
{
"code": null,
"e": 16739,
"s": 16598,
"text": "Variable length arguments: Dots argument (...) is also known as ellipsis which allows the function to take an undefined number of arguments."
},
{
"code": null,
"e": 16748,
"s": 16739,
"text": "Example:"
},
{
"code": null,
"e": 16750,
"s": 16748,
"text": "R"
},
{
"code": "# Function definition of dots operatorfun <- function(n, ...){ l <- c(n, ...) paste(l, collapse = \" \")} # Function callfun(5, 1L, 6i, TRUE, \"GFG\", 1:2)",
"e": 16908,
"s": 16750,
"text": null
},
{
"code": null,
"e": 16917,
"s": 16908,
"text": " Output:"
},
{
"code": null,
"e": 16939,
"s": 16917,
"text": "5 1 0+6i TRUE GFG 1 2"
},
{
"code": null,
"e": 17016,
"s": 16939,
"text": "Refer to the below articles to get detailed information about functions in R"
},
{
"code": null,
"e": 17043,
"s": 17016,
"text": "Functions in R Programming"
},
{
"code": null,
"e": 17079,
"s": 17043,
"text": "Function Arguments in R Programming"
},
{
"code": null,
"e": 17115,
"s": 17079,
"text": "Types of Functions in R Programming"
},
{
"code": null,
"e": 17222,
"s": 17115,
"text": "A data structure is a particular way of organizing data in a computer so that it can be used effectively. "
},
{
"code": null,
"e": 17436,
"s": 17222,
"text": "Vectors in R are the same as the arrays in C language which are used to hold multiple data values of the same type. One major key point is that in R the indexing of the vector will start from ‘1’ and not from ‘0’."
},
{
"code": null,
"e": 17449,
"s": 17440,
"text": "Example:"
},
{
"code": null,
"e": 17451,
"s": 17449,
"text": "R"
},
{
"code": "# R program to illustrate Vector # Numeric VectorN = c(1, 3, 5, 7, 8) # Character vectorC = c('Geeks', 'For', 'Geeks') # Logical VectorL = c(TRUE, FALSE, FALSE, TRUE) # Printing vectorsprint(N)print(C)print(L)",
"e": 17661,
"s": 17451,
"text": null
},
{
"code": null,
"e": 17670,
"s": 17661,
"text": " Output:"
},
{
"code": null,
"e": 17740,
"s": 17670,
"text": "[1] 1 3 5 7 8\n[1] \"Geeks\" \"For\" \"Geeks\"\n[1] TRUE FALSE FALSE TRUE"
},
{
"code": null,
"e": 17768,
"s": 17740,
"text": "Accessing Vector Elements: "
},
{
"code": null,
"e": 17887,
"s": 17768,
"text": "There are many ways through which we can access the elements of the vector. The most common is using the ‘[]’, symbol."
},
{
"code": null,
"e": 17896,
"s": 17887,
"text": "Example:"
},
{
"code": null,
"e": 17898,
"s": 17896,
"text": "R"
},
{
"code": "# Accessing elements using# the position number.X <- c(2, 9, 8, 0, 5)print('using Subscript operator')print(X[2]) # Accessing specific values by passing# a vector inside another vector.Y <- c(6, 2, 7, 4, 0)print('using c function')print(Y[c(4, 1)]) # Logical indexingZ <- c(1, 6, 9, 4, 6)print('Logical indexing')print(Z[Z>3])",
"e": 18225,
"s": 17898,
"text": null
},
{
"code": null,
"e": 18234,
"s": 18225,
"text": " Output:"
},
{
"code": null,
"e": 18337,
"s": 18234,
"text": "[1] \"using Subscript operator\"\n[1] 9\n[1] \"using c function\"\n[1] 4 6\n[1] \"Logical indexing\"\n[1] 6 9 4 6"
},
{
"code": null,
"e": 18413,
"s": 18337,
"text": "Refer to the below articles to get detailed information about vectors in R."
},
{
"code": null,
"e": 18424,
"s": 18413,
"text": "R – Vector"
},
{
"code": null,
"e": 18458,
"s": 18424,
"text": "Types of Vectors in R Programming"
},
{
"code": null,
"e": 18485,
"s": 18458,
"text": "Operations on Vectors in R"
},
{
"code": null,
"e": 18601,
"s": 18485,
"text": "A list is a generic object consisting of an ordered collection of objects. Lists are heterogeneous data structures."
},
{
"code": null,
"e": 18611,
"s": 18601,
"text": "Example: "
},
{
"code": null,
"e": 18613,
"s": 18611,
"text": "R"
},
{
"code": "# R program to create a List # The first attributes is a numeric vector# containing the employee IDs which is created# using the command hereempId = c(1, 2, 3, 4) # The second attribute is the employee name# which is created using this line of code here# which is the character vectorempName = c(\"Nisha\", \"Nikhil\", \"Akshu\", \"Sambha\") # The third attribute is the number of employees# which is a single numeric variable.numberOfEmp = 4 # The fourth attribute is the name of organization# which is a single character variable.Organization = \"GFG\" # We can combine all these three different# data types into a list# containing the details of employees# which can be done using a list commandempList = list(empId, empName, numberOfEmp, Organization) print(empList)",
"e": 19374,
"s": 18613,
"text": null
},
{
"code": null,
"e": 19384,
"s": 19374,
"text": " Output: "
},
{
"code": null,
"e": 19479,
"s": 19384,
"text": "[[1]]\n[1] 1 2 3 4\n\n[[2]]\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\n[[3]]\n[1] 4\n\n[[4]]\n[1] \"GFG\""
},
{
"code": null,
"e": 19504,
"s": 19479,
"text": "Accessing List Elements:"
},
{
"code": null,
"e": 19664,
"s": 19504,
"text": "Access components by names: All the components of a list can be named and we can use those names to access the components of the list using the dollar command."
},
{
"code": null,
"e": 20041,
"s": 19664,
"text": "Access components by indices: We can also access the components of the list using indices. To access the top-level components of a list we have to use a double slicing operator “[[ ]]” which is two square brackets and if we want to access the lower or inner level components of a list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]“."
},
{
"code": null,
"e": 20051,
"s": 20041,
"text": "Example: "
},
{
"code": null,
"e": 20053,
"s": 20051,
"text": "R"
},
{
"code": "# R program to access# components of a list # Creating a list by naming all its componentsempId = c(1, 2, 3, 4)empName = c(\"Nisha\", \"Nikhil\", \"Akshu\", \"Sambha\")numberOfEmp = 4empList = list(\"ID\" = empId,\"Names\" = empName,\"Total Staff\" = numberOfEmp)print(\"Initial List\")print(empList) # Accessing components by namescat(\"\\nAccessing name components using $ command\\n\")print(empList$Names) # Accessing a top level components by indicescat(\"\\nAccessing name components using indices\\n\")print(empList[[2]])print(empList[[1]][2])print(empList[[2]][4])",
"e": 20601,
"s": 20053,
"text": null
},
{
"code": null,
"e": 20610,
"s": 20601,
"text": " Output:"
},
{
"code": null,
"e": 20899,
"s": 20610,
"text": "[1] \"Initial List\"\n$ID\n[1] 1 2 3 4\n\n$Names\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\n$`Total Staff`\n[1] 4\n\n\nAccessing name components using $ command\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\nAccessing name components using indices\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n[1] 2\n[1] \"Sambha\""
},
{
"code": null,
"e": 20935,
"s": 20899,
"text": "Adding and Modifying list elements:"
},
{
"code": null,
"e": 21040,
"s": 20935,
"text": "A list can also be modified by accessing the components and replacing them with the ones which you want."
},
{
"code": null,
"e": 21114,
"s": 21040,
"text": "List elements can be added simply by assigning new values using new tags."
},
{
"code": null,
"e": 21123,
"s": 21114,
"text": "Example:"
},
{
"code": null,
"e": 21125,
"s": 21123,
"text": "R"
},
{
"code": "# R program to access# components of a list # Creating a list by naming all its componentsempId = c(1, 2, 3, 4)empName = c(\"Nisha\", \"Nikhil\", \"Akshu\", \"Sambha\")numberOfEmp = 4empList = list(\"ID\" = empId,\"Names\" = empName,\"Total Staff\" = numberOfEmp)print(\"Initial List\")print(empList) # Adding new elementempList[[\"organization\"]] <- \"GFG\"cat(\"\\nAfter adding new element\\n\")print(empList) # Modifying the top-level componentempList$\"Total Staff\" = 5 # Modifying inner level componentempList[[1]][5] = 7 cat(\"\\nAfter modification\\n\")print(empList)",
"e": 21674,
"s": 21125,
"text": null
},
{
"code": null,
"e": 21684,
"s": 21674,
"text": " Output: "
},
{
"code": null,
"e": 22061,
"s": 21684,
"text": "[1] \"Initial List\"\n$ID\n[1] 1 2 3 4\n\n$Names\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\n$`Total Staff`\n[1] 4\n\n\nAfter adding new element\n$ID\n[1] 1 2 3 4\n\n$Names\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\n$`Total Staff`\n[1] 4\n\n$organization\n[1] \"GFG\"\n\n\nAfter modification\n$ID\n[1] 1 2 3 4 7\n\n$Names\n[1] \"Nisha\" \"Nikhil\" \"Akshu\" \"Sambha\"\n\n$`Total Staff`\n[1] 5\n\n$organization\n[1] \"GFG\""
},
{
"code": null,
"e": 22134,
"s": 22061,
"text": "Refer to the below articles to get detailed information about lists in R"
},
{
"code": null,
"e": 22144,
"s": 22134,
"text": "R – Lists"
},
{
"code": null,
"e": 22181,
"s": 22144,
"text": "Operations on Lists in R Programming"
},
{
"code": null,
"e": 22219,
"s": 22181,
"text": "Two Dimensional List in R Programming"
},
{
"code": null,
"e": 22247,
"s": 22219,
"text": "Named List in R Programming"
},
{
"code": null,
"e": 22376,
"s": 22247,
"text": "A matrix is a rectangular arrangement of numbers in rows and columns. Matrices are two-dimensional, homogeneous data structures."
},
{
"code": null,
"e": 22385,
"s": 22376,
"text": "Example:"
},
{
"code": null,
"e": 22387,
"s": 22385,
"text": "R"
},
{
"code": "# R program to illustrate a matrix A = matrix( # Taking sequence of elements c(1, 4, 5, 6, 3, 8), # No of rows and columns nrow = 2, ncol = 3, # By default matrices are # in column-wise order # So this parameter decides # how to arrange the matrix byrow = TRUE) print(A)",
"e": 22687,
"s": 22387,
"text": null
},
{
"code": null,
"e": 22696,
"s": 22687,
"text": " Output:"
},
{
"code": null,
"e": 22756,
"s": 22696,
"text": " [,1] [,2] [,3]\n[1,] 1 4 5\n[2,] 6 3 8"
},
{
"code": null,
"e": 22783,
"s": 22756,
"text": "Accessing Matrix Elements:"
},
{
"code": null,
"e": 23008,
"s": 22783,
"text": "Matrix elements can be accessed using the matrix name followed by a square bracket with a comma in between the array. Value before the comma is used to access rows and value that is after the comma is used to access columns."
},
{
"code": null,
"e": 23017,
"s": 23008,
"text": "Example:"
},
{
"code": null,
"e": 23019,
"s": 23017,
"text": "R"
},
{
"code": "# R program to illustrate# access rows in metrics # Create a 3x3 matrixA = matrix(c(1, 4, 5, 6, 3, 8),nrow = 2, ncol = 3,byrow = TRUE )cat(\"The 2x3 matrix:\\n\")print(A) print(A[1, 1]) print(A[2, 2]) # Accessing first and second rowcat(\"Accessing first and second row\\n\")print(A[1:2, ]) # Accessing first and second columncat(\"\\nAccessing first and second column\\n\")print(A[, 1:2])",
"e": 23405,
"s": 23019,
"text": null
},
{
"code": null,
"e": 23414,
"s": 23405,
"text": " Output:"
},
{
"code": null,
"e": 23673,
"s": 23414,
"text": "The 2x3 matrix:\n [,1] [,2] [,3]\n[1,] 1 4 5\n[2,] 6 3 8\n[1] 1\n[1] 3\nAccessing first and second row\n [,1] [,2] [,3]\n[1,] 1 4 5\n[2,] 6 3 8\n\nAccessing first and second column\n [,1] [,2]\n[1,] 1 4\n[2,] 6 3"
},
{
"code": null,
"e": 23701,
"s": 23673,
"text": " Modifying Matrix Elements:"
},
{
"code": null,
"e": 23769,
"s": 23701,
"text": "You can modify the elements of the matrices by a direct assignment."
},
{
"code": null,
"e": 23778,
"s": 23769,
"text": "Example:"
},
{
"code": null,
"e": 23780,
"s": 23778,
"text": "R"
},
{
"code": "# R program to illustrate# editing elements in metrics # Create a 3x3 matrixA = matrix( c(1, 4, 5, 6, 3, 8), nrow = 2, ncol = 3, byrow = TRUE)cat(\"The 2x3 matrix:\\n\")print(A) # Editing the 3rd rows and 3rd# column element from 9 to 30# by direct assignmentsA[2, 1] = 30 cat(\"After edited the matrix\\n\")print(A)",
"e": 24103,
"s": 23780,
"text": null
},
{
"code": null,
"e": 24112,
"s": 24103,
"text": " Output:"
},
{
"code": null,
"e": 24272,
"s": 24112,
"text": "The 2x3 matrix:\n [,1] [,2] [,3]\n[1,] 1 4 5\n[2,] 6 3 8\nAfter edited the matrix\n [,1] [,2] [,3]\n[1,] 1 4 5\n[2,] 30 3 8"
},
{
"code": null,
"e": 24348,
"s": 24272,
"text": "Refer to the below articles to get detailed information about Matrices in R"
},
{
"code": null,
"e": 24361,
"s": 24348,
"text": "R – Matrices"
},
{
"code": null,
"e": 24389,
"s": 24361,
"text": "Operations on Matrices in R"
},
{
"code": null,
"e": 24427,
"s": 24389,
"text": "Algebraic Operations on a Matrix in R"
},
{
"code": null,
"e": 24449,
"s": 24427,
"text": "Matrix Transpose in R"
},
{
"code": null,
"e": 24472,
"s": 24449,
"text": "Inverse of Matrix in R"
},
{
"code": null,
"e": 24657,
"s": 24472,
"text": "Dataframes are generic data objects of R which are used to store the tabular data. They are two-dimensional, heterogeneous data structures. These are lists of vectors of equal lengths."
},
{
"code": null,
"e": 24666,
"s": 24657,
"text": "Example:"
},
{
"code": null,
"e": 24668,
"s": 24666,
"text": "R"
},
{
"code": "# R program to illustrate dataframe # A vector which is a character vectorName = c(\"Nisha\", \"Nikhil\", \"Raju\") # A vector which is a character vectorLanguage = c(\"R\", \"Python\", \"C\") # A vector which is a numeric vectorAge = c(40, 25, 10) # To create dataframe use data.frame command# and then pass each of the vectors# we have created as arguments# to the function data.frame()df = data.frame(Name, Language, Age) print(df)",
"e": 25091,
"s": 24668,
"text": null
},
{
"code": null,
"e": 25100,
"s": 25091,
"text": " Output:"
},
{
"code": null,
"e": 25188,
"s": 25100,
"text": " Name Language Age\n1 Nisha R 40\n2 Nikhil Python 25\n3 Raju C 10"
},
{
"code": null,
"e": 25235,
"s": 25188,
"text": "Getting the structure and data from DataFrame:"
},
{
"code": null,
"e": 25301,
"s": 25235,
"text": "One can get the structure of the data frame using str() function."
},
{
"code": null,
"e": 25376,
"s": 25301,
"text": "One can extract a specific column from a data frame using its column name."
},
{
"code": null,
"e": 25385,
"s": 25376,
"text": "Example:"
},
{
"code": null,
"e": 25387,
"s": 25385,
"text": "R"
},
{
"code": "# R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Aman\", \"Nisha\", \"Nikhil\", \"Raju\", \"Raj\"), stringsAsFactors = FALSE)# using str()print(str(friend.data)) # Extracting friend_name columnresult <- data.frame(friend.data$friend_name)print(result)",
"e": 25767,
"s": 25387,
"text": null
},
{
"code": null,
"e": 25777,
"s": 25767,
"text": " Output:"
},
{
"code": null,
"e": 26066,
"s": 25777,
"text": "'data.frame': 5 obs. of 2 variables:\n $ friend_id : int 1 2 3 4 5\n $ friend_name: chr \"Aman\" \"Nisha\" \"Nikhil\" \"Raju\" ...\nNULL\n friend.data.friend_name\n1 Aman\n2 Nisha\n3 Nikhil\n4 Raju\n5 Raj"
},
{
"code": null,
"e": 26088,
"s": 26066,
"text": "Summary of dataframe:"
},
{
"code": null,
"e": 26183,
"s": 26088,
"text": "The statistical summary and nature of the data can be obtained by applying summary() function."
},
{
"code": null,
"e": 26192,
"s": 26183,
"text": "Example:"
},
{
"code": null,
"e": 26194,
"s": 26192,
"text": "R"
},
{
"code": "# R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Aman\", \"Nisha\", \"Nikhil\", \"Raju\", \"Raj\"), stringsAsFactors = FALSE)# using summary()print(summary(friend.data))",
"e": 26492,
"s": 26194,
"text": null
},
{
"code": null,
"e": 26502,
"s": 26492,
"text": " Output:"
},
{
"code": null,
"e": 26726,
"s": 26502,
"text": " friend_id friend_name \n Min. :1 Length:5 \n 1st Qu.:2 Class :character \n Median :3 Mode :character \n Mean :3 \n 3rd Qu.:4 \n Max. :5 "
},
{
"code": null,
"e": 26804,
"s": 26726,
"text": "Refer to the below articles to get detailed information about DataFrames in R"
},
{
"code": null,
"e": 26820,
"s": 26804,
"text": "R – Data Frames"
},
{
"code": null,
"e": 26841,
"s": 26820,
"text": "DataFrame Operations"
},
{
"code": null,
"e": 26864,
"s": 26841,
"text": "DataFrame Manipulation"
},
{
"code": null,
"e": 26886,
"s": 26864,
"text": "Joining of Dataframes"
},
{
"code": null,
"e": 26901,
"s": 26886,
"text": "Data Reshaping"
},
{
"code": null,
"e": 26925,
"s": 26901,
"text": "Handling Missing Values"
},
{
"code": null,
"e": 27047,
"s": 26925,
"text": "Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures."
},
{
"code": null,
"e": 27056,
"s": 27047,
"text": "Example:"
},
{
"code": null,
"e": 27058,
"s": 27056,
"text": "R"
},
{
"code": "# R program to illustrate an array A = array( # Taking sequence of elements c(2, 4, 5, 7, 1, 8, 9, 2), # Creating two rectangular matrices # each with two rows and two columns dim = c(2, 2, 2)) print(A)",
"e": 27277,
"s": 27058,
"text": null
},
{
"code": null,
"e": 27286,
"s": 27277,
"text": " Output:"
},
{
"code": null,
"e": 27391,
"s": 27286,
"text": ", , 1\n\n [,1] [,2]\n[1,] 2 5\n[2,] 4 7\n\n, , 2\n\n [,1] [,2]\n[1,] 1 9\n[2,] 8 2"
},
{
"code": null,
"e": 27409,
"s": 27391,
"text": "Accessing arrays:"
},
{
"code": null,
"e": 27589,
"s": 27409,
"text": "The arrays can be accessed by using indices for different dimensions separated by commas. Different components can be specified by any combination of elements’ names or positions."
},
{
"code": null,
"e": 27598,
"s": 27589,
"text": "Example:"
},
{
"code": null,
"e": 27600,
"s": 27598,
"text": "R"
},
{
"code": "vec1 <- c(2, 4, 5, 7, 1, 8, 9, 2)vec2 <- c(12, 21, 34) row_names <- c(\"row1\", \"row2\")col_names <- c(\"col1\", \"col2\", \"col3\")mat_names <- c(\"Mat1\", \"Mat2\") arr = array(c(vec1, vec2), dim = c(2, 3, 2), dimnames = list(row_names, col_names, mat_names)) # accessing matrix 1 by index valueprint (\"Matrix 1\")print (arr[,,1]) # accessing matrix 2 by its nameprint (\"Matrix 2\")print(arr[,,\"Mat2\"]) # accessing matrix 1 by index valueprint (\"1st column of matrix 1\")print (arr[, 1, 1]) # accessing matrix 2 by its nameprint (\"2nd row of matrix 2\")print(arr[\"row2\",,\"Mat2\"]) # accessing matrix 1 by index valueprint (\"2nd row 3rd column matrix 1 element\")print (arr[2, \"col3\", 1]) # accessing matrix 2 by its nameprint (\"2nd row 1st column element of matrix 2\")print(arr[\"row2\", \"col1\", \"Mat2\"]) # print elements of both the rows and columns# 2 and 3 of matrix 1print (arr[, c(2, 3), 1])",
"e": 28520,
"s": 27600,
"text": null
},
{
"code": null,
"e": 28529,
"s": 28520,
"text": " Output:"
},
{
"code": null,
"e": 28932,
"s": 28529,
"text": "[1] \"Matrix 1\"\n col1 col2 col3\nrow1 2 5 1\nrow2 4 7 8\n[1] \"Matrix 2\"\n col1 col2 col3\nrow1 9 12 34\nrow2 2 21 2\n[1] \"1st column of matrix 1\"\nrow1 row2 \n 2 4 \n[1] \"2nd row of matrix 2\"\ncol1 col2 col3 \n 2 21 2 \n[1] \"2nd row 3rd column matrix 1 element\"\n[1] 8\n[1] \"2nd row 1st column element of matrix 2\"\n[1] 2\n col2 col3\nrow1 5 1\nrow2 7 8"
},
{
"code": null,
"e": 28958,
"s": 28932,
"text": "Adding elements to array:"
},
{
"code": null,
"e": 29173,
"s": 28958,
"text": "Elements can be appended at the different positions in the array. The sequence of elements is retained in order of their addition to the array. There are various in-built functions available in R to add new values:"
},
{
"code": null,
"e": 29191,
"s": 29173,
"text": "c(vector, values)"
},
{
"code": null,
"e": 29215,
"s": 29191,
"text": "append(vector, values):"
},
{
"code": null,
"e": 29254,
"s": 29215,
"text": "Using the length function of the array"
},
{
"code": null,
"e": 29263,
"s": 29254,
"text": "Example:"
},
{
"code": null,
"e": 29265,
"s": 29263,
"text": "R"
},
{
"code": "# creating a uni-dimensional arrayx <- c(1, 2, 3, 4, 5) # addition of element using c() functionx <- c(x, 6)print (\"Array after 1st modification \")print (x) # addition of element using append functionx <- append(x, 7)print (\"Array after 2nd modification \")print (x) # adding elements after computing the lengthlen <- length(x)x[len + 1] <- 8print (\"Array after 3rd modification \")print (x) # adding on length + 3 indexx[len + 3]<-9print (\"Array after 4th modification \")print (x) # append a vector of values to the# array after length + 3 of arrayprint (\"Array after 5th modification\")x <- append(x, c(10, 11, 12), after = length(x)+3)print (x) # adds new elements after 3rd indexprint (\"Array after 6th modification\")x <- append(x, c(-1, -1), after = 3)print (x)",
"e": 30029,
"s": 29265,
"text": null
},
{
"code": null,
"e": 30038,
"s": 30029,
"text": " Output:"
},
{
"code": null,
"e": 30435,
"s": 30038,
"text": "[1] \"Array after 1st modification \"\n[1] 1 2 3 4 5 6\n[1] \"Array after 2nd modification \"\n[1] 1 2 3 4 5 6 7\n[1] \"Array after 3rd modification \"\n[1] 1 2 3 4 5 6 7 8\n[1] \"Array after 4th modification \"\n [1] 1 2 3 4 5 6 7 8 NA 9\n[1] \"Array after 5th modification\"\n [1] 1 2 3 4 5 6 7 8 NA 9 10 11 12\n[1] \"Array after 6th modification\"\n [1] 1 2 3 -1 -1 4 5 6 7 8 NA 9 10 11 12"
},
{
"code": null,
"e": 30465,
"s": 30435,
"text": "Removing Elements from Array:"
},
{
"code": null,
"e": 30686,
"s": 30465,
"text": "Elements can be removed from arrays in R, either one at a time or multiple together. These elements are specified as indexes to the array, wherein the array values satisfying the conditions are retained and rest removed."
},
{
"code": null,
"e": 30872,
"s": 30686,
"text": "Another way to remove elements is by using %in% operator wherein the set of element values belonging to the TRUE values of the operator are displayed as result and the rest are removed."
},
{
"code": null,
"e": 30881,
"s": 30872,
"text": "Example:"
},
{
"code": null,
"e": 30883,
"s": 30881,
"text": "R"
},
{
"code": "# creating an array of length 9m <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)print (\"Original Array\")print (m) # remove a single value element:3# from arraym <- m[m != 3]print (\"After 1st modification\")print (m) # removing elements based on condition# where either element should be# greater than 2 and less than equal# to 8m <- m[m>2 & m<= 8]print (\"After 2nd modification\")print (m) # remove sequence of elements using# another arrayremove <- c(4, 6, 8) # check which element satisfies the# remove propertyprint (m % in % remove)print (\"After 3rd modification\")print (m [! m % in % remove])",
"e": 31463,
"s": 30883,
"text": null
},
{
"code": null,
"e": 31472,
"s": 31463,
"text": " Output:"
},
{
"code": null,
"e": 31678,
"s": 31472,
"text": "[1] \"Original Array\"\n[1] 1 2 3 4 5 6 7 8 9\n[1] \"After 1st modification\"\n[1] 1 2 4 5 6 7 8 9\n[1] \"After 2nd modification\"\n[1] 4 5 6 7 8\n[1] TRUE FALSE TRUE FALSE TRUE\n[1] \"After 3rd modification\"\n[1] 5 7"
},
{
"code": null,
"e": 31753,
"s": 31678,
"text": "Refer to the below articles to get detailed information about arrays in R."
},
{
"code": null,
"e": 31763,
"s": 31753,
"text": "R – Array"
},
{
"code": null,
"e": 31786,
"s": 31763,
"text": "Multidimensional Array"
},
{
"code": null,
"e": 31803,
"s": 31786,
"text": "Array Operations"
},
{
"code": null,
"e": 31940,
"s": 31803,
"text": "Factors are the data objects which are used to categorize the data and store it as levels. They are useful for storing categorical data."
},
{
"code": null,
"e": 31949,
"s": 31940,
"text": "Example:"
},
{
"code": null,
"e": 31951,
"s": 31949,
"text": "R"
},
{
"code": "# Creating a vectorx<-c(\"female\", \"male\", \"other\", \"female\", \"other\") # Converting the vector x into# a factor named gendergender<-factor(x)print(gender)",
"e": 32105,
"s": 31951,
"text": null
},
{
"code": null,
"e": 32115,
"s": 32105,
"text": " Output: "
},
{
"code": null,
"e": 32180,
"s": 32115,
"text": "[1] female male other female other \nLevels: female male other"
},
{
"code": null,
"e": 32212,
"s": 32180,
"text": "Accessing elements of a Factor:"
},
{
"code": null,
"e": 32298,
"s": 32212,
"text": "Like we access elements of a vector, the same way we access the elements of a factor "
},
{
"code": null,
"e": 32307,
"s": 32298,
"text": "Example:"
},
{
"code": null,
"e": 32309,
"s": 32307,
"text": "R"
},
{
"code": "x<-c(\"female\", \"male\", \"other\", \"female\", \"other\")print(x[3])",
"e": 32371,
"s": 32309,
"text": null
},
{
"code": null,
"e": 32380,
"s": 32371,
"text": " Output:"
},
{
"code": null,
"e": 32392,
"s": 32380,
"text": "[1] \"other\""
},
{
"code": null,
"e": 32415,
"s": 32392,
"text": "Modifying of a Factor:"
},
{
"code": null,
"e": 32550,
"s": 32415,
"text": "After a factor is formed, its components can be modified but the new values which need to be assigned must be in the predefined level."
},
{
"code": null,
"e": 32559,
"s": 32550,
"text": "Example:"
},
{
"code": null,
"e": 32561,
"s": 32559,
"text": "R"
},
{
"code": "x<-c(\"female\", \"male\", \"other\", \"female\", \"other\")x[1]<-\"male\"print(x)",
"e": 32632,
"s": 32561,
"text": null
},
{
"code": null,
"e": 32640,
"s": 32632,
"text": "Output:"
},
{
"code": null,
"e": 32689,
"s": 32640,
"text": "[1] \"male\" \"male\" \"other\" \"female\" \"other\" "
},
{
"code": null,
"e": 32754,
"s": 32689,
"text": "Refer to the below articles to get detailed information Factors."
},
{
"code": null,
"e": 32766,
"s": 32754,
"text": "R – Factors"
},
{
"code": null,
"e": 32792,
"s": 32766,
"text": "Level Ordering of Factors"
},
{
"code": null,
"e": 32950,
"s": 32792,
"text": "Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its execution. In R"
},
{
"code": null,
"e": 32991,
"s": 32950,
"text": "The stop() function will generate errors"
},
{
"code": null,
"e": 33156,
"s": 32991,
"text": "The stopifnot() function will take a logical expression and if any of the expressions is FALSE then it will generate the error specifying which expression is FALSE."
},
{
"code": null,
"e": 33227,
"s": 33156,
"text": "The warning() will create the warning but will not stop the execution."
},
{
"code": null,
"e": 33402,
"s": 33227,
"text": "Error handling can be done using tryCatch(). The first argument of this function is the expression which is followed by the condition specifying how to handle the conditions."
},
{
"code": null,
"e": 33410,
"s": 33402,
"text": "Syntax:"
},
{
"code": null,
"e": 33605,
"s": 33410,
"text": "check = tryCatch({\n expression\n}, warning = function(w){\n code that handles the warnings\n}, error = function(e){\n code that handles the errors\n}, finally = function(f){\n clean-up code\n})"
},
{
"code": null,
"e": 33614,
"s": 33605,
"text": "Example:"
},
{
"code": null,
"e": 33616,
"s": 33614,
"text": "R"
},
{
"code": "# R program illustrating error handling # Evaluation of tryCatchcheck <- function(expression){ tryCatch(expression, warning = function(w){ message(\"warning:\\n\", w) }, error = function(e){ message(\"error:\\n\", e) }, finally = { message(\"Completed\") })} check({10/2})check({10/0})check({10/'noe'})",
"e": 34001,
"s": 33616,
"text": null
},
{
"code": null,
"e": 34011,
"s": 34001,
"text": " Output:"
},
{
"code": null,
"e": 34093,
"s": 34011,
"text": "Refer to the below articles to get detailed information about error handling in R"
},
{
"code": null,
"e": 34126,
"s": 34093,
"text": "Handling Errors in R Programming"
},
{
"code": null,
"e": 34145,
"s": 34126,
"text": "Condition Handling"
},
{
"code": null,
"e": 34172,
"s": 34145,
"text": "Debugging in R Programming"
},
{
"code": null,
"e": 34524,
"s": 34172,
"text": "In a real-world scenario enormous amount of data is produced on daily basis, so, interpreting it can be somewhat hectic. Here data visualization comes into play because it is always better to visualize that data through charts and graphs, to gain meaningful insights instead of screening huge Excel sheets. Let’s see some basic plots in R Programming."
},
{
"code": null,
"e": 34630,
"s": 34524,
"text": "R uses the function barplot() to create bar charts. Here, both vertical and Horizontal bars can be drawn."
},
{
"code": null,
"e": 34639,
"s": 34630,
"text": "Example:"
},
{
"code": null,
"e": 34641,
"s": 34639,
"text": "R"
},
{
"code": "# Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chartbarplot(A, xlab = \"X-axis\", ylab = \"Y-axis\", main =\"Bar-Chart\")",
"e": 34788,
"s": 34641,
"text": null
},
{
"code": null,
"e": 34796,
"s": 34788,
"text": "Output:"
},
{
"code": null,
"e": 34846,
"s": 34796,
"text": "Note: For more information, refer Bar Charts in R"
},
{
"code": null,
"e": 34889,
"s": 34846,
"text": "R creates histogram using hist() function."
},
{
"code": null,
"e": 34899,
"s": 34889,
"text": "Example: "
},
{
"code": null,
"e": 34901,
"s": 34899,
"text": "R"
},
{
"code": "# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = \"No.of Articles \", col = \"green\", border = \"black\")",
"e": 35079,
"s": 34901,
"text": null
},
{
"code": null,
"e": 35089,
"s": 35079,
"text": " Output:"
},
{
"code": null,
"e": 35150,
"s": 35091,
"text": "Note: For more information, refer Histograms in R language"
},
{
"code": null,
"e": 35211,
"s": 35150,
"text": "The simple scatterplot is created using the plot() function."
},
{
"code": null,
"e": 35220,
"s": 35211,
"text": "Example:"
},
{
"code": null,
"e": 35222,
"s": 35220,
"text": "R"
},
{
"code": "# Create the data for the chartA <- c(17, 32, 8, 53, 1)B <- c(12, 43, 17, 43, 10) # Plot the bar chartplot(x=A, y=B, xlab = \"X-axis\", ylab = \"Y-axis\", main =\"Scatter Plot\")",
"e": 35403,
"s": 35222,
"text": null
},
{
"code": null,
"e": 35411,
"s": 35403,
"text": "Output:"
},
{
"code": null,
"e": 35475,
"s": 35413,
"text": "Note: For more information, refer Scatter plots in R Language"
},
{
"code": null,
"e": 35534,
"s": 35475,
"text": "The plot() function in R is used to create the line graph."
},
{
"code": null,
"e": 35543,
"s": 35534,
"text": "Example:"
},
{
"code": null,
"e": 35545,
"s": 35543,
"text": "R"
},
{
"code": "# Create the data for the chart.v <- c(17, 25, 38, 13, 41) # Plot the bar chart.plot(v, type = \"l\", xlab = \"X-axis\", ylab = \"Y-axis\", main =\"Line-Chart\")",
"e": 35706,
"s": 35545,
"text": null
},
{
"code": null,
"e": 35716,
"s": 35706,
"text": " Output:"
},
{
"code": null,
"e": 35779,
"s": 35718,
"text": "Note: For more information, refer Line Graphs in R Language."
},
{
"code": null,
"e": 35872,
"s": 35779,
"text": "R uses the function pie() to create pie charts. It takes positive numbers as a vector input."
},
{
"code": null,
"e": 35881,
"s": 35872,
"text": "Example:"
},
{
"code": null,
"e": 35883,
"s": 35881,
"text": "R"
},
{
"code": "# Create data for the graph.geeks<- c(23, 56, 20, 63)labels <- c(\"Mumbai\", \"Pune\", \"Chennai\", \"Bangalore\") # Plot the chart.pie(geeks, labels)",
"e": 36026,
"s": 35883,
"text": null
},
{
"code": null,
"e": 36036,
"s": 36026,
"text": " Output:"
},
{
"code": null,
"e": 36097,
"s": 36038,
"text": "Note: For more information, refer Pie Charts in R Language"
},
{
"code": null,
"e": 36156,
"s": 36097,
"text": "Boxplots are created in R by using the boxplot() function."
},
{
"code": null,
"e": 36158,
"s": 36156,
"text": "R"
},
{
"code": "input <- mtcars[, c('mpg', 'cyl')] # Plot the chart.boxplot(mpg ~ cyl, data = mtcars, xlab = \"Number of Cylinders\", ylab = \"Miles Per Gallon\", main = \"Mileage Data\")",
"e": 36345,
"s": 36158,
"text": null
},
{
"code": null,
"e": 36355,
"s": 36345,
"text": " Output:"
},
{
"code": null,
"e": 36414,
"s": 36357,
"text": "Note: For more information, refer Boxplots in R Language"
},
{
"code": null,
"e": 36465,
"s": 36414,
"text": "For more articles refer Data Visualization using R"
},
{
"code": null,
"e": 36802,
"s": 36465,
"text": "Statistics simply means numerical data, and is field of math that generally deals with collection of data, tabulation, and interpretation of numerical data. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. Statistics deals with how data can be used to solve complex problems."
},
{
"code": null,
"e": 36882,
"s": 36802,
"text": "Mean: It is the sum of observation divided by the total number of observations."
},
{
"code": null,
"e": 36930,
"s": 36882,
"text": "Median: It is the middle value of the data set."
},
{
"code": null,
"e": 37070,
"s": 36930,
"text": "Mode: It is the value that has the highest frequency in the given data set. R does not have a standard in-built function to calculate mode."
},
{
"code": null,
"e": 37079,
"s": 37070,
"text": "Example:"
},
{
"code": null,
"e": 37081,
"s": 37079,
"text": "R"
},
{
"code": "# Create the dataA <- c(17, 12, 8, 53, 1, 12, 43, 17, 43, 10) print(mean(A))print(median(A)) mode <- function(x) { a <- unique(x) a[which.max(tabulate(match(x, a)))]} # Calculate the mode using# the user function.print(mode(A)",
"e": 37318,
"s": 37081,
"text": null
},
{
"code": null,
"e": 37326,
"s": 37318,
"text": "Output:"
},
{
"code": null,
"e": 37351,
"s": 37326,
"text": "[1] 21.6\n[1] 14.5\n[1] 17"
},
{
"code": null,
"e": 37424,
"s": 37351,
"text": "Note: For more information, refer Mean, Median and Mode in R Programming"
},
{
"code": null,
"e": 37659,
"s": 37424,
"text": "Normal Distribution tells about how the data values are distributed. For example, the height of the population, shoe size, IQ level, rolling a dice, and many more. In R, there are 4 built-in functions to generate normal distribution: "
},
{
"code": null,
"e": 37736,
"s": 37659,
"text": "dnorm() function in R programming measures density function of distribution."
},
{
"code": null,
"e": 37755,
"s": 37736,
"text": "dnorm(x, mean, sd)"
},
{
"code": null,
"e": 37904,
"s": 37755,
"text": "pnorm() function is the cumulative distribution function which measures the probability that a random number X takes a value less than or equal to x"
},
{
"code": null,
"e": 37923,
"s": 37904,
"text": "pnorm(x, mean, sd)"
},
{
"code": null,
"e": 38068,
"s": 37923,
"text": "qnorm() function is the inverse of pnorm() function. It takes the probability value and gives output which corresponds to the probability value."
},
{
"code": null,
"e": 38087,
"s": 38068,
"text": "qnorm(p, mean, sd)"
},
{
"code": null,
"e": 38200,
"s": 38087,
"text": "rnorm() function in R programming is used to generate a vector of random numbers which are normally distributed."
},
{
"code": null,
"e": 38219,
"s": 38200,
"text": "rnorm(n, mean, sd)"
},
{
"code": null,
"e": 38228,
"s": 38219,
"text": "Example:"
},
{
"code": null,
"e": 38230,
"s": 38228,
"text": "R"
},
{
"code": "# creating a sequence of values# between -10 to 10 with a# difference of 0.1x <- seq(-10, 10, by=0.1) y = dnorm(x, mean(x), sd(x))plot(x, y, main='dnorm') y <- pnorm(x, mean(x), sd(x))plot(x, y, main='pnorm') y <- qnorm(x, mean(x), sd(x))plot(x, y, main='qnorm') x <- rnorm(x, mean(x), sd(x))hist(x, breaks=50, main='rnorm')",
"e": 38556,
"s": 38230,
"text": null
},
{
"code": null,
"e": 38566,
"s": 38556,
"text": " Output:"
},
{
"code": null,
"e": 38626,
"s": 38568,
"text": "Note: For more information refer Normal Distribution in R"
},
{
"code": null,
"e": 39054,
"s": 38626,
"text": "The binomial distribution is a discrete distribution and has only two outcomes i.e. success or failure. For example, determining whether a particular lottery ticket has won or not, whether a drug is able to cure a person or not, it can be used to determine the number of heads or tails in a finite number of tosses, for analyzing the outcome of a die, etc. We have four functions for handling binomial distribution in R namely:"
},
{
"code": null,
"e": 39063,
"s": 39054,
"text": "dbinom()"
},
{
"code": null,
"e": 39079,
"s": 39063,
"text": "dbinom(k, n, p)"
},
{
"code": null,
"e": 39088,
"s": 39079,
"text": "pbinom()"
},
{
"code": null,
"e": 39104,
"s": 39088,
"text": "pbinom(k, n, p)"
},
{
"code": null,
"e": 39229,
"s": 39104,
"text": "where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out."
},
{
"code": null,
"e": 39238,
"s": 39229,
"text": "qbinom()"
},
{
"code": null,
"e": 39254,
"s": 39238,
"text": "qbinom(P, n, p)"
},
{
"code": null,
"e": 39351,
"s": 39254,
"text": "Where P is the probability, n is the total number of trials and p is the probability of success."
},
{
"code": null,
"e": 39360,
"s": 39351,
"text": "rbinom()"
},
{
"code": null,
"e": 39376,
"s": 39360,
"text": "rbinom(n, N, p)"
},
{
"code": null,
"e": 39479,
"s": 39376,
"text": " Where n is numbers of observations, N is the total number of trials, p is the probability of success."
},
{
"code": null,
"e": 39488,
"s": 39479,
"text": "Example:"
},
{
"code": null,
"e": 39490,
"s": 39488,
"text": "R"
},
{
"code": "probabilities <- dbinom(x = c(0:10), size = 10, prob = 1 / 6)plot(0:10, probabilities, type = \"l\", main='dbinom') probabilities <- pbinom(0:10, size = 10, prob = 1 / 6)plot(0:10, , type = \"l\", main='pbinom') x <- seq(0, 1, by = 0.1)y <- qbinom(x, size = 13, prob = 1 / 6)plot(x, y, type = 'l') probabilities <- rbinom(8, size = 13, prob = 1 / 6)hist(probabilities)",
"e": 39855,
"s": 39490,
"text": null
},
{
"code": null,
"e": 39864,
"s": 39855,
"text": " Output:"
},
{
"code": null,
"e": 39939,
"s": 39866,
"text": "Note: For more information, refer Binomial Distribution in R Programming"
},
{
"code": null,
"e": 40062,
"s": 39939,
"text": "Time Series in R is used to see how an object behaves over a period of time. In R, it can be easily done by ts() function."
},
{
"code": null,
"e": 40258,
"s": 40062,
"text": "Example: Let’s take the example of COVID-19 pandemic situation. Taking total number of positive cases of COVID-19 cases weekly from 22 January, 2020 to 15 April, 2020 of the world in data vector."
},
{
"code": null,
"e": 40260,
"s": 40258,
"text": "R"
},
{
"code": "# Weekly data of COVID-19 positive cases from# 22 January, 2020 to 15 April, 2020x <- c(580, 7813, 28266, 59287, 75700, 87820, 95314, 126214, 218843, 471497, 936851, 1508725, 2072113) # library required for decimal_date() functionlibrary(lubridate) # creating time series object# from date 22 January, 2020mts <- ts(x, start = decimal_date(ymd(\"2020-01-22\")), frequency = 365.25 / 7) # plotting the graphplot(mts, xlab =\"Weekly Data\", ylab =\"Total Positive Cases\", main =\"COVID-19 Pandemic\", col.main =\"darkgreen\")",
"e": 40829,
"s": 40260,
"text": null
},
{
"code": null,
"e": 40837,
"s": 40829,
"text": "Output:"
},
{
"code": null,
"e": 40897,
"s": 40837,
"text": "Note: For more information, refer Time Series Analysis in R"
},
{
"code": null,
"e": 40909,
"s": 40897,
"text": "anikaseth98"
},
{
"code": null,
"e": 40923,
"s": 40909,
"text": "sumitgumber28"
},
{
"code": null,
"e": 40931,
"s": 40923,
"text": "clintra"
},
{
"code": null,
"e": 40948,
"s": 40931,
"text": "arorakashish0911"
},
{
"code": null,
"e": 40959,
"s": 40948,
"text": "R Language"
},
{
"code": null,
"e": 41057,
"s": 40959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41109,
"s": 41057,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 41167,
"s": 41109,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 41202,
"s": 41167,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 41240,
"s": 41202,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 41289,
"s": 41240,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 41306,
"s": 41289,
"text": "R - if statement"
},
{
"code": null,
"e": 41343,
"s": 41306,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 41386,
"s": 41343,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 41423,
"s": 41386,
"text": "How to import an Excel File into R ?"
}
] |
PyQt5 QDateEdit – Getting Date Time
|
07 Jul, 2020
In this article we will see how we can get the date time of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method. Unlike normal date, date time has date as well as the time although time is not shown on the date edit. Date time can set tot he date edit with the help of setDate method.
In order to do this we use dateTime method with the QDateEdit object
Syntax : date.dateTime()
Argument : It takes no argument
Return : It returns QDateTime object
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date time d = QDateTime(2020, 10, 10, 10, 20) # setting date time date.setDateTime(d) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry label.setGeometry(100, 150, 200, 60) # making label multiline label.setWordWrap(True) # getting date time value = date.dateTime() # setting text to the label label.setText("Date Time : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 514,
"s": 28,
"text": "In this article we will see how we can get the date time of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method. Unlike normal date, date time has date as well as the time although time is not shown on the date edit. Date time can set tot he date edit with the help of setDate method."
},
{
"code": null,
"e": 583,
"s": 514,
"text": "In order to do this we use dateTime method with the QDateEdit object"
},
{
"code": null,
"e": 608,
"s": 583,
"text": "Syntax : date.dateTime()"
},
{
"code": null,
"e": 640,
"s": 608,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 677,
"s": 640,
"text": "Return : It returns QDateTime object"
},
{
"code": null,
"e": 705,
"s": 677,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date time d = QDateTime(2020, 10, 10, 10, 20) # setting date time date.setDateTime(d) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry label.setGeometry(100, 150, 200, 60) # making label multiline label.setWordWrap(True) # getting date time value = date.dateTime() # setting text to the label label.setText(\"Date Time : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2009,
"s": 705,
"text": null
},
{
"code": null,
"e": 2018,
"s": 2009,
"text": "Output :"
},
{
"code": null,
"e": 2040,
"s": 2018,
"text": "Python PyQt-QDateEdit"
},
{
"code": null,
"e": 2051,
"s": 2040,
"text": "Python-gui"
},
{
"code": null,
"e": 2063,
"s": 2051,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Python"
}
] |
Autokey Cipher | Symmetric Ciphers
|
10 May, 2020
Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de Vigenère in 1586. In general, more secure than the Vigenere cipher.
Example-1:
Plaintext = "HELLO"
Autokey = N
Ciphertext = "ULPWZ"
Example-2:
Plaintext = "GEEKSFORGEEKS"
Autokey = P
Ciphertext = "VKIOCXTFXKIOC"
In this cipher, the key is a stream of subkeys which is used to encrypt the corresponding character in the plaintext.
As shown, the autokey is added at the first of the subkeys.
Let's explain Example 1:
Given plain text is : H E L L O
Key is : N H E L L
Let's encrypt:
Plain Text(P) : H E L L O
Corresponding Number: 7 4 11 11 14
Key(K) : N H E L L
Corresponding Number: 13 7 4 11 11
---------------------
Applying the formula: 20 11 15 22 25
Corresponding
Letters are : U L P W Z
Hence Ciphertext is: ULPWZ
Let's decrypt:
Cipher Text(C) : U L P W Z
Key(K) : N H E L L
---------------------
Applying the formula: H E L L O
Hence Plaintext is: HELLO
Here’s the java code for Autokey Cipher.
Java
// A JAVA program to illustrate// Autokey Cipher Technique // Importing required libraryimport java.lang.*;import java.util.*; public class AutoKey { private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void main(String[] args) { String msg = "HELLO"; String key = "N"; // This if statement is all about java regular expression // [] for range // // Extra \ is used to escape one \ // \\d acts as delimiter // ? once or not at all // . Any character (may or may not match line terminators) if (key.matches("[-+]?\\d*\\.?\\d+")) key = "" + alphabet.charAt(Integer.parseInt(key)); String enc = autoEncryption(msg, key); System.out.println("Plaintext : " + msg); System.out.println("Encrypted : " + enc); System.out.println("Decrypted : " + autoDecryption(enc, key)); } public static String autoEncryption(String msg, String key) { int len = msg.length(); // generating the keystream String newKey = key.concat(msg); newKey = newKey.substring(0, newKey.length() - key.length()); String encryptMsg = ""; // applying encryption algorithm for (int x = 0; x < len; x++) { int first = alphabet.indexOf(msg.charAt(x)); int second = alphabet.indexOf(newKey.charAt(x)); int total = (first + second) % 26; encryptMsg += alphabet.charAt(total); } return encryptMsg; } public static String autoDecryption(String msg, String key) { String currentKey = key; String decryptMsg = ""; // applying decryption algorithm for (int x = 0; x < msg.length(); x++) { int get1 = alphabet.indexOf(msg.charAt(x)); int get2 = alphabet.indexOf(currentKey.charAt(x)); int total = (get1 - get2) % 26; total = (total < 0) ? total + 26 : total; decryptMsg += alphabet.charAt(total); currentKey += alphabet.charAt(total); } return decryptMsg; }}
Output:
Plaintext : HELLO
Encrypted : ULPWZ
Decrypted : HELLO
cryptography
Technical Scripter
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de Vigenère in 1586. In general, more secure than the Vigenere cipher."
},
{
"code": null,
"e": 315,
"s": 304,
"text": "Example-1:"
},
{
"code": null,
"e": 369,
"s": 315,
"text": "Plaintext = \"HELLO\"\nAutokey = N\nCiphertext = \"ULPWZ\" "
},
{
"code": null,
"e": 380,
"s": 369,
"text": "Example-2:"
},
{
"code": null,
"e": 450,
"s": 380,
"text": "Plaintext = \"GEEKSFORGEEKS\"\nAutokey = P\nCiphertext = \"VKIOCXTFXKIOC\" "
},
{
"code": null,
"e": 568,
"s": 450,
"text": "In this cipher, the key is a stream of subkeys which is used to encrypt the corresponding character in the plaintext."
},
{
"code": null,
"e": 628,
"s": 568,
"text": "As shown, the autokey is added at the first of the subkeys."
},
{
"code": null,
"e": 1285,
"s": 628,
"text": "Let's explain Example 1:\n\nGiven plain text is : H E L L O\nKey is : N H E L L\n\nLet's encrypt:\n\nPlain Text(P) : H E L L O\nCorresponding Number: 7 4 11 11 14 \nKey(K) : N H E L L\nCorresponding Number: 13 7 4 11 11 \n ---------------------\nApplying the formula: 20 11 15 22 25 \n\nCorresponding \nLetters are : U L P W Z\n\nHence Ciphertext is: ULPWZ\n\nLet's decrypt:\n\nCipher Text(C) : U L P W Z\nKey(K) : N H E L L\n ---------------------\nApplying the formula: H E L L O\n\nHence Plaintext is: HELLO "
},
{
"code": null,
"e": 1326,
"s": 1285,
"text": "Here’s the java code for Autokey Cipher."
},
{
"code": null,
"e": 1331,
"s": 1326,
"text": "Java"
},
{
"code": "// A JAVA program to illustrate// Autokey Cipher Technique // Importing required libraryimport java.lang.*;import java.util.*; public class AutoKey { private static final String alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; public static void main(String[] args) { String msg = \"HELLO\"; String key = \"N\"; // This if statement is all about java regular expression // [] for range // // Extra \\ is used to escape one \\ // \\\\d acts as delimiter // ? once or not at all // . Any character (may or may not match line terminators) if (key.matches(\"[-+]?\\\\d*\\\\.?\\\\d+\")) key = \"\" + alphabet.charAt(Integer.parseInt(key)); String enc = autoEncryption(msg, key); System.out.println(\"Plaintext : \" + msg); System.out.println(\"Encrypted : \" + enc); System.out.println(\"Decrypted : \" + autoDecryption(enc, key)); } public static String autoEncryption(String msg, String key) { int len = msg.length(); // generating the keystream String newKey = key.concat(msg); newKey = newKey.substring(0, newKey.length() - key.length()); String encryptMsg = \"\"; // applying encryption algorithm for (int x = 0; x < len; x++) { int first = alphabet.indexOf(msg.charAt(x)); int second = alphabet.indexOf(newKey.charAt(x)); int total = (first + second) % 26; encryptMsg += alphabet.charAt(total); } return encryptMsg; } public static String autoDecryption(String msg, String key) { String currentKey = key; String decryptMsg = \"\"; // applying decryption algorithm for (int x = 0; x < msg.length(); x++) { int get1 = alphabet.indexOf(msg.charAt(x)); int get2 = alphabet.indexOf(currentKey.charAt(x)); int total = (get1 - get2) % 26; total = (total < 0) ? total + 26 : total; decryptMsg += alphabet.charAt(total); currentKey += alphabet.charAt(total); } return decryptMsg; }}",
"e": 3437,
"s": 1331,
"text": null
},
{
"code": null,
"e": 3502,
"s": 3437,
"text": "Output:\n\nPlaintext : HELLO\nEncrypted : ULPWZ\nDecrypted : HELLO\n\n"
},
{
"code": null,
"e": 3515,
"s": 3502,
"text": "cryptography"
},
{
"code": null,
"e": 3534,
"s": 3515,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3547,
"s": 3534,
"text": "cryptography"
}
] |
How to select first element in the drop-down list using jQuery ?
|
03 Aug, 2021
Given a drop-down list containing options elements and the task is to get the first element of the select element using JQuery.Approach 1:
Select first element of <select> element using JQuery selector.
Use .prop() property to get the access to properties of that particular element.
Change the selectedIndex property to 0 to get the access to the first element. (Index starts with 0)
Example: This example illustrate the approach discussed above.
html
<!DOCTYPE HTML> <html> <head> <title> How to select first element in the drop-down list using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <select id = "select"> <option value="GFG1">GFG1</option> <option value="GFG2">GFG2</option> <option value="GFG3">GFG3</option> <option value="GFG4">GFG4</option> <option value="GFG5">GFG5</option> </select> <br><br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the " + "first option's value using JQuery"; function gfg_Run() { el_down.innerHTML = $("#select").prop("selectedIndex", 0).val(); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Select the <select> element using JQuery selector.
This selector is more specific and selecting the first element using option:nth-child(1).
This will get access to the first element (Index starts with 1).
Example: This example illustrate the approach discussed above.
html
<!DOCTYPE HTML> <html> <head> <title> How to select first element in the drop-down list using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <select id = "select"> <option value="GFG1">GFG1</option> <option value="GFG2">GFG2</option> <option value="GFG3">GFG3</option> <option value="GFG4">GFG4</option> <option value="GFG5">GFG5</option> </select> <br><br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " first option's value using JQuery"; function gfg_Run() { el_down.innerHTML = $('#select option:nth-child(1)').val(); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
simmytarika5
JavaScript-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | prop() with Examples
jQuery | bind() with Examples
jQuery | change() with Examples
How to reverse array of DOM elements using jQuery ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
File uploading in React.js
Node.js fs.readFileSync() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Given a drop-down list containing options elements and the task is to get the first element of the select element using JQuery.Approach 1: "
},
{
"code": null,
"e": 233,
"s": 169,
"text": "Select first element of <select> element using JQuery selector."
},
{
"code": null,
"e": 314,
"s": 233,
"text": "Use .prop() property to get the access to properties of that particular element."
},
{
"code": null,
"e": 415,
"s": 314,
"text": "Change the selectedIndex property to 0 to get the access to the first element. (Index starts with 0)"
},
{
"code": null,
"e": 480,
"s": 415,
"text": "Example: This example illustrate the approach discussed above. "
},
{
"code": null,
"e": 485,
"s": 480,
"text": "html"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to select first element in the drop-down list using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <select id = \"select\"> <option value=\"GFG1\">GFG1</option> <option value=\"GFG2\">GFG2</option> <option value=\"GFG3\">GFG3</option> <option value=\"GFG4\">GFG4</option> <option value=\"GFG5\">GFG5</option> </select> <br><br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the \" + \"first option's value using JQuery\"; function gfg_Run() { el_down.innerHTML = $(\"#select\").prop(\"selectedIndex\", 0).val(); } </script> </body> </html>",
"e": 1825,
"s": 485,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1825,
"text": "Output: "
},
{
"code": null,
"e": 1868,
"s": 1835,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 1900,
"s": 1868,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 1914,
"s": 1900,
"text": "Approach 2: "
},
{
"code": null,
"e": 1965,
"s": 1914,
"text": "Select the <select> element using JQuery selector."
},
{
"code": null,
"e": 2055,
"s": 1965,
"text": "This selector is more specific and selecting the first element using option:nth-child(1)."
},
{
"code": null,
"e": 2120,
"s": 2055,
"text": "This will get access to the first element (Index starts with 1)."
},
{
"code": null,
"e": 2185,
"s": 2120,
"text": "Example: This example illustrate the approach discussed above. "
},
{
"code": null,
"e": 2190,
"s": 2185,
"text": "html"
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to select first element in the drop-down list using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <select id = \"select\"> <option value=\"GFG1\">GFG1</option> <option value=\"GFG2\">GFG2</option> <option value=\"GFG3\">GFG3</option> <option value=\"GFG4\">GFG4</option> <option value=\"GFG5\">GFG5</option> </select> <br><br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the\" + \" first option's value using JQuery\"; function gfg_Run() { el_down.innerHTML = $('#select option:nth-child(1)').val(); } </script> </body> </html>",
"e": 3515,
"s": 2190,
"text": null
},
{
"code": null,
"e": 3525,
"s": 3515,
"text": "Output: "
},
{
"code": null,
"e": 3558,
"s": 3525,
"text": "Before clicking on the button: "
},
{
"code": null,
"e": 3590,
"s": 3558,
"text": "After clicking on the button: "
},
{
"code": null,
"e": 3860,
"s": 3592,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 3873,
"s": 3860,
"text": "simmytarika5"
},
{
"code": null,
"e": 3889,
"s": 3873,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3896,
"s": 3889,
"text": "JQuery"
},
{
"code": null,
"e": 3913,
"s": 3896,
"text": "Web Technologies"
},
{
"code": null,
"e": 3940,
"s": 3913,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4038,
"s": 3940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4068,
"s": 4038,
"text": "jQuery | prop() with Examples"
},
{
"code": null,
"e": 4098,
"s": 4068,
"text": "jQuery | bind() with Examples"
},
{
"code": null,
"e": 4130,
"s": 4098,
"text": "jQuery | change() with Examples"
},
{
"code": null,
"e": 4182,
"s": 4130,
"text": "How to reverse array of DOM elements using jQuery ?"
},
{
"code": null,
"e": 4238,
"s": 4182,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 4271,
"s": 4238,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4321,
"s": 4271,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4383,
"s": 4321,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4410,
"s": 4383,
"text": "File uploading in React.js"
}
] |
Static and Dynamic Scoping
|
11 Nov, 2021
The scope of a variable x in the region of the program in which the use of x refers to its declaration. One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about naming of variables (e.g., I for an array index), in any program of moderate size the same variable name will be used in multiple different scopes.Scoping is generally divided into two classes: 1. Static Scoping 2. Dynamic ScopingStatic Scoping: Static scoping is also called lexical scoping. In this scoping, a variable always refers to its top-level environment. This is a property of the program text and is unrelated to the run-time call stack. Static scoping also makes it much easier to make a modular code as a programmer can figure out the scope just by looking at the code. In contrast, dynamic scope requires the programmer to anticipate all possible dynamic contexts.In most programming languages including C, C++, and Java, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, the output for the below program is 10, i.e., the value returned by f() is not dependent on who is calling it (Like g() calls it and has a x with value 20). f() always returns the value of global variable x.
C
// A C program to demonstrate static scoping.#include<stdio.h>int x = 10; // Called by g()int f(){ return x;} // g() has its own variable// named as x and calls f()int g(){ int x = 20; return f();} int main(){ printf("%d", g()); printf("\n"); return 0;}
Output :
10
To sum up, in static scoping the compiler first searches in the current block, then in global variables, then in successively smaller scopes.Dynamic Scoping: With dynamic scope, a global identifier refers to the identifier associated with the most recent environment and is uncommon in modern languages. In technical terms, this means that each identifier has a global stack of bindings and the occurrence of an identifier is searched in the most recent binding. In simpler terms, in dynamic scoping, the compiler first searches the current block and then successively all the calling functions.
C
// Since dynamic scoping is very uncommon in// the familiar languages, we consider the// following pseudo code as our example. It// prints 20 in a language that uses dynamic// scoping. int x = 10; // Called by g()int f(){ return x;} // g() has its own variable// named as x and calls f()int g(){ int x = 20; return f();} main(){ printf(g());}
Output in a language that uses Dynamic Scoping :
20
Static Vs Dynamic Scoping In most programming languages static scoping is dominant. This is simply because in static scoping it’s easy to reason about and understand just by looking at code. We can see what variables are in the scope just by looking at the text in the editor.Dynamic scoping does not care about how the code is written, but instead how it executes. Each time a new function is executed, a new scope is pushed onto the stack.Perl supports both dynamic and static scoping. Perl’s keyword “my” defines a statically scoped local variable, while the keyword “local” defines a dynamically scoped local variable.
Perl
# A perl code to demonstrate dynamic scoping$x = 10;sub f{ return $x;}sub g{ # Since local is used, x uses # dynamic scoping. local $x = 20; return f();}print g()."\n";
Output :
20
This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ritikchauhan2121
marcosarcticseal
Articles
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 1503,
"s": 54,
"text": "The scope of a variable x in the region of the program in which the use of x refers to its declaration. One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about naming of variables (e.g., I for an array index), in any program of moderate size the same variable name will be used in multiple different scopes.Scoping is generally divided into two classes: 1. Static Scoping 2. Dynamic ScopingStatic Scoping: Static scoping is also called lexical scoping. In this scoping, a variable always refers to its top-level environment. This is a property of the program text and is unrelated to the run-time call stack. Static scoping also makes it much easier to make a modular code as a programmer can figure out the scope just by looking at the code. In contrast, dynamic scope requires the programmer to anticipate all possible dynamic contexts.In most programming languages including C, C++, and Java, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, the output for the below program is 10, i.e., the value returned by f() is not dependent on who is calling it (Like g() calls it and has a x with value 20). f() always returns the value of global variable x. "
},
{
"code": null,
"e": 1505,
"s": 1503,
"text": "C"
},
{
"code": "// A C program to demonstrate static scoping.#include<stdio.h>int x = 10; // Called by g()int f(){ return x;} // g() has its own variable// named as x and calls f()int g(){ int x = 20; return f();} int main(){ printf(\"%d\", g()); printf(\"\\n\"); return 0;}",
"e": 1768,
"s": 1505,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1768,
"text": "Output : "
},
{
"code": null,
"e": 1781,
"s": 1778,
"text": "10"
},
{
"code": null,
"e": 2378,
"s": 1781,
"text": "To sum up, in static scoping the compiler first searches in the current block, then in global variables, then in successively smaller scopes.Dynamic Scoping: With dynamic scope, a global identifier refers to the identifier associated with the most recent environment and is uncommon in modern languages. In technical terms, this means that each identifier has a global stack of bindings and the occurrence of an identifier is searched in the most recent binding. In simpler terms, in dynamic scoping, the compiler first searches the current block and then successively all the calling functions. "
},
{
"code": null,
"e": 2380,
"s": 2378,
"text": "C"
},
{
"code": "// Since dynamic scoping is very uncommon in// the familiar languages, we consider the// following pseudo code as our example. It// prints 20 in a language that uses dynamic// scoping. int x = 10; // Called by g()int f(){ return x;} // g() has its own variable// named as x and calls f()int g(){ int x = 20; return f();} main(){ printf(g());}",
"e": 2732,
"s": 2380,
"text": null
},
{
"code": null,
"e": 2784,
"s": 2732,
"text": " Output in a language that uses Dynamic Scoping : "
},
{
"code": null,
"e": 2787,
"s": 2784,
"text": "20"
},
{
"code": null,
"e": 3412,
"s": 2787,
"text": "Static Vs Dynamic Scoping In most programming languages static scoping is dominant. This is simply because in static scoping it’s easy to reason about and understand just by looking at code. We can see what variables are in the scope just by looking at the text in the editor.Dynamic scoping does not care about how the code is written, but instead how it executes. Each time a new function is executed, a new scope is pushed onto the stack.Perl supports both dynamic and static scoping. Perl’s keyword “my” defines a statically scoped local variable, while the keyword “local” defines a dynamically scoped local variable. "
},
{
"code": null,
"e": 3417,
"s": 3412,
"text": "Perl"
},
{
"code": "# A perl code to demonstrate dynamic scoping$x = 10;sub f{ return $x;}sub g{ # Since local is used, x uses # dynamic scoping. local $x = 20; return f();}print g().\"\\n\";",
"e": 3597,
"s": 3417,
"text": null
},
{
"code": null,
"e": 3607,
"s": 3597,
"text": "Output : "
},
{
"code": null,
"e": 3610,
"s": 3607,
"text": "20"
},
{
"code": null,
"e": 4035,
"s": 3610,
"text": "This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4052,
"s": 4035,
"text": "ritikchauhan2121"
},
{
"code": null,
"e": 4069,
"s": 4052,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 4078,
"s": 4069,
"text": "Articles"
},
{
"code": null,
"e": 4094,
"s": 4078,
"text": "Compiler Design"
}
] |
OpenCV - Writing an Image
|
The write() method of the Imgcodecs class is used to write an image using OpenCV. To write an image, repeat the first three steps from the previous example.
To write an image, you need to invoke the imwrite() method of the Imgcodecs class.
Following is the syntax of this method.
imwrite(filename, mat)
This method accepts the following parameters −
filename − A String variable representing the path where to save the file.
filename − A String variable representing the path where to save the file.
mat − A Mat object representing the image to be written.
mat − A Mat object representing the image to be written.
Following program is an example to write an image using Java program using OpenCV library.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class WritingImages {
public static void main(String args[]) {
//Loading the OpenCV core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//Instantiating the imagecodecs class
Imgcodecs imageCodecs = new Imgcodecs();
//Reading the Image from the file and storing it in to a Matrix object
String file ="C:/EXAMPLES/OpenCV/sample.jpg";
Mat matrix = imageCodecs.imread(file);
System.out.println("Image Loaded ..........");
String file2 = "C:/EXAMPLES/OpenCV/sample_resaved.jpg";
//Writing the image
imageCodecs.imwrite(file2, matrix);
System.out.println("Image Saved ............");
}
}
On executing the above program, you will get the following output −
Image Loaded ..........
Image Saved ...........
If you open the specified path, you can observe the saved image as shown below −
|
[
{
"code": null,
"e": 3295,
"s": 3138,
"text": "The write() method of the Imgcodecs class is used to write an image using OpenCV. To write an image, repeat the first three steps from the previous example."
},
{
"code": null,
"e": 3378,
"s": 3295,
"text": "To write an image, you need to invoke the imwrite() method of the Imgcodecs class."
},
{
"code": null,
"e": 3418,
"s": 3378,
"text": "Following is the syntax of this method."
},
{
"code": null,
"e": 3442,
"s": 3418,
"text": "imwrite(filename, mat)\n"
},
{
"code": null,
"e": 3489,
"s": 3442,
"text": "This method accepts the following parameters −"
},
{
"code": null,
"e": 3564,
"s": 3489,
"text": "filename − A String variable representing the path where to save the file."
},
{
"code": null,
"e": 3639,
"s": 3564,
"text": "filename − A String variable representing the path where to save the file."
},
{
"code": null,
"e": 3696,
"s": 3639,
"text": "mat − A Mat object representing the image to be written."
},
{
"code": null,
"e": 3753,
"s": 3696,
"text": "mat − A Mat object representing the image to be written."
},
{
"code": null,
"e": 3844,
"s": 3753,
"text": "Following program is an example to write an image using Java program using OpenCV library."
},
{
"code": null,
"e": 4646,
"s": 3844,
"text": "import org.opencv.core.Core; \nimport org.opencv.core.Mat; \nimport org.opencv.imgcodecs.Imgcodecs;\n \npublic class WritingImages { \n public static void main(String args[]) { \n //Loading the OpenCV core library \n System.loadLibrary(Core.NATIVE_LIBRARY_NAME); \n \n //Instantiating the imagecodecs class \n Imgcodecs imageCodecs = new Imgcodecs(); \n\n //Reading the Image from the file and storing it in to a Matrix object \n String file =\"C:/EXAMPLES/OpenCV/sample.jpg\"; \n Mat matrix = imageCodecs.imread(file); \n\n System.out.println(\"Image Loaded ..........\");\n String file2 = \"C:/EXAMPLES/OpenCV/sample_resaved.jpg\"; \n\n //Writing the image \n imageCodecs.imwrite(file2, matrix); \n System.out.println(\"Image Saved ............\"); \n } \n}"
},
{
"code": null,
"e": 4714,
"s": 4646,
"text": "On executing the above program, you will get the following output −"
},
{
"code": null,
"e": 4764,
"s": 4714,
"text": "Image Loaded .......... \nImage Saved ...........\n"
}
] |
JavaScript | Statements
|
05 Jul, 2022
The programming instructions written in a program in a programming language are known as statements.
Order of execution of Statements is the same as they are written.
Semicolons:Semicolons separate JavaScript statements.Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id="geek"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( "geek").innerHTML = "The value of c is " + c + "."; </script> </body> </html>Output:Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;Code Blocks:JavaScript statements can be grouped together inside curly brackets. Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together.Example:JavaScript function<!DOCTYPE html><html> <body> <p>Welcome</p> <button type="button" onclick="myFunction()"> Click Me! </button> <p id="geek1"></p> <p id="geek2"></p> <script> function myFunction() { document.getElementById( "geek1").innerHTML = "Hello"; document.getElementById( "geek2").innerHTML = "How are you?"; } </script> </body> </html>Output:Before Click:After Click:White Space:Javascript ignores multiple white spaces.Javascript would treat following 2 statements as same:Example:var a="Hello Geek";
var a = "Hello Geek";
Line Length and Line Breaks:Javascript code preferred line length by most programmers is upto 80 characters.The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.Example:document.getElementById("geek1").innerHTML =
"Hello Geek!";
Keywords:Keywords are reserved words and cannot be used as variable name.A Javascript keyword tells about what kind of operation it will perform.Some commonly used keywords are:break: This is used to terminate a loop or switch.continue: This is used to skip a particular iteration in a loop and move to next iteration.do.... while: In this the statements written within do block are executed till the condition in while is true.for: It helps in executing a block of statements till the condition is true.function: This keyword is used to declare a function.return: This keyword is used to exit a function.switch: This helps in executing a block of codes depending on different cases.var: This keyword is used to declare a variable with a global scope.let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized.const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration.
Semicolons:Semicolons separate JavaScript statements.Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id="geek"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( "geek").innerHTML = "The value of c is " + c + "."; </script> </body> </html>Output:Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;
Semicolons separate JavaScript statements.
Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id="geek"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( "geek").innerHTML = "The value of c is " + c + "."; </script> </body> </html>Output:
Example:
<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id="geek"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( "geek").innerHTML = "The value of c is " + c + "."; </script> </body> </html>
Output:
Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;
a=2;b=3;z=a+b;
Code Blocks:JavaScript statements can be grouped together inside curly brackets. Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together.Example:JavaScript function<!DOCTYPE html><html> <body> <p>Welcome</p> <button type="button" onclick="myFunction()"> Click Me! </button> <p id="geek1"></p> <p id="geek2"></p> <script> function myFunction() { document.getElementById( "geek1").innerHTML = "Hello"; document.getElementById( "geek2").innerHTML = "How are you?"; } </script> </body> </html>Output:Before Click:After Click:
Example:JavaScript function
<!DOCTYPE html><html> <body> <p>Welcome</p> <button type="button" onclick="myFunction()"> Click Me! </button> <p id="geek1"></p> <p id="geek2"></p> <script> function myFunction() { document.getElementById( "geek1").innerHTML = "Hello"; document.getElementById( "geek2").innerHTML = "How are you?"; } </script> </body> </html>
Output:Before Click:After Click:
White Space:Javascript ignores multiple white spaces.Javascript would treat following 2 statements as same:Example:var a="Hello Geek";
var a = "Hello Geek";
Javascript ignores multiple white spaces.
Javascript would treat following 2 statements as same:Example:
var a="Hello Geek";
var a = "Hello Geek";
Line Length and Line Breaks:Javascript code preferred line length by most programmers is upto 80 characters.The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.Example:document.getElementById("geek1").innerHTML =
"Hello Geek!";
document.getElementById("geek1").innerHTML =
"Hello Geek!";
Keywords:Keywords are reserved words and cannot be used as variable name.A Javascript keyword tells about what kind of operation it will perform.Some commonly used keywords are:break: This is used to terminate a loop or switch.continue: This is used to skip a particular iteration in a loop and move to next iteration.do.... while: In this the statements written within do block are executed till the condition in while is true.for: It helps in executing a block of statements till the condition is true.function: This keyword is used to declare a function.return: This keyword is used to exit a function.switch: This helps in executing a block of codes depending on different cases.var: This keyword is used to declare a variable with a global scope.let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized.const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration.
Some commonly used keywords are:
break: This is used to terminate a loop or switch.
continue: This is used to skip a particular iteration in a loop and move to next iteration.
do.... while: In this the statements written within do block are executed till the condition in while is true.
for: It helps in executing a block of statements till the condition is true.
function: This keyword is used to declare a function.
return: This keyword is used to exit a function.
switch: This helps in executing a block of codes depending on different cases.
var: This keyword is used to declare a variable with a global scope.
let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized.
const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration.
farzams101
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 153,
"s": 52,
"text": "The programming instructions written in a program in a programming language are known as statements."
},
{
"code": null,
"e": 219,
"s": 153,
"text": "Order of execution of Statements is the same as they are written."
},
{
"code": null,
"e": 2983,
"s": 219,
"text": "Semicolons:Semicolons separate JavaScript statements.Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id=\"geek\"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( \"geek\").innerHTML = \"The value of c is \" + c + \".\"; </script> </body> </html>Output:Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;Code Blocks:JavaScript statements can be grouped together inside curly brackets. Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together.Example:JavaScript function<!DOCTYPE html><html> <body> <p>Welcome</p> <button type=\"button\" onclick=\"myFunction()\"> Click Me! </button> <p id=\"geek1\"></p> <p id=\"geek2\"></p> <script> function myFunction() { document.getElementById( \"geek1\").innerHTML = \"Hello\"; document.getElementById( \"geek2\").innerHTML = \"How are you?\"; } </script> </body> </html>Output:Before Click:After Click:White Space:Javascript ignores multiple white spaces.Javascript would treat following 2 statements as same:Example:var a=\"Hello Geek\";\nvar a = \"Hello Geek\";\nLine Length and Line Breaks:Javascript code preferred line length by most programmers is upto 80 characters.The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.Example:document.getElementById(\"geek1\").innerHTML =\n\"Hello Geek!\";\nKeywords:Keywords are reserved words and cannot be used as variable name.A Javascript keyword tells about what kind of operation it will perform.Some commonly used keywords are:break: This is used to terminate a loop or switch.continue: This is used to skip a particular iteration in a loop and move to next iteration.do.... while: In this the statements written within do block are executed till the condition in while is true.for: It helps in executing a block of statements till the condition is true.function: This keyword is used to declare a function.return: This keyword is used to exit a function.switch: This helps in executing a block of codes depending on different cases.var: This keyword is used to declare a variable with a global scope.let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized.const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration."
},
{
"code": null,
"e": 3585,
"s": 2983,
"text": "Semicolons:Semicolons separate JavaScript statements.Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id=\"geek\"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( \"geek\").innerHTML = \"The value of c is \" + c + \".\"; </script> </body> </html>Output:Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;"
},
{
"code": null,
"e": 3628,
"s": 3585,
"text": "Semicolons separate JavaScript statements."
},
{
"code": null,
"e": 4080,
"s": 3628,
"text": "Semicolon marks the end of a statement in javascript.Example:<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id=\"geek\"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( \"geek\").innerHTML = \"The value of c is \" + c + \".\"; </script> </body> </html>Output:"
},
{
"code": null,
"e": 4089,
"s": 4080,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome</h2> <p id=\"geek\"></p> <script> // Statement 1 var a, b, c; // Statement 2 a = 2; // Statement 3 b = 3; // Statement 4 c = a + b; document.getElementById( \"geek\").innerHTML = \"The value of c is \" + c + \".\"; </script> </body> </html>",
"e": 4473,
"s": 4089,
"text": null
},
{
"code": null,
"e": 4481,
"s": 4473,
"text": "Output:"
},
{
"code": null,
"e": 4579,
"s": 4481,
"text": "Multiple statements on one line are allowed if they are separated with a semicolon.a=2;b=3;z=a+b;"
},
{
"code": null,
"e": 4594,
"s": 4579,
"text": "a=2;b=3;z=a+b;"
},
{
"code": null,
"e": 5315,
"s": 4594,
"text": "Code Blocks:JavaScript statements can be grouped together inside curly brackets. Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together.Example:JavaScript function<!DOCTYPE html><html> <body> <p>Welcome</p> <button type=\"button\" onclick=\"myFunction()\"> Click Me! </button> <p id=\"geek1\"></p> <p id=\"geek2\"></p> <script> function myFunction() { document.getElementById( \"geek1\").innerHTML = \"Hello\"; document.getElementById( \"geek2\").innerHTML = \"How are you?\"; } </script> </body> </html>Output:Before Click:After Click:"
},
{
"code": null,
"e": 5343,
"s": 5315,
"text": "Example:JavaScript function"
},
{
"code": "<!DOCTYPE html><html> <body> <p>Welcome</p> <button type=\"button\" onclick=\"myFunction()\"> Click Me! </button> <p id=\"geek1\"></p> <p id=\"geek2\"></p> <script> function myFunction() { document.getElementById( \"geek1\").innerHTML = \"Hello\"; document.getElementById( \"geek2\").innerHTML = \"How are you?\"; } </script> </body> </html>",
"e": 5814,
"s": 5343,
"text": null
},
{
"code": null,
"e": 5847,
"s": 5814,
"text": "Output:Before Click:After Click:"
},
{
"code": null,
"e": 6005,
"s": 5847,
"text": "White Space:Javascript ignores multiple white spaces.Javascript would treat following 2 statements as same:Example:var a=\"Hello Geek\";\nvar a = \"Hello Geek\";\n"
},
{
"code": null,
"e": 6047,
"s": 6005,
"text": "Javascript ignores multiple white spaces."
},
{
"code": null,
"e": 6110,
"s": 6047,
"text": "Javascript would treat following 2 statements as same:Example:"
},
{
"code": null,
"e": 6153,
"s": 6110,
"text": "var a=\"Hello Geek\";\nvar a = \"Hello Geek\";\n"
},
{
"code": null,
"e": 6422,
"s": 6153,
"text": "Line Length and Line Breaks:Javascript code preferred line length by most programmers is upto 80 characters.The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.Example:document.getElementById(\"geek1\").innerHTML =\n\"Hello Geek!\";\n"
},
{
"code": null,
"e": 6483,
"s": 6422,
"text": "document.getElementById(\"geek1\").innerHTML =\n\"Hello Geek!\";\n"
},
{
"code": null,
"e": 7501,
"s": 6483,
"text": "Keywords:Keywords are reserved words and cannot be used as variable name.A Javascript keyword tells about what kind of operation it will perform.Some commonly used keywords are:break: This is used to terminate a loop or switch.continue: This is used to skip a particular iteration in a loop and move to next iteration.do.... while: In this the statements written within do block are executed till the condition in while is true.for: It helps in executing a block of statements till the condition is true.function: This keyword is used to declare a function.return: This keyword is used to exit a function.switch: This helps in executing a block of codes depending on different cases.var: This keyword is used to declare a variable with a global scope.let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized.const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration."
},
{
"code": null,
"e": 7534,
"s": 7501,
"text": "Some commonly used keywords are:"
},
{
"code": null,
"e": 7585,
"s": 7534,
"text": "break: This is used to terminate a loop or switch."
},
{
"code": null,
"e": 7677,
"s": 7585,
"text": "continue: This is used to skip a particular iteration in a loop and move to next iteration."
},
{
"code": null,
"e": 7788,
"s": 7677,
"text": "do.... while: In this the statements written within do block are executed till the condition in while is true."
},
{
"code": null,
"e": 7865,
"s": 7788,
"text": "for: It helps in executing a block of statements till the condition is true."
},
{
"code": null,
"e": 7919,
"s": 7865,
"text": "function: This keyword is used to declare a function."
},
{
"code": null,
"e": 7968,
"s": 7919,
"text": "return: This keyword is used to exit a function."
},
{
"code": null,
"e": 8047,
"s": 7968,
"text": "switch: This helps in executing a block of codes depending on different cases."
},
{
"code": null,
"e": 8116,
"s": 8047,
"text": "var: This keyword is used to declare a variable with a global scope."
},
{
"code": null,
"e": 8236,
"s": 8116,
"text": "let: This keyword is used to declare a variable with block scope. Variables declared using let need not be initialized."
},
{
"code": null,
"e": 8384,
"s": 8236,
"text": "const: This keyword is used to declare a variable with block scope. Variables declared using const must be initialized at the place of declaration."
},
{
"code": null,
"e": 8395,
"s": 8384,
"text": "farzams101"
},
{
"code": null,
"e": 8413,
"s": 8395,
"text": "javascript-basics"
},
{
"code": null,
"e": 8420,
"s": 8413,
"text": "Picked"
},
{
"code": null,
"e": 8431,
"s": 8420,
"text": "JavaScript"
},
{
"code": null,
"e": 8448,
"s": 8431,
"text": "Web Technologies"
},
{
"code": null,
"e": 8546,
"s": 8448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8607,
"s": 8546,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8679,
"s": 8607,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 8719,
"s": 8679,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 8772,
"s": 8719,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 8814,
"s": 8772,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 8847,
"s": 8814,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 8909,
"s": 8847,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8970,
"s": 8909,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9020,
"s": 8970,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Remove Widgets from grid in Tkinter
|
01 Apr, 2021
Do you know that you can remove or display the widgets from a grid on a single button click while working in your app? We can remove widgets from the grid by declaring the function for remove with grid_remove() method for every widget and then call that function in the button. Similarly, for displaying the widgets back on screen, We can declare the function for display with grid() method for every widget and then call that function in the button.
Step 1: First, import the library tkinter.
from tkinter import *
Step 2: Now, create a GUI app using tkinter.
app=Tk()
Step 3: Then, create a function to remove widgets from the grid in tkinter. In the function created, we have used the inbuilt function grid_remove() to remove certain widgets.
def remove(widget1):
widget1.grid_remove()
Here, we have passed one widget as an argument. You can add as many widgets you want which you wish to remove from a certain grid.
Step 4: Further, create a function to display widgets back in the grid in tkinter. In the function created, we have used the inbuilt function grid() to display the certain widgets back with the grid values where you want to display them back.
def display(widget1):
widget1.grid(column=#Column value where you want to get back the widget,
row=#Row value where you want to get the widget back,
padx=10,
pady=10)
Here, we have passed one widget as an argument. You can add as many widgets you want which you wish to display back in a certain grid by specifying its grid location.
Step 5: Next, we create the widgets which we need to hide or display using the functions declared above. For removing and displaying back the widget from a certain row and column of the grid:
For widget Label, declare label as:
l1=Label(app, text=”#Text you wish to show in label”)
l1.grid(column=#Column value where you want to specify label,
row=#Row value where you want to specify label,
padx=#Padding Value of x,
pady=#Padding Value of y)
For widget Textbox, declare textbox as:
l = StringVar()
l1 = Entry(app, width = 15, textvariable = l)
l1.grid(column=#Column value where you want to specify textbox,
row=#Row value where you want to specify textbox,
padx=#Padding Value of x,
pady=#Padding Value of y)
For widget Button, declare button as:
l1 = Button(app, text=”#Text you want to show in button”)
l1.grid(column=#Column value where you want to specify button,
row=#Row value where you want to specify button,
padx=#Padding Value of x,
pady=#Padding Value of y)
For any other widget other than the above specified, declare that widget in place of these.
Step 6: Later on, create a button which when clicked will remove the widgets from the screen.
remove_btn = Button(app, text = “Remove widgets”, command = lambda : remove(l1))
remove_btn.grid(column=0, row=0, padx=10, pady=10)
IMPORTANT NOTE: Don’t forget to call the remove function in the command attribute of the button by specifying the number of arguments in the function which you have created earlier.
Step 7: Moreover, create a button which when clicked will display the widgets back on the screen.
display_btn = Button(app, text = “#Text you wish to give to button”, command = lambda : display(l1))
display_btn.grid(column=0, row=1, padx=10, pady=10)
IMPORTANT NOTE: Don’t forget to call the display function in the command attribute of the button by specifying the number of arguments in the function which you have created earlier.
Step 8: Finally, make the loop for displaying the GUI app on the screen.
app.mainloop()
Example:
In this example, we will remove one label titled ‘Vinayak’ from the grid value (row=3, column=0) and one label titled ‘Rai‘ from grid value (row=4, column=0) using the single button ‘Remove Widgets‘ while display the label back at grid value (row=3, column=0) and button back at the grid value (row=4, column=0) using the button ‘Display Widgets.’
Python
# Python program to remove widgets# from grid in tkinter # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Creating a function for removing widgets from griddef remove(widget1, widget2): widget1.grid_remove() widget2.grid_remove() # Creating a function for making widget visible againdef display(widget1, widget2): widget1.grid(column=0, row=3, padx=10, pady=10) widget2.grid(column=0, row=4, padx=10, pady=10) # Button widgetsb1 = Button(app, text="Vinayak")b1.grid(column=0, row=3, padx=10, pady=10) # Label Widgetsl1 = Label(app, text="Rai")l1.grid(column=0, row=4, padx=10, pady=10) # Create and show button with remove() functionremove_btn = Button(app, text="Remove widgets", command=lambda: remove(b1, l1))remove_btn.grid(column=0, row=0, padx=10, pady=10) # Create and show button with display() functiondisplay_btn = Button(app, text="Display widgets", command=lambda: display(b1, l1))display_btn.grid(column=0, row=1, padx=10, pady=10) # Make infinite loop for displaying app on screenapp.mainloop()
Output:
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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": "\n01 Apr, 2021"
},
{
"code": null,
"e": 479,
"s": 28,
"text": "Do you know that you can remove or display the widgets from a grid on a single button click while working in your app? We can remove widgets from the grid by declaring the function for remove with grid_remove() method for every widget and then call that function in the button. Similarly, for displaying the widgets back on screen, We can declare the function for display with grid() method for every widget and then call that function in the button."
},
{
"code": null,
"e": 522,
"s": 479,
"text": "Step 1: First, import the library tkinter."
},
{
"code": null,
"e": 544,
"s": 522,
"text": "from tkinter import *"
},
{
"code": null,
"e": 589,
"s": 544,
"text": "Step 2: Now, create a GUI app using tkinter."
},
{
"code": null,
"e": 598,
"s": 589,
"text": "app=Tk()"
},
{
"code": null,
"e": 774,
"s": 598,
"text": "Step 3: Then, create a function to remove widgets from the grid in tkinter. In the function created, we have used the inbuilt function grid_remove() to remove certain widgets."
},
{
"code": null,
"e": 821,
"s": 774,
"text": "def remove(widget1):\n widget1.grid_remove()"
},
{
"code": null,
"e": 952,
"s": 821,
"text": "Here, we have passed one widget as an argument. You can add as many widgets you want which you wish to remove from a certain grid."
},
{
"code": null,
"e": 1195,
"s": 952,
"text": "Step 4: Further, create a function to display widgets back in the grid in tkinter. In the function created, we have used the inbuilt function grid() to display the certain widgets back with the grid values where you want to display them back."
},
{
"code": null,
"e": 1217,
"s": 1195,
"text": "def display(widget1):"
},
{
"code": null,
"e": 1295,
"s": 1217,
"text": " widget1.grid(column=#Column value where you want to get back the widget, "
},
{
"code": null,
"e": 1367,
"s": 1295,
"text": " row=#Row value where you want to get the widget back, "
},
{
"code": null,
"e": 1394,
"s": 1367,
"text": " padx=10, "
},
{
"code": null,
"e": 1420,
"s": 1394,
"text": " pady=10)"
},
{
"code": null,
"e": 1587,
"s": 1420,
"text": "Here, we have passed one widget as an argument. You can add as many widgets you want which you wish to display back in a certain grid by specifying its grid location."
},
{
"code": null,
"e": 1779,
"s": 1587,
"text": "Step 5: Next, we create the widgets which we need to hide or display using the functions declared above. For removing and displaying back the widget from a certain row and column of the grid:"
},
{
"code": null,
"e": 1815,
"s": 1779,
"text": "For widget Label, declare label as:"
},
{
"code": null,
"e": 1869,
"s": 1815,
"text": "l1=Label(app, text=”#Text you wish to show in label”)"
},
{
"code": null,
"e": 1932,
"s": 1869,
"text": "l1.grid(column=#Column value where you want to specify label, "
},
{
"code": null,
"e": 1989,
"s": 1932,
"text": " row=#Row value where you want to specify label, "
},
{
"code": null,
"e": 2024,
"s": 1989,
"text": " padx=#Padding Value of x, "
},
{
"code": null,
"e": 2058,
"s": 2024,
"text": " pady=#Padding Value of y)"
},
{
"code": null,
"e": 2098,
"s": 2058,
"text": "For widget Textbox, declare textbox as:"
},
{
"code": null,
"e": 2114,
"s": 2098,
"text": "l = StringVar()"
},
{
"code": null,
"e": 2160,
"s": 2114,
"text": "l1 = Entry(app, width = 15, textvariable = l)"
},
{
"code": null,
"e": 2225,
"s": 2160,
"text": "l1.grid(column=#Column value where you want to specify textbox, "
},
{
"code": null,
"e": 2284,
"s": 2225,
"text": " row=#Row value where you want to specify textbox, "
},
{
"code": null,
"e": 2318,
"s": 2284,
"text": " padx=#Padding Value of x,"
},
{
"code": null,
"e": 2352,
"s": 2318,
"text": " pady=#Padding Value of y)"
},
{
"code": null,
"e": 2390,
"s": 2352,
"text": "For widget Button, declare button as:"
},
{
"code": null,
"e": 2448,
"s": 2390,
"text": "l1 = Button(app, text=”#Text you want to show in button”)"
},
{
"code": null,
"e": 2512,
"s": 2448,
"text": "l1.grid(column=#Column value where you want to specify button, "
},
{
"code": null,
"e": 2570,
"s": 2512,
"text": " row=#Row value where you want to specify button, "
},
{
"code": null,
"e": 2605,
"s": 2570,
"text": " padx=#Padding Value of x, "
},
{
"code": null,
"e": 2639,
"s": 2605,
"text": " pady=#Padding Value of y)"
},
{
"code": null,
"e": 2731,
"s": 2639,
"text": "For any other widget other than the above specified, declare that widget in place of these."
},
{
"code": null,
"e": 2825,
"s": 2731,
"text": "Step 6: Later on, create a button which when clicked will remove the widgets from the screen."
},
{
"code": null,
"e": 2906,
"s": 2825,
"text": "remove_btn = Button(app, text = “Remove widgets”, command = lambda : remove(l1))"
},
{
"code": null,
"e": 2957,
"s": 2906,
"text": "remove_btn.grid(column=0, row=0, padx=10, pady=10)"
},
{
"code": null,
"e": 3139,
"s": 2957,
"text": "IMPORTANT NOTE: Don’t forget to call the remove function in the command attribute of the button by specifying the number of arguments in the function which you have created earlier."
},
{
"code": null,
"e": 3237,
"s": 3139,
"text": "Step 7: Moreover, create a button which when clicked will display the widgets back on the screen."
},
{
"code": null,
"e": 3338,
"s": 3237,
"text": "display_btn = Button(app, text = “#Text you wish to give to button”, command = lambda : display(l1))"
},
{
"code": null,
"e": 3390,
"s": 3338,
"text": "display_btn.grid(column=0, row=1, padx=10, pady=10)"
},
{
"code": null,
"e": 3573,
"s": 3390,
"text": "IMPORTANT NOTE: Don’t forget to call the display function in the command attribute of the button by specifying the number of arguments in the function which you have created earlier."
},
{
"code": null,
"e": 3646,
"s": 3573,
"text": "Step 8: Finally, make the loop for displaying the GUI app on the screen."
},
{
"code": null,
"e": 3661,
"s": 3646,
"text": "app.mainloop()"
},
{
"code": null,
"e": 3670,
"s": 3661,
"text": "Example:"
},
{
"code": null,
"e": 4018,
"s": 3670,
"text": "In this example, we will remove one label titled ‘Vinayak’ from the grid value (row=3, column=0) and one label titled ‘Rai‘ from grid value (row=4, column=0) using the single button ‘Remove Widgets‘ while display the label back at grid value (row=3, column=0) and button back at the grid value (row=4, column=0) using the button ‘Display Widgets.’"
},
{
"code": null,
"e": 4025,
"s": 4018,
"text": "Python"
},
{
"code": "# Python program to remove widgets# from grid in tkinter # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Creating a function for removing widgets from griddef remove(widget1, widget2): widget1.grid_remove() widget2.grid_remove() # Creating a function for making widget visible againdef display(widget1, widget2): widget1.grid(column=0, row=3, padx=10, pady=10) widget2.grid(column=0, row=4, padx=10, pady=10) # Button widgetsb1 = Button(app, text=\"Vinayak\")b1.grid(column=0, row=3, padx=10, pady=10) # Label Widgetsl1 = Label(app, text=\"Rai\")l1.grid(column=0, row=4, padx=10, pady=10) # Create and show button with remove() functionremove_btn = Button(app, text=\"Remove widgets\", command=lambda: remove(b1, l1))remove_btn.grid(column=0, row=0, padx=10, pady=10) # Create and show button with display() functiondisplay_btn = Button(app, text=\"Display widgets\", command=lambda: display(b1, l1))display_btn.grid(column=0, row=1, padx=10, pady=10) # Make infinite loop for displaying app on screenapp.mainloop()",
"e": 5127,
"s": 4025,
"text": null
},
{
"code": null,
"e": 5135,
"s": 5127,
"text": "Output:"
},
{
"code": null,
"e": 5142,
"s": 5135,
"text": "Picked"
},
{
"code": null,
"e": 5157,
"s": 5142,
"text": "Python-tkinter"
},
{
"code": null,
"e": 5164,
"s": 5157,
"text": "Python"
},
{
"code": null,
"e": 5262,
"s": 5164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5294,
"s": 5262,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5321,
"s": 5294,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5342,
"s": 5321,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5365,
"s": 5342,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5421,
"s": 5365,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5452,
"s": 5421,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5494,
"s": 5452,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5536,
"s": 5494,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5575,
"s": 5536,
"text": "Python | Get unique values from a list"
}
] |
Lua - Strings
|
String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes −
Characters between single quotes
Characters between double quotes
Characters between [[ and ]]
An example for the above three forms are shown below.
string1 = "Lua"
print("\"String 1 is\"",string1)
string2 = 'Tutorial'
print("String 2 is",string2)
string3 = [["Lua Tutorial"]]
print("String 3 is",string3)
When we run the above program, we will get the following output.
"String 1 is" Lua
String 2 is Tutorial
String 3 is "Lua Tutorial"
Escape sequence characters are used in string to change the normal interpretation of characters. For example, to print double inverted commas (""), we have used \" in the above example. The escape sequence and its use is listed below in the table.
Lua supports string to manipulate strings −
string.upper(argument)
Returns a capitalized representation of the argument.
string.lower(argument)
Returns a lower case representation of the argument.
string.gsub(mainString,findString,replaceString)
Returns a string by replacing occurrences of findString with replaceString.
string.find(mainString,findString,
optionalStartIndex,optionalEndIndex)
Returns the start index and end index of the findString in the main string and nil if not found.
string.reverse(arg)
Returns a string by reversing the characters of the passed string.
string.format(...)
Returns a formatted string.
string.char(arg) and string.byte(arg)
Returns internal numeric and character representations of input argument.
string.len(arg)
Returns a length of the passed string.
string.rep(string, n))
Returns a string by repeating the same string n number times.
..
Thus operator concatenates two strings.
Now, let's dive into a few examples to exactly see how these string manipulation functions behave.
A sample code for manipulating the strings to upper and lower case is given below.
string1 = "Lua";
print(string.upper(string1))
print(string.lower(string1))
When we run the above program, we will get the following output.
LUA
lua
A sample code for replacing occurrences of one string with another is given below.
string = "Lua Tutorial"
-- replacing strings
newstring = string.gsub(string,"Tutorial","Language")
print("The new string is "..newstring)
When we run the above program, we will get the following output.
The new string is Lua Language
A sample code for finding the index of substring and reversing string is given below.
string = "Lua Tutorial"
-- replacing strings
print(string.find(string,"Tutorial"))
reversedString = string.reverse(string)
print("The new string is",reversedString)
When we run the above program, we will get the following output.
5 12
The new string is lairotuT auL
Many times in our programming, we may need to print strings in a formatted way. You can use the string.format function to format the output as shown below.
string1 = "Lua"
string2 = "Tutorial"
number1 = 10
number2 = 20
-- Basic string formatting
print(string.format("Basic formatting %s %s",string1,string2))
-- Date formatting
date = 2; month = 1; year = 2014
print(string.format("Date formatting %02d/%02d/%03d", date, month, year))
-- Decimal formatting
print(string.format("%.4f",1/3))
When we run the above program, we will get the following output.
Basic formatting Lua Tutorial
Date formatting 02/01/2014
0.3333
A sample code for character and byte representation, which is used for converting the string from string to internal representation and vice versa.
-- Byte conversion
-- First character
print(string.byte("Lua"))
-- Third character
print(string.byte("Lua",3))
-- first character from last
print(string.byte("Lua",-1))
-- Second character
print(string.byte("Lua",2))
-- Second character from last
print(string.byte("Lua",-2))
-- Internal Numeric ASCII Conversion
print(string.char(97))
When we run the above program, we will get the following output.
76
97
97
117
117
a
The common string manipulations include string concatenation, finding length of string and at times repeating the same string multiple times. The example for these operations is given below.
string1 = "Lua"
string2 = "Tutorial"
-- String Concatenations using ..
print("Concatenated string",string1..string2)
-- Length of string
print("Length of string1 is ",string.len(string1))
-- Repeating strings
repeatedString = string.rep(string1,3)
print(repeatedString)
When we run the above program, we will get the following output.
Concatenated string LuaTutorial
Length of string1 is 3
|
[
{
"code": null,
"e": 2378,
"s": 2237,
"text": "String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes −"
},
{
"code": null,
"e": 2411,
"s": 2378,
"text": "Characters between single quotes"
},
{
"code": null,
"e": 2444,
"s": 2411,
"text": "Characters between double quotes"
},
{
"code": null,
"e": 2474,
"s": 2444,
"text": "Characters between [[ and ]]"
},
{
"code": null,
"e": 2528,
"s": 2474,
"text": "An example for the above three forms are shown below."
},
{
"code": null,
"e": 2687,
"s": 2528,
"text": "string1 = \"Lua\"\nprint(\"\\\"String 1 is\\\"\",string1)\n\nstring2 = 'Tutorial'\nprint(\"String 2 is\",string2)\n\nstring3 = [[\"Lua Tutorial\"]]\nprint(\"String 3 is\",string3)"
},
{
"code": null,
"e": 2752,
"s": 2687,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 2819,
"s": 2752,
"text": "\"String 1 is\"\tLua\nString 2 is\tTutorial\nString 3 is\t\"Lua Tutorial\"\n"
},
{
"code": null,
"e": 3067,
"s": 2819,
"text": "Escape sequence characters are used in string to change the normal interpretation of characters. For example, to print double inverted commas (\"\"), we have used \\\" in the above example. The escape sequence and its use is listed below in the table."
},
{
"code": null,
"e": 3111,
"s": 3067,
"text": "Lua supports string to manipulate strings −"
},
{
"code": null,
"e": 3134,
"s": 3111,
"text": "string.upper(argument)"
},
{
"code": null,
"e": 3188,
"s": 3134,
"text": "Returns a capitalized representation of the argument."
},
{
"code": null,
"e": 3211,
"s": 3188,
"text": "string.lower(argument)"
},
{
"code": null,
"e": 3264,
"s": 3211,
"text": "Returns a lower case representation of the argument."
},
{
"code": null,
"e": 3313,
"s": 3264,
"text": "string.gsub(mainString,findString,replaceString)"
},
{
"code": null,
"e": 3389,
"s": 3313,
"text": "Returns a string by replacing occurrences of findString with replaceString."
},
{
"code": null,
"e": 3424,
"s": 3389,
"text": "string.find(mainString,findString,"
},
{
"code": null,
"e": 3461,
"s": 3424,
"text": "optionalStartIndex,optionalEndIndex)"
},
{
"code": null,
"e": 3558,
"s": 3461,
"text": "Returns the start index and end index of the findString in the main string and nil if not found."
},
{
"code": null,
"e": 3578,
"s": 3558,
"text": "string.reverse(arg)"
},
{
"code": null,
"e": 3645,
"s": 3578,
"text": "Returns a string by reversing the characters of the passed string."
},
{
"code": null,
"e": 3664,
"s": 3645,
"text": "string.format(...)"
},
{
"code": null,
"e": 3692,
"s": 3664,
"text": "Returns a formatted string."
},
{
"code": null,
"e": 3730,
"s": 3692,
"text": "string.char(arg) and string.byte(arg)"
},
{
"code": null,
"e": 3804,
"s": 3730,
"text": "Returns internal numeric and character representations of input argument."
},
{
"code": null,
"e": 3820,
"s": 3804,
"text": "string.len(arg)"
},
{
"code": null,
"e": 3859,
"s": 3820,
"text": "Returns a length of the passed string."
},
{
"code": null,
"e": 3882,
"s": 3859,
"text": "string.rep(string, n))"
},
{
"code": null,
"e": 3944,
"s": 3882,
"text": "Returns a string by repeating the same string n number times."
},
{
"code": null,
"e": 3947,
"s": 3944,
"text": ".."
},
{
"code": null,
"e": 3987,
"s": 3947,
"text": "Thus operator concatenates two strings."
},
{
"code": null,
"e": 4086,
"s": 3987,
"text": "Now, let's dive into a few examples to exactly see how these string manipulation functions behave."
},
{
"code": null,
"e": 4169,
"s": 4086,
"text": "A sample code for manipulating the strings to upper and lower case is given below."
},
{
"code": null,
"e": 4245,
"s": 4169,
"text": "string1 = \"Lua\";\n\nprint(string.upper(string1))\nprint(string.lower(string1))"
},
{
"code": null,
"e": 4310,
"s": 4245,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 4319,
"s": 4310,
"text": "LUA\nlua\n"
},
{
"code": null,
"e": 4402,
"s": 4319,
"text": "A sample code for replacing occurrences of one string with another is given below."
},
{
"code": null,
"e": 4541,
"s": 4402,
"text": "string = \"Lua Tutorial\"\n\n-- replacing strings\nnewstring = string.gsub(string,\"Tutorial\",\"Language\")\nprint(\"The new string is \"..newstring)"
},
{
"code": null,
"e": 4606,
"s": 4541,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 4638,
"s": 4606,
"text": "The new string is Lua Language\n"
},
{
"code": null,
"e": 4724,
"s": 4638,
"text": "A sample code for finding the index of substring and reversing string is given below."
},
{
"code": null,
"e": 4890,
"s": 4724,
"text": "string = \"Lua Tutorial\"\n\n-- replacing strings\nprint(string.find(string,\"Tutorial\"))\nreversedString = string.reverse(string)\nprint(\"The new string is\",reversedString)"
},
{
"code": null,
"e": 4955,
"s": 4890,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 4992,
"s": 4955,
"text": "5\t12\nThe new string is\tlairotuT auL\n"
},
{
"code": null,
"e": 5148,
"s": 4992,
"text": "Many times in our programming, we may need to print strings in a formatted way. You can use the string.format function to format the output as shown below."
},
{
"code": null,
"e": 5486,
"s": 5148,
"text": "string1 = \"Lua\"\nstring2 = \"Tutorial\"\n\nnumber1 = 10\nnumber2 = 20\n\n-- Basic string formatting\nprint(string.format(\"Basic formatting %s %s\",string1,string2))\n\n-- Date formatting\ndate = 2; month = 1; year = 2014\nprint(string.format(\"Date formatting %02d/%02d/%03d\", date, month, year))\n\n-- Decimal formatting\nprint(string.format(\"%.4f\",1/3))"
},
{
"code": null,
"e": 5551,
"s": 5486,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 5616,
"s": 5551,
"text": "Basic formatting Lua Tutorial\nDate formatting 02/01/2014\n0.3333\n"
},
{
"code": null,
"e": 5764,
"s": 5616,
"text": "A sample code for character and byte representation, which is used for converting the string from string to internal representation and vice versa."
},
{
"code": null,
"e": 6106,
"s": 5764,
"text": "-- Byte conversion\n\n-- First character\nprint(string.byte(\"Lua\"))\n\n-- Third character\nprint(string.byte(\"Lua\",3))\n\n-- first character from last\nprint(string.byte(\"Lua\",-1))\n\n-- Second character\nprint(string.byte(\"Lua\",2))\n\n-- Second character from last\nprint(string.byte(\"Lua\",-2))\n\n-- Internal Numeric ASCII Conversion\nprint(string.char(97))"
},
{
"code": null,
"e": 6171,
"s": 6106,
"text": "When we run the above program, we will get the following output."
},
{
"code": null,
"e": 6191,
"s": 6171,
"text": "76\n97\n97\n117\n117\na\n"
},
{
"code": null,
"e": 6382,
"s": 6191,
"text": "The common string manipulations include string concatenation, finding length of string and at times repeating the same string multiple times. The example for these operations is given below."
},
{
"code": null,
"e": 6655,
"s": 6382,
"text": "string1 = \"Lua\"\nstring2 = \"Tutorial\"\n\n-- String Concatenations using ..\nprint(\"Concatenated string\",string1..string2)\n\n-- Length of string\nprint(\"Length of string1 is \",string.len(string1))\n\n-- Repeating strings\nrepeatedString = string.rep(string1,3)\nprint(repeatedString)"
},
{
"code": null,
"e": 6720,
"s": 6655,
"text": "When we run the above program, we will get the following output."
}
] |
Python – API.followers() in Tweepy
|
05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The followers() method of the API class in Tweepy module is used to get the specified user’s followers ordered in which they were added.
Syntax : API.followers(id / user_id / screen_name)
Parameters : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID
Returns : a list of objects of the class User
Example 1 :The followers() method returns the 20 most recent followers.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen_name of the targeted userscreen_name = "geeksforgeeks" # printing the latest 20 followers of the userfor follower in api.followers(screen_name): print(follower.screen_name)
Output :
ManojChevula
davidasem_
rajneesosho
sl_jens
Sandeep06081
abdulwhabalras2
chryptografio
_Mohit_Rajput_
elamineyamani
abhiSharma0311
PawanYa87321156
yagneshmb
yogeekabhi
DarioGallardo2
imharsan
MOHAMMA18757894
ArunKum79855492
ans_human_ap
1nonlyabhi
Example 2: More than 20 followers can be accessed using the Cursor() method.
# the screen_name of the targeted userscreen_name = "geeksforgeeks" # getting only 30 followersfor follower in tweepy.Cursor(api.followers, screen_name).items(30): print(follower.screen_name)
Output :
mr_manav852
MohsinI09002010
educatorly
JimXu_artist
JaiHin303
Indrajeet307
sainisajal147
aryangarg22
Ashutos11691851
ManojChevula
davidasem_
osho957
sl_jens
Sandeep06081
abdulwhabalras2
chryptografio
_Mohit_Rajput_
elamineyamani
abhiSharma0311
PawanYa87321156
yagneshmb
yogeekabhi
DarioGallardo2
imharsan
MOHAMMA18757894
ArunKum79855492
ans_human_ap
1nonlyabhi
SimplicitySol2
prateekmaj21
Example 3: Counting the number of followers.
# the screen_name of the targeted userscreen_name = "geeksforgeeks" # getting all the followersc = tweepy.Cursor(api.followers, screen_name) # counting the number of followerscount = 0for follower in c.items(): count += 1print(screen_name + " has " + str(count) + " followers.")
Output :
geeksforgeeks has 17338 followers.
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 428,
"s": 28,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 565,
"s": 428,
"text": "The followers() method of the API class in Tweepy module is used to get the specified user’s followers ordered in which they were added."
},
{
"code": null,
"e": 616,
"s": 565,
"text": "Syntax : API.followers(id / user_id / screen_name)"
},
{
"code": null,
"e": 961,
"s": 616,
"text": "Parameters : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user ID"
},
{
"code": null,
"e": 1007,
"s": 961,
"text": "Returns : a list of objects of the class User"
},
{
"code": null,
"e": 1079,
"s": 1007,
"text": "Example 1 :The followers() method returns the 20 most recent followers."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen_name of the targeted userscreen_name = \"geeksforgeeks\" # printing the latest 20 followers of the userfor follower in api.followers(screen_name): print(follower.screen_name)",
"e": 1676,
"s": 1079,
"text": null
},
{
"code": null,
"e": 1685,
"s": 1676,
"text": "Output :"
},
{
"code": null,
"e": 1934,
"s": 1685,
"text": "ManojChevula\ndavidasem_\nrajneesosho\nsl_jens\nSandeep06081\nabdulwhabalras2\nchryptografio\n_Mohit_Rajput_\nelamineyamani\nabhiSharma0311\nPawanYa87321156\nyagneshmb\nyogeekabhi\nDarioGallardo2\nimharsan\nMOHAMMA18757894\nArunKum79855492\nans_human_ap\n1nonlyabhi\n"
},
{
"code": null,
"e": 2011,
"s": 1934,
"text": "Example 2: More than 20 followers can be accessed using the Cursor() method."
},
{
"code": "# the screen_name of the targeted userscreen_name = \"geeksforgeeks\" # getting only 30 followersfor follower in tweepy.Cursor(api.followers, screen_name).items(30): print(follower.screen_name)",
"e": 2207,
"s": 2011,
"text": null
},
{
"code": null,
"e": 2216,
"s": 2207,
"text": "Output :"
},
{
"code": null,
"e": 2606,
"s": 2216,
"text": "mr_manav852\nMohsinI09002010\neducatorly\nJimXu_artist\nJaiHin303\nIndrajeet307\nsainisajal147\naryangarg22\nAshutos11691851\nManojChevula\ndavidasem_\nosho957\nsl_jens\nSandeep06081\nabdulwhabalras2\nchryptografio\n_Mohit_Rajput_\nelamineyamani\nabhiSharma0311\nPawanYa87321156\nyagneshmb\nyogeekabhi\nDarioGallardo2\nimharsan\nMOHAMMA18757894\nArunKum79855492\nans_human_ap\n1nonlyabhi\nSimplicitySol2\nprateekmaj21\n"
},
{
"code": null,
"e": 2651,
"s": 2606,
"text": "Example 3: Counting the number of followers."
},
{
"code": "# the screen_name of the targeted userscreen_name = \"geeksforgeeks\" # getting all the followersc = tweepy.Cursor(api.followers, screen_name) # counting the number of followerscount = 0for follower in c.items(): count += 1print(screen_name + \" has \" + str(count) + \" followers.\")",
"e": 2935,
"s": 2651,
"text": null
},
{
"code": null,
"e": 2944,
"s": 2935,
"text": "Output :"
},
{
"code": null,
"e": 2979,
"s": 2944,
"text": "geeksforgeeks has 17338 followers."
},
{
"code": null,
"e": 2993,
"s": 2979,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 3000,
"s": 2993,
"text": "Python"
},
{
"code": null,
"e": 3098,
"s": 3000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3116,
"s": 3098,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3158,
"s": 3116,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3180,
"s": 3158,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3215,
"s": 3180,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3241,
"s": 3215,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3273,
"s": 3241,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3302,
"s": 3273,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3329,
"s": 3302,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3359,
"s": 3329,
"text": "Iterate over a list in Python"
}
] |
YetAnotherSMSBomber – SMS Bomber in kali linux
|
17 Jun, 2021
YetAnotherSMSBomber is a free and open-source tool available on GitHub. This tool doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of YetAnotherSMSBomber from GitHub in order to not get stuck with the working of the tool. This tool is used to perform call and SMS bombing on the target phone number. This tool is written in python, so you must have python installed in your kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing.
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/AvinashReddy3108/YetAnotherSMSBomber.git
cd YetAnotherSMSBomber
Step 2: Now you have to download some dependencies of the tool using the following command.
pip3 install -r requirements.txt
Step 3: The tool has been downloaded and now the tool using the following command.
python3 bomber.py -h
Example :
You can see that the tool has been downloaded successfully. Now let’s see an example of using the tool by running the following command to perform SMS bombing on a number.
python3 bomber.py <phone number>
The tool has started sending SMS and some of them get success whereas some of them failed, but you can try again and again to have the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 688,
"s": 28,
"text": "YetAnotherSMSBomber is a free and open-source tool available on GitHub. This tool doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of YetAnotherSMSBomber from GitHub in order to not get stuck with the working of the tool. This tool is used to perform call and SMS bombing on the target phone number. This tool is written in python, so you must have python installed in your kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. "
},
{
"code": null,
"e": 858,
"s": 688,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command."
},
{
"code": null,
"e": 928,
"s": 858,
"text": "git clone https://github.com/AvinashReddy3108/YetAnotherSMSBomber.git"
},
{
"code": null,
"e": 951,
"s": 928,
"text": "cd YetAnotherSMSBomber"
},
{
"code": null,
"e": 1043,
"s": 951,
"text": "Step 2: Now you have to download some dependencies of the tool using the following command."
},
{
"code": null,
"e": 1076,
"s": 1043,
"text": "pip3 install -r requirements.txt"
},
{
"code": null,
"e": 1159,
"s": 1076,
"text": "Step 3: The tool has been downloaded and now the tool using the following command."
},
{
"code": null,
"e": 1180,
"s": 1159,
"text": "python3 bomber.py -h"
},
{
"code": null,
"e": 1191,
"s": 1180,
"text": "Example : "
},
{
"code": null,
"e": 1363,
"s": 1191,
"text": "You can see that the tool has been downloaded successfully. Now let’s see an example of using the tool by running the following command to perform SMS bombing on a number."
},
{
"code": null,
"e": 1396,
"s": 1363,
"text": "python3 bomber.py <phone number>"
},
{
"code": null,
"e": 1653,
"s": 1396,
"text": "The tool has started sending SMS and some of them get success whereas some of them failed, but you can try again and again to have the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail."
},
{
"code": null,
"e": 1664,
"s": 1653,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1676,
"s": 1664,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1687,
"s": 1676,
"text": "Linux-Unix"
}
] |
refresh driver method – Selenium Python
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around refresh driver method in Selenium. refresh method refreshes the current page.
Syntax –
driver.refresh()
Example –Now one can use refresh method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.refresh()
To demonstrate, refresh method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s refresh window,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # refresh window driver.refresh()
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 767,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 874,
"s": 767,
"text": "This article revolves around refresh driver method in Selenium. refresh method refreshes the current page."
},
{
"code": null,
"e": 883,
"s": 874,
"text": "Syntax –"
},
{
"code": null,
"e": 900,
"s": 883,
"text": "driver.refresh()"
},
{
"code": null,
"e": 970,
"s": 900,
"text": "Example –Now one can use refresh method as a driver method as below –"
},
{
"code": null,
"e": 1032,
"s": 970,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.refresh()\n"
},
{
"code": null,
"e": 1192,
"s": 1032,
"text": "To demonstrate, refresh method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s refresh window,"
},
{
"code": null,
"e": 1202,
"s": 1192,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # refresh window driver.refresh()",
"e": 1410,
"s": 1202,
"text": null
},
{
"code": null,
"e": 1437,
"s": 1410,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 1453,
"s": 1437,
"text": "Python-selenium"
},
{
"code": null,
"e": 1462,
"s": 1453,
"text": "selenium"
},
{
"code": null,
"e": 1469,
"s": 1462,
"text": "Python"
}
] |
plt.subplot() or plt.subplots()? Understanding state-based vs. object-oriented programming in Pyplot | by Kaleb Nyquist | Towards Data Science
|
When I was learning how to code using the Python programming language, the introduction of the Pyplot module (part of the Matplotlib library, here referred to by the alias plt) was particularly non-intuitive...and, honestly, kind of disorientating. For example, the functions plt.subplot() and plt.subplots() may appear to be off by a single letter s, but typically the former is followed by a plotting function in the form plt.plot(data_x, data_y) whereas the latter is usually followed by ax[0,0].plot(data_x, data_y). Even more confusingly, even though the “journeys” may be different, the output “destinations” can often be identical, making anyone wonder what the actual difference is in the end.
After a deeper dive into the Pyplot documentation and with some help from the internet-at-large, I learned that behind these subtle error-generating differences are two radically different approaches to programming that are accommodated by the Pyplot interface: the first being “state-based” and the second being “object-oriented”.
While it is considered best practice for Matplotlib learners to start with the “object-oriented” approach and stick with it, taking a moment to work with the “state-based” approach is a good mini-lesson for better understanding one of the larger conceptual debates in computer science. Pyplot users like myself who do not take time to understand these subtle distinctions might find themselves in a never-ending struggle with a two-headed beast of a module, never quite able to tame it in order to get the data visualizations they envision.
For Matplotlib novices learning Pyplot, what follows is a brief historical note on why “state-based” and “object-oriented” programming philosophies exist, and how they try to exist simultaneously in a single module. In other words, this is the insight I wish I had back when I was first trying to make sense of this seemingly strange and contradictory tool.
The more Pythonic but also more complicated approach, “object-oriented programming”, has historical roots in the Norwegian Computing Center during the 1960’s, where Kristen Nygaard and Ole-Johan Dahl created the first version of the Simula programming language designed for programming computer simulations where different actors and unknown factors interacted with each other in complex yet reproducible ways (for example, if a nuclear reactor were to be built in 10,000 parallel universes, in how many of those universes would there be a severe accident?). Decades later, the rise of the Internet and other computer networks popularized “object-oriented programming”. Python is one of many languages that takes this common approach, along with other mainstays such as Java, C++, and Ruby.
As Python popularized, the Matplotlib library was created in 2003 to make Python an open-source alternative to the proprietary software MATLAB that had been first developed in the late 1970’s. However, rather than being “object-oriented”, MATLAB’s approach was closer to something called “state-based programming”. This simpler approach runs variables through established processes, resulting in a series of states that eventually terminates at a desired result. This is not unlike what happens when one uses a basic calculator. For example:
The calculator starts us with initial state, “0”
We input “1”, a constant variable. This replaces the initial state with a new state, “1”.
We now add the additive process “+” and a new constant variable, which in this case also happens to be “1”.
We combine state, process & variable using the equal sign “=”.
This gives us a new state, “2”. We can modify this state using more processes (“+”, “−”, “×”, “÷”, “±”, “√”, or “%”).
(🤦🏼♂️ I sometimes will accidentally write state-based programming as “stage-based” because in my imagination, I see the procedure as a series of stages each progressing towards a final goal. But the correct terminology is state-based.)
While being quite literally straight-forward, MATLAB and other state-based languages have the disadvantage of not being as easily able to encapsulate objects and abstract functions, resulting in lengthier and more disorganized code for more complex programs.
Matplotlib was meant to be a bridge for MATLAB users into Python, and accordingly it was originally designed to accommodate both state-based programming and object-oriented programming. Although some state-based programming features (especially Pylab) have have now been deprecated for the sake of easing confusion, the state-based MATLAB legacy lives on through the Pyplot module.
These different programming philosophies converge in the Pyplot module. Doing the digital version of an archeological dig, it is possible to contrast the two bring these histories to life by comparing two different sets of code that will eventually arrive at the same result.
For this example, we will try to create a figure with three subplots, as seen below.
Note that the following code assumes that Pyplot has been imported, and that data_x and data_y have have already been defined. You can find this preliminary code on GitHub.
First, we create this graph using the state-based approach.
plt.figure(facecolor='lightgrey')plt.subplot(2,2,1)plt.plot(data_x, data_y, 'r-')plt.subplot(2,2,2)plt.plot(data_x, data_y, 'b-')plt.subplot(2,2,4)plt.plot(data_x, data_y, 'g-')
I have found that a helpful trick for understanding what is going on here is that “subplot” is a noun and “plot” is a verb. That is, plt.subplot(2,2,1) creates and focuses the program on the first subplot (going left-to-right, up-to-down) in a 2×2 grid. Then plt.plot(data_x, data_Y, 'r-') actively plots a red line using the provided data in the first subplot.
(🕵🏽♀️ Careful observers might also notice that the third subplot has been omitted in the above code.)
Second, the same graph can be achieved through the object-oriented approach:
fig, ax = plt.subplots(2,2)fig.set_facecolor('lightgrey')ax[0,0].plot(data_x, data_y, 'r-')ax[0,1].plot(data_x, data_y, 'b-')fig.delaxes(ax[1,0])ax[1,1].plot(data_x, data_y, 'g-')
Here, the plt.subplots(2,2) (notice the additional s) has generated a comparable figure object (“ fig”) that holds a 2×2 array of subplots (or “axes” objects). Now, however, instead of focusing the program on a subplot and then plotting within that subplot, the object-oriented approach first retrieves the “axes” object from the ax array. Then, arguments within the axes method are responsible for the plotting.
(🕵🏽♀️ Notice that the third subplot, referred to here in array form as ax[1,0], is created and then deleted in the above code, rather than simply omitted as in the state-based approach.)
Other than saving a line of code in the object-oriented approach, these subtle differences might seem inconsequential. But, for those still learning Pyplot, they should be warned that unknowingly mixing these methods can make for seemingly inexplicable coding snafus. The animation below shows, line-by-line, the fundamental differences in the state-based versus object-oriented processes. It takes only a little bit of imagination to see how trying to mix-and-match these processes could create quite a headache!
For further experimentation in how these approaches differ from each other yet arrive at the same (or at least similar) results, plug-and-play with these snippets of Pyplot code for adding axis labels and graph titles:
plt.suptitle("Your Title Here")plt.xlabel("X Axis")plt.ylabel("Y Axis")
fig.suptitle("Your Title Here")ax[1,1].set_xlabel("X Axis")ax[1,1].set_ylabel("Y Axis")
(💡 Hint: when experimenting with the above approaches, note how the position of the code relative to plt.subplot() makes a difference in the state-based approach in determining which axis gets titled, whereas the object-oriented approach is position-agnostic thanks to the array of axes objects.)
For your convenience, a Jupyter Notebook is available on GitHub, containing the code used to generate the above graphs.
By now, you should have a solid foundation for understanding the dual nature of Pyplot’s interface, as well as having a small window into the DNA of coding languages.
If you would like to learn more about Pyplot’s dual nature, there are a number of online readings I found particularly helpful, including “The Lifecycle of a Plot” and “Effectively Using Matplotlib”. For more on object-oriented programming, “How to explain Object-Oriented Programming to a Six-Year-Old” was particularly illuminating. Finally, Ankit Gupta has helpful resources that contextualize the latest releases of Matplotlib within their historical development context.
An earlier draft of this article was completed as part of a 2019 Data Science Fellowship with the Flatiron School’s Washington DC Campus. Special thanks to my fellow cohort members and instructors for providing feedback.
|
[
{
"code": null,
"e": 874,
"s": 172,
"text": "When I was learning how to code using the Python programming language, the introduction of the Pyplot module (part of the Matplotlib library, here referred to by the alias plt) was particularly non-intuitive...and, honestly, kind of disorientating. For example, the functions plt.subplot() and plt.subplots() may appear to be off by a single letter s, but typically the former is followed by a plotting function in the form plt.plot(data_x, data_y) whereas the latter is usually followed by ax[0,0].plot(data_x, data_y). Even more confusingly, even though the “journeys” may be different, the output “destinations” can often be identical, making anyone wonder what the actual difference is in the end."
},
{
"code": null,
"e": 1206,
"s": 874,
"text": "After a deeper dive into the Pyplot documentation and with some help from the internet-at-large, I learned that behind these subtle error-generating differences are two radically different approaches to programming that are accommodated by the Pyplot interface: the first being “state-based” and the second being “object-oriented”."
},
{
"code": null,
"e": 1747,
"s": 1206,
"text": "While it is considered best practice for Matplotlib learners to start with the “object-oriented” approach and stick with it, taking a moment to work with the “state-based” approach is a good mini-lesson for better understanding one of the larger conceptual debates in computer science. Pyplot users like myself who do not take time to understand these subtle distinctions might find themselves in a never-ending struggle with a two-headed beast of a module, never quite able to tame it in order to get the data visualizations they envision."
},
{
"code": null,
"e": 2105,
"s": 1747,
"text": "For Matplotlib novices learning Pyplot, what follows is a brief historical note on why “state-based” and “object-oriented” programming philosophies exist, and how they try to exist simultaneously in a single module. In other words, this is the insight I wish I had back when I was first trying to make sense of this seemingly strange and contradictory tool."
},
{
"code": null,
"e": 2896,
"s": 2105,
"text": "The more Pythonic but also more complicated approach, “object-oriented programming”, has historical roots in the Norwegian Computing Center during the 1960’s, where Kristen Nygaard and Ole-Johan Dahl created the first version of the Simula programming language designed for programming computer simulations where different actors and unknown factors interacted with each other in complex yet reproducible ways (for example, if a nuclear reactor were to be built in 10,000 parallel universes, in how many of those universes would there be a severe accident?). Decades later, the rise of the Internet and other computer networks popularized “object-oriented programming”. Python is one of many languages that takes this common approach, along with other mainstays such as Java, C++, and Ruby."
},
{
"code": null,
"e": 3438,
"s": 2896,
"text": "As Python popularized, the Matplotlib library was created in 2003 to make Python an open-source alternative to the proprietary software MATLAB that had been first developed in the late 1970’s. However, rather than being “object-oriented”, MATLAB’s approach was closer to something called “state-based programming”. This simpler approach runs variables through established processes, resulting in a series of states that eventually terminates at a desired result. This is not unlike what happens when one uses a basic calculator. For example:"
},
{
"code": null,
"e": 3487,
"s": 3438,
"text": "The calculator starts us with initial state, “0”"
},
{
"code": null,
"e": 3577,
"s": 3487,
"text": "We input “1”, a constant variable. This replaces the initial state with a new state, “1”."
},
{
"code": null,
"e": 3685,
"s": 3577,
"text": "We now add the additive process “+” and a new constant variable, which in this case also happens to be “1”."
},
{
"code": null,
"e": 3748,
"s": 3685,
"text": "We combine state, process & variable using the equal sign “=”."
},
{
"code": null,
"e": 3866,
"s": 3748,
"text": "This gives us a new state, “2”. We can modify this state using more processes (“+”, “−”, “×”, “÷”, “±”, “√”, or “%”)."
},
{
"code": null,
"e": 4103,
"s": 3866,
"text": "(🤦🏼♂️ I sometimes will accidentally write state-based programming as “stage-based” because in my imagination, I see the procedure as a series of stages each progressing towards a final goal. But the correct terminology is state-based.)"
},
{
"code": null,
"e": 4362,
"s": 4103,
"text": "While being quite literally straight-forward, MATLAB and other state-based languages have the disadvantage of not being as easily able to encapsulate objects and abstract functions, resulting in lengthier and more disorganized code for more complex programs."
},
{
"code": null,
"e": 4744,
"s": 4362,
"text": "Matplotlib was meant to be a bridge for MATLAB users into Python, and accordingly it was originally designed to accommodate both state-based programming and object-oriented programming. Although some state-based programming features (especially Pylab) have have now been deprecated for the sake of easing confusion, the state-based MATLAB legacy lives on through the Pyplot module."
},
{
"code": null,
"e": 5020,
"s": 4744,
"text": "These different programming philosophies converge in the Pyplot module. Doing the digital version of an archeological dig, it is possible to contrast the two bring these histories to life by comparing two different sets of code that will eventually arrive at the same result."
},
{
"code": null,
"e": 5105,
"s": 5020,
"text": "For this example, we will try to create a figure with three subplots, as seen below."
},
{
"code": null,
"e": 5278,
"s": 5105,
"text": "Note that the following code assumes that Pyplot has been imported, and that data_x and data_y have have already been defined. You can find this preliminary code on GitHub."
},
{
"code": null,
"e": 5338,
"s": 5278,
"text": "First, we create this graph using the state-based approach."
},
{
"code": null,
"e": 5516,
"s": 5338,
"text": "plt.figure(facecolor='lightgrey')plt.subplot(2,2,1)plt.plot(data_x, data_y, 'r-')plt.subplot(2,2,2)plt.plot(data_x, data_y, 'b-')plt.subplot(2,2,4)plt.plot(data_x, data_y, 'g-')"
},
{
"code": null,
"e": 5878,
"s": 5516,
"text": "I have found that a helpful trick for understanding what is going on here is that “subplot” is a noun and “plot” is a verb. That is, plt.subplot(2,2,1) creates and focuses the program on the first subplot (going left-to-right, up-to-down) in a 2×2 grid. Then plt.plot(data_x, data_Y, 'r-') actively plots a red line using the provided data in the first subplot."
},
{
"code": null,
"e": 5981,
"s": 5878,
"text": "(🕵🏽♀️ Careful observers might also notice that the third subplot has been omitted in the above code.)"
},
{
"code": null,
"e": 6058,
"s": 5981,
"text": "Second, the same graph can be achieved through the object-oriented approach:"
},
{
"code": null,
"e": 6238,
"s": 6058,
"text": "fig, ax = plt.subplots(2,2)fig.set_facecolor('lightgrey')ax[0,0].plot(data_x, data_y, 'r-')ax[0,1].plot(data_x, data_y, 'b-')fig.delaxes(ax[1,0])ax[1,1].plot(data_x, data_y, 'g-')"
},
{
"code": null,
"e": 6651,
"s": 6238,
"text": "Here, the plt.subplots(2,2) (notice the additional s) has generated a comparable figure object (“ fig”) that holds a 2×2 array of subplots (or “axes” objects). Now, however, instead of focusing the program on a subplot and then plotting within that subplot, the object-oriented approach first retrieves the “axes” object from the ax array. Then, arguments within the axes method are responsible for the plotting."
},
{
"code": null,
"e": 6839,
"s": 6651,
"text": "(🕵🏽♀️ Notice that the third subplot, referred to here in array form as ax[1,0], is created and then deleted in the above code, rather than simply omitted as in the state-based approach.)"
},
{
"code": null,
"e": 7353,
"s": 6839,
"text": "Other than saving a line of code in the object-oriented approach, these subtle differences might seem inconsequential. But, for those still learning Pyplot, they should be warned that unknowingly mixing these methods can make for seemingly inexplicable coding snafus. The animation below shows, line-by-line, the fundamental differences in the state-based versus object-oriented processes. It takes only a little bit of imagination to see how trying to mix-and-match these processes could create quite a headache!"
},
{
"code": null,
"e": 7572,
"s": 7353,
"text": "For further experimentation in how these approaches differ from each other yet arrive at the same (or at least similar) results, plug-and-play with these snippets of Pyplot code for adding axis labels and graph titles:"
},
{
"code": null,
"e": 7644,
"s": 7572,
"text": "plt.suptitle(\"Your Title Here\")plt.xlabel(\"X Axis\")plt.ylabel(\"Y Axis\")"
},
{
"code": null,
"e": 7732,
"s": 7644,
"text": "fig.suptitle(\"Your Title Here\")ax[1,1].set_xlabel(\"X Axis\")ax[1,1].set_ylabel(\"Y Axis\")"
},
{
"code": null,
"e": 8029,
"s": 7732,
"text": "(💡 Hint: when experimenting with the above approaches, note how the position of the code relative to plt.subplot() makes a difference in the state-based approach in determining which axis gets titled, whereas the object-oriented approach is position-agnostic thanks to the array of axes objects.)"
},
{
"code": null,
"e": 8149,
"s": 8029,
"text": "For your convenience, a Jupyter Notebook is available on GitHub, containing the code used to generate the above graphs."
},
{
"code": null,
"e": 8316,
"s": 8149,
"text": "By now, you should have a solid foundation for understanding the dual nature of Pyplot’s interface, as well as having a small window into the DNA of coding languages."
},
{
"code": null,
"e": 8792,
"s": 8316,
"text": "If you would like to learn more about Pyplot’s dual nature, there are a number of online readings I found particularly helpful, including “The Lifecycle of a Plot” and “Effectively Using Matplotlib”. For more on object-oriented programming, “How to explain Object-Oriented Programming to a Six-Year-Old” was particularly illuminating. Finally, Ankit Gupta has helpful resources that contextualize the latest releases of Matplotlib within their historical development context."
}
] |
File Type Validation while Uploading it using JavaScript - GeeksforGeeks
|
30 Jul, 2021
In this article, we will learn how to implement file type validation by checking file extension before uploading it using Javascript. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time.
Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code. In this function we will use regex to check the type of file by the given pattern.
Below examples implement the above approach:
Example 1: In this example we upload file having extensions .jpeg/.jpg/.png/.gif only. We store an extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use regular expression and also preview the uploaded file if the uploaded file extension follows the file type.
<!DOCTYPE html><html> <head> <title> File Type Validation while Uploading it using JavaScript </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <h3> Validation of file type while uploading using JavaScript? </h3> <!-- File input field --> <p>Upload an Image</p> <input type="file" id="file" onchange="return fileValidation()" /> <!-- Image preview --> <div id="imagePreview"></div> <script> function fileValidation() { var fileInput = document.getElementById('file'); var filePath = fileInput.value; // Allowing file type var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i; if (!allowedExtensions.exec(filePath)) { alert('Invalid file type'); fileInput.value = ''; return false; } else { // Image preview if (fileInput.files && fileInput.files[0]) { var reader = new FileReader(); reader.onload = function(e) { document.getElementById( 'imagePreview').innerHTML = '<img src="' + e.target.result + '"/>'; }; reader.readAsDataURL(fileInput.files[0]); } } } </script></body> </html>
Output:
Example 2: Uploading the file having extensions .doc/.docx/.odt/.pdf/.tex/.txt/.rtf/.wps/.wks/.wpd only. Store the extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use a regular expression.
<!DOCTYPE html><html> <head> <title> File Type Validation while Uploading it using JavaScript </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <h3> Validation of file type while uploading using JavaScript? </h3> <!-- File input field --> <p>Upload an Image</p> <input type="file" id="file" onchange="return fileValidation()" /> <!-- Image preview --> <div id="imagePreview"></div> <script> function fileValidation() { var fileInput = document.getElementById('file'); var filePath = fileInput.value; // Allowing file type var allowedExtensions = /(\.doc|\.docx|\.odt|\.pdf|\.tex|\.txt|\.rtf|\.wps|\.wks|\.wpd)$/i; if (!allowedExtensions.exec(filePath)) { alert('Invalid file type'); fileInput.value = ''; return false; } } </script></body> </html>
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
|
[
{
"code": null,
"e": 24874,
"s": 24846,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25240,
"s": 24874,
"text": "In this article, we will learn how to implement file type validation by checking file extension before uploading it using Javascript. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time."
},
{
"code": null,
"e": 25627,
"s": 25240,
"text": "Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code. In this function we will use regex to check the type of file by the given pattern."
},
{
"code": null,
"e": 25672,
"s": 25627,
"text": "Below examples implement the above approach:"
},
{
"code": null,
"e": 26028,
"s": 25672,
"text": "Example 1: In this example we upload file having extensions .jpeg/.jpg/.png/.gif only. We store an extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use regular expression and also preview the uploaded file if the uploaded file extension follows the file type."
},
{
"code": "<!DOCTYPE html><html> <head> <title> File Type Validation while Uploading it using JavaScript </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <h3> Validation of file type while uploading using JavaScript? </h3> <!-- File input field --> <p>Upload an Image</p> <input type=\"file\" id=\"file\" onchange=\"return fileValidation()\" /> <!-- Image preview --> <div id=\"imagePreview\"></div> <script> function fileValidation() { var fileInput = document.getElementById('file'); var filePath = fileInput.value; // Allowing file type var allowedExtensions = /(\\.jpg|\\.jpeg|\\.png|\\.gif)$/i; if (!allowedExtensions.exec(filePath)) { alert('Invalid file type'); fileInput.value = ''; return false; } else { // Image preview if (fileInput.files && fileInput.files[0]) { var reader = new FileReader(); reader.onload = function(e) { document.getElementById( 'imagePreview').innerHTML = '<img src=\"' + e.target.result + '\"/>'; }; reader.readAsDataURL(fileInput.files[0]); } } } </script></body> </html>",
"e": 27736,
"s": 26028,
"text": null
},
{
"code": null,
"e": 27744,
"s": 27736,
"text": "Output:"
},
{
"code": null,
"e": 28030,
"s": 27744,
"text": "Example 2: Uploading the file having extensions .doc/.docx/.odt/.pdf/.tex/.txt/.rtf/.wps/.wks/.wpd only. Store the extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use a regular expression."
},
{
"code": "<!DOCTYPE html><html> <head> <title> File Type Validation while Uploading it using JavaScript </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1> GeeksforGeeks </h1> <h3> Validation of file type while uploading using JavaScript? </h3> <!-- File input field --> <p>Upload an Image</p> <input type=\"file\" id=\"file\" onchange=\"return fileValidation()\" /> <!-- Image preview --> <div id=\"imagePreview\"></div> <script> function fileValidation() { var fileInput = document.getElementById('file'); var filePath = fileInput.value; // Allowing file type var allowedExtensions = /(\\.doc|\\.docx|\\.odt|\\.pdf|\\.tex|\\.txt|\\.rtf|\\.wps|\\.wks|\\.wpd)$/i; if (!allowedExtensions.exec(filePath)) { alert('Invalid file type'); fileInput.value = ''; return false; } } </script></body> </html>",
"e": 29186,
"s": 28030,
"text": null
},
{
"code": null,
"e": 29194,
"s": 29186,
"text": "Output:"
},
{
"code": null,
"e": 29413,
"s": 29194,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 29607,
"s": 29413,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 29793,
"s": 29607,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 29802,
"s": 29793,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29812,
"s": 29802,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29828,
"s": 29812,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29835,
"s": 29828,
"text": "Picked"
},
{
"code": null,
"e": 29839,
"s": 29835,
"text": "CSS"
},
{
"code": null,
"e": 29844,
"s": 29839,
"text": "HTML"
},
{
"code": null,
"e": 29855,
"s": 29844,
"text": "JavaScript"
},
{
"code": null,
"e": 29872,
"s": 29855,
"text": "Web Technologies"
},
{
"code": null,
"e": 29899,
"s": 29872,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29904,
"s": 29899,
"text": "HTML"
},
{
"code": null,
"e": 30002,
"s": 29904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30060,
"s": 30002,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30097,
"s": 30060,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30161,
"s": 30097,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30202,
"s": 30161,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30239,
"s": 30202,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30299,
"s": 30239,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30360,
"s": 30299,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30413,
"s": 30360,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30463,
"s": 30413,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Advanced Ensemble Learning Techniques | by Charu Makhijani | Towards Data Science
|
In my previous post about ensemble learning, I have explained what is ensemble learning, how it relates with Bias and Variance in machine learning and what are the simple techniques of ensemble learning. If you haven’t read the post, please refer here.
In this post I will cover ensemble learning types, advanced ensemble learning methods — Bagging, Boosting, Stacking and Blending with code samples. At the end I will explain some pros and cons of using ensemble learning.
Ensemble learning methods can be categorized into two groups:
1. Sequential Ensemble Methods
In this method base learners are dependent on the results from previous base learners. Every subsequent base model corrects the prediction made by its predecessor fixing the errors in it. Hence the overall performance can be increased via improving the weight of previous labels.
2. Parallel Ensemble Methods
In this method there is no dependency between the base learners and all base learners execute in parallel and the results of all base models are combined in the end (using averaging for regression and voting for classification problems).
Parallel Ensemble methods are divided in two categories-
1. Homogeneous Parallel Ensemble Methods- In this method a single machine learning algorithm is used as a base learner.
2. Heterogeneous Parallel Ensemble Methods- In this method multiple machine learning algorithms are used as base learners.
Bagging or Bootstrap Aggregation is a parallel ensemble learning technique to reduce the variance in the final prediction.
The Bagging process is very similar to averaging, only difference is that bagging uses random sub-samples of the original dataset to train same/multiple models and then combines the prediction, whereas in averaging the same dataset is used to train models. Hence the technique is called Bootstrap Aggregation as it combines both Bootstrapping (or Sampling of data) and Aggregation to form an ensemble model.
Bagging is a 3 step process-
2. Model is built (either a classifier or a decision tree) with every sample.
3. Predictions of all the base models are combined (using averaging or weighted averaging for regression problems or majority voting for classification problems) to get the final result.
All three steps can be parallelized across different sub-samples, hence the training can be done faster when working on larger datasets.
In bagging, every base model is trained on a different subset of data and all the results are combined, so the final model is less overfitted and variance is reduced.
Bagging is more useful when the model is unstable, with stable models bagging is not useful in improving the performance. Model is called stable when it’s less sensitive for small fluctuations in the training data.
Some examples of Bagging are — Random Forest, Bagged Decision Trees, Extra Trees. sklearn library also provides BaggingClassifier and BaggingRegressor classes to create your own bagging algorithms.
Let's see this in the example below-
LogisticRegression :::: Mean: 0.7995780505454071 , Std Dev: 0.006888373667690784Bagging LogisticRegression :::: Mean: 0.8023420359806932 Std Dev: 0.00669463780099821 DecisionTreeClassifier :::: Mean: 0.8119073077604059 , Std Dev: 0.005729415273647502Bagging DecisionTreeClassifier :::: Mean: 0.849639923635328 Std Dev: 0.0046034229502244905 RandomForestClassifier :::: Mean: 0.8489381115139759 , Std Dev: 0.005116577814042257Bagging RandomForestClassifier :::: Mean: 0.8567037712754901 Std Dev: 0.004468761007278419 ExtraTreesClassifier :::: Mean: 0.8414792383547726 , Std Dev: 0.0064275238258043816Bagging ExtraTreesClassifier :::: Mean: 0.8511317483045042 Std Dev: 0.004708539080690846 KNeighborsClassifier :::: Mean: 0.8238853221249702 , Std Dev: 0.006423083088668752Bagging KNeighborsClassifier :::: Mean: 0.8396364017767104 Std Dev: 0.00599320955270458 VotingClassifier :::: Mean: 0.8462174468641986 Std Dev: 0.006423083088668752
As we see in the example, Bagging Classifiers are improving the variance of ML models and reducing the deviation. Same is the case when using VotingClassifier which improves the average variance of ML models.
Boosting is a sequential ensemble learning technique to convert weak base learners to strong learner that performs better and is less bias. The intuition here is that individual models may not perform very well on the entire dataset, but they work well on some part of the entire dataset. Hence each model in the ensemble actually boosts the overall performance.
Boosting is an iterative method that adjusts the weight of an observation based on the previous classification. If an observation was classified incorrectly, then the weight of that observation is increased in the next iteration. In the same way, if an observation was classified correctly then the weight of that observation is reduced in the next iteration.
Boosting is used to decrease the bias error, but it can also overfit the training data. That is why the parameter tuning is an important part of boosting algorithms to make them avoid overfitting the data.
Boosting was originally designed for classification problems but extended for regression problems as well.
Some examples of Boosting algorithms are — AdaBoost, Gradient Boosting Machine (GBM), XGBoost, LightGBM, CatBoost.
Lets see Boosting with an example-
AdaBoostClassifier :::: Mean: 0.8604337082284473 Std Dev: 0.0032409094349287403GradientBoostingClassifier :::: Mean: 0.8644262257222698 Std Dev: 0.0032315430892614675XGBClassifier :::: Mean: 0.8641189579917322 Std Dev: 0.004561102596800773VotingClassifier :::: Mean: 0.864645581703271 Std Dev: 0.0032985215353102735
Stacking, also known as stacked generalization, is an ensemble learning technique that combines multiple machine learning algorithms via meta learning (either a meta-classifier or a meta-regressor).
The base level algorithms are trained on entire training dataset, and then the meta model is trained on the predictions from all the base level models as features. The base models are called level-0 models, and meta model which combines the base models predictions is called level-1 model.
The level-1 model training data is prepared via k-fold cross-validation of the base models, and out-of-fold predictions (real numbers for regression and class labels for classification) are used as the training dataset.
The level-0 models can be either diverse range of algorithms or same algorithm (most often they are diverse). The level-1 meta model is most often a simple model, like Linear Regression for regression problems and Logistic Regression for Classification problems.
Stacking method can reduce the bias or variance based on the algorithms used in level-0.
There are many libraries for Stacking, like — StackingClassifier, StackingRegressor, make_classification, make_regression, ML Ensemble, H20.
Lets see Stacking with an example using StackingClassifier-
LogisticRegression :::: Mean: 0.799198344149096 Std Dev: 0.004958323931953346DecisionTreeClassifier :::: Mean: 0.8130779055654346 Std Dev: 0.008467878845801694KNeighborsClassifier :::: Mean: 0.8251287819886122 Std Dev: 0.00634438876282278SVC :::: Mean: 0.8004562250294449 Std Dev: 0.005221775246052317GaussianNB :::: Mean: 0.7964780515718138 Std Dev: 0.004996489474526567StackingClassifier :::: Mean: 0.8376917712960184 Std Dev: 0.005593816155570199
As we see in this example, we have used different ML models in the level0 and stacked them with StackingClassifier using LogisticRegression in level1, and it has improved the variance.
Multi-levels Stacking is an extension of stacking where stacking is applied on multiple layers.
For example in a 3-level stacking, Level-0 is same where diverse range of base learners are trained using k-fold cross validation. In level-1, instead of single meta model, N such meta models are used. In level-2, the final meta model is used that takes the predictions from N meta models of level-1 .
Adding multiple levels is both data expensive (as lots of data needed to be trained) and time expensive (as each layer adds multiple models).
Blending is most often used interchangeable with Stacking. And it is almost similar to Stacking with only one difference, Stacking uses out-of-fold predictions for the training set whereas Blending uses a hold-out (validation) set (10–20% of the training set) to train the next layer.
Although Blending is simpler than stacking and uses less data, the final model may overfit on the holdout set.
1. Ensemble methods have higher predictive accuracy, compared to the individual models.
2. Ensemble methods are very useful when there is both linear and non-linear type of data in the dataset; different models can be combined to handle this type of data.
3. With ensemble methods bias/variance can be reduced and most of the times, model is not underfitted/overfitted.
4. Ensemble of models is always less noisy and is more stable.
1. Ensembling is less interpretable, the output of the ensembled model is hard to predict and explain. Hence the idea with ensemble is hard to sell and get useful business insights.
2. The art of ensembling is hard to learn and any wrong selection can lead to lower predictive accuracy than an individual model.
3. Ensembling is expensive in terms of both time and space. Hence ROI can increase with ensembling.
After looking at the fundamentals of ensemble learning techniques above and the pros/cons of ensemble learning, it won’t be wrong to say that if used correctly ensemble methods are great for improving the overall performance of ML models. When its hard to rely on one model, ensemble makes the life easier and that’s the reason why in most of the ML competitions ensemble methods are the choices for winners.
Although selecting the right ensemble methods and using them is not an easy job but this art can be learned with experience. The techniques described in this post are most often reliable source for ensembling, but other variants are also possible based on specific problems/needs.
To access the complete code for the Advanced Ensemble Techniques, please check this Github link.
Thanks for the read. If you like the story please like, share and follow for more such content. As always, please reach out for any questions / comments / feedback.
Github: https://github.com/charumakhijaniLinkedIn: https://www.linkedin.com/in/charu-makhijani-23b18318/
|
[
{
"code": null,
"e": 424,
"s": 171,
"text": "In my previous post about ensemble learning, I have explained what is ensemble learning, how it relates with Bias and Variance in machine learning and what are the simple techniques of ensemble learning. If you haven’t read the post, please refer here."
},
{
"code": null,
"e": 645,
"s": 424,
"text": "In this post I will cover ensemble learning types, advanced ensemble learning methods — Bagging, Boosting, Stacking and Blending with code samples. At the end I will explain some pros and cons of using ensemble learning."
},
{
"code": null,
"e": 707,
"s": 645,
"text": "Ensemble learning methods can be categorized into two groups:"
},
{
"code": null,
"e": 738,
"s": 707,
"text": "1. Sequential Ensemble Methods"
},
{
"code": null,
"e": 1018,
"s": 738,
"text": "In this method base learners are dependent on the results from previous base learners. Every subsequent base model corrects the prediction made by its predecessor fixing the errors in it. Hence the overall performance can be increased via improving the weight of previous labels."
},
{
"code": null,
"e": 1047,
"s": 1018,
"text": "2. Parallel Ensemble Methods"
},
{
"code": null,
"e": 1285,
"s": 1047,
"text": "In this method there is no dependency between the base learners and all base learners execute in parallel and the results of all base models are combined in the end (using averaging for regression and voting for classification problems)."
},
{
"code": null,
"e": 1342,
"s": 1285,
"text": "Parallel Ensemble methods are divided in two categories-"
},
{
"code": null,
"e": 1462,
"s": 1342,
"text": "1. Homogeneous Parallel Ensemble Methods- In this method a single machine learning algorithm is used as a base learner."
},
{
"code": null,
"e": 1585,
"s": 1462,
"text": "2. Heterogeneous Parallel Ensemble Methods- In this method multiple machine learning algorithms are used as base learners."
},
{
"code": null,
"e": 1708,
"s": 1585,
"text": "Bagging or Bootstrap Aggregation is a parallel ensemble learning technique to reduce the variance in the final prediction."
},
{
"code": null,
"e": 2116,
"s": 1708,
"text": "The Bagging process is very similar to averaging, only difference is that bagging uses random sub-samples of the original dataset to train same/multiple models and then combines the prediction, whereas in averaging the same dataset is used to train models. Hence the technique is called Bootstrap Aggregation as it combines both Bootstrapping (or Sampling of data) and Aggregation to form an ensemble model."
},
{
"code": null,
"e": 2145,
"s": 2116,
"text": "Bagging is a 3 step process-"
},
{
"code": null,
"e": 2223,
"s": 2145,
"text": "2. Model is built (either a classifier or a decision tree) with every sample."
},
{
"code": null,
"e": 2410,
"s": 2223,
"text": "3. Predictions of all the base models are combined (using averaging or weighted averaging for regression problems or majority voting for classification problems) to get the final result."
},
{
"code": null,
"e": 2547,
"s": 2410,
"text": "All three steps can be parallelized across different sub-samples, hence the training can be done faster when working on larger datasets."
},
{
"code": null,
"e": 2714,
"s": 2547,
"text": "In bagging, every base model is trained on a different subset of data and all the results are combined, so the final model is less overfitted and variance is reduced."
},
{
"code": null,
"e": 2929,
"s": 2714,
"text": "Bagging is more useful when the model is unstable, with stable models bagging is not useful in improving the performance. Model is called stable when it’s less sensitive for small fluctuations in the training data."
},
{
"code": null,
"e": 3127,
"s": 2929,
"text": "Some examples of Bagging are — Random Forest, Bagged Decision Trees, Extra Trees. sklearn library also provides BaggingClassifier and BaggingRegressor classes to create your own bagging algorithms."
},
{
"code": null,
"e": 3164,
"s": 3127,
"text": "Let's see this in the example below-"
},
{
"code": null,
"e": 4099,
"s": 3164,
"text": "LogisticRegression :::: Mean: 0.7995780505454071 , Std Dev: 0.006888373667690784Bagging LogisticRegression :::: Mean: 0.8023420359806932 Std Dev: 0.00669463780099821 DecisionTreeClassifier :::: Mean: 0.8119073077604059 , Std Dev: 0.005729415273647502Bagging DecisionTreeClassifier :::: Mean: 0.849639923635328 Std Dev: 0.0046034229502244905 RandomForestClassifier :::: Mean: 0.8489381115139759 , Std Dev: 0.005116577814042257Bagging RandomForestClassifier :::: Mean: 0.8567037712754901 Std Dev: 0.004468761007278419 ExtraTreesClassifier :::: Mean: 0.8414792383547726 , Std Dev: 0.0064275238258043816Bagging ExtraTreesClassifier :::: Mean: 0.8511317483045042 Std Dev: 0.004708539080690846 KNeighborsClassifier :::: Mean: 0.8238853221249702 , Std Dev: 0.006423083088668752Bagging KNeighborsClassifier :::: Mean: 0.8396364017767104 Std Dev: 0.00599320955270458 VotingClassifier :::: Mean: 0.8462174468641986 Std Dev: 0.006423083088668752"
},
{
"code": null,
"e": 4308,
"s": 4099,
"text": "As we see in the example, Bagging Classifiers are improving the variance of ML models and reducing the deviation. Same is the case when using VotingClassifier which improves the average variance of ML models."
},
{
"code": null,
"e": 4671,
"s": 4308,
"text": "Boosting is a sequential ensemble learning technique to convert weak base learners to strong learner that performs better and is less bias. The intuition here is that individual models may not perform very well on the entire dataset, but they work well on some part of the entire dataset. Hence each model in the ensemble actually boosts the overall performance."
},
{
"code": null,
"e": 5031,
"s": 4671,
"text": "Boosting is an iterative method that adjusts the weight of an observation based on the previous classification. If an observation was classified incorrectly, then the weight of that observation is increased in the next iteration. In the same way, if an observation was classified correctly then the weight of that observation is reduced in the next iteration."
},
{
"code": null,
"e": 5237,
"s": 5031,
"text": "Boosting is used to decrease the bias error, but it can also overfit the training data. That is why the parameter tuning is an important part of boosting algorithms to make them avoid overfitting the data."
},
{
"code": null,
"e": 5344,
"s": 5237,
"text": "Boosting was originally designed for classification problems but extended for regression problems as well."
},
{
"code": null,
"e": 5459,
"s": 5344,
"text": "Some examples of Boosting algorithms are — AdaBoost, Gradient Boosting Machine (GBM), XGBoost, LightGBM, CatBoost."
},
{
"code": null,
"e": 5494,
"s": 5459,
"text": "Lets see Boosting with an example-"
},
{
"code": null,
"e": 5810,
"s": 5494,
"text": "AdaBoostClassifier :::: Mean: 0.8604337082284473 Std Dev: 0.0032409094349287403GradientBoostingClassifier :::: Mean: 0.8644262257222698 Std Dev: 0.0032315430892614675XGBClassifier :::: Mean: 0.8641189579917322 Std Dev: 0.004561102596800773VotingClassifier :::: Mean: 0.864645581703271 Std Dev: 0.0032985215353102735"
},
{
"code": null,
"e": 6009,
"s": 5810,
"text": "Stacking, also known as stacked generalization, is an ensemble learning technique that combines multiple machine learning algorithms via meta learning (either a meta-classifier or a meta-regressor)."
},
{
"code": null,
"e": 6299,
"s": 6009,
"text": "The base level algorithms are trained on entire training dataset, and then the meta model is trained on the predictions from all the base level models as features. The base models are called level-0 models, and meta model which combines the base models predictions is called level-1 model."
},
{
"code": null,
"e": 6519,
"s": 6299,
"text": "The level-1 model training data is prepared via k-fold cross-validation of the base models, and out-of-fold predictions (real numbers for regression and class labels for classification) are used as the training dataset."
},
{
"code": null,
"e": 6782,
"s": 6519,
"text": "The level-0 models can be either diverse range of algorithms or same algorithm (most often they are diverse). The level-1 meta model is most often a simple model, like Linear Regression for regression problems and Logistic Regression for Classification problems."
},
{
"code": null,
"e": 6871,
"s": 6782,
"text": "Stacking method can reduce the bias or variance based on the algorithms used in level-0."
},
{
"code": null,
"e": 7012,
"s": 6871,
"text": "There are many libraries for Stacking, like — StackingClassifier, StackingRegressor, make_classification, make_regression, ML Ensemble, H20."
},
{
"code": null,
"e": 7072,
"s": 7012,
"text": "Lets see Stacking with an example using StackingClassifier-"
},
{
"code": null,
"e": 7522,
"s": 7072,
"text": "LogisticRegression :::: Mean: 0.799198344149096 Std Dev: 0.004958323931953346DecisionTreeClassifier :::: Mean: 0.8130779055654346 Std Dev: 0.008467878845801694KNeighborsClassifier :::: Mean: 0.8251287819886122 Std Dev: 0.00634438876282278SVC :::: Mean: 0.8004562250294449 Std Dev: 0.005221775246052317GaussianNB :::: Mean: 0.7964780515718138 Std Dev: 0.004996489474526567StackingClassifier :::: Mean: 0.8376917712960184 Std Dev: 0.005593816155570199"
},
{
"code": null,
"e": 7707,
"s": 7522,
"text": "As we see in this example, we have used different ML models in the level0 and stacked them with StackingClassifier using LogisticRegression in level1, and it has improved the variance."
},
{
"code": null,
"e": 7803,
"s": 7707,
"text": "Multi-levels Stacking is an extension of stacking where stacking is applied on multiple layers."
},
{
"code": null,
"e": 8105,
"s": 7803,
"text": "For example in a 3-level stacking, Level-0 is same where diverse range of base learners are trained using k-fold cross validation. In level-1, instead of single meta model, N such meta models are used. In level-2, the final meta model is used that takes the predictions from N meta models of level-1 ."
},
{
"code": null,
"e": 8247,
"s": 8105,
"text": "Adding multiple levels is both data expensive (as lots of data needed to be trained) and time expensive (as each layer adds multiple models)."
},
{
"code": null,
"e": 8532,
"s": 8247,
"text": "Blending is most often used interchangeable with Stacking. And it is almost similar to Stacking with only one difference, Stacking uses out-of-fold predictions for the training set whereas Blending uses a hold-out (validation) set (10–20% of the training set) to train the next layer."
},
{
"code": null,
"e": 8643,
"s": 8532,
"text": "Although Blending is simpler than stacking and uses less data, the final model may overfit on the holdout set."
},
{
"code": null,
"e": 8731,
"s": 8643,
"text": "1. Ensemble methods have higher predictive accuracy, compared to the individual models."
},
{
"code": null,
"e": 8899,
"s": 8731,
"text": "2. Ensemble methods are very useful when there is both linear and non-linear type of data in the dataset; different models can be combined to handle this type of data."
},
{
"code": null,
"e": 9013,
"s": 8899,
"text": "3. With ensemble methods bias/variance can be reduced and most of the times, model is not underfitted/overfitted."
},
{
"code": null,
"e": 9076,
"s": 9013,
"text": "4. Ensemble of models is always less noisy and is more stable."
},
{
"code": null,
"e": 9258,
"s": 9076,
"text": "1. Ensembling is less interpretable, the output of the ensembled model is hard to predict and explain. Hence the idea with ensemble is hard to sell and get useful business insights."
},
{
"code": null,
"e": 9388,
"s": 9258,
"text": "2. The art of ensembling is hard to learn and any wrong selection can lead to lower predictive accuracy than an individual model."
},
{
"code": null,
"e": 9488,
"s": 9388,
"text": "3. Ensembling is expensive in terms of both time and space. Hence ROI can increase with ensembling."
},
{
"code": null,
"e": 9897,
"s": 9488,
"text": "After looking at the fundamentals of ensemble learning techniques above and the pros/cons of ensemble learning, it won’t be wrong to say that if used correctly ensemble methods are great for improving the overall performance of ML models. When its hard to rely on one model, ensemble makes the life easier and that’s the reason why in most of the ML competitions ensemble methods are the choices for winners."
},
{
"code": null,
"e": 10178,
"s": 9897,
"text": "Although selecting the right ensemble methods and using them is not an easy job but this art can be learned with experience. The techniques described in this post are most often reliable source for ensembling, but other variants are also possible based on specific problems/needs."
},
{
"code": null,
"e": 10275,
"s": 10178,
"text": "To access the complete code for the Advanced Ensemble Techniques, please check this Github link."
},
{
"code": null,
"e": 10440,
"s": 10275,
"text": "Thanks for the read. If you like the story please like, share and follow for more such content. As always, please reach out for any questions / comments / feedback."
}
] |
Expedia Coding Round Experience - Intern 2021 - GeeksforGeeks
|
24 Jun, 2021
Coding problems for Expedia Inten 2021: There were 2 coding questions and 6 MCQ’s for the coding round of the Expedia 2021 Intern Round.
Question 1: A number of ways to divide objects into groups, such that no group will have fewer objects than previously formed groups?
Example:
objects=8, groups=4 Answer: 5
[1,1,1,5], [1,1,2,4], [1,1,3,3], [1,2,2,3], [2,2,2,2]
Input:
8 4
Output:
5
Solution:
Simple Approach: This problem can be solved by using recursion.
C++
// C++ program to count the// number of ways to divide objetcs in// groups. #include <bits/stdc++.h> using namespace std; // Function to count the number// of ways to divide the number objects// in groups.int count(int pos, int prev, int objects, int groups){ if (pos == groups) { if (objects == 0) return 1; else return 0; } // if objects is divides completely // into less than groups if (objects == 0) return 0; int solution = 0; // put all possible values // greater equal to prev for (int i = prev; i <= objects; i++) { solution += count(pos + 1, i, objects - i, groups); } return solution;} // Function to count the number of// ways to divide into objectsint WaysToGo(int objects, int groups){ return count(0, 1, objects, groups);} // Main Codeint main(){ int objects, groups; objects = 8; groups = 4; cout << WaysToGo(objects, groups); return 0;}
Time complexity: O(ObjectGroups)
Dynamic Approach: The above approach will fail as time complexity will exceed, so we will apply Dynamic Programming.
C++
// C++ implementation to count the// number of ways to divide objects in// groups. #include <bits/stdc++.h> using namespace std;// DP 3DArrayint dp[500][500][500]; // Function to count the number// of ways to divide the objects// in groups.int count(int pos, int prev, int objects, int groups){ // Base Case if (pos == groups) { if (left == 0) return 1; else return 0; } // if objects is divides completely // into groups if (objects == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][objects] != -1) return dp[pos][prev][objects]; int solution = 0; // put all possible values // greater equal to prev for (int i = prev; i <= objects; i++) { solution += count(pos + 1, i, objects - i, groups); } return dp[pos][prev][objects] = solution;} // Function to count the number of// ways to divide into groupsint WaystoDivide(int objects, int groups){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return count(0, 1, objects, groups);} // Main Codeint main(){ int objects, groups; objects = 8; groups = 4; cout << WaystoDivide(objects, groups); return 0;}
Question 2: Minimum number of distinct elements after removing m items
Given an array of items, and i-th index element denotes the item id’s and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct IDs.
Examples:
Input : arr[] = { 2, 2, 1, 3, 3, 3}
m = 3
Output : 1
Remove 1 and both 2's.So, only 3 will be
left that's why distinct id is 1.
Input : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3}
m = 2
Output : 3
Remove 2 and 4 completely. So, remaining ids
are 1, 3 and 5 i.e. 3
C++
#include <bits/stdc++.h>using namespace std; // Function to find distintc id'sint distIds(int a[], int n, int m){ unordered_map<int, int> mi; vector<pair<int, int> > v; int count = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) mi[a[i]]++; // Store into the vector second as first and vice-versa for (auto it = mi.begin(); it != mi.end(); it++) v.push_back(make_pair(it->second, it->first)); // Sort the vector sort(v.begin(), v.end()); int size = v.size(); // Start removing elements from the beginning for (int i = 0; i < size; i++) { // Remove if current value is less than // or equal to m if (v[i].first <= m) { m -= v[i].first; count++; } // Return the remaining size else return size - count; } return size - count;} // Main codeint main(){ int arr[] = { 2, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 3; cout << distIds(arr, n, m); return 0;}
Time Complexity: O(n log n)
Expedia
Internship
Interview Experiences
Expedia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Interview Experience for Internship (Via Engage)
Persistent Systems Interview Experience (Martian Program)
Zoho Interview Experience (Off-Campus ) 2022
Zoho Corporation (Internship cum Offer Experience )
HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Questions
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience
Microsoft Interview Experience for Internship (Via Engage)
|
[
{
"code": null,
"e": 25500,
"s": 25472,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 25637,
"s": 25500,
"text": "Coding problems for Expedia Inten 2021: There were 2 coding questions and 6 MCQ’s for the coding round of the Expedia 2021 Intern Round."
},
{
"code": null,
"e": 25771,
"s": 25637,
"text": "Question 1: A number of ways to divide objects into groups, such that no group will have fewer objects than previously formed groups?"
},
{
"code": null,
"e": 25781,
"s": 25771,
"text": "Example: "
},
{
"code": null,
"e": 25887,
"s": 25781,
"text": "objects=8, groups=4 Answer: 5\n[1,1,1,5], [1,1,2,4], [1,1,3,3], [1,2,2,3], [2,2,2,2]\nInput:\n8 4 \nOutput:\n5"
},
{
"code": null,
"e": 25898,
"s": 25887,
"text": "Solution: "
},
{
"code": null,
"e": 25962,
"s": 25898,
"text": "Simple Approach: This problem can be solved by using recursion."
},
{
"code": null,
"e": 25968,
"s": 25964,
"text": "C++"
},
{
"code": "// C++ program to count the// number of ways to divide objetcs in// groups. #include <bits/stdc++.h> using namespace std; // Function to count the number// of ways to divide the number objects// in groups.int count(int pos, int prev, int objects, int groups){ if (pos == groups) { if (objects == 0) return 1; else return 0; } // if objects is divides completely // into less than groups if (objects == 0) return 0; int solution = 0; // put all possible values // greater equal to prev for (int i = prev; i <= objects; i++) { solution += count(pos + 1, i, objects - i, groups); } return solution;} // Function to count the number of// ways to divide into objectsint WaysToGo(int objects, int groups){ return count(0, 1, objects, groups);} // Main Codeint main(){ int objects, groups; objects = 8; groups = 4; cout << WaysToGo(objects, groups); return 0;}",
"e": 26927,
"s": 25968,
"text": null
},
{
"code": null,
"e": 26962,
"s": 26929,
"text": "Time complexity: O(ObjectGroups)"
},
{
"code": null,
"e": 27079,
"s": 26962,
"text": "Dynamic Approach: The above approach will fail as time complexity will exceed, so we will apply Dynamic Programming."
},
{
"code": null,
"e": 27085,
"s": 27081,
"text": "C++"
},
{
"code": "// C++ implementation to count the// number of ways to divide objects in// groups. #include <bits/stdc++.h> using namespace std;// DP 3DArrayint dp[500][500][500]; // Function to count the number// of ways to divide the objects// in groups.int count(int pos, int prev, int objects, int groups){ // Base Case if (pos == groups) { if (left == 0) return 1; else return 0; } // if objects is divides completely // into groups if (objects == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][objects] != -1) return dp[pos][prev][objects]; int solution = 0; // put all possible values // greater equal to prev for (int i = prev; i <= objects; i++) { solution += count(pos + 1, i, objects - i, groups); } return dp[pos][prev][objects] = solution;} // Function to count the number of// ways to divide into groupsint WaystoDivide(int objects, int groups){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return count(0, 1, objects, groups);} // Main Codeint main(){ int objects, groups; objects = 8; groups = 4; cout << WaystoDivide(objects, groups); return 0;}",
"e": 28313,
"s": 27085,
"text": null
},
{
"code": null,
"e": 28384,
"s": 28313,
"text": "Question 2: Minimum number of distinct elements after removing m items"
},
{
"code": null,
"e": 28597,
"s": 28384,
"text": "Given an array of items, and i-th index element denotes the item id’s and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct IDs."
},
{
"code": null,
"e": 28607,
"s": 28597,
"text": "Examples:"
},
{
"code": null,
"e": 28671,
"s": 28607,
"text": "Input : arr[] = { 2, 2, 1, 3, 3, 3}\n m = 3\nOutput : 1"
},
{
"code": null,
"e": 28883,
"s": 28671,
"text": "Remove 1 and both 2's.So, only 3 will be\nleft that's why distinct id is 1.\nInput : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3}\n m = 2\nOutput : 3\nRemove 2 and 4 completely. So, remaining ids\nare 1, 3 and 5 i.e. 3"
},
{
"code": null,
"e": 28887,
"s": 28883,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find distintc id'sint distIds(int a[], int n, int m){ unordered_map<int, int> mi; vector<pair<int, int> > v; int count = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) mi[a[i]]++; // Store into the vector second as first and vice-versa for (auto it = mi.begin(); it != mi.end(); it++) v.push_back(make_pair(it->second, it->first)); // Sort the vector sort(v.begin(), v.end()); int size = v.size(); // Start removing elements from the beginning for (int i = 0; i < size; i++) { // Remove if current value is less than // or equal to m if (v[i].first <= m) { m -= v[i].first; count++; } // Return the remaining size else return size - count; } return size - count;} // Main codeint main(){ int arr[] = { 2, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 3; cout << distIds(arr, n, m); return 0;}",
"e": 29927,
"s": 28887,
"text": null
},
{
"code": null,
"e": 29955,
"s": 29927,
"text": "Time Complexity: O(n log n)"
},
{
"code": null,
"e": 29963,
"s": 29955,
"text": "Expedia"
},
{
"code": null,
"e": 29974,
"s": 29963,
"text": "Internship"
},
{
"code": null,
"e": 29996,
"s": 29974,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30004,
"s": 29996,
"text": "Expedia"
},
{
"code": null,
"e": 30102,
"s": 30004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30161,
"s": 30102,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 30219,
"s": 30161,
"text": "Persistent Systems Interview Experience (Martian Program)"
},
{
"code": null,
"e": 30264,
"s": 30219,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 30316,
"s": 30264,
"text": "Zoho Corporation (Internship cum Offer Experience )"
},
{
"code": null,
"e": 30397,
"s": 30316,
"text": "HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022"
},
{
"code": null,
"e": 30457,
"s": 30397,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 30484,
"s": 30457,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 30534,
"s": 30484,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 30562,
"s": 30534,
"text": "Amazon Interview Experience"
}
] |
Python Program to Print all Integers that Aren't Divisible by Either 2 or 3 - GeeksforGeeks
|
26 Nov, 2020
We can input a set of integer, and check which integers in this range, beginning with 1 are not divisible by 2 or 3, by checking the remainder of the integer with 2 and 3.
Example:
Input: 10
Output: Numbers not divisible by 2 and 3
1
5
7
Method 1: We check if the number is not divisible by 2 and 3 using the and clause, then outputs the number.
Python3
# input the maximum number to# which you want to sendmax_num = 20 # starting numbers from 0n = 1 # run until it reaches maximum numberprint("Numbers not divisible by 2 and 3")while n <= max_num: # check if number is divisible by 2 and 3 if n % 2 != 0 and n % 3 != 0: print(n) # incrementing the counter n = n+1
Output:
Numbers not divisible by 2 and 3
1
5
7
11
13
17
19
Method 2: We traverse the odd numbers starting with 1 since even numbers are divisible by 2. So, we increment the for a loop by 2, traversing only odd numbers and check, which one of them is not divisible by 3. This approach is better than the previous one since it only iterates through half the number of elements in the specified range.
The following Python code illustrates this :
Python3
# input the maximum number to# which you want to sendmax_num = 40print("Numbers not divisible by 2 or 3 : ") # run until it reaches maximum number# we increment the loop by +2 each time,# since odd numbers are not divisible by 2for i in range(1, max_num, 2): # check if number is not divisible by 3 if i % 3 != 0: print(i)
Output:
Numbers not divisible by 2 or 3 :
1
5
7
11
13
17
19
23
25
29
31
35
37
Number Divisibility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24074,
"s": 23901,
"text": "We can input a set of integer, and check which integers in this range, beginning with 1 are not divisible by 2 or 3, by checking the remainder of the integer with 2 and 3. "
},
{
"code": null,
"e": 24083,
"s": 24074,
"text": "Example:"
},
{
"code": null,
"e": 24141,
"s": 24083,
"text": "Input: 10\nOutput: Numbers not divisible by 2 and 3\n1\n5\n7\n"
},
{
"code": null,
"e": 24250,
"s": 24141,
"text": "Method 1: We check if the number is not divisible by 2 and 3 using the and clause, then outputs the number. "
},
{
"code": null,
"e": 24258,
"s": 24250,
"text": "Python3"
},
{
"code": "# input the maximum number to# which you want to sendmax_num = 20 # starting numbers from 0n = 1 # run until it reaches maximum numberprint(\"Numbers not divisible by 2 and 3\")while n <= max_num: # check if number is divisible by 2 and 3 if n % 2 != 0 and n % 3 != 0: print(n) # incrementing the counter n = n+1",
"e": 24602,
"s": 24258,
"text": null
},
{
"code": null,
"e": 24610,
"s": 24602,
"text": "Output:"
},
{
"code": null,
"e": 24661,
"s": 24610,
"text": "Numbers not divisible by 2 and 3\n1\n5\n7\n11\n13\n17\n19"
},
{
"code": null,
"e": 25001,
"s": 24661,
"text": "Method 2: We traverse the odd numbers starting with 1 since even numbers are divisible by 2. So, we increment the for a loop by 2, traversing only odd numbers and check, which one of them is not divisible by 3. This approach is better than the previous one since it only iterates through half the number of elements in the specified range."
},
{
"code": null,
"e": 25047,
"s": 25001,
"text": "The following Python code illustrates this : "
},
{
"code": null,
"e": 25055,
"s": 25047,
"text": "Python3"
},
{
"code": "# input the maximum number to# which you want to sendmax_num = 40print(\"Numbers not divisible by 2 or 3 : \") # run until it reaches maximum number# we increment the loop by +2 each time,# since odd numbers are not divisible by 2for i in range(1, max_num, 2): # check if number is not divisible by 3 if i % 3 != 0: print(i)",
"e": 25399,
"s": 25055,
"text": null
},
{
"code": null,
"e": 25407,
"s": 25399,
"text": "Output:"
},
{
"code": null,
"e": 25479,
"s": 25407,
"text": "Numbers not divisible by 2 or 3 : \n1\n5\n7\n11\n13\n17\n19\n23\n25\n29\n31\n35\n37\n"
},
{
"code": null,
"e": 25499,
"s": 25479,
"text": "Number Divisibility"
},
{
"code": null,
"e": 25506,
"s": 25499,
"text": "Python"
},
{
"code": null,
"e": 25522,
"s": 25506,
"text": "Python Programs"
},
{
"code": null,
"e": 25620,
"s": 25522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25629,
"s": 25620,
"text": "Comments"
},
{
"code": null,
"e": 25642,
"s": 25629,
"text": "Old Comments"
},
{
"code": null,
"e": 25678,
"s": 25642,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25717,
"s": 25678,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25740,
"s": 25717,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25791,
"s": 25740,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 25823,
"s": 25791,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 25845,
"s": 25823,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25884,
"s": 25845,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25930,
"s": 25884,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 25987,
"s": 25930,
"text": "Python program to check whether a number is Prime or not"
}
] |
Object-Oriented Programming in Python — Corey Schafer & DataCamp | by Md Arman Hossen | Towards Data Science
|
Object-oriented programming (OOP) is a programming paradigm based on “object” which is a way to define something in a programming language containing variable as “field/attributes” and functions as “method”. OOP allows programmers to create their own objects that have methods and attributes. OOP allows a user to create their own object which is repeatable and organized.
In this article, I’ve tried to summarize my ideas on OOP in python. I would like to thank Jose Marcial Portilla, DataCamp Team and Corey Schaffer for their amazing descriptive tutorials. It helps me a lot. I’ll try to add a GitHub repository ASAP for this.
Class is a reusable chunk of code that has methods and variables. Precisely class is a template for an object. Classes allow us to logically group our data and functions in a way that’s easy to reuse and also easy to build upon if need be. Here data and functions are called attributes and methods. In the below figure a class Datashell is defined without passing any attributes. passdoesn’t do anything, it's just a placeholder.
selfrepresents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods. Anything can be used in place of selfbut to make it sensible to others we should use self. To print a method we need to use parentheses()at the end. If we skip()then it only prints the method instead of the return value. Class, method, and instances are being described clearly describe through the below figure.
<blockquote>
In OOP, variables at the class level are referred to as class variables, whereas variables at the object level are called instance variables. In the following figure general form and an example of a class variable is delineated. Here ‘spam’ is defined as class variable data which is being used as instance variable later in several methods.
If we change the class variable through calling class then the value will be changed in all places whereas if we change variable through instances then only that vale will be changed. Suppose if we change the value of data to “not spam” then all values of instances including data will be changed but if we change the instance variable in any method then it will be only within that method.
Regular methods automatically pass the instances as the first argument and we call it self. Class methods automatically pass the class as the first argument and we call it cls . Static methods don’t pass anything automatically, they don’t pass instances or class, they behave just like a regular function and they have some logical connection with the class. The methods mentioned in all the above examples are regular methods. But for class method and static method we need to mention it [@classmethod / @staticmethod ] before apply.
@classmethoddef set_raise(cls,amount): cls.raise = amount
Inheritance allows us to inherit attributes and methods from a parent class. it's the ability to reuse and reduce complexity. We can create subclasses and get all the functionality of our parent class and then we can overwrite or add completely new functionality without affecting the parent class in any way. Inheritance is being described clearly through the below example.
Now if we want to copy any attribute from another class and add more attributes on it then we can do it following ways. We can either use super() whereselfshould be avoided or we can call the class directly mentioningself.
class hi(hello): def __init__(self, name, age): super().__init__(data)or "hello.__init__(self, data)"
Special methods allow us to emulate some built-in behavior within python. By defining our own special methods we’ll be able to change some of the built-in behavior and operations. Special methods are always surrounded by __method__. A lot of people call them double underscore Dunder. Here are some common special methods:
__init__(self) : implicitly called when we create our objects and it sets all attributes.
__repr__(self) : unambiguous representation of the object and should be used for debugging and logging
__str__(self) : readable representation of an object and meant to be used as a display to the end-user.
__add__(self) : to add objects.
__len__(self) : to generate the length of objects.
Property decorator allows us to define a method but we can access it like an attribute. In the following example name is a method but we can call it like an attribute.
That’s the end of my knowledge about OOP in python. I’ve tried my best to describe in detail within my limit. It’ll be highly appreciated if you can make comments or critics on this. I’m not from CS background and still, I’m learning each and every day. If you like this article then you can check my other article on Markdown Cells — Jupyter Notebook.
|
[
{
"code": null,
"e": 544,
"s": 171,
"text": "Object-oriented programming (OOP) is a programming paradigm based on “object” which is a way to define something in a programming language containing variable as “field/attributes” and functions as “method”. OOP allows programmers to create their own objects that have methods and attributes. OOP allows a user to create their own object which is repeatable and organized."
},
{
"code": null,
"e": 801,
"s": 544,
"text": "In this article, I’ve tried to summarize my ideas on OOP in python. I would like to thank Jose Marcial Portilla, DataCamp Team and Corey Schaffer for their amazing descriptive tutorials. It helps me a lot. I’ll try to add a GitHub repository ASAP for this."
},
{
"code": null,
"e": 1231,
"s": 801,
"text": "Class is a reusable chunk of code that has methods and variables. Precisely class is a template for an object. Classes allow us to logically group our data and functions in a way that’s easy to reuse and also easy to build upon if need be. Here data and functions are called attributes and methods. In the below figure a class Datashell is defined without passing any attributes. passdoesn’t do anything, it's just a placeholder."
},
{
"code": null,
"e": 1673,
"s": 1231,
"text": "selfrepresents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods. Anything can be used in place of selfbut to make it sensible to others we should use self. To print a method we need to use parentheses()at the end. If we skip()then it only prints the method instead of the return value. Class, method, and instances are being described clearly describe through the below figure."
},
{
"code": null,
"e": 1686,
"s": 1673,
"text": "<blockquote>"
},
{
"code": null,
"e": 2028,
"s": 1686,
"text": "In OOP, variables at the class level are referred to as class variables, whereas variables at the object level are called instance variables. In the following figure general form and an example of a class variable is delineated. Here ‘spam’ is defined as class variable data which is being used as instance variable later in several methods."
},
{
"code": null,
"e": 2419,
"s": 2028,
"text": "If we change the class variable through calling class then the value will be changed in all places whereas if we change variable through instances then only that vale will be changed. Suppose if we change the value of data to “not spam” then all values of instances including data will be changed but if we change the instance variable in any method then it will be only within that method."
},
{
"code": null,
"e": 2954,
"s": 2419,
"text": "Regular methods automatically pass the instances as the first argument and we call it self. Class methods automatically pass the class as the first argument and we call it cls . Static methods don’t pass anything automatically, they don’t pass instances or class, they behave just like a regular function and they have some logical connection with the class. The methods mentioned in all the above examples are regular methods. But for class method and static method we need to mention it [@classmethod / @staticmethod ] before apply."
},
{
"code": null,
"e": 3015,
"s": 2954,
"text": "@classmethoddef set_raise(cls,amount): cls.raise = amount"
},
{
"code": null,
"e": 3391,
"s": 3015,
"text": "Inheritance allows us to inherit attributes and methods from a parent class. it's the ability to reuse and reduce complexity. We can create subclasses and get all the functionality of our parent class and then we can overwrite or add completely new functionality without affecting the parent class in any way. Inheritance is being described clearly through the below example."
},
{
"code": null,
"e": 3614,
"s": 3391,
"text": "Now if we want to copy any attribute from another class and add more attributes on it then we can do it following ways. We can either use super() whereselfshould be avoided or we can call the class directly mentioningself."
},
{
"code": null,
"e": 3731,
"s": 3614,
"text": "class hi(hello): def __init__(self, name, age): super().__init__(data)or \"hello.__init__(self, data)\""
},
{
"code": null,
"e": 4054,
"s": 3731,
"text": "Special methods allow us to emulate some built-in behavior within python. By defining our own special methods we’ll be able to change some of the built-in behavior and operations. Special methods are always surrounded by __method__. A lot of people call them double underscore Dunder. Here are some common special methods:"
},
{
"code": null,
"e": 4144,
"s": 4054,
"text": "__init__(self) : implicitly called when we create our objects and it sets all attributes."
},
{
"code": null,
"e": 4247,
"s": 4144,
"text": "__repr__(self) : unambiguous representation of the object and should be used for debugging and logging"
},
{
"code": null,
"e": 4351,
"s": 4247,
"text": "__str__(self) : readable representation of an object and meant to be used as a display to the end-user."
},
{
"code": null,
"e": 4383,
"s": 4351,
"text": "__add__(self) : to add objects."
},
{
"code": null,
"e": 4434,
"s": 4383,
"text": "__len__(self) : to generate the length of objects."
},
{
"code": null,
"e": 4602,
"s": 4434,
"text": "Property decorator allows us to define a method but we can access it like an attribute. In the following example name is a method but we can call it like an attribute."
}
] |
How to Force User to Change Password at Next Login in Linux?
|
Because of security concerns, the users in a system are required to update their passwords regularly. In this article we will see how we can force an user to change their password when they login to the system next time.
First lets have a look at the users available in the system.
$ cut -d: -f1 /etc/passwd
Running the above code gives us the following result −
mail
news
uucp
proxy
www-data
backup
list
...
Ubuntu
uname1
Next we check the settings for users current password system configuration.
$ sudo chage -l uname1
[sudo] password for ubuntu:
Running the above code gives us the following result −
Last password change: Dec 30, 2019
Password expires: never
Password inactive: never
Account expires: never
Minimum number of days between password change: 0
Maximum number of days between password change: 99999
Number of days of warning before password expires: 7
Now we sue the expire option to set the timeline for password expiry and then query it with the chage to find the expiry implemented.
$ sudo passwd --expire uname1
passwd: password expiry information changed.
$ sudo chage -l uname1
Running the above code gives us the following result −
Last password change: password must be changed
Password expires: password must be changed
Password inactive: password must be changed
Account expires: never
Minimum number of days between password change: 0
Maximum number of days between password change: 99999
Number of days of warning before password expires: 7
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "Because of security concerns, the users in a system are required to update their passwords regularly. In this article we will see how we can force an user to change their password when they login to the system next time."
},
{
"code": null,
"e": 1344,
"s": 1283,
"text": "First lets have a look at the users available in the system."
},
{
"code": null,
"e": 1370,
"s": 1344,
"text": "$ cut -d: -f1 /etc/passwd"
},
{
"code": null,
"e": 1425,
"s": 1370,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1485,
"s": 1425,
"text": "mail\nnews\nuucp\nproxy\nwww-data\nbackup\nlist\n...\nUbuntu\nuname1"
},
{
"code": null,
"e": 1561,
"s": 1485,
"text": "Next we check the settings for users current password system configuration."
},
{
"code": null,
"e": 1612,
"s": 1561,
"text": "$ sudo chage -l uname1\n[sudo] password for ubuntu:"
},
{
"code": null,
"e": 1667,
"s": 1612,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1931,
"s": 1667,
"text": "Last password change: Dec 30, 2019\nPassword expires: never\nPassword inactive: never\nAccount expires: never\nMinimum number of days between password change: 0\nMaximum number of days between password change: 99999\nNumber of days of warning before password expires: 7"
},
{
"code": null,
"e": 2065,
"s": 1931,
"text": "Now we sue the expire option to set the timeline for password expiry and then query it with the chage to find the expiry implemented."
},
{
"code": null,
"e": 2163,
"s": 2065,
"text": "$ sudo passwd --expire uname1\npasswd: password expiry information changed.\n$ sudo chage -l uname1"
},
{
"code": null,
"e": 2218,
"s": 2163,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2532,
"s": 2218,
"text": "Last password change: password must be changed\nPassword expires: password must be changed\nPassword inactive: password must be changed\nAccount expires: never\nMinimum number of days between password change: 0\nMaximum number of days between password change: 99999\nNumber of days of warning before password expires: 7"
}
] |
Drink Water notification system in Python - GeeksforGeeks
|
13 Jan, 2021
The idea behind this article is to create a notification system that reminds the user to drink water after a fixed interval of time. The program coded below first asks its user to input time interval for notification. Then until user ends script, it sends repeated notifications to user to drink water. After each interval it creates a text file which contains a log of when user drank water.
time: To manage the interval time.
win10Toast : To send quick notification.
datetime : To keep record of time and date in log.
Import module
Get time interval from the user, it asks user to input hour, minutes and seconds
Convert them to seconds and return time to main function.
Add loop to start timer and generate a toast message when timer reaches the set time
After sending notification program will call to function to write log file. This function will get current time and date
Create a .txt file and append drink water log to it.
Program:
Python3
import timefrom win10toast import ToastNotifierimport datetime def getTimeInput(): hour = int(input("hours of interval :")) minutes = int(input("Mins of interval :")) seconds = int(input("Secs of interval :")) time_interval = seconds+(minutes*60)+(hour*3600) return time_interval def log(): now = datetime.datetime.now() start_time = now.strftime("%H:%M:%S") with open("log.txt", 'a') as f: f.write(f"You drank water {now} \n") return 0 def notify(): notification = ToastNotifier() notification.show_toast("Time to drink water") log() return 0 def starttime(time_interval): while True: time.sleep(time_interval) notify() if __name__ == '__main__': time_interval = getTimeInput() starttime(time_interval)
Output:
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 24685,
"s": 24292,
"text": "The idea behind this article is to create a notification system that reminds the user to drink water after a fixed interval of time. The program coded below first asks its user to input time interval for notification. Then until user ends script, it sends repeated notifications to user to drink water. After each interval it creates a text file which contains a log of when user drank water."
},
{
"code": null,
"e": 24720,
"s": 24685,
"text": "time: To manage the interval time."
},
{
"code": null,
"e": 24761,
"s": 24720,
"text": "win10Toast : To send quick notification."
},
{
"code": null,
"e": 24812,
"s": 24761,
"text": "datetime : To keep record of time and date in log."
},
{
"code": null,
"e": 24826,
"s": 24812,
"text": "Import module"
},
{
"code": null,
"e": 24907,
"s": 24826,
"text": "Get time interval from the user, it asks user to input hour, minutes and seconds"
},
{
"code": null,
"e": 24965,
"s": 24907,
"text": "Convert them to seconds and return time to main function."
},
{
"code": null,
"e": 25050,
"s": 24965,
"text": "Add loop to start timer and generate a toast message when timer reaches the set time"
},
{
"code": null,
"e": 25173,
"s": 25050,
"text": "After sending notification program will call to function to write log file. This function will get current time and date "
},
{
"code": null,
"e": 25226,
"s": 25173,
"text": "Create a .txt file and append drink water log to it."
},
{
"code": null,
"e": 25235,
"s": 25226,
"text": "Program:"
},
{
"code": null,
"e": 25243,
"s": 25235,
"text": "Python3"
},
{
"code": "import timefrom win10toast import ToastNotifierimport datetime def getTimeInput(): hour = int(input(\"hours of interval :\")) minutes = int(input(\"Mins of interval :\")) seconds = int(input(\"Secs of interval :\")) time_interval = seconds+(minutes*60)+(hour*3600) return time_interval def log(): now = datetime.datetime.now() start_time = now.strftime(\"%H:%M:%S\") with open(\"log.txt\", 'a') as f: f.write(f\"You drank water {now} \\n\") return 0 def notify(): notification = ToastNotifier() notification.show_toast(\"Time to drink water\") log() return 0 def starttime(time_interval): while True: time.sleep(time_interval) notify() if __name__ == '__main__': time_interval = getTimeInput() starttime(time_interval)",
"e": 26031,
"s": 25243,
"text": null
},
{
"code": null,
"e": 26039,
"s": 26031,
"text": "Output:"
},
{
"code": null,
"e": 26054,
"s": 26039,
"text": "python-utility"
},
{
"code": null,
"e": 26078,
"s": 26054,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26085,
"s": 26078,
"text": "Python"
},
{
"code": null,
"e": 26104,
"s": 26085,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26202,
"s": 26104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26234,
"s": 26202,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26276,
"s": 26234,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26332,
"s": 26276,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26374,
"s": 26332,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26396,
"s": 26374,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26451,
"s": 26396,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26482,
"s": 26451,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26521,
"s": 26482,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26550,
"s": 26521,
"text": "Create a directory in Python"
}
] |
Understand Data Analysis & Visualisation using Time series data. | by Shamim Ahmed | Towards Data Science
|
Humanity is blessed to have AI and Data Science because it helps us solve day to day problems. And quite often we encounter time series data in abundance, which has a strong resemblance with our daily activities.
In this post, we will learn how to get insights into data using data analysis and understand how data is behaving from time to time.
We used “Junglee Rummy business” time series dataset, download here. The dataset is owned by “Junglee Games”. Visit the link to get an overview of the dataset. You can also play the game.
We must get acknowledged to the terms associated with the dataset. Let’s have a look:-
Entry Fee: This is the Buy-in (money user pays) in rupees to enter the game.
Seat: Max number of players that can sit on the table i.e. 2,6 for the data set.
Composition: Actual number of players that actually joined the table.
Date: It’s a data set of 1st July 2018 to 30 Sep 2018 which gives daily data for each table configuration.
Configuration: Defined as the combination of Entry Fees — Seats — Composition.
Cut %: %age amount deducted for each game from each user.
‘#Users’: Distinct count of players (unique players) who played at least 1 game for table configuration for the date.
User Cash Game Count: Total number of games played by users on table configuration for the date. If user A, B, C play together a single game, then the value will be 3.
Rake: Total amount generated in revenue from a table configuration for the date.
Wager: Total amount paid by the users in terms of Entry Fees to play the game.
Let’s get started!
We would load important libraries and let's have a peek of the data.
import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np# reading the data using pandasdf = pd.read_excel('BI Skill Test - Data Set.xlsx')df.head()
The dataset is quite intuitive. If it's not understandable, please read the column descriptions above. We would multiply the Cut% by 100 to make it computationally simple.
# Multiplying cut% with 100 to make it easy for computationdf['Cut %'] = df['Cut %'] * 100
Now that we had a brief overlook of the data. It’s very essential to analyze the basic statistics of the dataset.
# Basic statistics of tha datapd.options.display.float_format = '{:.0f}'.formatdf.describe()
In Data Science those stats play a vital role to get insights into the data. Few of the observations after getting through the numbers in the above table are:
Entry Fee: Average entry fee paid by users to play a game is Rs.854, the minimum entry fee is Rs 5 and the maximum entry fee is Rs 10000. Most of the time users pay Rs 100 as an entry fee to play a game.Seat: Average number of players sit together is 5, out of them, 4 play on average. Whereas 6 number of players play at max.Cut%: Average cut % is 13%. Most of the players pay 15% as a cut.#Users: Average number of users played at least one game per day is 165 whereas the maximum number of users played at least one game per day is 1155.Rake: Average amount of money, company earns per day is Rs 10137. The maximum amount of money, the company earned in a day is Rs 271200. Most of the time the company earns Rs 3195.Wager: Maximum amount players invested to play the game is Rs 4520000, whereas most of the time users pay Rs 24000.
Entry Fee: Average entry fee paid by users to play a game is Rs.854, the minimum entry fee is Rs 5 and the maximum entry fee is Rs 10000. Most of the time users pay Rs 100 as an entry fee to play a game.
Seat: Average number of players sit together is 5, out of them, 4 play on average. Whereas 6 number of players play at max.
Cut%: Average cut % is 13%. Most of the players pay 15% as a cut.
#Users: Average number of users played at least one game per day is 165 whereas the maximum number of users played at least one game per day is 1155.
Rake: Average amount of money, company earns per day is Rs 10137. The maximum amount of money, the company earned in a day is Rs 271200. Most of the time the company earns Rs 3195.
Wager: Maximum amount players invested to play the game is Rs 4520000, whereas most of the time users pay Rs 24000.
That’s pretty much tons of information with just one line of code. Thanks to pandas.
It would be interesting to visualize a few information a step further. We would use matplotlibpython library to perform the same.
Let's start with the total amount paid by the users as entry fees to play the game.
plt.figure(figsize=(9, 8))sns.distplot(df['Wager'], color='g', bins=100, hist_kws={'alpha': 0.4})plt.title("Total amount paid by the users in terms of Entry Fees to play the game")
By the graph above, we observe that most of the time users pay around Rs 25000 on a particular day.
Now let's see the total amount generated in revenue from a table configuration for the date.
plt.figure(figsize=(9, 8))sns.distplot(df['Rake'], color='b', bins=100, hist_kws={'alpha': 0.4})plt.title("Total amount generated in revenue from a table configuration for the date")
By the graph above and basic statistics, it can be realized that most of the time the company earns around Rs 3000 per day.
Buy-in (money user pays) in rupees to enter the game
num_bins = 60plt.hist(df['Entry Fee'], num_bins, facecolor='blue', alpha=0.5)plt.title("Buy-in (money user pays) in rupees to enter the game")plt.show()
We observe that most of the people buy tickets costing less than 1000 Rs. There are some users who spend Rs 10000 as an entry fee to play the game.
Data analysis and visualization gives us insights into the data in-depth and in a few instances we might encounter magic. So let's dive deep into the dataset any perform time series analysis.
Our main focus is on the behavior of the data from time to time.
We would convert the date (which is written alphabetically) to numerical counterpart and create separate columns for date, month and year. It's easy to perform data analysis using numerical data.
We would use datetimepython class to convert date to datetime format. Let’s see how it works.
# introducing datetimefrom datetime import datetime, date, timedatetime.strptime('July 1, 2018', '%B %d, %Y')
Output:
datetime.datetime(2018, 7, 1, 0, 0)
Now we would perform the same operation on our entire Date column.
# converting date to datetime formatdate = []for d in df['Date']: x = datetime.strptime(d, '%B %d, %Y') date.append(x)df['my_date'] = date
print(df['my_date'][0].month)print(df['my_date'][0].day)print(df['my_date'][0].year)Output:712018
Converting DateTime to individual columns
# converting datetime to individual columnsday = []month = []year = []for i in df['my_date']: day.append(i.day) month.append(i.month) year.append(i.year)df['day'] = daydf['month'] = monthdf['year'] = yeardf.head(2)
So now that we have converted the Date to individuals columns of date, month and year. Let’s perform a time-series analysis.
#sale by monthsales_by_month = df.groupby('month').size()print(sales_by_month)#Plotting the Graphplot_by_month = sales_by_month.plot(title='Monthly Sales',xticks=(1,2,3,4,5,6,7,8,9,10,11,12))plot_by_month.set_xlabel('Months')plot_by_month.set_ylabel('Total Sales')plt.title("Monthly sales analysis")
It is observed that the number of sales in the month of January is high as compared to other months. As the months progressed the number of sales decreased.
#Sale by Daysales_by_day = df.groupby('day').size()plot_by_day = sales_by_day.plot(title='Daily Sales',xticks=(range(1,31)),rot=55)plot_by_day.set_xlabel('Day')plot_by_day.set_ylabel('Total Sales')plt.title("Daily sales analysis")
We observe that the number of sales in the first five days of the month is high as compared to other months.
We could have analyzed the behavior of the sales even better if we could have got the hourly data.
It’s a good idea to observe the number of users engaged in the game per month. We would use boxplot to visualize the same.
# number of users played per monthsns.boxplot(x='month', y='# Users', data=df)plt.title("Number of users played per month")plt.show()
As time progressed the number of users per month increased gradually. If we focus on the quantiles, in January there were around 100 people on an average per day. But there were around 400 at maximum. In the month of September, there were around 220 users on an average per day whereas there was around 1200 user per day. Same can be understood for other months as well.
# Number of users played in table configuration per month.sns.boxplot(x='month', y='User Cash Game Count', data=df)plt.title("Number of users played in table configuration per month")plt.show()
Similarly, if we focus on the number of games played per month on a table. In January around 100 people played in a day whereas at max 800 people played in a day. We observed that there was a slight decrease in the number of games played in the month of April. In the month of September in an average of 500 people played on the table whereas at max 3000 people played on table, 75% time 900 people played the game on table.
# Profit earned by company every monthsns.boxplot(x='month', y='Rake', data=df)plt.title("Profit earned by company every month")plt.show()
If we observe the boxplot, the company earned most of the profit in the month of September in an average. We also see that maximum profit earned at a time is around 300000 in the month of May. In the month of February, the company earned the least revenue.
# total amount payed by users as entry fee to play games per month.sns.boxplot(x='month', y='Wager', data=df)plt.title("Total amount payed by users as entry fee to play games per month")plt.show()
We observed that same scenario is observed as above RAGE plots. In the month of May, the maximum amount is spent by users to play a game. In an average September has a good record.
Now let's perform day-wise analysis and see if we can get any further important information.
# number of cash games played by users per day. plt.figure(figsize=(20,18))df.plot(kind='scatter', x='day', y='User Cash Game Count');plt.title("Number of cash games played by users per day")plt.show()
# Revenue earned by users in days of monthdf.plot(kind='scatter', x='day', y='Rake');plt.title("Revenue earned by users in days of month")plt.show()
# Amount spent by user every day of the month.df.plot(kind='scatter', x='day', y='Wager');plt.title("Amount spent by user every day of the month")plt.show()
We have performed basic data analysis on the time series data and could get lots of information out of it. It's just the game of data manipulation and inculcating ideas.
Entry Fee: Firstly, the maximum number of people spend 100 Rs to enter the game.
Seat: At maximum 6 players can sit on a table, among them, 3 players play most of the time.
Cut%: In most cases, 15% of the amount is deducted per user.
No of Users: In a day 112 players play at least a table game per day mostly.
User cash game: In most cases, 212 players play table game in a day.
Rake: Per day company earns Rs 3195 in an average.
Wager: Per day users spends Rs 24000 in an average.
We observed that most of the users pay less than Rs 1000 to play a game.
It is observed that the number of sales in the month of January is high as compared to other months. As the months progressed the number of sales decreased.
We observe that the number of sales in the first five days of the month is high as compared to other months.
We observe that the number of users gradually increased as the days progressed. But May month had significant high user engagement from preceding months.
We see that May month had very high revenue generation by the company.
We had observed that every day of the month shown uniform revenue generation by the company.
Overall we observed that the month of May had been best for the company’s profitability. It had shown significant growth in the same. Whereas the month of February was a little bit odd for the company in terms of profitability.
Source code can be found on my Github repo. I look forward to hearing any feedback or questions. Thanks for reading the article.
Follow me on LinkedIn.
|
[
{
"code": null,
"e": 385,
"s": 172,
"text": "Humanity is blessed to have AI and Data Science because it helps us solve day to day problems. And quite often we encounter time series data in abundance, which has a strong resemblance with our daily activities."
},
{
"code": null,
"e": 518,
"s": 385,
"text": "In this post, we will learn how to get insights into data using data analysis and understand how data is behaving from time to time."
},
{
"code": null,
"e": 706,
"s": 518,
"text": "We used “Junglee Rummy business” time series dataset, download here. The dataset is owned by “Junglee Games”. Visit the link to get an overview of the dataset. You can also play the game."
},
{
"code": null,
"e": 793,
"s": 706,
"text": "We must get acknowledged to the terms associated with the dataset. Let’s have a look:-"
},
{
"code": null,
"e": 870,
"s": 793,
"text": "Entry Fee: This is the Buy-in (money user pays) in rupees to enter the game."
},
{
"code": null,
"e": 951,
"s": 870,
"text": "Seat: Max number of players that can sit on the table i.e. 2,6 for the data set."
},
{
"code": null,
"e": 1021,
"s": 951,
"text": "Composition: Actual number of players that actually joined the table."
},
{
"code": null,
"e": 1128,
"s": 1021,
"text": "Date: It’s a data set of 1st July 2018 to 30 Sep 2018 which gives daily data for each table configuration."
},
{
"code": null,
"e": 1207,
"s": 1128,
"text": "Configuration: Defined as the combination of Entry Fees — Seats — Composition."
},
{
"code": null,
"e": 1265,
"s": 1207,
"text": "Cut %: %age amount deducted for each game from each user."
},
{
"code": null,
"e": 1383,
"s": 1265,
"text": "‘#Users’: Distinct count of players (unique players) who played at least 1 game for table configuration for the date."
},
{
"code": null,
"e": 1551,
"s": 1383,
"text": "User Cash Game Count: Total number of games played by users on table configuration for the date. If user A, B, C play together a single game, then the value will be 3."
},
{
"code": null,
"e": 1632,
"s": 1551,
"text": "Rake: Total amount generated in revenue from a table configuration for the date."
},
{
"code": null,
"e": 1711,
"s": 1632,
"text": "Wager: Total amount paid by the users in terms of Entry Fees to play the game."
},
{
"code": null,
"e": 1730,
"s": 1711,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1799,
"s": 1730,
"text": "We would load important libraries and let's have a peek of the data."
},
{
"code": null,
"e": 1980,
"s": 1799,
"text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np# reading the data using pandasdf = pd.read_excel('BI Skill Test - Data Set.xlsx')df.head()"
},
{
"code": null,
"e": 2152,
"s": 1980,
"text": "The dataset is quite intuitive. If it's not understandable, please read the column descriptions above. We would multiply the Cut% by 100 to make it computationally simple."
},
{
"code": null,
"e": 2243,
"s": 2152,
"text": "# Multiplying cut% with 100 to make it easy for computationdf['Cut %'] = df['Cut %'] * 100"
},
{
"code": null,
"e": 2357,
"s": 2243,
"text": "Now that we had a brief overlook of the data. It’s very essential to analyze the basic statistics of the dataset."
},
{
"code": null,
"e": 2450,
"s": 2357,
"text": "# Basic statistics of tha datapd.options.display.float_format = '{:.0f}'.formatdf.describe()"
},
{
"code": null,
"e": 2609,
"s": 2450,
"text": "In Data Science those stats play a vital role to get insights into the data. Few of the observations after getting through the numbers in the above table are:"
},
{
"code": null,
"e": 3445,
"s": 2609,
"text": "Entry Fee: Average entry fee paid by users to play a game is Rs.854, the minimum entry fee is Rs 5 and the maximum entry fee is Rs 10000. Most of the time users pay Rs 100 as an entry fee to play a game.Seat: Average number of players sit together is 5, out of them, 4 play on average. Whereas 6 number of players play at max.Cut%: Average cut % is 13%. Most of the players pay 15% as a cut.#Users: Average number of users played at least one game per day is 165 whereas the maximum number of users played at least one game per day is 1155.Rake: Average amount of money, company earns per day is Rs 10137. The maximum amount of money, the company earned in a day is Rs 271200. Most of the time the company earns Rs 3195.Wager: Maximum amount players invested to play the game is Rs 4520000, whereas most of the time users pay Rs 24000."
},
{
"code": null,
"e": 3649,
"s": 3445,
"text": "Entry Fee: Average entry fee paid by users to play a game is Rs.854, the minimum entry fee is Rs 5 and the maximum entry fee is Rs 10000. Most of the time users pay Rs 100 as an entry fee to play a game."
},
{
"code": null,
"e": 3773,
"s": 3649,
"text": "Seat: Average number of players sit together is 5, out of them, 4 play on average. Whereas 6 number of players play at max."
},
{
"code": null,
"e": 3839,
"s": 3773,
"text": "Cut%: Average cut % is 13%. Most of the players pay 15% as a cut."
},
{
"code": null,
"e": 3989,
"s": 3839,
"text": "#Users: Average number of users played at least one game per day is 165 whereas the maximum number of users played at least one game per day is 1155."
},
{
"code": null,
"e": 4170,
"s": 3989,
"text": "Rake: Average amount of money, company earns per day is Rs 10137. The maximum amount of money, the company earned in a day is Rs 271200. Most of the time the company earns Rs 3195."
},
{
"code": null,
"e": 4286,
"s": 4170,
"text": "Wager: Maximum amount players invested to play the game is Rs 4520000, whereas most of the time users pay Rs 24000."
},
{
"code": null,
"e": 4371,
"s": 4286,
"text": "That’s pretty much tons of information with just one line of code. Thanks to pandas."
},
{
"code": null,
"e": 4501,
"s": 4371,
"text": "It would be interesting to visualize a few information a step further. We would use matplotlibpython library to perform the same."
},
{
"code": null,
"e": 4585,
"s": 4501,
"text": "Let's start with the total amount paid by the users as entry fees to play the game."
},
{
"code": null,
"e": 4766,
"s": 4585,
"text": "plt.figure(figsize=(9, 8))sns.distplot(df['Wager'], color='g', bins=100, hist_kws={'alpha': 0.4})plt.title(\"Total amount paid by the users in terms of Entry Fees to play the game\")"
},
{
"code": null,
"e": 4866,
"s": 4766,
"text": "By the graph above, we observe that most of the time users pay around Rs 25000 on a particular day."
},
{
"code": null,
"e": 4959,
"s": 4866,
"text": "Now let's see the total amount generated in revenue from a table configuration for the date."
},
{
"code": null,
"e": 5142,
"s": 4959,
"text": "plt.figure(figsize=(9, 8))sns.distplot(df['Rake'], color='b', bins=100, hist_kws={'alpha': 0.4})plt.title(\"Total amount generated in revenue from a table configuration for the date\")"
},
{
"code": null,
"e": 5266,
"s": 5142,
"text": "By the graph above and basic statistics, it can be realized that most of the time the company earns around Rs 3000 per day."
},
{
"code": null,
"e": 5319,
"s": 5266,
"text": "Buy-in (money user pays) in rupees to enter the game"
},
{
"code": null,
"e": 5472,
"s": 5319,
"text": "num_bins = 60plt.hist(df['Entry Fee'], num_bins, facecolor='blue', alpha=0.5)plt.title(\"Buy-in (money user pays) in rupees to enter the game\")plt.show()"
},
{
"code": null,
"e": 5620,
"s": 5472,
"text": "We observe that most of the people buy tickets costing less than 1000 Rs. There are some users who spend Rs 10000 as an entry fee to play the game."
},
{
"code": null,
"e": 5812,
"s": 5620,
"text": "Data analysis and visualization gives us insights into the data in-depth and in a few instances we might encounter magic. So let's dive deep into the dataset any perform time series analysis."
},
{
"code": null,
"e": 5877,
"s": 5812,
"text": "Our main focus is on the behavior of the data from time to time."
},
{
"code": null,
"e": 6073,
"s": 5877,
"text": "We would convert the date (which is written alphabetically) to numerical counterpart and create separate columns for date, month and year. It's easy to perform data analysis using numerical data."
},
{
"code": null,
"e": 6167,
"s": 6073,
"text": "We would use datetimepython class to convert date to datetime format. Let’s see how it works."
},
{
"code": null,
"e": 6277,
"s": 6167,
"text": "# introducing datetimefrom datetime import datetime, date, timedatetime.strptime('July 1, 2018', '%B %d, %Y')"
},
{
"code": null,
"e": 6285,
"s": 6277,
"text": "Output:"
},
{
"code": null,
"e": 6321,
"s": 6285,
"text": "datetime.datetime(2018, 7, 1, 0, 0)"
},
{
"code": null,
"e": 6388,
"s": 6321,
"text": "Now we would perform the same operation on our entire Date column."
},
{
"code": null,
"e": 6533,
"s": 6388,
"text": "# converting date to datetime formatdate = []for d in df['Date']: x = datetime.strptime(d, '%B %d, %Y') date.append(x)df['my_date'] = date"
},
{
"code": null,
"e": 6631,
"s": 6533,
"text": "print(df['my_date'][0].month)print(df['my_date'][0].day)print(df['my_date'][0].year)Output:712018"
},
{
"code": null,
"e": 6673,
"s": 6631,
"text": "Converting DateTime to individual columns"
},
{
"code": null,
"e": 6897,
"s": 6673,
"text": "# converting datetime to individual columnsday = []month = []year = []for i in df['my_date']: day.append(i.day) month.append(i.month) year.append(i.year)df['day'] = daydf['month'] = monthdf['year'] = yeardf.head(2)"
},
{
"code": null,
"e": 7022,
"s": 6897,
"text": "So now that we have converted the Date to individuals columns of date, month and year. Let’s perform a time-series analysis."
},
{
"code": null,
"e": 7322,
"s": 7022,
"text": "#sale by monthsales_by_month = df.groupby('month').size()print(sales_by_month)#Plotting the Graphplot_by_month = sales_by_month.plot(title='Monthly Sales',xticks=(1,2,3,4,5,6,7,8,9,10,11,12))plot_by_month.set_xlabel('Months')plot_by_month.set_ylabel('Total Sales')plt.title(\"Monthly sales analysis\")"
},
{
"code": null,
"e": 7479,
"s": 7322,
"text": "It is observed that the number of sales in the month of January is high as compared to other months. As the months progressed the number of sales decreased."
},
{
"code": null,
"e": 7710,
"s": 7479,
"text": "#Sale by Daysales_by_day = df.groupby('day').size()plot_by_day = sales_by_day.plot(title='Daily Sales',xticks=(range(1,31)),rot=55)plot_by_day.set_xlabel('Day')plot_by_day.set_ylabel('Total Sales')plt.title(\"Daily sales analysis\")"
},
{
"code": null,
"e": 7819,
"s": 7710,
"text": "We observe that the number of sales in the first five days of the month is high as compared to other months."
},
{
"code": null,
"e": 7918,
"s": 7819,
"text": "We could have analyzed the behavior of the sales even better if we could have got the hourly data."
},
{
"code": null,
"e": 8041,
"s": 7918,
"text": "It’s a good idea to observe the number of users engaged in the game per month. We would use boxplot to visualize the same."
},
{
"code": null,
"e": 8175,
"s": 8041,
"text": "# number of users played per monthsns.boxplot(x='month', y='# Users', data=df)plt.title(\"Number of users played per month\")plt.show()"
},
{
"code": null,
"e": 8546,
"s": 8175,
"text": "As time progressed the number of users per month increased gradually. If we focus on the quantiles, in January there were around 100 people on an average per day. But there were around 400 at maximum. In the month of September, there were around 220 users on an average per day whereas there was around 1200 user per day. Same can be understood for other months as well."
},
{
"code": null,
"e": 8740,
"s": 8546,
"text": "# Number of users played in table configuration per month.sns.boxplot(x='month', y='User Cash Game Count', data=df)plt.title(\"Number of users played in table configuration per month\")plt.show()"
},
{
"code": null,
"e": 9165,
"s": 8740,
"text": "Similarly, if we focus on the number of games played per month on a table. In January around 100 people played in a day whereas at max 800 people played in a day. We observed that there was a slight decrease in the number of games played in the month of April. In the month of September in an average of 500 people played on the table whereas at max 3000 people played on table, 75% time 900 people played the game on table."
},
{
"code": null,
"e": 9304,
"s": 9165,
"text": "# Profit earned by company every monthsns.boxplot(x='month', y='Rake', data=df)plt.title(\"Profit earned by company every month\")plt.show()"
},
{
"code": null,
"e": 9561,
"s": 9304,
"text": "If we observe the boxplot, the company earned most of the profit in the month of September in an average. We also see that maximum profit earned at a time is around 300000 in the month of May. In the month of February, the company earned the least revenue."
},
{
"code": null,
"e": 9758,
"s": 9561,
"text": "# total amount payed by users as entry fee to play games per month.sns.boxplot(x='month', y='Wager', data=df)plt.title(\"Total amount payed by users as entry fee to play games per month\")plt.show()"
},
{
"code": null,
"e": 9939,
"s": 9758,
"text": "We observed that same scenario is observed as above RAGE plots. In the month of May, the maximum amount is spent by users to play a game. In an average September has a good record."
},
{
"code": null,
"e": 10032,
"s": 9939,
"text": "Now let's perform day-wise analysis and see if we can get any further important information."
},
{
"code": null,
"e": 10234,
"s": 10032,
"text": "# number of cash games played by users per day. plt.figure(figsize=(20,18))df.plot(kind='scatter', x='day', y='User Cash Game Count');plt.title(\"Number of cash games played by users per day\")plt.show()"
},
{
"code": null,
"e": 10383,
"s": 10234,
"text": "# Revenue earned by users in days of monthdf.plot(kind='scatter', x='day', y='Rake');plt.title(\"Revenue earned by users in days of month\")plt.show()"
},
{
"code": null,
"e": 10540,
"s": 10383,
"text": "# Amount spent by user every day of the month.df.plot(kind='scatter', x='day', y='Wager');plt.title(\"Amount spent by user every day of the month\")plt.show()"
},
{
"code": null,
"e": 10710,
"s": 10540,
"text": "We have performed basic data analysis on the time series data and could get lots of information out of it. It's just the game of data manipulation and inculcating ideas."
},
{
"code": null,
"e": 10791,
"s": 10710,
"text": "Entry Fee: Firstly, the maximum number of people spend 100 Rs to enter the game."
},
{
"code": null,
"e": 10883,
"s": 10791,
"text": "Seat: At maximum 6 players can sit on a table, among them, 3 players play most of the time."
},
{
"code": null,
"e": 10944,
"s": 10883,
"text": "Cut%: In most cases, 15% of the amount is deducted per user."
},
{
"code": null,
"e": 11021,
"s": 10944,
"text": "No of Users: In a day 112 players play at least a table game per day mostly."
},
{
"code": null,
"e": 11090,
"s": 11021,
"text": "User cash game: In most cases, 212 players play table game in a day."
},
{
"code": null,
"e": 11141,
"s": 11090,
"text": "Rake: Per day company earns Rs 3195 in an average."
},
{
"code": null,
"e": 11193,
"s": 11141,
"text": "Wager: Per day users spends Rs 24000 in an average."
},
{
"code": null,
"e": 11266,
"s": 11193,
"text": "We observed that most of the users pay less than Rs 1000 to play a game."
},
{
"code": null,
"e": 11423,
"s": 11266,
"text": "It is observed that the number of sales in the month of January is high as compared to other months. As the months progressed the number of sales decreased."
},
{
"code": null,
"e": 11532,
"s": 11423,
"text": "We observe that the number of sales in the first five days of the month is high as compared to other months."
},
{
"code": null,
"e": 11686,
"s": 11532,
"text": "We observe that the number of users gradually increased as the days progressed. But May month had significant high user engagement from preceding months."
},
{
"code": null,
"e": 11757,
"s": 11686,
"text": "We see that May month had very high revenue generation by the company."
},
{
"code": null,
"e": 11850,
"s": 11757,
"text": "We had observed that every day of the month shown uniform revenue generation by the company."
},
{
"code": null,
"e": 12078,
"s": 11850,
"text": "Overall we observed that the month of May had been best for the company’s profitability. It had shown significant growth in the same. Whereas the month of February was a little bit odd for the company in terms of profitability."
},
{
"code": null,
"e": 12207,
"s": 12078,
"text": "Source code can be found on my Github repo. I look forward to hearing any feedback or questions. Thanks for reading the article."
}
] |
NumPy - Iterating Over Array
|
NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.
Let us create a 3X4 array using arange() function and iterate over it using nditer.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Modified array is:'
for x in np.nditer(a):
print x,
The output of this program is as follows −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55
The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Transpose of the original array is:'
b = a.T
print b
print '\n'
print 'Modified array is:'
for x in np.nditer(b):
print x,
The output of the above program is as follows −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Transpose of the original array is:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
Modified array is:
0 5 10 15 20 25 30 35 40 45 50 55
If the same elements are stored using F-style order, the iterator chooses the more efficient way of iterating over an array.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Transpose of the original array is:'
b = a.T
print b
print '\n'
print 'Sorted in C-style order:'
c = b.copy(order = 'C')
print c
for x in np.nditer(c):
print x,
print '\n'
print 'Sorted in F-style order:'
c = b.copy(order = 'F')
print c
for x in np.nditer(c):
print x,
Its output would be as follows −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Transpose of the original array is:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
Sorted in C-style order:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
0 20 40 5 25 45 10 30 50 15 35 55
Sorted in F-style order:
[[ 0 20 40]
[ 5 25 45]
[10 30 50]
[15 35 55]]
0 5 10 15 20 25 30 35 40 45 50 55
It is possible to force nditer object to use a specific order by explicitly mentioning it.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Sorted in C-style order:'
for x in np.nditer(a, order = 'C'):
print x,
print '\n'
print 'Sorted in F-style order:'
for x in np.nditer(a, order = 'F'):
print x,
Its output would be −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Sorted in C-style order:
0 5 10 15 20 25 30 35 40 45 50 55
Sorted in F-style order:
0 20 40 5 25 45 10 30 50 15 35 55
The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
for x in np.nditer(a, op_flags = ['readwrite']):
x[...] = 2*x
print 'Modified array is:'
print a
Its output is as follows −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array is:
[[ 0 10 20 30]
[ 40 50 60 70]
[ 80 90 100 110]]
The nditer class constructor has a ‘flags’ parameter, which can take the following values −
c_index
C_order index can be tracked
f_index
Fortran_order index is tracked
multi-index
Type of indexes with one per iteration can be tracked
external_loop
Causes values given to be one-dimensional arrays with multiple values instead of zero-dimensional array
In the following example, one-dimensional arrays corresponding to each column is traversed by the iterator.
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'Original array is:'
print a
print '\n'
print 'Modified array is:'
for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
print x,
The output is as follows −
Original array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Modified array is:
[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]
If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a).
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
print 'First array is:'
print a
print '\n'
print 'Second array is:'
b = np.array([1, 2, 3, 4], dtype = int)
print b
print '\n'
print 'Modified array is:'
for x,y in np.nditer([a,b]):
print "%d:%d" % (x,y),
Its output would be as follows −
First array is:
[[ 0 5 10 15]
[20 25 30 35]
[40 45 50 55]]
Second array is:
[1 2 3 4]
Modified array is:
0:1 5:2 10:3 15:4 20:1 25:2 30:3 35:4 40:1 45:2 50:3 55:4
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2484,
"s": 2243,
"text": "NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface."
},
{
"code": null,
"e": 2568,
"s": 2484,
"text": "Let us create a 3X4 array using arange() function and iterate over it using nditer."
},
{
"code": null,
"e": 2738,
"s": 2568,
"text": "import numpy as np\na = np.arange(0,60,5)\na = a.reshape(3,4)\n\nprint 'Original array is:'\nprint a\nprint '\\n'\n\nprint 'Modified array is:'\nfor x in np.nditer(a):\n print x,"
},
{
"code": null,
"e": 2781,
"s": 2738,
"text": "The output of this program is as follows −"
},
{
"code": null,
"e": 2900,
"s": 2781,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nModified array is:\n0 5 10 15 20 25 30 35 40 45 50 55\n"
},
{
"code": null,
"e": 3085,
"s": 2900,
"text": "The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array."
},
{
"code": null,
"e": 3349,
"s": 3085,
"text": "import numpy as np \na = np.arange(0,60,5) \na = a.reshape(3,4) \n \nprint 'Original array is:'\nprint a \nprint '\\n' \n \nprint 'Transpose of the original array is:' \nb = a.T \nprint b \nprint '\\n' \n \nprint 'Modified array is:' \nfor x in np.nditer(b): \n print x,"
},
{
"code": null,
"e": 3397,
"s": 3349,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 3602,
"s": 3397,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nTranspose of the original array is:\n[[ 0 20 40]\n [ 5 25 45]\n [10 30 50]\n [15 35 55]]\n\nModified array is:\n0 5 10 15 20 25 30 35 40 45 50 55\n"
},
{
"code": null,
"e": 3727,
"s": 3602,
"text": "If the same elements are stored using F-style order, the iterator chooses the more efficient way of iterating over an array."
},
{
"code": null,
"e": 4119,
"s": 3727,
"text": "import numpy as np\na = np.arange(0,60,5)\na = a.reshape(3,4)\nprint 'Original array is:'\nprint a\nprint '\\n'\n\nprint 'Transpose of the original array is:'\nb = a.T\nprint b\nprint '\\n'\n\nprint 'Sorted in C-style order:'\nc = b.copy(order = 'C')\nprint c\nfor x in np.nditer(c):\n print x,\n\nprint '\\n'\n\nprint 'Sorted in F-style order:'\nc = b.copy(order = 'F')\nprint c\nfor x in np.nditer(c):\n print x,"
},
{
"code": null,
"e": 4152,
"s": 4119,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 4521,
"s": 4152,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nTranspose of the original array is:\n[[ 0 20 40]\n [ 5 25 45]\n [10 30 50]\n [15 35 55]]\n\nSorted in C-style order:\n[[ 0 20 40]\n [ 5 25 45]\n [10 30 50]\n [15 35 55]]\n0 20 40 5 25 45 10 30 50 15 35 55\n\nSorted in F-style order:\n[[ 0 20 40]\n [ 5 25 45]\n [10 30 50]\n [15 35 55]]\n0 5 10 15 20 25 30 35 40 45 50 55\n"
},
{
"code": null,
"e": 4612,
"s": 4521,
"text": "It is possible to force nditer object to use a specific order by explicitly mentioning it."
},
{
"code": null,
"e": 4908,
"s": 4612,
"text": "import numpy as np \na = np.arange(0,60,5) \na = a.reshape(3,4) \n\nprint 'Original array is:' \nprint a \nprint '\\n' \n\nprint 'Sorted in C-style order:' \nfor x in np.nditer(a, order = 'C'): \n print x, \nprint '\\n' \n\nprint 'Sorted in F-style order:' \nfor x in np.nditer(a, order = 'F'): \n print x,"
},
{
"code": null,
"e": 4930,
"s": 4908,
"text": "Its output would be −"
},
{
"code": null,
"e": 5115,
"s": 4930,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nSorted in C-style order:\n0 5 10 15 20 25 30 35 40 45 50 55\n\nSorted in F-style order:\n0 20 40 5 25 45 10 30 50 15 35 55\n"
},
{
"code": null,
"e": 5325,
"s": 5115,
"text": "The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator."
},
{
"code": null,
"e": 5532,
"s": 5325,
"text": "import numpy as np\na = np.arange(0,60,5)\na = a.reshape(3,4)\nprint 'Original array is:'\nprint a\nprint '\\n'\n\nfor x in np.nditer(a, op_flags = ['readwrite']):\n x[...] = 2*x\nprint 'Modified array is:'\nprint a"
},
{
"code": null,
"e": 5559,
"s": 5532,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5694,
"s": 5559,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nModified array is:\n[[ 0 10 20 30]\n [ 40 50 60 70]\n [ 80 90 100 110]]\n"
},
{
"code": null,
"e": 5786,
"s": 5694,
"text": "The nditer class constructor has a ‘flags’ parameter, which can take the following values −"
},
{
"code": null,
"e": 5794,
"s": 5786,
"text": "c_index"
},
{
"code": null,
"e": 5823,
"s": 5794,
"text": "C_order index can be tracked"
},
{
"code": null,
"e": 5831,
"s": 5823,
"text": "f_index"
},
{
"code": null,
"e": 5862,
"s": 5831,
"text": "Fortran_order index is tracked"
},
{
"code": null,
"e": 5874,
"s": 5862,
"text": "multi-index"
},
{
"code": null,
"e": 5928,
"s": 5874,
"text": "Type of indexes with one per iteration can be tracked"
},
{
"code": null,
"e": 5942,
"s": 5928,
"text": "external_loop"
},
{
"code": null,
"e": 6046,
"s": 5942,
"text": "Causes values given to be one-dimensional arrays with multiple values instead of zero-dimensional array"
},
{
"code": null,
"e": 6154,
"s": 6046,
"text": "In the following example, one-dimensional arrays corresponding to each column is traversed by the iterator."
},
{
"code": null,
"e": 6372,
"s": 6154,
"text": "import numpy as np \na = np.arange(0,60,5) \na = a.reshape(3,4) \n\nprint 'Original array is:' \nprint a \nprint '\\n' \n\nprint 'Modified array is:' \nfor x in np.nditer(a, flags = ['external_loop'], order = 'F'):\n print x,"
},
{
"code": null,
"e": 6399,
"s": 6372,
"text": "The output is as follows −"
},
{
"code": null,
"e": 6528,
"s": 6399,
"text": "Original array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nModified array is:\n[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]\n"
},
{
"code": null,
"e": 6796,
"s": 6528,
"text": "If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a)."
},
{
"code": null,
"e": 7082,
"s": 6796,
"text": "import numpy as np \na = np.arange(0,60,5) \na = a.reshape(3,4) \n\nprint 'First array is:' \nprint a \nprint '\\n' \n\nprint 'Second array is:' \nb = np.array([1, 2, 3, 4], dtype = int) \nprint b \nprint '\\n' \n\nprint 'Modified array is:' \nfor x,y in np.nditer([a,b]): \n print \"%d:%d\" % (x,y),"
},
{
"code": null,
"e": 7115,
"s": 7082,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 7283,
"s": 7115,
"text": "First array is:\n[[ 0 5 10 15]\n [20 25 30 35]\n [40 45 50 55]]\n\nSecond array is:\n[1 2 3 4]\n\nModified array is:\n0:1 5:2 10:3 15:4 20:1 25:2 30:3 35:4 40:1 45:2 50:3 55:4\n"
},
{
"code": null,
"e": 7316,
"s": 7283,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7333,
"s": 7316,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7366,
"s": 7333,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7401,
"s": 7366,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 7434,
"s": 7401,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7469,
"s": 7434,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 7504,
"s": 7469,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7516,
"s": 7504,
"text": " Akbar Khan"
},
{
"code": null,
"e": 7549,
"s": 7516,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7564,
"s": 7549,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 7597,
"s": 7564,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7604,
"s": 7597,
"text": " Anmol"
},
{
"code": null,
"e": 7611,
"s": 7604,
"text": " Print"
},
{
"code": null,
"e": 7622,
"s": 7611,
"text": " Add Notes"
}
] |
How to create responsive "Meet The Team" page with CSS?
|
Following is the code to produce a responsive “meet the team” page using HTML and CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {
box-sizing: border-box;
}
body{
font-family: monospace,serif,sans-serif;
}
img{
height: 300px;
width: 100%;
}
*, *:before, *:after {
box-sizing: inherit;
}
.teamColumn {
float: left;
width: 33.3%;
margin-bottom: 16px;
padding: 0 8px;
}
@media screen and (max-width: 650px) {
.teamColumn {
width: 100%;
display: block;
}
}
.teamCard {
background-color: rgb(162, 162, 255);
text-align: center;
font-size: 20px;
}
.personContainer {
padding: 0 16px;
}
.personContainer::after, .teamContainer::after {
content: "";
clear: both;
display: table;
}
.Designation {
color: rgb(15, 0, 100);
font-weight: bolder;
font-size: 40px;
}
.contact {
border: none;
outline: 0;
display: inline-block;
padding: 12px;
color: white;
font-weight: bolder;
background-color: rgb(78, 0, 102);
text-align: center;
cursor: pointer;
width: 100%;
}
.contact:hover {
background-color: #555;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Responsive Meet the team example </h1>
<div class="teamContainer">
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" >
<div class="personContainer">
<h2>Jane Doe</h2>
<p class="Designation">CTO</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<div class="personContainer">
<h2>Mike Ross</h2>
<p class="Designation">Front End Developer</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
<div class="teamColumn">
<div class="teamCard">
<img src="https://images.pexels.com/photos/736716/pexels-photo-736716.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<div class="personContainer">
<h2>John Doe</h2>
<p class="Designation">FullStack Developer</p>
<p><button class="contact">Contact</button></p>
</div>
</div>
</div>
</div>
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "Following is the code to produce a responsive “meet the team” page using HTML and CSS −"
},
{
"code": null,
"e": 1161,
"s": 1150,
"text": " Live Demo"
},
{
"code": null,
"e": 3345,
"s": 1161,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nhtml {\n box-sizing: border-box;\n}\nbody{\n font-family: monospace,serif,sans-serif;\n}\nimg{\n height: 300px;\n width: 100%;\n}\n*, *:before, *:after {\n box-sizing: inherit;\n}\n.teamColumn {\n float: left;\n width: 33.3%;\n margin-bottom: 16px;\n padding: 0 8px;\n}\n@media screen and (max-width: 650px) {\n.teamColumn {\n width: 100%;\n display: block;\n}\n}\n.teamCard {\n background-color: rgb(162, 162, 255);\n text-align: center;\n font-size: 20px;\n}\n.personContainer {\n padding: 0 16px;\n}\n.personContainer::after, .teamContainer::after {\n content: \"\";\n clear: both;\n display: table;\n}\n.Designation {\n color: rgb(15, 0, 100);\n font-weight: bolder;\n font-size: 40px;\n}\n.contact {\n border: none;\n outline: 0;\n display: inline-block;\n padding: 12px;\n color: white;\n font-weight: bolder;\n background-color: rgb(78, 0, 102);\n text-align: center;\n cursor: pointer;\n width: 100%;\n}\n.contact:hover {\n background-color: #555;\n}\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">Responsive Meet the team example </h1>\n<div class=\"teamContainer\">\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img src=\"https://images.pexels.com/photos/839011/pexels-photo-839011.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\" >\n<div class=\"personContainer\">\n<h2>Jane Doe</h2>\n<p class=\"Designation\">CTO</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img src=\"https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\">\n<div class=\"personContainer\">\n<h2>Mike Ross</h2>\n<p class=\"Designation\">Front End Developer</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n<div class=\"teamColumn\">\n<div class=\"teamCard\">\n<img src=\"https://images.pexels.com/photos/736716/pexels-photo-736716.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\">\n<div class=\"personContainer\">\n<h2>John Doe</h2>\n<p class=\"Designation\">FullStack Developer</p>\n<p><button class=\"contact\">Contact</button></p>\n</div>\n</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 3396,
"s": 3345,
"text": "The above code will produce the following output −"
}
] |
Create and Manage Notification Channels in Android
|
This example demonstrate about Create and Manage Notification Channels in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :padding = "16dp"
tools :context = ".MainActivity" >
<Button
android :id = "@+id/btnCreateNotification"
android :layout_width = "0dp"
android :layout_height = "wrap_content"
android :text = "Create notification"
app :layout_constraintBottom_toBottomOf = "parent"
app :layout_constraintEnd_toEndOf = "parent"
app :layout_constraintStart_toStartOf = "parent"
app :layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add a sound into raw folder
Step 4 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.ContentResolver ;
import android.content.Context ;
import android.graphics.Color ;
import android.media.AudioAttributes ;
import android.net.Uri ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
import android.view.View ;
import android.widget.Button ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
Uri sound = Uri. parse (ContentResolver. SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/quite_impressed.mp3" ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this,
default_notification_channel_id )
.setSmallIcon(R.drawable. ic_launcher_foreground )
.setContentTitle( "Test" )
.setSound(sound)
.setContentText( "Hello! This is my first push notification" );
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes. CONTENT_TYPE_SONIFICATION )
.setUsage(AudioAttributes. USAGE_ALARM )
.build() ;
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new
NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
notificationChannel.enableLights( true ) ;
notificationChannel.setLightColor(Color. RED ) ;
notificationChannel.enableVibration( true ) ;
notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;
notificationChannel.setSound(sound , audioAttributes) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;
}
}) ;
}
}
Step 5 − Add the following code to androidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "app.tutorialspoint.com.notifyme" >
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrate about Create and Manage Notification Channels in Android"
},
{
"code": null,
"e": 1273,
"s": 1144,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2204,
"s": 1338,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<android.support.constraint.ConstraintLayout\n xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :id = \"@+id/btnCreateNotification\"\n android :layout_width = \"0dp\"\n android :layout_height = \"wrap_content\"\n android :text = \"Create notification\"\n app :layout_constraintBottom_toBottomOf = \"parent\"\n app :layout_constraintEnd_toEndOf = \"parent\"\n app :layout_constraintStart_toStartOf = \"parent\"\n app :layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2241,
"s": 2204,
"text": "Step 3 − Add a sound into raw folder"
},
{
"code": null,
"e": 2298,
"s": 2241,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5341,
"s": 2298,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.ContentResolver ;\nimport android.content.Context ;\nimport android.graphics.Color ;\nimport android.media.AudioAttributes ;\nimport android.net.Uri ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.os.Bundle ;\nimport android.view.View ;\nimport android.widget.Button ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n Uri sound = Uri. parse (ContentResolver. SCHEME_ANDROID_RESOURCE + \"://\" + getPackageName() + \"/raw/quite_impressed.mp3\" ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this,\n default_notification_channel_id )\n .setSmallIcon(R.drawable. ic_launcher_foreground )\n .setContentTitle( \"Test\" )\n .setSound(sound)\n .setContentText( \"Hello! This is my first push notification\" );\n NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n AudioAttributes audioAttributes = new AudioAttributes.Builder()\n .setContentType(AudioAttributes. CONTENT_TYPE_SONIFICATION )\n .setUsage(AudioAttributes. USAGE_ALARM )\n .build() ;\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new\n NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n notificationChannel.enableLights( true ) ;\n notificationChannel.setLightColor(Color. RED ) ;\n notificationChannel.enableVibration( true ) ;\n notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;\n notificationChannel.setSound(sound , audioAttributes) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;\n }\n }) ;\n }\n}"
},
{
"code": null,
"e": 5396,
"s": 5341,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6127,
"s": 5396,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 6474,
"s": 6127,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 6516,
"s": 6474,
"text": "Click here to download the project code"
}
] |
React Native - Modal
|
In this chapter, we will show you how to use the modal component in React Native.
Let us now create a new file: ModalExample.js
We will put logic inside ModalExample. We can update the initial state by running the toggleModal.
After updating the initial state by running the toggleModal, we will set the visible property to our modal. This prop will be updated when the state changes.
The onRequestClose is required for Android devices.
import React, { Component } from 'react'
import WebViewExample from './modal_example.js'
const Home = () => {
return (
<WebViewExample/>
)
}
export default Home;
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet}
from 'react-native'
class ModalExample extends Component {
state = {
modalVisible: false,
}
toggleModal(visible) {
this.setState({ modalVisible: visible });
}
render() {
return (
<View style = {styles.container}>
<Modal animationType = {"slide"} transparent = {false}
visible = {this.state.modalVisible}
onRequestClose = {() => { console.log("Modal has been closed.") } }>
<View style = {styles.modal}>
<Text style = {styles.text}>Modal is open!</Text>
<TouchableHighlight onPress = {() => {
this.toggleModal(!this.state.modalVisible)}}>
<Text style = {styles.text}>Close Modal</Text>
</TouchableHighlight>
</View>
</Modal>
<TouchableHighlight onPress = {() => {this.toggleModal(true)}}>
<Text style = {styles.text}>Open Modal</Text>
</TouchableHighlight>
</View>
)
}
}
export default ModalExample
const styles = StyleSheet.create ({
container: {
alignItems: 'center',
backgroundColor: '#ede3f2',
padding: 100
},
modal: {
flex: 1,
alignItems: 'center',
backgroundColor: '#f7021a',
padding: 100
},
text: {
color: '#3f2949',
marginTop: 10
}
})
Our starting screen will look like this −
If we click the button, the modal will open.
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2426,
"s": 2344,
"text": "In this chapter, we will show you how to use the modal component in React Native."
},
{
"code": null,
"e": 2472,
"s": 2426,
"text": "Let us now create a new file: ModalExample.js"
},
{
"code": null,
"e": 2571,
"s": 2472,
"text": "We will put logic inside ModalExample. We can update the initial state by running the toggleModal."
},
{
"code": null,
"e": 2729,
"s": 2571,
"text": "After updating the initial state by running the toggleModal, we will set the visible property to our modal. This prop will be updated when the state changes."
},
{
"code": null,
"e": 2781,
"s": 2729,
"text": "The onRequestClose is required for Android devices."
},
{
"code": null,
"e": 2956,
"s": 2781,
"text": "import React, { Component } from 'react'\nimport WebViewExample from './modal_example.js'\n\nconst Home = () => {\n return (\n <WebViewExample/>\n )\n}\nexport default Home;"
},
{
"code": null,
"e": 4523,
"s": 2956,
"text": "import React, { Component } from 'react';\nimport { Modal, Text, TouchableHighlight, View, StyleSheet}\n\nfrom 'react-native'\nclass ModalExample extends Component {\n state = {\n modalVisible: false,\n }\n toggleModal(visible) {\n this.setState({ modalVisible: visible });\n }\n render() {\n return (\n <View style = {styles.container}>\n <Modal animationType = {\"slide\"} transparent = {false}\n visible = {this.state.modalVisible}\n onRequestClose = {() => { console.log(\"Modal has been closed.\") } }>\n \n <View style = {styles.modal}>\n <Text style = {styles.text}>Modal is open!</Text>\n \n <TouchableHighlight onPress = {() => {\n this.toggleModal(!this.state.modalVisible)}}>\n \n <Text style = {styles.text}>Close Modal</Text>\n </TouchableHighlight>\n </View>\n </Modal>\n \n <TouchableHighlight onPress = {() => {this.toggleModal(true)}}>\n <Text style = {styles.text}>Open Modal</Text>\n </TouchableHighlight>\n </View>\n )\n }\n}\nexport default ModalExample\n\nconst styles = StyleSheet.create ({\n container: {\n alignItems: 'center',\n backgroundColor: '#ede3f2',\n padding: 100\n },\n modal: {\n flex: 1,\n alignItems: 'center',\n backgroundColor: '#f7021a',\n padding: 100\n },\n text: {\n color: '#3f2949',\n marginTop: 10\n }\n})"
},
{
"code": null,
"e": 4565,
"s": 4523,
"text": "Our starting screen will look like this −"
},
{
"code": null,
"e": 4610,
"s": 4565,
"text": "If we click the button, the modal will open."
},
{
"code": null,
"e": 4645,
"s": 4610,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4659,
"s": 4645,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4694,
"s": 4659,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4709,
"s": 4694,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 4744,
"s": 4709,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4772,
"s": 4744,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4808,
"s": 4772,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4836,
"s": 4808,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4871,
"s": 4836,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4883,
"s": 4871,
"text": " Senol Atac"
},
{
"code": null,
"e": 4918,
"s": 4883,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4930,
"s": 4918,
"text": " Senol Atac"
},
{
"code": null,
"e": 4937,
"s": 4930,
"text": " Print"
},
{
"code": null,
"e": 4948,
"s": 4937,
"text": " Add Notes"
}
] |
Detect Cycle in a Linked List using Map - GeeksforGeeks
|
29 Oct, 2021
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List
Example
Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list.
Input: 20->4->5->10->20 Output: Loop detected. Explanation: While traversing the linked list, reaching the node with value 10, it is linked with the head node, which depicts a loop in the linked list. Therefore, a loop is present in the linked list.
Approach:
Create a map that will store the visited node in the linked list.Traverse the linked list and do the following: Check whether the current node is present on the map or not.If the current node is not present in the map then, insert the current node into the map.If the Node is present in the map, the loop in a linked list is detected.If we reach the Null Node while traversing the linked list then, the given linked list has no loop present in it.
Create a map that will store the visited node in the linked list.
Traverse the linked list and do the following: Check whether the current node is present on the map or not.If the current node is not present in the map then, insert the current node into the map.If the Node is present in the map, the loop in a linked list is detected.
Check whether the current node is present on the map or not.
If the current node is not present in the map then, insert the current node into the map.
If the Node is present in the map, the loop in a linked list is detected.
If we reach the Null Node while traversing the linked list then, the given linked list has no loop present in it.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to detect loop in// given linked list using map#include <bits/stdc++.h>using namespace std; // Structure for a node in Linked Liststruct Node { int data; Node* next;}; // Function to create Linked List// NodeNode* newNode(int d){ Node* temp = new Node; temp->data = d; temp->next = NULL; return temp;} // Declaration of Map to keep// mark of visited Nodemap<Node*, bool> vis;bool flag = 0; // Function to check cycle in Linked// Listvoid check(Node* head){ // If head is NULL return ; if (head == NULL) { flag = 0; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis[head]) { vis[head] = true; check(head->next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = 1; return; }} // Driver Codeint main(){ // Create a head Node Node* head = newNode(20); // Inserting Node in Linked List head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(10); // Just to make a cycle head->next->next->next->next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) cout << "Loop detected."; // If flag is false, No Loop // detected else cout << "No Loop Found."; cout << endl; return 0;}
// Java program to detect loop in// given linked list using mapimport java.util.*; class GFG{ // Structure for a node in Linked Liststatic class Node{ int data; Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){ Node temp = new Node(); temp.data = d; temp.next = null; return temp;} // Declaration of Map to keep// mark of visited Nodestatic HashMap<Node, Boolean> vis = new HashMap<>();static boolean flag = false; // Function to check cycle in Linked// Liststatic void check(Node head){ // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (vis.containsKey(head)) { vis.put(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; }} // Driver Codepublic static void main(String[] args){ // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) System.out.print("Loop detected."); // If flag is false, No Loop // detected else System.out.print("No Loop Found."); System.out.println();}} // This code is contributed by Rajput-Ji
# Python3 program to detect loop in# given linked list using map # Structure for a node in Linked Listclass Node: def __init__(self, val): self.data = val self.Next = None # Function to create Linked List Nodedef newNode(d): temp = Node(d) return temp # Declaration of Map to keep# mark of visited Nodevis = {}flag = False # Function to check cycle in Linked# Listdef check(head): global vis, flag # If head is null return ; if head == None: flag = False return # Mark the incoming Node as # visited if it is not visited yet if head not in vis: vis[head] = True check(head.Next) # If a visited Node is found # Update the flag value to 1 # and return ; else: flag = True return # Create a head Nodehead = newNode(20) # Inserting Node in Linked Listhead.Next = newNode(4)head.Next.Next = newNode(5)head.Next.Next.Next = newNode(10) # Just to make a cyclehead.Next.Next.Next.Next = head # Function that detect cycle in# Linked Listcheck(head) # If flag is true, loop is foundif flag: print("Loop detected.") # If flag is false, No Loop# detectedelse: print("No Loop Found.") # This code is contributed by suresh07.
// C# program to detect loop in// given linked list using mapusing System;using System.Collections.Generic; class GFG{ // Structure for a node in Linked Listpublic class Node{ public int data; public Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){ Node temp = new Node(); temp.data = d; temp.next = null; return temp;} // Declaration of Map to keep// mark of visited Nodestatic Dictionary<Node, Boolean> vis = new Dictionary<Node, Boolean>();static bool flag = false; // Function to check cycle in Linked// Liststatic void check(Node head){ // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (vis.ContainsKey(head)) { vis.Add(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; }} // Driver Codepublic static void Main(String[] args){ // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) Console.Write("Loop detected."); // If flag is false, No Loop // detected else Console.Write("No Loop Found."); Console.WriteLine();}} // This code is contributed by gauravrajput1
<script>// javascript program to detect loop in// given linked list using map// Structure for a node in Linked List class Node { constructor(val) { this.data = val; this.next = null; } } // Function to create Linked List // Node function newNode(d) { var temp = new Node(); temp.data = d; temp.next = null; return temp; } // Declaration of Map to keep // mark of visited Node var vis = new Map();; var flag = false; // Function to check cycle in Linked // List function check(head) { // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis.has(head)) { vis.set(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; } } // Driver Code // Create a head Node var head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) document.write("Loop detected."); // If flag is false, No Loop // detected else document.write("No Loop Found."); document.write(); // This code contributed by Rajput-Ji</script>
Loop detected.
Time Complexity: O(N*log N) Auxiliary Space: O(N)
Code_Mech
Rajput-Ji
GauravRajput1
suresh07
Linked Lists
Algorithms
Linked List
Recursion
Linked List
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 24676,
"s": 24648,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 24806,
"s": 24676,
"text": "Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List"
},
{
"code": null,
"e": 24816,
"s": 24806,
"text": "Example "
},
{
"code": null,
"e": 25005,
"s": 24816,
"text": "Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list."
},
{
"code": null,
"e": 25256,
"s": 25005,
"text": "Input: 20->4->5->10->20 Output: Loop detected. Explanation: While traversing the linked list, reaching the node with value 10, it is linked with the head node, which depicts a loop in the linked list. Therefore, a loop is present in the linked list. "
},
{
"code": null,
"e": 25266,
"s": 25256,
"text": "Approach:"
},
{
"code": null,
"e": 25714,
"s": 25266,
"text": "Create a map that will store the visited node in the linked list.Traverse the linked list and do the following: Check whether the current node is present on the map or not.If the current node is not present in the map then, insert the current node into the map.If the Node is present in the map, the loop in a linked list is detected.If we reach the Null Node while traversing the linked list then, the given linked list has no loop present in it."
},
{
"code": null,
"e": 25780,
"s": 25714,
"text": "Create a map that will store the visited node in the linked list."
},
{
"code": null,
"e": 26050,
"s": 25780,
"text": "Traverse the linked list and do the following: Check whether the current node is present on the map or not.If the current node is not present in the map then, insert the current node into the map.If the Node is present in the map, the loop in a linked list is detected."
},
{
"code": null,
"e": 26111,
"s": 26050,
"text": "Check whether the current node is present on the map or not."
},
{
"code": null,
"e": 26201,
"s": 26111,
"text": "If the current node is not present in the map then, insert the current node into the map."
},
{
"code": null,
"e": 26275,
"s": 26201,
"text": "If the Node is present in the map, the loop in a linked list is detected."
},
{
"code": null,
"e": 26389,
"s": 26275,
"text": "If we reach the Null Node while traversing the linked list then, the given linked list has no loop present in it."
},
{
"code": null,
"e": 26440,
"s": 26389,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26444,
"s": 26440,
"text": "C++"
},
{
"code": null,
"e": 26449,
"s": 26444,
"text": "Java"
},
{
"code": null,
"e": 26457,
"s": 26449,
"text": "Python3"
},
{
"code": null,
"e": 26460,
"s": 26457,
"text": "C#"
},
{
"code": null,
"e": 26471,
"s": 26460,
"text": "Javascript"
},
{
"code": "// C++ program to detect loop in// given linked list using map#include <bits/stdc++.h>using namespace std; // Structure for a node in Linked Liststruct Node { int data; Node* next;}; // Function to create Linked List// NodeNode* newNode(int d){ Node* temp = new Node; temp->data = d; temp->next = NULL; return temp;} // Declaration of Map to keep// mark of visited Nodemap<Node*, bool> vis;bool flag = 0; // Function to check cycle in Linked// Listvoid check(Node* head){ // If head is NULL return ; if (head == NULL) { flag = 0; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis[head]) { vis[head] = true; check(head->next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = 1; return; }} // Driver Codeint main(){ // Create a head Node Node* head = newNode(20); // Inserting Node in Linked List head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(10); // Just to make a cycle head->next->next->next->next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) cout << \"Loop detected.\"; // If flag is false, No Loop // detected else cout << \"No Loop Found.\"; cout << endl; return 0;}",
"e": 27899,
"s": 26471,
"text": null
},
{
"code": "// Java program to detect loop in// given linked list using mapimport java.util.*; class GFG{ // Structure for a node in Linked Liststatic class Node{ int data; Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){ Node temp = new Node(); temp.data = d; temp.next = null; return temp;} // Declaration of Map to keep// mark of visited Nodestatic HashMap<Node, Boolean> vis = new HashMap<>();static boolean flag = false; // Function to check cycle in Linked// Liststatic void check(Node head){ // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (vis.containsKey(head)) { vis.put(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; }} // Driver Codepublic static void main(String[] args){ // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) System.out.print(\"Loop detected.\"); // If flag is false, No Loop // detected else System.out.print(\"No Loop Found.\"); System.out.println();}} // This code is contributed by Rajput-Ji",
"e": 29495,
"s": 27899,
"text": null
},
{
"code": "# Python3 program to detect loop in# given linked list using map # Structure for a node in Linked Listclass Node: def __init__(self, val): self.data = val self.Next = None # Function to create Linked List Nodedef newNode(d): temp = Node(d) return temp # Declaration of Map to keep# mark of visited Nodevis = {}flag = False # Function to check cycle in Linked# Listdef check(head): global vis, flag # If head is null return ; if head == None: flag = False return # Mark the incoming Node as # visited if it is not visited yet if head not in vis: vis[head] = True check(head.Next) # If a visited Node is found # Update the flag value to 1 # and return ; else: flag = True return # Create a head Nodehead = newNode(20) # Inserting Node in Linked Listhead.Next = newNode(4)head.Next.Next = newNode(5)head.Next.Next.Next = newNode(10) # Just to make a cyclehead.Next.Next.Next.Next = head # Function that detect cycle in# Linked Listcheck(head) # If flag is true, loop is foundif flag: print(\"Loop detected.\") # If flag is false, No Loop# detectedelse: print(\"No Loop Found.\") # This code is contributed by suresh07.",
"e": 30718,
"s": 29495,
"text": null
},
{
"code": "// C# program to detect loop in// given linked list using mapusing System;using System.Collections.Generic; class GFG{ // Structure for a node in Linked Listpublic class Node{ public int data; public Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){ Node temp = new Node(); temp.data = d; temp.next = null; return temp;} // Declaration of Map to keep// mark of visited Nodestatic Dictionary<Node, Boolean> vis = new Dictionary<Node, Boolean>();static bool flag = false; // Function to check cycle in Linked// Liststatic void check(Node head){ // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (vis.ContainsKey(head)) { vis.Add(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; }} // Driver Codepublic static void Main(String[] args){ // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) Console.Write(\"Loop detected.\"); // If flag is false, No Loop // detected else Console.Write(\"No Loop Found.\"); Console.WriteLine();}} // This code is contributed by gauravrajput1",
"e": 32438,
"s": 30718,
"text": null
},
{
"code": "<script>// javascript program to detect loop in// given linked list using map// Structure for a node in Linked List class Node { constructor(val) { this.data = val; this.next = null; } } // Function to create Linked List // Node function newNode(d) { var temp = new Node(); temp.data = d; temp.next = null; return temp; } // Declaration of Map to keep // mark of visited Node var vis = new Map();; var flag = false; // Function to check cycle in Linked // List function check(head) { // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis.has(head)) { vis.set(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; } } // Driver Code // Create a head Node var head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) document.write(\"Loop detected.\"); // If flag is false, No Loop // detected else document.write(\"No Loop Found.\"); document.write(); // This code contributed by Rajput-Ji</script>",
"e": 34173,
"s": 32438,
"text": null
},
{
"code": null,
"e": 34188,
"s": 34173,
"text": "Loop detected."
},
{
"code": null,
"e": 34241,
"s": 34190,
"text": "Time Complexity: O(N*log N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34251,
"s": 34241,
"text": "Code_Mech"
},
{
"code": null,
"e": 34261,
"s": 34251,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34275,
"s": 34261,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34284,
"s": 34275,
"text": "suresh07"
},
{
"code": null,
"e": 34297,
"s": 34284,
"text": "Linked Lists"
},
{
"code": null,
"e": 34308,
"s": 34297,
"text": "Algorithms"
},
{
"code": null,
"e": 34320,
"s": 34308,
"text": "Linked List"
},
{
"code": null,
"e": 34330,
"s": 34320,
"text": "Recursion"
},
{
"code": null,
"e": 34342,
"s": 34330,
"text": "Linked List"
},
{
"code": null,
"e": 34352,
"s": 34342,
"text": "Recursion"
},
{
"code": null,
"e": 34363,
"s": 34352,
"text": "Algorithms"
},
{
"code": null,
"e": 34461,
"s": 34363,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34486,
"s": 34461,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34529,
"s": 34486,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 34572,
"s": 34529,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 34618,
"s": 34572,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 34647,
"s": 34618,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 34682,
"s": 34647,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 34721,
"s": 34682,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 34743,
"s": 34721,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 34791,
"s": 34743,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
C++ List Library - resize() Function
|
The C++ function std::list::resize() changes the size of list. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of list.
Following is the declaration for std::list::resize() function form std::list header.
void resize (size_type n);
n − Number of element to be inserted.
None
If reallocation fails then bad_alloc exception is thrown.
Linear i.e. O(n)
The following example shows the usage of std::list::resize() function.
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l;
cout << "Initial size of list = " << l.size() << endl;
l.resize(5);
cout << "Size of list after resize operation = " << l.size() << endl;
cout << "List contains following elements" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial size of list = 0
Size of list after resize operation = 5
List contains following elements
0
0
0
0
0
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2830,
"s": 2603,
"text": "The C++ function std::list::resize() changes the size of list. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of list."
},
{
"code": null,
"e": 2915,
"s": 2830,
"text": "Following is the declaration for std::list::resize() function form std::list header."
},
{
"code": null,
"e": 2943,
"s": 2915,
"text": "void resize (size_type n);\n"
},
{
"code": null,
"e": 2981,
"s": 2943,
"text": "n − Number of element to be inserted."
},
{
"code": null,
"e": 2986,
"s": 2981,
"text": "None"
},
{
"code": null,
"e": 3044,
"s": 2986,
"text": "If reallocation fails then bad_alloc exception is thrown."
},
{
"code": null,
"e": 3061,
"s": 3044,
"text": "Linear i.e. O(n)"
},
{
"code": null,
"e": 3132,
"s": 3061,
"text": "The following example shows the usage of std::list::resize() function."
},
{
"code": null,
"e": 3524,
"s": 3132,
"text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l;\n\n cout << \"Initial size of list = \" << l.size() << endl;\n\n l.resize(5);\n\n cout << \"Size of list after resize operation = \" << l.size() << endl;\n\n cout << \"List contains following elements\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3607,
"s": 3524,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3716,
"s": 3607,
"text": "Initial size of list = 0\nSize of list after resize operation = 5\nList contains following elements\n0\n0\n0\n0\n0\n"
},
{
"code": null,
"e": 3723,
"s": 3716,
"text": " Print"
},
{
"code": null,
"e": 3734,
"s": 3723,
"text": " Add Notes"
}
] |
Convert a string to an integer in JavaScript - GeeksforGeeks
|
26 Jul, 2021
In JavaScript parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function.parseInt() function returns Nan( not a number) when the string doesn’t contain number.
Syntax:
parseInt(Value, radix)
It accepts string as a value and converts it to specified radix system and returns an integer.
Program to convert string to integer:Example-1:
<script> function convertStoI() { var a = "100"; var b = parseInt(a); document.write("Integer value is" + b); var d = parseInt("3 11 43"); document.write("</br>"); document.write('Integer value is ' + d); }convertStoI(); </script>
Output:
Integer value is100
Integer value is 3
ParseInt() function converts number which is present in any base to base 10. It parses string and converts until it faces a string literal and stops parsing.
Example-2:
<script> function convertStoI() { var r = parseInt("1011", 2); var k = parseInt("234", 8); document.write('Integer value is ' + r); document.write("<br>"); document.write("integer value is " + k); document.write("<br>"); document.write(parseInt("528GeeksforGeeks")); }convertStoI();</script>
Output:
Integer value is 11
integer value is 156
528
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
How to read a local text file using JavaScript?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24592,
"s": 24564,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24860,
"s": 24592,
"text": "In JavaScript parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function.parseInt() function returns Nan( not a number) when the string doesn’t contain number."
},
{
"code": null,
"e": 24868,
"s": 24860,
"text": "Syntax:"
},
{
"code": null,
"e": 24891,
"s": 24868,
"text": "parseInt(Value, radix)"
},
{
"code": null,
"e": 24986,
"s": 24891,
"text": "It accepts string as a value and converts it to specified radix system and returns an integer."
},
{
"code": null,
"e": 25034,
"s": 24986,
"text": "Program to convert string to integer:Example-1:"
},
{
"code": "<script> function convertStoI() { var a = \"100\"; var b = parseInt(a); document.write(\"Integer value is\" + b); var d = parseInt(\"3 11 43\"); document.write(\"</br>\"); document.write('Integer value is ' + d); }convertStoI(); </script> ",
"e": 25323,
"s": 25034,
"text": null
},
{
"code": null,
"e": 25331,
"s": 25323,
"text": "Output:"
},
{
"code": null,
"e": 25370,
"s": 25331,
"text": "Integer value is100\nInteger value is 3"
},
{
"code": null,
"e": 25528,
"s": 25370,
"text": "ParseInt() function converts number which is present in any base to base 10. It parses string and converts until it faces a string literal and stops parsing."
},
{
"code": null,
"e": 25539,
"s": 25528,
"text": "Example-2:"
},
{
"code": "<script> function convertStoI() { var r = parseInt(\"1011\", 2); var k = parseInt(\"234\", 8); document.write('Integer value is ' + r); document.write(\"<br>\"); document.write(\"integer value is \" + k); document.write(\"<br>\"); document.write(parseInt(\"528GeeksforGeeks\")); }convertStoI();</script> ",
"e": 25912,
"s": 25539,
"text": null
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Output:"
},
{
"code": null,
"e": 25965,
"s": 25920,
"text": "Integer value is 11\ninteger value is 156\n528"
},
{
"code": null,
"e": 26184,
"s": 25965,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 26205,
"s": 26184,
"text": "javascript-functions"
},
{
"code": null,
"e": 26212,
"s": 26205,
"text": "Picked"
},
{
"code": null,
"e": 26223,
"s": 26212,
"text": "JavaScript"
},
{
"code": null,
"e": 26240,
"s": 26223,
"text": "Web Technologies"
},
{
"code": null,
"e": 26338,
"s": 26240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26347,
"s": 26338,
"text": "Comments"
},
{
"code": null,
"e": 26360,
"s": 26347,
"text": "Old Comments"
},
{
"code": null,
"e": 26421,
"s": 26360,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26493,
"s": 26421,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26534,
"s": 26493,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26580,
"s": 26534,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 26628,
"s": 26580,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 26670,
"s": 26628,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26703,
"s": 26670,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26746,
"s": 26703,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26808,
"s": 26746,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Program to find sum of given sequence in C++
|
In this problem, we are given two numbers n and k for a series. Our task is to
create a program to find sum of given sequence in C++.
The sequence is −
(1*2*3*...*k) + (2*3*...k*(k+1)) + (3*4*...*k*k+1*k+2) + ((n-k+1)*(nk+
2)*... *(n-k+k).
Problem description − Here, we will find the sum of the given series till nth term based on the given value of k.
Let’s take an example to understand the problem
n = 4, k = 3
30
Series: (1*2*3) + (2*3*4) = 30
A simple solution is to find the sum using iteration. We will use two loops,
one for each term and second for finding the value of the term. Then adding
the value of each term to get the result.
Program to illustrate the working of our solution
Live Demo
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
int sumVal = 0, term = 1;
for(int i = 1; i <= (n-k + 1); i++){
term = 1;
for(int j = i; j< (k+i); j++){
term *= j;
}
sumVal += term;
}
return sumVal;
}
int main(){
int n = 4, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}
The sum of series is 30
This solution is not efficient as it needs a nested loop that makes the time
complexity of the order O(n2).
An efficient solution could be using the general formula for the series. The formula is,
(◻+1)∗◻∗(◻−1)∗(◻−2)∗....∗(◻−◻+1)◻+1
Program to illustrate the working of our solution
Live Demo
#include <iostream>
using namespace std;
int findSeriesSum(int n, int k){
int sumVal = 1;
for(int i = n+1; i > n-k; i--)
sumVal *= i;
sumVal /= (k + 1);
return sumVal;
}
int main(){
int n = 4, k = 3;
cout<<"The sum of series is "<<findSeriesSum(n, k);
return 0;
}
The sum of series is 30
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "In this problem, we are given two numbers n and k for a series. Our task is to\ncreate a program to find sum of given sequence in C++."
},
{
"code": null,
"e": 1214,
"s": 1196,
"text": "The sequence is −"
},
{
"code": null,
"e": 1302,
"s": 1214,
"text": "(1*2*3*...*k) + (2*3*...k*(k+1)) + (3*4*...*k*k+1*k+2) + ((n-k+1)*(nk+\n2)*... *(n-k+k)."
},
{
"code": null,
"e": 1416,
"s": 1302,
"text": "Problem description − Here, we will find the sum of the given series till nth term based on the given value of k."
},
{
"code": null,
"e": 1464,
"s": 1416,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1477,
"s": 1464,
"text": "n = 4, k = 3"
},
{
"code": null,
"e": 1480,
"s": 1477,
"text": "30"
},
{
"code": null,
"e": 1511,
"s": 1480,
"text": "Series: (1*2*3) + (2*3*4) = 30"
},
{
"code": null,
"e": 1706,
"s": 1511,
"text": "A simple solution is to find the sum using iteration. We will use two loops,\none for each term and second for finding the value of the term. Then adding\nthe value of each term to get the result."
},
{
"code": null,
"e": 1756,
"s": 1706,
"text": "Program to illustrate the working of our solution"
},
{
"code": null,
"e": 1767,
"s": 1756,
"text": " Live Demo"
},
{
"code": null,
"e": 2141,
"s": 1767,
"text": "#include <iostream>\nusing namespace std;\nint findSeriesSum(int n, int k){\n int sumVal = 0, term = 1;\n for(int i = 1; i <= (n-k + 1); i++){\n term = 1;\n for(int j = i; j< (k+i); j++){\n term *= j;\n }\n sumVal += term;\n }\n return sumVal;\n}\nint main(){\n int n = 4, k = 3;\n cout<<\"The sum of series is \"<<findSeriesSum(n, k);\n return 0;\n}"
},
{
"code": null,
"e": 2165,
"s": 2141,
"text": "The sum of series is 30"
},
{
"code": null,
"e": 2273,
"s": 2165,
"text": "This solution is not efficient as it needs a nested loop that makes the time\ncomplexity of the order O(n2)."
},
{
"code": null,
"e": 2362,
"s": 2273,
"text": "An efficient solution could be using the general formula for the series. The formula is,"
},
{
"code": null,
"e": 2398,
"s": 2362,
"text": "(◻+1)∗◻∗(◻−1)∗(◻−2)∗....∗(◻−◻+1)◻+1"
},
{
"code": null,
"e": 2448,
"s": 2398,
"text": "Program to illustrate the working of our solution"
},
{
"code": null,
"e": 2459,
"s": 2448,
"text": " Live Demo"
},
{
"code": null,
"e": 2747,
"s": 2459,
"text": "#include <iostream>\nusing namespace std;\nint findSeriesSum(int n, int k){\n int sumVal = 1;\n for(int i = n+1; i > n-k; i--)\n sumVal *= i;\n sumVal /= (k + 1);\n return sumVal;\n}\nint main(){\n int n = 4, k = 3;\n cout<<\"The sum of series is \"<<findSeriesSum(n, k);\n return 0;\n}"
},
{
"code": null,
"e": 2771,
"s": 2747,
"text": "The sum of series is 30"
}
] |
DataTables lengthMenu Option - GeeksforGeeks
|
21 Jul, 2021
DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed.
The lengthMenu option is used to specify the options that are available in the drop-down list that controls the number of rows that a single page will have when pagination is enabled. It can be specified with either a one-dimensional list that allows only specifying the number of rows or a two-dimensional list that allows specifying both the number of rows and the text that will be actually displayed in the drop-down list.
The length values specified have to be a positive number. Any negative value specified will display all available rows in the table and disable pagination.
Syntax:
{ lengthMenu: value }
Parameters: This option has a single value as mentioned above and described below:
value: This can be a one-dimensional or two-dimensional array that determines the pagination length menu along with the text that will be displayed.
The examples below illustrate the use of this option.
Example 1: In this example, a one-dimensional array is used to specify the options drop-down length.
HTML
<!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the pagination length menu // to the given allowed sizes lengthMenu: [ 3, 5, 10 ] }); }); </script></body> </html>
Output:
Example 2: In this example, a two-dimensional array is used to specify the options drop-down length and the text that will be used for them.
HTML
<!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the pagination length menu // to the given allowed sizes // and display the given labels lengthMenu: [ [ 3, 5, 10, -1 ], [ "Some", "More", "Some More", "All"] ] }); }); </script></body> </html>
Output:
Reference: https://datatables.net/reference/option/lengthMenu
jQuery-DataTables
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
jQuery | parent() & parents() with Examples
Difference Between JavaScript and jQuery
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 25755,
"s": 25727,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 26093,
"s": 25755,
"text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed."
},
{
"code": null,
"e": 26520,
"s": 26093,
"text": "The lengthMenu option is used to specify the options that are available in the drop-down list that controls the number of rows that a single page will have when pagination is enabled. It can be specified with either a one-dimensional list that allows only specifying the number of rows or a two-dimensional list that allows specifying both the number of rows and the text that will be actually displayed in the drop-down list."
},
{
"code": null,
"e": 26676,
"s": 26520,
"text": "The length values specified have to be a positive number. Any negative value specified will display all available rows in the table and disable pagination."
},
{
"code": null,
"e": 26684,
"s": 26676,
"text": "Syntax:"
},
{
"code": null,
"e": 26706,
"s": 26684,
"text": "{ lengthMenu: value }"
},
{
"code": null,
"e": 26791,
"s": 26708,
"text": "Parameters: This option has a single value as mentioned above and described below:"
},
{
"code": null,
"e": 26940,
"s": 26791,
"text": "value: This can be a one-dimensional or two-dimensional array that determines the pagination length menu along with the text that will be displayed."
},
{
"code": null,
"e": 26994,
"s": 26940,
"text": "The examples below illustrate the use of this option."
},
{
"code": null,
"e": 27095,
"s": 26994,
"text": "Example 1: In this example, a one-dimensional array is used to specify the options drop-down length."
},
{
"code": null,
"e": 27100,
"s": 27095,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the pagination length menu // to the given allowed sizes lengthMenu: [ 3, 5, 10 ] }); }); </script></body> </html>",
"e": 29061,
"s": 27100,
"text": null
},
{
"code": null,
"e": 29069,
"s": 29061,
"text": "Output:"
},
{
"code": null,
"e": 29210,
"s": 29069,
"text": "Example 2: In this example, a two-dimensional array is used to specify the options drop-down length and the text that will be used for them."
},
{
"code": null,
"e": 29215,
"s": 29210,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the pagination length menu // to the given allowed sizes // and display the given labels lengthMenu: [ [ 3, 5, 10, -1 ], [ \"Some\", \"More\", \"Some More\", \"All\"] ] }); }); </script></body> </html>",
"e": 31287,
"s": 29215,
"text": null
},
{
"code": null,
"e": 31295,
"s": 31287,
"text": "Output:"
},
{
"code": null,
"e": 31357,
"s": 31295,
"text": "Reference: https://datatables.net/reference/option/lengthMenu"
},
{
"code": null,
"e": 31375,
"s": 31357,
"text": "jQuery-DataTables"
},
{
"code": null,
"e": 31382,
"s": 31375,
"text": "JQuery"
},
{
"code": null,
"e": 31399,
"s": 31382,
"text": "Web Technologies"
},
{
"code": null,
"e": 31497,
"s": 31399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31570,
"s": 31497,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 31593,
"s": 31570,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 31650,
"s": 31593,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 31694,
"s": 31650,
"text": "jQuery | parent() & parents() with Examples"
},
{
"code": null,
"e": 31735,
"s": 31694,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 31777,
"s": 31735,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31810,
"s": 31777,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31853,
"s": 31810,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31915,
"s": 31853,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Set.forEach() function in JavaScript
|
The forEach() function of the Set object accepts the name of a particular function and runs that function for every value in the current set. For Example, if you have written a function to print a value, if you use forEach() function it prints the value of every element in the set.
Its Syntax is as follows
setObj.forEach()
Live Demo
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
function sampleFunction(value){
document.writeln(value+",");
}
const setObj1 = new Set();
setObj1.add('Java');
setObj1.add('JavaFX');
setObj1.add('JavaScript');
setObj1.add('HBase');
setObj1.forEach(sampleFunction);
document.write("<br>");
var sum = 0;
function mathExample(value) {
sum = value+sum;
//document.write(value);
}
const setObj2 = new Set();
setObj2.add(172);
setObj2.add(364);
setObj2.add(885);
setObj2.add(746);
setObj2.forEach(mathExample);
document.write("Sum of all elements in the set: "+sum);
</script>
</body>
</html>
Java, JavaFX, JavaScript, HBase,
Sum of all elements in the set: 2167
|
[
{
"code": null,
"e": 1345,
"s": 1062,
"text": "The forEach() function of the Set object accepts the name of a particular function and runs that function for every value in the current set. For Example, if you have written a function to print a value, if you use forEach() function it prints the value of every element in the set."
},
{
"code": null,
"e": 1370,
"s": 1345,
"text": "Its Syntax is as follows"
},
{
"code": null,
"e": 1387,
"s": 1370,
"text": "setObj.forEach()"
},
{
"code": null,
"e": 1398,
"s": 1387,
"text": " Live Demo"
},
{
"code": null,
"e": 2181,
"s": 1398,
"text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n function sampleFunction(value){\n document.writeln(value+\",\");\n }\n const setObj1 = new Set();\n setObj1.add('Java');\n setObj1.add('JavaFX');\n setObj1.add('JavaScript');\n setObj1.add('HBase');\n setObj1.forEach(sampleFunction);\n document.write(\"<br>\");\n var sum = 0;\n function mathExample(value) {\n sum = value+sum;\n //document.write(value);\n }\n const setObj2 = new Set();\n setObj2.add(172);\n setObj2.add(364);\n setObj2.add(885);\n setObj2.add(746);\n setObj2.forEach(mathExample);\n document.write(\"Sum of all elements in the set: \"+sum);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2251,
"s": 2181,
"text": "Java, JavaFX, JavaScript, HBase,\nSum of all elements in the set: 2167"
}
] |
What is Kestrel and how does it differ from IIS? (ASP.NET)
|
Kestrel is a lightweight, cross-platform, and open-source web server for ASP.NET Core. It is included and enabled by default in ASP.NET Core. Kestrel is supported on all platforms and versions supported by .NET Core.
In the Program class, the ConfigureWebHostDefaults() method configures Kestrel as the web server for the ASP.NET Core application.
public class Program{
public static void Main(string[] args){
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>{
webBuilder.UseStartup<Startup>();
});
}
Though Kestrel can serve an ASP.NET Core application on its own, Microsoft recommends using it along with a reverse proxy such as Apache, IIS, or Nginx for better performance, security, and reliability.
The main difference between IIS and Kestrel is that Kestrel is a cross-platform server. It runs on Linux, Windows, and Mac, whereas IIS is Windows-specific.
Another essential difference between the two is that Kestrel is fully open-source, whereas IIS is closed-source and developed and maintained only by Microsoft.
IIS is an old, albeit powerful software. With Kestrel, Microsoft started with cross-platform and high performance as explicit design goals. Since the Kestrel codebase started from scratch, it allowed developers to ignore the legacy/compatibility issues and focus on speed and efficiency.
However, Kestrel doesn’t provide all the rich functionality of a full-fledged web server such as IIS, Nginx, or Apache. Hence, we typically use it as an application server, with one of the above servers acting as a reverse proxy.
|
[
{
"code": null,
"e": 1279,
"s": 1062,
"text": "Kestrel is a lightweight, cross-platform, and open-source web server for ASP.NET Core. It is included and enabled by default in ASP.NET Core. Kestrel is supported on all platforms and versions supported by .NET Core."
},
{
"code": null,
"e": 1410,
"s": 1279,
"text": "In the Program class, the ConfigureWebHostDefaults() method configures Kestrel as the web server for the ASP.NET Core application."
},
{
"code": null,
"e": 1741,
"s": 1410,
"text": "public class Program{\n public static void Main(string[] args){\n CreateHostBuilder(args).Build().Run();\n }\n\n public static IHostBuilder CreateHostBuilder(string[] args) =>\n Host.CreateDefaultBuilder(args)\n .ConfigureWebHostDefaults(webBuilder =>{\n webBuilder.UseStartup<Startup>();\n });\n}"
},
{
"code": null,
"e": 1944,
"s": 1741,
"text": "Though Kestrel can serve an ASP.NET Core application on its own, Microsoft recommends using it along with a reverse proxy such as Apache, IIS, or Nginx for better performance, security, and reliability."
},
{
"code": null,
"e": 2101,
"s": 1944,
"text": "The main difference between IIS and Kestrel is that Kestrel is a cross-platform server. It runs on Linux, Windows, and Mac, whereas IIS is Windows-specific."
},
{
"code": null,
"e": 2261,
"s": 2101,
"text": "Another essential difference between the two is that Kestrel is fully open-source, whereas IIS is closed-source and developed and maintained only by Microsoft."
},
{
"code": null,
"e": 2549,
"s": 2261,
"text": "IIS is an old, albeit powerful software. With Kestrel, Microsoft started with cross-platform and high performance as explicit design goals. Since the Kestrel codebase started from scratch, it allowed developers to ignore the legacy/compatibility issues and focus on speed and efficiency."
},
{
"code": null,
"e": 2779,
"s": 2549,
"text": "However, Kestrel doesn’t provide all the rich functionality of a full-fledged web server such as IIS, Nginx, or Apache. Hence, we typically use it as an application server, with one of the above servers acting as a reverse proxy."
}
] |
Python unittest - assertAlmostEqual() function - GeeksforGeeks
|
29 Aug, 2020
assertAlmostEqual() in Python is a unittest library function that is used in unit testing to check whether two given values are almost equal or not. This function will take five parameters as input and return a boolean value depending upon the assert condition.
This function check that first and second are approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.
If delta is supplied instead of places then the difference between first and second must be less or equal to delta.
Syntax: assertAlmostEqual(first, second, places=7, message=None, delta=None)
Parameters: assertAlmostEqual() accept three parameters which are listed below with explanation:
first: first input value (integer)
second: second input value (integer)
places: decimal places for approximation
message: a string sentence as a message which got displayed when the test case got failed.
delta: delta value for approximation
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example :
Python3
# test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values are almost equal with place def test_negativeWithPlaces(self): first = 4.4555 second = 4.4566 decimalPlace = 3 # error message in case if test case got failed message = "first and second are not almost equal." # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, decimalPlace, message) # positive test function to test if values are almost equal with place def test_positiveWithPlaces(self): first = 4.4555 second = 4.4566 decimalPlace = 2 # error message in case if test case got failed message = "first and second are not almost equal." # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, decimalPlace, message) # negative test function to test if values are almost equal with delta def test_negativeWithDelta(self): first = 4.4555 second = 4.4566 delta = 0.0001 # error message in case if test case got failed message = "first and second are not almost equal." # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, None, message, delta) # positive test function to test if values are almost equal with delta def test_positiveWithDelta(self): first = 4.4555 second = 4.4566 delta = 0.002 # error message in case if test case got failed message = "first and second are not almost equal." # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, None, message, delta) if __name__ == '__main__': unittest.main()
Output:
FF..
======================================================================
FAIL: test_negativeWithDelta (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/2c36bbd2c940a6c7b81a901ebfdd2ad8.py", line 34, in test_negativeWithDelta
self.assertAlmostEqual(first, second, None, message, delta)
AssertionError: 4.4555 != 4.4566 within 0.0001 delta : first and second are not almost equal.
======================================================================
FAIL: test_negativeWithPlaces (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/2c36bbd2c940a6c7b81a901ebfdd2ad8.py", line 14, in test_negativeWithPlaces
self.assertAlmostEqual(first, second, decimalPlace, message)
AssertionError: 4.4555 != 4.4566 within 3 places : first and second are not almost equal.
----------------------------------------------------------------------
Ran 4 tests in 0.001s
FAILED (failures=2)
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24777,
"s": 24514,
"text": "assertAlmostEqual() in Python is a unittest library function that is used in unit testing to check whether two given values are almost equal or not. This function will take five parameters as input and return a boolean value depending upon the assert condition. "
},
{
"code": null,
"e": 24955,
"s": 24777,
"text": "This function check that first and second are approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero."
},
{
"code": null,
"e": 25071,
"s": 24955,
"text": "If delta is supplied instead of places then the difference between first and second must be less or equal to delta."
},
{
"code": null,
"e": 25148,
"s": 25071,
"text": "Syntax: assertAlmostEqual(first, second, places=7, message=None, delta=None)"
},
{
"code": null,
"e": 25245,
"s": 25148,
"text": "Parameters: assertAlmostEqual() accept three parameters which are listed below with explanation:"
},
{
"code": null,
"e": 25280,
"s": 25245,
"text": "first: first input value (integer)"
},
{
"code": null,
"e": 25318,
"s": 25280,
"text": "second: second input value (integer)"
},
{
"code": null,
"e": 25359,
"s": 25318,
"text": "places: decimal places for approximation"
},
{
"code": null,
"e": 25450,
"s": 25359,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 25487,
"s": 25450,
"text": "delta: delta value for approximation"
},
{
"code": null,
"e": 25603,
"s": 25487,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 25613,
"s": 25603,
"text": "Example :"
},
{
"code": null,
"e": 25621,
"s": 25613,
"text": "Python3"
},
{
"code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values are almost equal with place def test_negativeWithPlaces(self): first = 4.4555 second = 4.4566 decimalPlace = 3 # error message in case if test case got failed message = \"first and second are not almost equal.\" # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, decimalPlace, message) # positive test function to test if values are almost equal with place def test_positiveWithPlaces(self): first = 4.4555 second = 4.4566 decimalPlace = 2 # error message in case if test case got failed message = \"first and second are not almost equal.\" # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, decimalPlace, message) # negative test function to test if values are almost equal with delta def test_negativeWithDelta(self): first = 4.4555 second = 4.4566 delta = 0.0001 # error message in case if test case got failed message = \"first and second are not almost equal.\" # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, None, message, delta) # positive test function to test if values are almost equal with delta def test_positiveWithDelta(self): first = 4.4555 second = 4.4566 delta = 0.002 # error message in case if test case got failed message = \"first and second are not almost equal.\" # assert function() to check if values are almost equal self.assertAlmostEqual(first, second, None, message, delta) if __name__ == '__main__': unittest.main()",
"e": 27442,
"s": 25621,
"text": null
},
{
"code": null,
"e": 27450,
"s": 27442,
"text": "Output:"
},
{
"code": null,
"e": 28532,
"s": 27450,
"text": "FF..\n======================================================================\nFAIL: test_negativeWithDelta (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/2c36bbd2c940a6c7b81a901ebfdd2ad8.py\", line 34, in test_negativeWithDelta\n self.assertAlmostEqual(first, second, None, message, delta)\nAssertionError: 4.4555 != 4.4566 within 0.0001 delta : first and second are not almost equal.\n\n======================================================================\nFAIL: test_negativeWithPlaces (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/2c36bbd2c940a6c7b81a901ebfdd2ad8.py\", line 14, in test_negativeWithPlaces\n self.assertAlmostEqual(first, second, decimalPlace, message)\nAssertionError: 4.4555 != 4.4566 within 3 places : first and second are not almost equal.\n\n----------------------------------------------------------------------\nRan 4 tests in 0.001s\n\nFAILED (failures=2)\n\n"
},
{
"code": null,
"e": 28591,
"s": 28532,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 28615,
"s": 28591,
"text": "Python unittest-library"
},
{
"code": null,
"e": 28622,
"s": 28615,
"text": "Python"
},
{
"code": null,
"e": 28720,
"s": 28622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28729,
"s": 28720,
"text": "Comments"
},
{
"code": null,
"e": 28742,
"s": 28729,
"text": "Old Comments"
},
{
"code": null,
"e": 28760,
"s": 28742,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28795,
"s": 28760,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28817,
"s": 28795,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28849,
"s": 28817,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28879,
"s": 28849,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28921,
"s": 28879,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28947,
"s": 28921,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28990,
"s": 28947,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29027,
"s": 28990,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How To Implement Custom Regularization in TensorFlow(Keras) | by Richmond Alake | Towards Data Science
|
This article introduces the topic of regularization within neural networks. It includes details on how machine learning engineers and data scientist can go about implementing custom regularization techniques.
Regularization techniques reduce the possibility of a neural network overfitting by constraining the range of values that the weight values within the network hold.
The article below presents conventional regularization techniques and how they are implemented within TensorFlow(Keras). The referenced article below is aimed at readers who prefer an in-depth overview on the topic of regularization within neural networks.
towardsdatascience.com
Before we proceed further, it might be worth noting that in most scenarios, you will not be required to implement your custom regularization techniques.
Popular machine learning libraries such as TensorFlow, Keras and PyTorch have standard regularization techniques implemented within them.
The regularization technique I’m going to be implementing is the L2 regularization technique.
L2 regularization penalizes weight values. For both small weight values and relatively large ones, L2 regularization transforms the values to a number close to 0, but not quite 0.
L2 penalizes the sum of the square of the weights (weight2), therefore we will be implementing this logic in a python function.
def custom_l2_regularizer(weights): return tf.reduce_sum(0.02 * tf.square(weights))
The code above is our custom L2 regularization technique.
Using TensorFlow’s mathematical operations we can calculate the sum of the square of the weights passed into the function.
tf.reduce_sum: Math operation that provides as its result, the sum of the values passed into the function.
tf.square: Math operation that squares the values within its arguments
And that’s all there is to it.
To utilize our custom regularizer, we pass it into a neural network layer, as shown below:
keras.layers.Dense(200, activation='relu', kernel_regularizer=custom_l2_regularizer),
Keas neural network layers can accept within its ‘kernel_regularizer’ argument custom-defined functions.
To see how well the implemented custom regularization technique works, we will build a simple neural network and perform the trivial task of image classification.
This section will include snippets of code that perform some common neural network implementation tasks, and also a GitHub repo link is available here that includes all code within this article.
To implement our neural network and load datasets, we will be utilizing the following tools and libraries: Keras, TensorFlow and NumPy.
import tensorflow as tffrom tensorflow import kerasimport numpy as np
Load and partition dataset into testing, validation and training.
It is also required that the pixel intensity of the images within the dataset are normalized from the value range 0–255 to 0–1.
An array ‘class_names’ is initialized to hold the item labels of the pieces of clothing represented in the images within the dataset.
(train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000]class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
Here we define the custom regularizer as explained earlier.
def custom_l2_regularizer(weights): return tf.reduce_sum(0.02 * tf.square(weights))
Next step is to implement our neural network and its layers. An assignment of the appropriate parameters to each layer takes place here, including our custom regularizer.
model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28,28]), keras.layers.Dense(200, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(100, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(50, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(10, activation='softmax')])
To ensure that our neural network trains properly, we utilize the stochastic gradient descent optimization algorithm and set some arbitrary hyperparameters such as epochs and learning rates.
sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss="sparse_categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels))
After training, an evaluation of the trained model is conducted on the test dataset. The evaluation data must contain data that the model has not encountered during training.
model.evaluate(test_images, test_labels)
To verify the accuracy of our model, we can take a subset of our test images and run inference to verify their results.
practical_test_images = test_images[:10]predictions = model.predict_classes(practical_test_images)print(predictions)print(np.array(class_names)[predictions])
Implementing custom components of neural networks such as regularizers is very easy with Keras; you could even go further and explore how to implement custom metrics, activation functions, loss functions and plenty more with Keras.
To connect with me or find more content similar to this article, do the following:
Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn
Subscribe to my YouTube channel for video contents coming soon here
Follow me on Medium
Connect and reach me on LinkedIn
|
[
{
"code": null,
"e": 256,
"s": 47,
"text": "This article introduces the topic of regularization within neural networks. It includes details on how machine learning engineers and data scientist can go about implementing custom regularization techniques."
},
{
"code": null,
"e": 421,
"s": 256,
"text": "Regularization techniques reduce the possibility of a neural network overfitting by constraining the range of values that the weight values within the network hold."
},
{
"code": null,
"e": 678,
"s": 421,
"text": "The article below presents conventional regularization techniques and how they are implemented within TensorFlow(Keras). The referenced article below is aimed at readers who prefer an in-depth overview on the topic of regularization within neural networks."
},
{
"code": null,
"e": 701,
"s": 678,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 854,
"s": 701,
"text": "Before we proceed further, it might be worth noting that in most scenarios, you will not be required to implement your custom regularization techniques."
},
{
"code": null,
"e": 992,
"s": 854,
"text": "Popular machine learning libraries such as TensorFlow, Keras and PyTorch have standard regularization techniques implemented within them."
},
{
"code": null,
"e": 1086,
"s": 992,
"text": "The regularization technique I’m going to be implementing is the L2 regularization technique."
},
{
"code": null,
"e": 1266,
"s": 1086,
"text": "L2 regularization penalizes weight values. For both small weight values and relatively large ones, L2 regularization transforms the values to a number close to 0, but not quite 0."
},
{
"code": null,
"e": 1394,
"s": 1266,
"text": "L2 penalizes the sum of the square of the weights (weight2), therefore we will be implementing this logic in a python function."
},
{
"code": null,
"e": 1481,
"s": 1394,
"text": "def custom_l2_regularizer(weights): return tf.reduce_sum(0.02 * tf.square(weights))"
},
{
"code": null,
"e": 1539,
"s": 1481,
"text": "The code above is our custom L2 regularization technique."
},
{
"code": null,
"e": 1662,
"s": 1539,
"text": "Using TensorFlow’s mathematical operations we can calculate the sum of the square of the weights passed into the function."
},
{
"code": null,
"e": 1769,
"s": 1662,
"text": "tf.reduce_sum: Math operation that provides as its result, the sum of the values passed into the function."
},
{
"code": null,
"e": 1840,
"s": 1769,
"text": "tf.square: Math operation that squares the values within its arguments"
},
{
"code": null,
"e": 1871,
"s": 1840,
"text": "And that’s all there is to it."
},
{
"code": null,
"e": 1962,
"s": 1871,
"text": "To utilize our custom regularizer, we pass it into a neural network layer, as shown below:"
},
{
"code": null,
"e": 2048,
"s": 1962,
"text": "keras.layers.Dense(200, activation='relu', kernel_regularizer=custom_l2_regularizer),"
},
{
"code": null,
"e": 2153,
"s": 2048,
"text": "Keas neural network layers can accept within its ‘kernel_regularizer’ argument custom-defined functions."
},
{
"code": null,
"e": 2316,
"s": 2153,
"text": "To see how well the implemented custom regularization technique works, we will build a simple neural network and perform the trivial task of image classification."
},
{
"code": null,
"e": 2511,
"s": 2316,
"text": "This section will include snippets of code that perform some common neural network implementation tasks, and also a GitHub repo link is available here that includes all code within this article."
},
{
"code": null,
"e": 2647,
"s": 2511,
"text": "To implement our neural network and load datasets, we will be utilizing the following tools and libraries: Keras, TensorFlow and NumPy."
},
{
"code": null,
"e": 2717,
"s": 2647,
"text": "import tensorflow as tffrom tensorflow import kerasimport numpy as np"
},
{
"code": null,
"e": 2783,
"s": 2717,
"text": "Load and partition dataset into testing, validation and training."
},
{
"code": null,
"e": 2911,
"s": 2783,
"text": "It is also required that the pixel intensity of the images within the dataset are normalized from the value range 0–255 to 0–1."
},
{
"code": null,
"e": 3045,
"s": 2911,
"text": "An array ‘class_names’ is initialized to hold the item labels of the pieces of clothing represented in the images within the dataset."
},
{
"code": null,
"e": 3410,
"s": 3045,
"text": "(train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000]class_names = [\"T-shirt/top\", \"Trouser\", \"Pullover\", \"Dress\", \"Coat\", \"Sandal\", \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\"]"
},
{
"code": null,
"e": 3470,
"s": 3410,
"text": "Here we define the custom regularizer as explained earlier."
},
{
"code": null,
"e": 3557,
"s": 3470,
"text": "def custom_l2_regularizer(weights): return tf.reduce_sum(0.02 * tf.square(weights))"
},
{
"code": null,
"e": 3728,
"s": 3557,
"text": "Next step is to implement our neural network and its layers. An assignment of the appropriate parameters to each layer takes place here, including our custom regularizer."
},
{
"code": null,
"e": 4124,
"s": 3728,
"text": "model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28,28]), keras.layers.Dense(200, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(100, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(50, activation='relu', kernel_regularizer=custom_l2_regularizer), keras.layers.Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 4315,
"s": 4124,
"text": "To ensure that our neural network trains properly, we utilize the stochastic gradient descent optimization algorithm and set some arbitrary hyperparameters such as epochs and learning rates."
},
{
"code": null,
"e": 4545,
"s": 4315,
"text": "sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=sgd, metrics=[\"accuracy\"])model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels))"
},
{
"code": null,
"e": 4720,
"s": 4545,
"text": "After training, an evaluation of the trained model is conducted on the test dataset. The evaluation data must contain data that the model has not encountered during training."
},
{
"code": null,
"e": 4761,
"s": 4720,
"text": "model.evaluate(test_images, test_labels)"
},
{
"code": null,
"e": 4881,
"s": 4761,
"text": "To verify the accuracy of our model, we can take a subset of our test images and run inference to verify their results."
},
{
"code": null,
"e": 5040,
"s": 4881,
"text": "practical_test_images = test_images[:10]predictions = model.predict_classes(practical_test_images)print(predictions)print(np.array(class_names)[predictions])"
},
{
"code": null,
"e": 5272,
"s": 5040,
"text": "Implementing custom components of neural networks such as regularizers is very easy with Keras; you could even go further and explore how to implement custom metrics, activation functions, loss functions and plenty more with Keras."
},
{
"code": null,
"e": 5355,
"s": 5272,
"text": "To connect with me or find more content similar to this article, do the following:"
},
{
"code": null,
"e": 5474,
"s": 5355,
"text": "Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn"
},
{
"code": null,
"e": 5542,
"s": 5474,
"text": "Subscribe to my YouTube channel for video contents coming soon here"
},
{
"code": null,
"e": 5562,
"s": 5542,
"text": "Follow me on Medium"
}
] |
SAS - Arrays
|
Arrays in SAS are used to store and retrieve a series of values using an index value. The index represents the location in a reserved memory area.
In SAS an array is declared by using the following syntax −
ARRAY ARRAY-NAME(SUBSCRIPT) ($) VARIABLE-LIST ARRAY-VALUES
In the above syntax −
ARRAY is the SAS keyword to declare an array.
ARRAY is the SAS keyword to declare an array.
ARRAY-NAME is the name of the array which follows the same rule as variable names.
ARRAY-NAME is the name of the array which follows the same rule as variable names.
SUBSCRIPT is the number of values the array is going to store.
SUBSCRIPT is the number of values the array is going to store.
($) is an optional parameter to be used only if the array is going to store character values.
($) is an optional parameter to be used only if the array is going to store character values.
VARIABLE-LIST is the optional list of variables which are the place holders for array values.
VARIABLE-LIST is the optional list of variables which are the place holders for array values.
ARRAY-VALUES are the actual values that are stored in the array. They can be declared here or can be read from a file or dataline.
ARRAY-VALUES are the actual values that are stored in the array. They can be declared here or can be read from a file or dataline.
Arrays can be declared in many ways using the above syntax. Below are the examples.
# Declare an array of length 5 named AGE with values.
ARRAY AGE[5] (12 18 5 62 44);
# Declare an array of length 5 named COUNTRIES with values starting at index 0.
ARRAY COUNTRIES(0:8) A B C D E F G H I;
# Declare an array of length 5 named QUESTS which contain character values.
ARRAY QUESTS(1:5) $ Q1-Q5;
# Declare an array of required length as per the number of values supplied.
ARRAY ANSWER(*) A1-A100;
The values stored in an array can be accessed by using the print procedure as shown below. After it is declared using one of the above methods, the data is supplied using DATALINES statement.
DATA array_example;
INPUT a1 $ a2 $ a3 $ a4 $ a5 $;
ARRAY colours(5) $ a1-a5;
mix = a1||'+'||a2;
DATALINES;
yello pink orange green blue
;
RUN;
PROC PRINT DATA = array_example;
RUN;
When we execute above code, it produces following result −
The OF operator is used when analysing the data forma an Array to perform calculations on the entire row of an array. In the below example we apply the Sum and Mean of values in each row.
DATA array_example_OF;
INPUT A1 A2 A3 A4;
ARRAY A(4) A1-A4;
A_SUM = SUM(OF A(*));
A_MEAN = MEAN(OF A(*));
A_MIN = MIN(OF A(*));
DATALINES;
21 4 52 11
96 25 42 6
;
RUN;
PROC PRINT DATA = array_example_OF;
RUN;
When we execute above code, it produces following result −
The value in an array can also be accessed using the IN operator which checks for the presence of a value in the row of the array. In the below example we check for the availability of the colour "Yellow" in the data. This value is case sensitive.
DATA array_in_example;
INPUT A1 $ A2 $ A3 $ A4 $;
ARRAY COLOURS(4) A1-A4;
IF 'yellow' IN COLOURS THEN available = 'Yes';ELSE available = 'No';
DATALINES;
Orange pink violet yellow
;
RUN;
PROC PRINT DATA = array_in_example;
RUN;
When we execute above code, it produces following result −
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
35 Lectures
2.5 hours
Ermin Dedic
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2730,
"s": 2583,
"text": "Arrays in SAS are used to store and retrieve a series of values using an index value. The index represents the location in a reserved memory area."
},
{
"code": null,
"e": 2790,
"s": 2730,
"text": "In SAS an array is declared by using the following syntax −"
},
{
"code": null,
"e": 2850,
"s": 2790,
"text": "ARRAY ARRAY-NAME(SUBSCRIPT) ($) VARIABLE-LIST ARRAY-VALUES\n"
},
{
"code": null,
"e": 2872,
"s": 2850,
"text": "In the above syntax −"
},
{
"code": null,
"e": 2918,
"s": 2872,
"text": "ARRAY is the SAS keyword to declare an array."
},
{
"code": null,
"e": 2964,
"s": 2918,
"text": "ARRAY is the SAS keyword to declare an array."
},
{
"code": null,
"e": 3047,
"s": 2964,
"text": "ARRAY-NAME is the name of the array which follows the same rule as variable names."
},
{
"code": null,
"e": 3130,
"s": 3047,
"text": "ARRAY-NAME is the name of the array which follows the same rule as variable names."
},
{
"code": null,
"e": 3193,
"s": 3130,
"text": "SUBSCRIPT is the number of values the array is going to store."
},
{
"code": null,
"e": 3256,
"s": 3193,
"text": "SUBSCRIPT is the number of values the array is going to store."
},
{
"code": null,
"e": 3350,
"s": 3256,
"text": "($) is an optional parameter to be used only if the array is going to store character values."
},
{
"code": null,
"e": 3444,
"s": 3350,
"text": "($) is an optional parameter to be used only if the array is going to store character values."
},
{
"code": null,
"e": 3538,
"s": 3444,
"text": "VARIABLE-LIST is the optional list of variables which are the place holders for array values."
},
{
"code": null,
"e": 3632,
"s": 3538,
"text": "VARIABLE-LIST is the optional list of variables which are the place holders for array values."
},
{
"code": null,
"e": 3763,
"s": 3632,
"text": "ARRAY-VALUES are the actual values that are stored in the array. They can be declared here or can be read from a file or dataline."
},
{
"code": null,
"e": 3894,
"s": 3763,
"text": "ARRAY-VALUES are the actual values that are stored in the array. They can be declared here or can be read from a file or dataline."
},
{
"code": null,
"e": 3979,
"s": 3894,
"text": "Arrays can be declared in many ways using the above syntax. Below are the examples.\n"
},
{
"code": null,
"e": 4391,
"s": 3979,
"text": "# Declare an array of length 5 named AGE with values.\nARRAY AGE[5] (12 18 5 62 44);\n\n# Declare an array of length 5 named COUNTRIES with values starting at index 0.\nARRAY COUNTRIES(0:8) A B C D E F G H I;\n\n# Declare an array of length 5 named QUESTS which contain character values.\nARRAY QUESTS(1:5) $ Q1-Q5;\n\n# Declare an array of required length as per the number of values supplied.\nARRAY ANSWER(*) A1-A100;\n"
},
{
"code": null,
"e": 4583,
"s": 4391,
"text": "The values stored in an array can be accessed by using the print procedure as shown below. After it is declared using one of the above methods, the data is supplied using DATALINES statement."
},
{
"code": null,
"e": 4766,
"s": 4583,
"text": "DATA array_example;\nINPUT a1 $ a2 $ a3 $ a4 $ a5 $;\nARRAY colours(5) $ a1-a5;\nmix = a1||'+'||a2;\nDATALINES;\nyello pink orange green blue\n;\nRUN;\nPROC PRINT DATA = array_example;\nRUN;\n"
},
{
"code": null,
"e": 4825,
"s": 4766,
"text": "When we execute above code, it produces following result −"
},
{
"code": null,
"e": 5013,
"s": 4825,
"text": "The OF operator is used when analysing the data forma an Array to perform calculations on the entire row of an array. In the below example we apply the Sum and Mean of values in each row."
},
{
"code": null,
"e": 5258,
"s": 5013,
"text": "DATA array_example_OF;\n INPUT A1 A2 A3 A4;\n ARRAY A(4) A1-A4;\n A_SUM = SUM(OF A(*));\n A_MEAN = MEAN(OF A(*));\n A_MIN = MIN(OF A(*));\n DATALINES;\n 21 4 52 11\n 96 25 42 6\n ;\n RUN;\n PROC PRINT DATA = array_example_OF;\n RUN;"
},
{
"code": null,
"e": 5317,
"s": 5258,
"text": "When we execute above code, it produces following result −"
},
{
"code": null,
"e": 5565,
"s": 5317,
"text": "The value in an array can also be accessed using the IN operator which checks for the presence of a value in the row of the array. In the below example we check for the availability of the colour \"Yellow\" in the data. This value is case sensitive."
},
{
"code": null,
"e": 5820,
"s": 5565,
"text": "DATA array_in_example;\n INPUT A1 $ A2 $ A3 $ A4 $;\n ARRAY COLOURS(4) A1-A4;\n IF 'yellow' IN COLOURS THEN available = 'Yes';ELSE available = 'No';\n DATALINES;\n Orange pink violet yellow\n ;\n RUN;\n PROC PRINT DATA = array_in_example;\n RUN;"
},
{
"code": null,
"e": 5879,
"s": 5820,
"text": "When we execute above code, it produces following result −"
},
{
"code": null,
"e": 5914,
"s": 5879,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5931,
"s": 5914,
"text": " Code And Create"
},
{
"code": null,
"e": 5966,
"s": 5931,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 5979,
"s": 5966,
"text": " Juan Galvan"
},
{
"code": null,
"e": 6016,
"s": 5979,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 6036,
"s": 6016,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 6071,
"s": 6036,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6084,
"s": 6071,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 6121,
"s": 6084,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 6137,
"s": 6121,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 6144,
"s": 6137,
"text": " Print"
},
{
"code": null,
"e": 6155,
"s": 6144,
"text": " Add Notes"
}
] |
Get or Set Dimensions of a Matrix in R Programming - dim() Function - GeeksforGeeks
|
04 Jun, 2020
dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame.
Syntax: dim(x)
Parameters:x: array, matrix or data frame.
Example 1:
# R program to illustrate# dim function # Getting R Biochemical Oxygen Demand DatasetBOD # Getting dimension of the above datasetdim(BOD)
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
[1] 6 2
Example 2:
# R program to illustrate# dim function # Getting the number from 1 to 9x <- rep(1:9)x # Calling the dim() function to# Set dimension of 3 * 3dim(x) <- c(3, 3) # Getting the numbers# in 3 * 3 representationx
Output:
[1] 1 2 3 4 5 6 7 8 9
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 25353,
"s": 25242,
"text": "dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame."
},
{
"code": null,
"e": 25368,
"s": 25353,
"text": "Syntax: dim(x)"
},
{
"code": null,
"e": 25411,
"s": 25368,
"text": "Parameters:x: array, matrix or data frame."
},
{
"code": null,
"e": 25422,
"s": 25411,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# dim function # Getting R Biochemical Oxygen Demand DatasetBOD # Getting dimension of the above datasetdim(BOD) ",
"e": 25564,
"s": 25422,
"text": null
},
{
"code": null,
"e": 25572,
"s": 25564,
"text": "Output:"
},
{
"code": null,
"e": 25680,
"s": 25572,
"text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19.0\n4 4 16.0\n5 5 15.6\n6 7 19.8\n\n[1] 6 2\n"
},
{
"code": null,
"e": 25691,
"s": 25680,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# dim function # Getting the number from 1 to 9x <- rep(1:9)x # Calling the dim() function to# Set dimension of 3 * 3dim(x) <- c(3, 3) # Getting the numbers# in 3 * 3 representationx",
"e": 25902,
"s": 25691,
"text": null
},
{
"code": null,
"e": 25910,
"s": 25902,
"text": "Output:"
},
{
"code": null,
"e": 26020,
"s": 25910,
"text": "[1] 1 2 3 4 5 6 7 8 9\n\n [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n"
},
{
"code": null,
"e": 26038,
"s": 26020,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 26049,
"s": 26038,
"text": "R Language"
},
{
"code": null,
"e": 26147,
"s": 26049,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26199,
"s": 26147,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26237,
"s": 26199,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26272,
"s": 26237,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26330,
"s": 26272,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26379,
"s": 26330,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26416,
"s": 26379,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 26466,
"s": 26416,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26509,
"s": 26466,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26526,
"s": 26509,
"text": "R - if statement"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.