title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
What are wildcards arguments in Generics In Java?
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype. To define a generic class you need to specify the type parameter you are using in the angle brackets “<>” after the class name and you can treat this as datatype of the instance variable an proceed with the code. Live Demo class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); Student<String> std2 = new Student<String>("25"); std2.display(); Student<Integer> std3 = new Student<Integer>(25); std3.display(); } } Value: 25.5 Value: 25 Value: 25 Instead of the typed parameter in generics (T) you can also use “?”, representing an unknown type. You can use a wild card as a − Type of parameter. Field Local field. The only restriction on wilds cards is that you cannot it as a type argument of a generic method while invoking it. Java provides 3 types of wild cards namely upper-bounded, lower-bounded, un-bounded. Upper bounds in wild cards is similar to the bounded type in generics. Using this you can enable the usage of all the subtypes of a particular class as a typed parameter. For example, if want to accept a Collection object as a parameter of a method with the typed parameter as a sub class of the number class, you just need to declare a wild card with the Number class as upper bound. To create/declare an upper-bounded wildcard, you just need to specify the extends keyword after the “?” followed by the class name. Following Java example demonstrates the creation of the upper-bounded wildcard. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.HashSet; public class UpperBoundExample { public static void sampleMethod(Collection<? extends Number> col){ for (Number num: col) { System.out.print(num+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); List<Float> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); sampleMethod(col2); HashSet<Double> col3 = new HashSet<Double>(); col3.add(25.225d); col3.add(554.32d); col3.add(2254.22d); col3.add(445.21d); sampleMethod(col3); } } 24 56 89 75 36 22.1 3.32 51.4 82.7 95.4 625.0 25.225 554.32 2254.22 445.21 If you pass a collection object other than type that is subclass of Number as a parameter to the sampleMethod() of the above program a compile time error will be generated. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.HashSet; public class UpperBoundExample { public static void sampleMethod(Collection<? extends Number> col){ for (Number num: col) { System.out.print(num+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); List<Float> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); sampleMethod(col2); HashSet<String> col3 = new HashSet<String>(); col3.add("Raju"); col3.add("Ramu"); col3.add("Raghu"); col3.add("Radha"); sampleMethod(col3); } } UpperBoundExample.java:31: error: incompatible types: HashSet<String> cannot be converted to Collection<? extends Number> sampleMethod(col3); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error upper-bounded wildcard enables the usage of all the subtypes of a particular class as a typed parameter. Similarly, if we use the lower-bounded wildcards you can restrict the type of the “?” to a particular type or a super type of it. For example, if want to accept a Collection object as a parameter of a method with the typed parameter as a super class of the Integer class, you just need to declare a wildcard with the Integer class as lower bound. To create/declare a lower-bounded wildcard, you just need to specify the super keyword after the “?” followed by the class name. Following Java example demonstrates the creation of the Lower-bounded wildcard. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Iterator; public class LowerBoundExample { public static void sampleMethod(Collection<? super Integer> col){ Iterator it = col.iterator(); while (it.hasNext()) { System.out.print(it.next()+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); sampleMethod(col2); } } 24 56 89 75 36 22.1 3.32 51.4 82.7 95.4 625.0 If you pass a collection object other of type other than Integer and its super type as a parameter to the sampleMethod() of the above program a compile time error will be generated. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Iterator; import java.util.HashSet; public class LowerBoundExample { public static void sampleMethod(Collection<? super Integer> col){ Iterator it = col.iterator(); while (it.hasNext()) { System.out.print(it.next()+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); sampleMethod(col2); HashSet<Double> col3 = new HashSet<Double>(); col3.add(25.225d); col3.add(554.32d); col3.add(2254.22d); col3.add(445.21d); sampleMethod(col3); } } LowerBoundExample.java:34: error: incompatible types: HashSet<Double> cannot be converted to Collection<? super Integer> sampleMethod(col3); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error An unbounded wildcard is the one which enables the usage of all the subtypes of an unknown type i.e. any type (Object) is accepted as typed-parameter. For example, if want to accept an ArrayList of object type as a parameter, you just need to declare an unbounded wildcard. To create/declare a Unbounded wildcard, you just need to specify the wild card character “?” as a typed parameter within angle brackets. Following Java example demonstrates the creation of the Unbounded wildcard. import java.util.List; import java.util.Arrays; public class UnboundedExample { public static void sampleMethod(List<?> col){ for (Object ele : col) { System.out.print(ele+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); ArrayList<Double> col2 = new ArrayList<Double>(); col2.add(24.12d); col2.add(56.25d); col2.add(89.36d); col2.add(75.98d); col2.add(36.47d); sampleMethod(col2); } } 24 56 89 75 36 24.12 56.25 89.36 75.98 36.47 If you pass an List object created from arrays (contains elements of primitive type) a compile time error will be generated. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class UnboundedExample { public static void sampleMethod(List<?> col){ for (Object ele : col) { System.out.print(ele+" "); } System.out.println(""); } public static void main(String args[]) { ArrayList<Integer> col1 = new ArrayList<Integer>(); col1.add(24); col1.add(56); col1.add(89); col1.add(75); col1.add(36); sampleMethod(col1); ArrayList<Double> col2 = new ArrayList<Double>(); col2.add(24.12d); col2.add(56.25d); col2.add(89.36d); col2.add(75.98d); col2.add(36.47d); sampleMethod(col2); List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); sampleMethod(col2); } } UnboundedExample.java:27: error: variable col2 is already defined in method main(String[]) List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f); ^ 1 error
[ { "code": null, "e": 1430, "s": 1062, "text": "Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype." }, { "code": null, "e": 1643, "s": 1430, "text": "To define a generic class you need to specify the type parameter you are using in the angle brackets “<>” after the class name and you can treat this as datatype of the instance variable an proceed with the code." }, { "code": null, "e": 1654, "s": 1643, "text": " Live Demo" }, { "code": null, "e": 2123, "s": 1654, "text": "class Student<T>{\n T age;\n Student(T age){\n this.age = age;\n }\n public void display() {\n System.out.println(\"Value: \"+this.age);\n }\n}\npublic class GenericsExample {\n public static void main(String args[]) {\n Student<Float> std1 = new Student<Float>(25.5f);\n std1.display();\n Student<String> std2 = new Student<String>(\"25\");\n std2.display();\n Student<Integer> std3 = new Student<Integer>(25);\n std3.display();\n }\n}" }, { "code": null, "e": 2155, "s": 2123, "text": "Value: 25.5\nValue: 25\nValue: 25" }, { "code": null, "e": 2285, "s": 2155, "text": "Instead of the typed parameter in generics (T) you can also use “?”, representing an unknown type. You can use a wild card as a −" }, { "code": null, "e": 2304, "s": 2285, "text": "Type of parameter." }, { "code": null, "e": 2310, "s": 2304, "text": "Field" }, { "code": null, "e": 2323, "s": 2310, "text": "Local field." }, { "code": null, "e": 2439, "s": 2323, "text": "The only restriction on wilds cards is that you cannot it as a type argument of a generic method while invoking it." }, { "code": null, "e": 2524, "s": 2439, "text": "Java provides 3 types of wild cards namely upper-bounded, lower-bounded, un-bounded." }, { "code": null, "e": 2695, "s": 2524, "text": "Upper bounds in wild cards is similar to the bounded type in generics. Using this you can enable the usage of all the subtypes of a particular class as a typed parameter." }, { "code": null, "e": 2909, "s": 2695, "text": "For example, if want to accept a Collection object as a parameter of a method with the typed parameter as a sub class of the number class, you just need to declare a wild card with the Number class as upper bound." }, { "code": null, "e": 3041, "s": 2909, "text": "To create/declare an upper-bounded wildcard, you just need to specify the extends keyword after the “?” followed by the class name." }, { "code": null, "e": 3121, "s": 3041, "text": "Following Java example demonstrates the creation of the upper-bounded wildcard." }, { "code": null, "e": 3132, "s": 3121, "text": " Live Demo" }, { "code": null, "e": 3997, "s": 3132, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.HashSet;\npublic class UpperBoundExample {\n public static void sampleMethod(Collection<? extends Number> col){\n for (Number num: col) {\n System.out.print(num+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n List<Float> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n sampleMethod(col2);\n HashSet<Double> col3 = new HashSet<Double>();\n col3.add(25.225d);\n col3.add(554.32d);\n col3.add(2254.22d);\n col3.add(445.21d);\n sampleMethod(col3);\n }\n}" }, { "code": null, "e": 4072, "s": 3997, "text": "24 56 89 75 36\n22.1 3.32 51.4 82.7 95.4 625.0\n25.225 554.32 2254.22 445.21" }, { "code": null, "e": 4245, "s": 4072, "text": "If you pass a collection object other than type that is subclass of Number as a parameter to the sampleMethod() of the above program a compile time error will be generated." }, { "code": null, "e": 4256, "s": 4245, "text": " Live Demo" }, { "code": null, "e": 5118, "s": 4256, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.HashSet;\npublic class UpperBoundExample {\n public static void sampleMethod(Collection<? extends Number> col){\n for (Number num: col) {\n System.out.print(num+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n List<Float> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n sampleMethod(col2);\n HashSet<String> col3 = new HashSet<String>();\n col3.add(\"Raju\");\n col3.add(\"Ramu\");\n col3.add(\"Raghu\");\n col3.add(\"Radha\");\n sampleMethod(col3);\n }\n}" }, { "code": null, "e": 5386, "s": 5118, "text": "UpperBoundExample.java:31: error: incompatible types: HashSet<String> cannot be converted to Collection<? extends Number>\n sampleMethod(col3);\n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n1 error" }, { "code": null, "e": 5491, "s": 5386, "text": "upper-bounded wildcard enables the usage of all the subtypes of a particular class as a typed parameter." }, { "code": null, "e": 5621, "s": 5491, "text": "Similarly, if we use the lower-bounded wildcards you can restrict the type of the “?” to a particular type or a super type of it." }, { "code": null, "e": 5838, "s": 5621, "text": "For example, if want to accept a Collection object as a parameter of a method with the typed parameter as a super class of the Integer class, you just need to declare a wildcard with the Integer class as lower bound." }, { "code": null, "e": 5967, "s": 5838, "text": "To create/declare a lower-bounded wildcard, you just need to specify the super keyword after the “?” followed by the class name." }, { "code": null, "e": 6047, "s": 5967, "text": "Following Java example demonstrates the creation of the Lower-bounded wildcard." }, { "code": null, "e": 6058, "s": 6047, "text": " Live Demo" }, { "code": null, "e": 6786, "s": 6058, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Iterator;\npublic class LowerBoundExample {\n public static void sampleMethod(Collection<? super Integer> col){\n Iterator it = col.iterator();\n while (it.hasNext()) {\n System.out.print(it.next()+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n sampleMethod(col2);\n }\n}" }, { "code": null, "e": 6832, "s": 6786, "text": "24 56 89 75 36\n22.1 3.32 51.4 82.7 95.4 625.0" }, { "code": null, "e": 7014, "s": 6832, "text": "If you pass a collection object other of type other than Integer and its super type as a parameter to the sampleMethod() of the above program a compile time error will be generated." }, { "code": null, "e": 7025, "s": 7014, "text": " Live Demo" }, { "code": null, "e": 7961, "s": 7025, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Iterator;\nimport java.util.HashSet;\npublic class LowerBoundExample {\n public static void sampleMethod(Collection<? super Integer> col){\n Iterator it = col.iterator();\n while (it.hasNext()) {\n System.out.print(it.next()+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n sampleMethod(col2);\n HashSet<Double> col3 = new HashSet<Double>();\n col3.add(25.225d);\n col3.add(554.32d);\n col3.add(2254.22d);\n col3.add(445.21d);\n sampleMethod(col3);\n }\n}" }, { "code": null, "e": 8229, "s": 7961, "text": "LowerBoundExample.java:34: error: incompatible types: HashSet<Double> cannot be converted to Collection<? super Integer>\n sampleMethod(col3);\n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n1 error" }, { "code": null, "e": 8380, "s": 8229, "text": "An unbounded wildcard is the one which enables the usage of all the subtypes of an unknown type i.e. any type (Object) is accepted as typed-parameter." }, { "code": null, "e": 8503, "s": 8380, "text": "For example, if want to accept an ArrayList of object type as a parameter, you just need to declare an unbounded wildcard." }, { "code": null, "e": 8640, "s": 8503, "text": "To create/declare a Unbounded wildcard, you just need to specify the wild card character “?” as a typed parameter within angle brackets." }, { "code": null, "e": 8716, "s": 8640, "text": "Following Java example demonstrates the creation of the Unbounded wildcard." }, { "code": null, "e": 9392, "s": 8716, "text": "import java.util.List;\nimport java.util.Arrays;\npublic class UnboundedExample {\n public static void sampleMethod(List<?> col){\n for (Object ele : col) {\n System.out.print(ele+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n ArrayList<Double> col2 = new ArrayList<Double>();\n col2.add(24.12d);\n col2.add(56.25d);\n col2.add(89.36d);\n col2.add(75.98d);\n col2.add(36.47d);\n sampleMethod(col2);\n }\n}" }, { "code": null, "e": 9437, "s": 9392, "text": "24 56 89 75 36\n24.12 56.25 89.36 75.98 36.47" }, { "code": null, "e": 9562, "s": 9437, "text": "If you pass an List object created from arrays (contains elements of primitive type) a compile time error will be generated." }, { "code": null, "e": 9573, "s": 9562, "text": " Live Demo" }, { "code": null, "e": 10386, "s": 9573, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\npublic class UnboundedExample {\n public static void sampleMethod(List<?> col){\n for (Object ele : col) {\n System.out.print(ele+\" \");\n }\n System.out.println(\"\");\n }\n public static void main(String args[]) {\n ArrayList<Integer> col1 = new ArrayList<Integer>();\n col1.add(24);\n col1.add(56);\n col1.add(89);\n col1.add(75);\n col1.add(36);\n sampleMethod(col1);\n ArrayList<Double> col2 = new ArrayList<Double>();\n col2.add(24.12d);\n col2.add(56.25d);\n col2.add(89.36d);\n col2.add(75.98d);\n col2.add(36.47d);\n sampleMethod(col2);\n List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n sampleMethod(col2);\n }\n}" }, { "code": null, "e": 10588, "s": 10386, "text": "UnboundedExample.java:27: error: variable col2 is already defined in method main(String[])\n List<Object> col2 = Arrays.asList(22.1f, 3.32f, 51.4f, 82.7f, 95.4f, 625.f);\n ^\n1 error" } ]
JSON.simple - Using JSONValue
JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below. import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class JsonDemo { public static void main(String[] args) { String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Object obj = JSONValue.parse(s); JSONArray array = (JSONArray)obj; System.out.println("The 2nd element of array"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2 = (JSONObject)array.get(1); System.out.println("Field \"1\""); System.out.println(obj2.get("1")); s = "{}"; obj = JSONValue.parse(s); System.out.println(obj); s = "[5,]"; obj = JSONValue.parse(s); System.out.println(obj); s = "[5,,2]"; obj = JSONValue.parse(s); System.out.println(obj); } } The 2nd element of array {"1":{"2":{"3":{"4":[5,{"6":7}]}}}} Field "1" {"2":{"3":{"4":[5,{"6":7}]}}} {} [5] [5,2] 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2223, "text": "JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below." }, { "code": null, "e": 3225, "s": 2391, "text": "import org.json.simple.JSONArray;\nimport org.json.simple.JSONObject;\nimport org.json.simple.JSONValue;\n\npublic class JsonDemo {\n public static void main(String[] args) {\n String s = \"[0,{\\\"1\\\":{\\\"2\\\":{\\\"3\\\":{\\\"4\\\":[5,{\\\"6\\\":7}]}}}}]\";\n Object obj = JSONValue.parse(s);\n JSONArray array = (JSONArray)obj;\n\n System.out.println(\"The 2nd element of array\");\n System.out.println(array.get(1));\n System.out.println();\n\n JSONObject obj2 = (JSONObject)array.get(1);\n System.out.println(\"Field \\\"1\\\"\");\n System.out.println(obj2.get(\"1\")); \n\n s = \"{}\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n\n s = \"[5,]\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n\n s = \"[5,,2]\";\n obj = JSONValue.parse(s);\n System.out.println(obj);\n }\n}" }, { "code": null, "e": 3341, "s": 3225, "text": "The 2nd element of array\n{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}\n\nField \"1\"\n{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}\n{}\n[5]\n[5,2]\n" }, { "code": null, "e": 3374, "s": 3341, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 3391, "s": 3374, "text": " Laurence Svekis" }, { "code": null, "e": 3424, "s": 3391, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3441, "s": 3424, "text": " Laurence Svekis" }, { "code": null, "e": 3474, "s": 3441, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 3491, "s": 3474, "text": " Laurence Svekis" }, { "code": null, "e": 3526, "s": 3491, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3543, "s": 3526, "text": " Laurence Svekis" }, { "code": null, "e": 3574, "s": 3543, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 3587, "s": 3574, "text": " Nilay Mehta" }, { "code": null, "e": 3622, "s": 3587, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3645, "s": 3622, "text": " Stone River ELearning" }, { "code": null, "e": 3652, "s": 3645, "text": " Print" }, { "code": null, "e": 3663, "s": 3652, "text": " Add Notes" } ]
\tfrac - Tex Command
\tfrac - Used to create textstyle fraction. { \tfrac} \tfrac command draws textstyle fraction. \tfrac ab \frac ab abab \tfrac ab \frac ab abab \tfrac ab \frac ab 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": 8030, "s": 7986, "text": "\\tfrac - Used to create textstyle fraction." }, { "code": null, "e": 8040, "s": 8030, "text": "{ \\tfrac}" }, { "code": null, "e": 8081, "s": 8040, "text": "\\tfrac command draws textstyle fraction." }, { "code": null, "e": 8110, "s": 8081, "text": "\n\\tfrac ab \\frac ab\n\nabab\n\n\n" }, { "code": null, "e": 8137, "s": 8110, "text": "\\tfrac ab \\frac ab\n\nabab\n\n" }, { "code": null, "e": 8156, "s": 8137, "text": "\\tfrac ab \\frac ab" }, { "code": null, "e": 8188, "s": 8156, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8201, "s": 8188, "text": " Ashraf Said" }, { "code": null, "e": 8234, "s": 8201, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8247, "s": 8234, "text": " Ashraf Said" }, { "code": null, "e": 8279, "s": 8247, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8315, "s": 8279, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8350, "s": 8315, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8367, "s": 8350, "text": " Mohammad Nauman" }, { "code": null, "e": 8400, "s": 8367, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8414, "s": 8400, "text": " Daniel Stern" }, { "code": null, "e": 8446, "s": 8414, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8461, "s": 8446, "text": " Nishant Kumar" }, { "code": null, "e": 8468, "s": 8461, "text": " Print" }, { "code": null, "e": 8479, "s": 8468, "text": " Add Notes" } ]
Output of Python Programs | Set 18 (List and Tuples)
30 Nov, 2021 1) What is the output of the following program? PYTHON L = list('123456')L[0] = L[5] = 0L[3] = L[-2]print(L) a) [0, ‘2’, ‘3’, ‘4’, ‘5’, 0] b) [‘6’, ‘2’, ‘3’, ‘5’, ‘5’, ‘6’] c) [‘0’, ‘2’, ‘3’, ‘5’, ‘5’, ‘0’] d) [0, ‘2’, ‘3’, ‘5’, ‘5’, 0] Ans. (d) Explanation: L[0] is ‘1’ and L[5] is ‘6’, both of these elements will be replaced by 0 in the List. L[3], which is 4 will be replaced L[-2] i.e. 5.2) What is the output of the following program? PYTHON3 T = 'geeks'a, b, c, d, e = Tb = c = '*'T = (a, b, c, d, e)print(T) a) (‘g’, ‘*’, ‘*’, ‘k’, ‘s’) b) (‘g’, ‘e’, ‘e’, ‘k’, ‘s’) c) (‘geeks’, ‘*’, ‘*’) d) KeyError Ans. (a) Explanation: A tuple is created as T = (‘g’, ‘e’, ‘e’, ‘k’, ‘s’), then it is unpacked into a, b, c, d and e, mapping from ‘g’ to a and ‘s’ to e. b and c which are both ‘e’ are equal to ‘*’ and then the existing tuple is replaced by packing a, b, c, d and e into a tuple T.3) What is the value of L at the end of execution of the following program? PYTHON3 L = [2e-04, 'a', False, 87]T = (6.22, 'boy', True, 554)for i in range(len(L)): if L[i]: L[i] = L[i] + T[i] else: T[i] = L[i] + T[i] break a) [6.222e-04, ‘aboy’, True, 641] b) [6.2202, ‘aboy’, 1, 641] c) TypeError d) [6.2202, ‘aboy’, False, 87] Ans. (c) Explanation: The for loop will run for i = 0 to i = 3, i.e. 4 times(len(L) = 4). 2e-04 is same as 0.0002, thus L[i] = 6.22 + 0.0002 = 6.2202. String addition will result in concatenation, ‘a’ + ‘boy’ = ‘aboy’. False + True is True, it’ll return the integer value of 1. As tuples are immutable, the code will end with TypeError, but elements of L will be updated.4) What is the output of the following program? PYTHON T = (2e-04, True, False, 8, 1.001, True)val = 0for x in T: val += int(x)print(val) a) 12 b) 11 c) 11.001199999999999 d) TypeError Ans. (b) Explanation: Integer value of 2e-04(0.0002) is 0, True holds a value 1 and False a 0, integer value of 1.001 is 1. Thus total 0 + 1 + 0 + 8 + 1 + 1 = 11.5) Which of the options below could possibly be the output of the following program? PYTHON L = [3, 1, 2, 4]T = ('A', 'b', 'c', 'd')L.sort()counter = 0for x in T: L[counter] += int(x) counter += 1 breakprint(L) a) [66, 97, 99, 101] b) [66, 68, 70, 72] c) [66, 67, 68, 69] d) ValueError Ans. (d) Explanation: After sort(L), L will be = [1, 2, 3, 4]. Counter = 0, L[0] i.e. 1, x = ‘A’, but Type Conversion of char ‘A’ to integer will throw error and the value cannot be stored in L[0], thus a ValueError.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 python-list Python-Output python-tuple Program Output python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 101, "s": 52, "text": "1) What is the output of the following program? " }, { "code": null, "e": 108, "s": 101, "text": "PYTHON" }, { "code": "L = list('123456')L[0] = L[5] = 0L[3] = L[-2]print(L)", "e": 162, "s": 108, "text": null }, { "code": null, "e": 495, "s": 162, "text": "a) [0, ‘2’, ‘3’, ‘4’, ‘5’, 0] b) [‘6’, ‘2’, ‘3’, ‘5’, ‘5’, ‘6’] c) [‘0’, ‘2’, ‘3’, ‘5’, ‘5’, ‘0’] d) [0, ‘2’, ‘3’, ‘5’, ‘5’, 0] Ans. (d) Explanation: L[0] is ‘1’ and L[5] is ‘6’, both of these elements will be replaced by 0 in the List. L[3], which is 4 will be replaced L[-2] i.e. 5.2) What is the output of the following program? " }, { "code": null, "e": 503, "s": 495, "text": "PYTHON3" }, { "code": "T = 'geeks'a, b, c, d, e = Tb = c = '*'T = (a, b, c, d, e)print(T)", "e": 570, "s": 503, "text": null }, { "code": null, "e": 1021, "s": 570, "text": "a) (‘g’, ‘*’, ‘*’, ‘k’, ‘s’) b) (‘g’, ‘e’, ‘e’, ‘k’, ‘s’) c) (‘geeks’, ‘*’, ‘*’) d) KeyError Ans. (a) Explanation: A tuple is created as T = (‘g’, ‘e’, ‘e’, ‘k’, ‘s’), then it is unpacked into a, b, c, d and e, mapping from ‘g’ to a and ‘s’ to e. b and c which are both ‘e’ are equal to ‘*’ and then the existing tuple is replaced by packing a, b, c, d and e into a tuple T.3) What is the value of L at the end of execution of the following program? " }, { "code": null, "e": 1029, "s": 1021, "text": "PYTHON3" }, { "code": "L = [2e-04, 'a', False, 87]T = (6.22, 'boy', True, 554)for i in range(len(L)): if L[i]: L[i] = L[i] + T[i] else: T[i] = L[i] + T[i] break", "e": 1194, "s": 1029, "text": null }, { "code": null, "e": 1720, "s": 1194, "text": "a) [6.222e-04, ‘aboy’, True, 641] b) [6.2202, ‘aboy’, 1, 641] c) TypeError d) [6.2202, ‘aboy’, False, 87] Ans. (c) Explanation: The for loop will run for i = 0 to i = 3, i.e. 4 times(len(L) = 4). 2e-04 is same as 0.0002, thus L[i] = 6.22 + 0.0002 = 6.2202. String addition will result in concatenation, ‘a’ + ‘boy’ = ‘aboy’. False + True is True, it’ll return the integer value of 1. As tuples are immutable, the code will end with TypeError, but elements of L will be updated.4) What is the output of the following program? " }, { "code": null, "e": 1727, "s": 1720, "text": "PYTHON" }, { "code": "T = (2e-04, True, False, 8, 1.001, True)val = 0for x in T: val += int(x)print(val)", "e": 1813, "s": 1727, "text": null }, { "code": null, "e": 2108, "s": 1813, "text": "a) 12 b) 11 c) 11.001199999999999 d) TypeError Ans. (b) Explanation: Integer value of 2e-04(0.0002) is 0, True holds a value 1 and False a 0, integer value of 1.001 is 1. Thus total 0 + 1 + 0 + 8 + 1 + 1 = 11.5) Which of the options below could possibly be the output of the following program? " }, { "code": null, "e": 2115, "s": 2108, "text": "PYTHON" }, { "code": "L = [3, 1, 2, 4]T = ('A', 'b', 'c', 'd')L.sort()counter = 0for x in T: L[counter] += int(x) counter += 1 breakprint(L)", "e": 2243, "s": 2115, "text": null }, { "code": null, "e": 2957, "s": 2243, "text": "a) [66, 97, 99, 101] b) [66, 68, 70, 72] c) [66, 67, 68, 69] d) ValueError Ans. (d) Explanation: After sort(L), L will be = [1, 2, 3, 4]. Counter = 0, L[0] i.e. 1, x = ‘A’, but Type Conversion of char ‘A’ to integer will throw error and the value cannot be stored in L[0], thus a ValueError.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2970, "s": 2957, "text": "simmytarika5" }, { "code": null, "e": 2982, "s": 2970, "text": "python-list" }, { "code": null, "e": 2996, "s": 2982, "text": "Python-Output" }, { "code": null, "e": 3009, "s": 2996, "text": "python-tuple" }, { "code": null, "e": 3024, "s": 3009, "text": "Program Output" }, { "code": null, "e": 3036, "s": 3024, "text": "python-list" } ]
SQL queries on FILM Database
29 May, 2020 Consider the following tables in Film Database: ARTIST (Art_id, Art_Name, Art_Gender) PRODUCER (Prod_id, Prod_Name, Prod_Phone) FILMS (Film_id, Film_Title, Film_Year, Film_Lang, Prod_id) CASTING (Art_id, Film_id, Part) REVIEW (Film_id, Stars) The data content of these five tables are shown below: SELECT * FROM ARTIST; SELECT * FROM PRODUCER; SELECT * FROM FILMS; SELECT * FROM CASTING; SELECT * FROM REVIEW; Query-1:Find the name of all the Films whose producer is “NIRAJ”. First we will find the Producer ID for the Producer Named “NIRAJ” and for this we use the PRODUCER table. SELECT PROD_ID FROM PRODUCER WHERE PROD_NAME = ‘NIRAJ’ The above query will return the Prod_id “203”. Now we will find the title of films whose pros_id is “203”. For doing this we use the table FILMS and use the above query as a sub query. SELECT FILM_TITLE FROM FILMS WHERE PROD_ID IN (SELECT PROD_ID FROM PRODUCER WHERE PROD_NAME = ‘NIRAJ’); Output: Query-2:Display all artists who acted in a film between 2016 and 2018. For finding this we need to use the ARTIST_NAME field of ARTIST table as well as the FILM_YEAR field of FILMS table. For joining these two tables we use a third table CASTING using Art_id and Film_id.After joining we use the BETWEEN operator for checking the FILM_YEAR in between 2016 and 2018. SELECT A.ART_NAME, F.FILM_TITLE, F.FILM_YEAR FROM ARTIST A, CASTING C, FILMS F WHERE A.ART_ID=C.ART_ID AND C.FILM_ID=F.FILM_ID AND F.FILM_YEAR BETWEEN 2016 AND 2018; Output: Query-3:Display the names of films with the stars received and sort the result on the basis of stars. For this we need FILM_TITLE field of FILMS table as well as STARS field of REVIEW table. For joining these two tables we will use the common field which is the FILM_ID. And after joining we display the result in the order of increasing STARS by using ORDER BY clause. SELECT F.FILM_TITLE, R_STARS FROM FILMS F, REVIEW R WHERE F.FILM_ID=R.FILM_ID ORDER BY R.STARS DESC Output: Query-4:Update the stars of all films whose producer is ‘NIRAJ’ to 5. First we find the PRODUCER ID of the PRODUCER named “NIRAJ” by using this query: SELECT PROD_ID FROM PRODUCER WHERE PROD_NAME = ‘NIRAJ’ Then find the FILM_ID from the FILMS table using this PROD_ID. SELECT FILM_ID FROM FILMS WHERE PROD_ID IN (SELECT PROD_ID FROM PRODUCER WHERE PROD_NAME = ‘NIRAJ’) And then this FILM_ID helps in Updating the value of STARS in REVIEW table using UPDATE command. UPDATE REVIEW SET STARS=5 WHERE FILM_ID IN (SELECT FILM_ID FROM FILMS WHERE PROD_ID IN (SELECT PROD_ID FROM PRODUCER WHERE PROD_NAME = ‘NIRAJ’)); Output: 1 row updated. To observe the changes we can use SELECT * command in REVIEW table. SELECT * FROM REVIEW; DBMS-SQL DBMS GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 May, 2020" }, { "code": null, "e": 101, "s": 53, "text": "Consider the following tables in Film Database:" }, { "code": null, "e": 300, "s": 101, "text": "ARTIST (Art_id, Art_Name, Art_Gender) \nPRODUCER (Prod_id, Prod_Name, Prod_Phone)\nFILMS (Film_id, Film_Title, Film_Year, Film_Lang, Prod_id) \nCASTING (Art_id, Film_id, Part) \nREVIEW (Film_id, Stars) " }, { "code": null, "e": 355, "s": 300, "text": "The data content of these five tables are shown below:" }, { "code": null, "e": 377, "s": 355, "text": "SELECT * FROM ARTIST;" }, { "code": null, "e": 401, "s": 377, "text": "SELECT * FROM PRODUCER;" }, { "code": null, "e": 422, "s": 401, "text": "SELECT * FROM FILMS;" }, { "code": null, "e": 445, "s": 422, "text": "SELECT * FROM CASTING;" }, { "code": null, "e": 467, "s": 445, "text": "SELECT * FROM REVIEW;" }, { "code": null, "e": 533, "s": 467, "text": "Query-1:Find the name of all the Films whose producer is “NIRAJ”." }, { "code": null, "e": 639, "s": 533, "text": "First we will find the Producer ID for the Producer Named “NIRAJ” and for this we use the PRODUCER table." }, { "code": null, "e": 696, "s": 639, "text": "SELECT PROD_ID \nFROM PRODUCER \nWHERE PROD_NAME = ‘NIRAJ’" }, { "code": null, "e": 881, "s": 696, "text": "The above query will return the Prod_id “203”. Now we will find the title of films whose pros_id is “203”. For doing this we use the table FILMS and use the above query as a sub query." }, { "code": null, "e": 989, "s": 881, "text": "SELECT FILM_TITLE \nFROM FILMS \nWHERE PROD_ID IN (SELECT PROD_ID \nFROM PRODUCER \nWHERE PROD_NAME = ‘NIRAJ’);" }, { "code": null, "e": 997, "s": 989, "text": "Output:" }, { "code": null, "e": 1068, "s": 997, "text": "Query-2:Display all artists who acted in a film between 2016 and 2018." }, { "code": null, "e": 1363, "s": 1068, "text": "For finding this we need to use the ARTIST_NAME field of ARTIST table as well as the FILM_YEAR field of FILMS table. For joining these two tables we use a third table CASTING using Art_id and Film_id.After joining we use the BETWEEN operator for checking the FILM_YEAR in between 2016 and 2018." }, { "code": null, "e": 1534, "s": 1363, "text": "SELECT A.ART_NAME, F.FILM_TITLE, F.FILM_YEAR \nFROM ARTIST A, CASTING C, FILMS F\nWHERE A.ART_ID=C.ART_ID \nAND C.FILM_ID=F.FILM_ID \nAND F.FILM_YEAR BETWEEN 2016 AND 2018;" }, { "code": null, "e": 1542, "s": 1534, "text": "Output:" }, { "code": null, "e": 1644, "s": 1542, "text": "Query-3:Display the names of films with the stars received and sort the result on the basis of stars." }, { "code": null, "e": 1912, "s": 1644, "text": "For this we need FILM_TITLE field of FILMS table as well as STARS field of REVIEW table. For joining these two tables we will use the common field which is the FILM_ID. And after joining we display the result in the order of increasing STARS by using ORDER BY clause." }, { "code": null, "e": 2012, "s": 1912, "text": "SELECT F.FILM_TITLE, R_STARS\nFROM FILMS F, REVIEW R\nWHERE F.FILM_ID=R.FILM_ID\nORDER BY R.STARS DESC" }, { "code": null, "e": 2020, "s": 2012, "text": "Output:" }, { "code": null, "e": 2090, "s": 2020, "text": "Query-4:Update the stars of all films whose producer is ‘NIRAJ’ to 5." }, { "code": null, "e": 2171, "s": 2090, "text": "First we find the PRODUCER ID of the PRODUCER named “NIRAJ” by using this query:" }, { "code": null, "e": 2228, "s": 2171, "text": "SELECT PROD_ID \nFROM PRODUCER \nWHERE PROD_NAME = ‘NIRAJ’" }, { "code": null, "e": 2291, "s": 2228, "text": "Then find the FILM_ID from the FILMS table using this PROD_ID." }, { "code": null, "e": 2394, "s": 2291, "text": "SELECT FILM_ID FROM FILMS \nWHERE PROD_ID IN (SELECT PROD_ID \nFROM PRODUCER \nWHERE PROD_NAME = ‘NIRAJ’)" }, { "code": null, "e": 2491, "s": 2394, "text": "And then this FILM_ID helps in Updating the value of STARS in REVIEW table using UPDATE command." }, { "code": null, "e": 2642, "s": 2491, "text": "UPDATE REVIEW \nSET STARS=5 \nWHERE FILM_ID IN (SELECT FILM_ID FROM FILMS \nWHERE PROD_ID IN (SELECT PROD_ID \nFROM PRODUCER \nWHERE PROD_NAME = ‘NIRAJ’));" }, { "code": null, "e": 2650, "s": 2642, "text": "Output:" }, { "code": null, "e": 2665, "s": 2650, "text": "1 row updated." }, { "code": null, "e": 2733, "s": 2665, "text": "To observe the changes we can use SELECT * command in REVIEW table." }, { "code": null, "e": 2755, "s": 2733, "text": "SELECT * FROM REVIEW;" }, { "code": null, "e": 2764, "s": 2755, "text": "DBMS-SQL" }, { "code": null, "e": 2769, "s": 2764, "text": "DBMS" }, { "code": null, "e": 2777, "s": 2769, "text": "GATE CS" }, { "code": null, "e": 2781, "s": 2777, "text": "SQL" }, { "code": null, "e": 2786, "s": 2781, "text": "DBMS" }, { "code": null, "e": 2790, "s": 2786, "text": "SQL" } ]
How to copy a map to another map in Golang?
10 May, 2020 Maps in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Map, you can copy a map to another map using the for loop provided by the Go language. In for loop, we fetch the index value 1 by 1 with the element and assign it to another map. Syntax: for key, value := range originalMap{ } Let us discuss this concept with the help of the examples: Example 1: // Go program to illustrate how to // copy a map to another map package main import "fmt" func main() { // Creating and initializing a map // Using shorthand declaration and // using map literals originalMap := make(map[string]int) originalMap["one"] = 1 originalMap["two"] = 2 originalMap["three"] = 3 originalMap["four"] = 4 originalMap["five"] = 5 originalMap["six"] = 6 originalMap["seven"] = 7 originalMap["eight"] = 8 originalMap["nine"] = 9 // Creating empty map CopiedMap:= make(map[string]int) /* Copy Content from Map1 to Map2*/ for index, element := range originalMap{ CopiedMap[index] = element } for index, element := range CopiedMap{ fmt.Println(index, "=>", element) }} Output: seven => 7 eight => 8 two => 2 four => 4 three => 3 six => 6 nine => 9 one => 1 five => 5 Example 2: // Go program to illustrate how to // copy a map to another map package main import "fmt" func main() { // Creating and initializing a map // Using shorthand declaration and // using map literals map_1 := map[int]string{ 90: "Dog", 91: "Cat", 92: "Cow", 93: "Bird", 94: "Rabbit", } // Creating and initializing empty map map2 := map[string]int{} /* Copy Content from Map1 to Map2*/ for key, value := range map_1{ map2[value] = key } fmt.Println("Copied Map :", map2) } Output: Copied Map : map[Bird:93 Rabbit:94 Dog:90 Cat:91 Cow:92] Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 396, "s": 28, "text": "Maps in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update, or delete with the help of keys. In Map, you can copy a map to another map using the for loop provided by the Go language. In for loop, we fetch the index value 1 by 1 with the element and assign it to another map." }, { "code": null, "e": 404, "s": 396, "text": "Syntax:" }, { "code": null, "e": 444, "s": 404, "text": "for key, value := range originalMap{\n}\n" }, { "code": null, "e": 503, "s": 444, "text": "Let us discuss this concept with the help of the examples:" }, { "code": null, "e": 514, "s": 503, "text": "Example 1:" }, { "code": "// Go program to illustrate how to // copy a map to another map package main import \"fmt\" func main() { // Creating and initializing a map // Using shorthand declaration and // using map literals originalMap := make(map[string]int) originalMap[\"one\"] = 1 originalMap[\"two\"] = 2 originalMap[\"three\"] = 3 originalMap[\"four\"] = 4 originalMap[\"five\"] = 5 originalMap[\"six\"] = 6 originalMap[\"seven\"] = 7 originalMap[\"eight\"] = 8 originalMap[\"nine\"] = 9 // Creating empty map CopiedMap:= make(map[string]int) /* Copy Content from Map1 to Map2*/ for index, element := range originalMap{ CopiedMap[index] = element } for index, element := range CopiedMap{ fmt.Println(index, \"=>\", element) }}", "e": 1330, "s": 514, "text": null }, { "code": null, "e": 1338, "s": 1330, "text": "Output:" }, { "code": null, "e": 1429, "s": 1338, "text": "seven => 7\neight => 8\ntwo => 2\nfour => 4\nthree => 3\nsix => 6\nnine => 9\none => 1\nfive => 5\n" }, { "code": null, "e": 1440, "s": 1429, "text": "Example 2:" }, { "code": "// Go program to illustrate how to // copy a map to another map package main import \"fmt\" func main() { // Creating and initializing a map // Using shorthand declaration and // using map literals map_1 := map[int]string{ 90: \"Dog\", 91: \"Cat\", 92: \"Cow\", 93: \"Bird\", 94: \"Rabbit\", } // Creating and initializing empty map map2 := map[string]int{} /* Copy Content from Map1 to Map2*/ for key, value := range map_1{ map2[value] = key } fmt.Println(\"Copied Map :\", map2) }", "e": 2066, "s": 1440, "text": null }, { "code": null, "e": 2074, "s": 2066, "text": "Output:" }, { "code": null, "e": 2132, "s": 2074, "text": "Copied Map : map[Bird:93 Rabbit:94 Dog:90 Cat:91 Cow:92]\n" }, { "code": null, "e": 2147, "s": 2132, "text": "Golang-Program" }, { "code": null, "e": 2154, "s": 2147, "text": "Picked" }, { "code": null, "e": 2166, "s": 2154, "text": "Go Language" } ]
Time Complexity of Euclidean Algorithm
27 Jan, 2022 In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved. Euclid’s Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as: gcd(a, b) = gcd(b, a%b), where, a and b are two integers. Proof: Suppose, a and b are two integers such that a >b then according to Euclid’s Algorithm: gcd(a, b) = gcd(b, a%b) Use the above formula repetitively until reach a step where b is 0. At this step, the result will be the GCD of the two integers, which will be equal to a. So, after observing carefully, it can be said that the time complexity of this algorithm would be proportional to the number of steps required to reduce b to 0. Let’s assume, the number of steps required to reduce b to 0 using this algorithm is N. gcd(a, b) ------> N steps Now, if the Euclidean Algorithm for two numbers a and b reduces in N steps then, a should be at least f(N + 2) and b should be at least f(N + 1). gcd(a, b) ——> N stepsThen, a >= f(N + 2) and b >= f(N + 1)where, fN is the Nth term in the Fibonacci series(0, 1, 1, 2, 3, ...) and N >= 0. To prove the above statement by using the Principle of Mathematical Induction(PMI): Base Case:Let’s assume a = 2 and b = 1. Then, gcd(2, 1) will reduce to gcd(1, 0) in 1 step, i.e., N = 1.This means 2 should be at least f3 and 1 should be at least f2 and f3 = 2 and f2 = 1.This implies, a is at least f(N + 2) and b is at least f(N + 1). It can be concluded that the statement holds true for the Base Case. Let’s assume a = 2 and b = 1. Then, gcd(2, 1) will reduce to gcd(1, 0) in 1 step, i.e., N = 1. This means 2 should be at least f3 and 1 should be at least f2 and f3 = 2 and f2 = 1. This implies, a is at least f(N + 2) and b is at least f(N + 1). It can be concluded that the statement holds true for the Base Case. Inductive Step: Assume that the statement holds true for the (N – 1)th Step. So, Below are the steps to prove it for the Nth Step: gcd(b, a%b) ——> (N – 1) stepsThen, b >= f(N – 1 + 2) i.e., b >= f(N + 1)a%b >= f(N – 1 + 1) i.e., a%b >= fN It can also be written as: a = floor(a/b)*b + a%b floor(a/b)*b means highest multiple which is closest to b. ex – floor(5/2)*2 = 4. If we then add 5%2=1, we will get a(=5) back. Now, (a/b) would always be greater than 1 ( as a >= b). So, from the above result, it is concluded that: a >= b + (a%b)This implies, a >= f(N + 1) + fN It is known that each number is the sum of the two preceding terms in a Fibonacci series. This implies f(N + 2) = f(N + 1) + fN. a >= f(N + 2) and b >= f(N + 1) Since the above statement holds true for the inductive step as well. This proves that the statement is correct. Before proceeding further, Look at the Binet Formula: Binet Formula: fN = {((1 + √5)/2)N – ((1 – √5)/2)N}/√5 orfN ≈ ∅N where, ∅ is known as the golden ratio(∅≈1.618), and fN is the Nth Fibonacci Number. Now, it is already stated that the time complexity will be proportional to N i.e., the number of steps required to reduce b to 0. So, to prove the time complexity, it is known that: fN ≈ ∅NN ≈ log∅(fN) Now, from the above statement, it is proved that using the Principle of Mathematical Induction, it can be said that if the Euclidean algorithm for two numbers a and b reduces in N steps then, a should be at least f(N + 2) and b should be at least f(N + 1). From the above two results, it can be concluded that: => fN+1 ≈ min(a, b)=> N+1 ≈ log∅min(a, b) => O(N) = O(N+1) = log(min(a, b)) gus4734 harshdangi HCF time complexity Algorithms Analysis Mathematical Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Practice Questions on Time Complexity Analysis Time Complexity and Space Complexity Time Complexity of building a heap Analysis of different sorting techniques Time complexities of different data structures
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jan, 2022" }, { "code": null, "e": 178, "s": 52, "text": "In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved." }, { "code": null, "e": 382, "s": 178, "text": "Euclid’s Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as:" }, { "code": null, "e": 440, "s": 382, "text": "gcd(a, b) = gcd(b, a%b), where, a and b are two integers." }, { "code": null, "e": 535, "s": 440, "text": "Proof: Suppose, a and b are two integers such that a >b then according to Euclid’s Algorithm:" }, { "code": null, "e": 559, "s": 535, "text": "gcd(a, b) = gcd(b, a%b)" }, { "code": null, "e": 876, "s": 559, "text": "Use the above formula repetitively until reach a step where b is 0. At this step, the result will be the GCD of the two integers, which will be equal to a. So, after observing carefully, it can be said that the time complexity of this algorithm would be proportional to the number of steps required to reduce b to 0." }, { "code": null, "e": 963, "s": 876, "text": "Let’s assume, the number of steps required to reduce b to 0 using this algorithm is N." }, { "code": null, "e": 989, "s": 963, "text": "gcd(a, b) ------> N steps" }, { "code": null, "e": 1135, "s": 989, "text": "Now, if the Euclidean Algorithm for two numbers a and b reduces in N steps then, a should be at least f(N + 2) and b should be at least f(N + 1)." }, { "code": null, "e": 1275, "s": 1135, "text": "gcd(a, b) ——> N stepsThen, a >= f(N + 2) and b >= f(N + 1)where, fN is the Nth term in the Fibonacci series(0, 1, 1, 2, 3, ...) and N >= 0." }, { "code": null, "e": 1359, "s": 1275, "text": "To prove the above statement by using the Principle of Mathematical Induction(PMI):" }, { "code": null, "e": 1683, "s": 1359, "text": "Base Case:Let’s assume a = 2 and b = 1. Then, gcd(2, 1) will reduce to gcd(1, 0) in 1 step, i.e., N = 1.This means 2 should be at least f3 and 1 should be at least f2 and f3 = 2 and f2 = 1.This implies, a is at least f(N + 2) and b is at least f(N + 1). It can be concluded that the statement holds true for the Base Case. " }, { "code": null, "e": 1778, "s": 1683, "text": "Let’s assume a = 2 and b = 1. Then, gcd(2, 1) will reduce to gcd(1, 0) in 1 step, i.e., N = 1." }, { "code": null, "e": 1864, "s": 1778, "text": "This means 2 should be at least f3 and 1 should be at least f2 and f3 = 2 and f2 = 1." }, { "code": null, "e": 1929, "s": 1864, "text": "This implies, a is at least f(N + 2) and b is at least f(N + 1)." }, { "code": null, "e": 2001, "s": 1931, "text": "It can be concluded that the statement holds true for the Base Case. " }, { "code": null, "e": 2132, "s": 2001, "text": "Inductive Step: Assume that the statement holds true for the (N – 1)th Step. So, Below are the steps to prove it for the Nth Step:" }, { "code": null, "e": 2241, "s": 2132, "text": "gcd(b, a%b) ——> (N – 1) stepsThen, b >= f(N – 1 + 2) i.e., b >= f(N + 1)a%b >= f(N – 1 + 1) i.e., a%b >= fN" }, { "code": null, "e": 2268, "s": 2241, "text": "It can also be written as:" }, { "code": null, "e": 2291, "s": 2268, "text": "a = floor(a/b)*b + a%b" }, { "code": null, "e": 2350, "s": 2291, "text": "floor(a/b)*b means highest multiple which is closest to b." }, { "code": null, "e": 2420, "s": 2350, "text": "ex – floor(5/2)*2 = 4. If we then add 5%2=1, we will get a(=5) back. " }, { "code": null, "e": 2525, "s": 2420, "text": "Now, (a/b) would always be greater than 1 ( as a >= b). So, from the above result, it is concluded that:" }, { "code": null, "e": 2572, "s": 2525, "text": "a >= b + (a%b)This implies, a >= f(N + 1) + fN" }, { "code": null, "e": 2701, "s": 2572, "text": "It is known that each number is the sum of the two preceding terms in a Fibonacci series. This implies f(N + 2) = f(N + 1) + fN." }, { "code": null, "e": 2733, "s": 2701, "text": "a >= f(N + 2) and b >= f(N + 1)" }, { "code": null, "e": 2845, "s": 2733, "text": "Since the above statement holds true for the inductive step as well. This proves that the statement is correct." }, { "code": null, "e": 2899, "s": 2845, "text": "Before proceeding further, Look at the Binet Formula:" }, { "code": null, "e": 2914, "s": 2899, "text": "Binet Formula:" }, { "code": null, "e": 2973, "s": 2914, "text": "fN = {((1 + √5)/2)N – ((1 – √5)/2)N}/√5 orfN ≈ ∅N" }, { "code": null, "e": 3057, "s": 2973, "text": "where, ∅ is known as the golden ratio(∅≈1.618), and fN is the Nth Fibonacci Number." }, { "code": null, "e": 3187, "s": 3057, "text": "Now, it is already stated that the time complexity will be proportional to N i.e., the number of steps required to reduce b to 0." }, { "code": null, "e": 3239, "s": 3187, "text": "So, to prove the time complexity, it is known that:" }, { "code": null, "e": 3259, "s": 3239, "text": "fN ≈ ∅NN ≈ log∅(fN)" }, { "code": null, "e": 3517, "s": 3259, "text": "Now, from the above statement, it is proved that using the Principle of Mathematical Induction, it can be said that if the Euclidean algorithm for two numbers a and b reduces in N steps then, a should be at least f(N + 2) and b should be at least f(N + 1)." }, { "code": null, "e": 3571, "s": 3517, "text": "From the above two results, it can be concluded that:" }, { "code": null, "e": 3613, "s": 3571, "text": "=> fN+1 ≈ min(a, b)=> N+1 ≈ log∅min(a, b)" }, { "code": null, "e": 3648, "s": 3613, "text": "=> O(N) = O(N+1) = log(min(a, b))" }, { "code": null, "e": 3656, "s": 3648, "text": "gus4734" }, { "code": null, "e": 3667, "s": 3656, "text": "harshdangi" }, { "code": null, "e": 3671, "s": 3667, "text": "HCF" }, { "code": null, "e": 3687, "s": 3671, "text": "time complexity" }, { "code": null, "e": 3698, "s": 3687, "text": "Algorithms" }, { "code": null, "e": 3707, "s": 3698, "text": "Analysis" }, { "code": null, "e": 3720, "s": 3707, "text": "Mathematical" }, { "code": null, "e": 3733, "s": 3720, "text": "Mathematical" }, { "code": null, "e": 3744, "s": 3733, "text": "Algorithms" }, { "code": null, "e": 3842, "s": 3744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3880, "s": 3842, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 3948, "s": 3880, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 3975, "s": 3948, "text": "How to Start Learning DSA?" }, { "code": null, "e": 4018, "s": 3975, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 4085, "s": 4018, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 4132, "s": 4085, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 4169, "s": 4132, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 4204, "s": 4169, "text": "Time Complexity of building a heap" }, { "code": null, "e": 4245, "s": 4204, "text": "Analysis of different sorting techniques" } ]
Find maximum volume of a cuboid from the given perimeter and area
07 Sep, 2021 Given a perimeter P and area A, the task is to calculate the maximum volume that can be made in form of cuboid from the given perimeter and surface area. Examples : Input: P = 24, A = 24 Output: 8 Input: P = 20, A = 14 Output: 3 Approach: For a given perimeter of cuboid we have P = 4(l+b+h) —(i), for given area of cuboid we have A = 2 (lb+bh+lh) —(ii). Volume of cuboid is V = lbhVolume is dependent on 3 variables l, b, h. Lets make it dependent on only length. as V = lbh, => V = l (A/2-(lb+lh)) {from equation (ii)} => V = lA/2 – l2(b+h) => V = lA/2 – l2(P/4-l) {from equation (i)} => V = lA/2 – l2P/4 + l3 —-(iii)Now differentiate V w.r.t l for finding maximum of volume. dV/dl = A/2 – lP/2 + 3l2 After solving the quadratic in l we have l = (P – (P2-24A)1/2) / 12 Substituting value of l in (iii), we can easily find the maximum volume. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to return maximum volumefloat maxVol(float P, float A){ // calculate length float l = (P - sqrt(P * P - 24 * A)) / 12; // calculate volume float V = l * (A / 2.0 - l * (P / 4.0 - l)); // return result return V;} // Driver codeint main(){ float P = 20, A = 16; // Function call cout << maxVol(P, A); return 0;} // Java implementation of the above approachimport java.util.*; class Geeks { // function to return maximum volume static float maxVol(float P, float A) { // calculate length float l = (float)(P - Math.sqrt(P * P - 24 * A)) / 12; // calculate volume float V = (float)(l * (A / 2.0 - l * (P / 4.0 - l))); // return result return V; } // Driver code public static void main(String args[]) { float P = 20, A = 16; // Function call System.out.println(maxVol(P, A)); }} // This code is contributed by Kirti_Mangal # Python3 implementation of the# above approachfrom math import sqrt # function to return maximum volume def maxVol(P, A): # calculate length l = (P - sqrt(P * P - 24 * A)) / 12 # calculate volume V = l * (A / 2.0 - l * (P / 4.0 - l)) # return result return V # Driver codeif __name__ == '__main__': P = 20 A = 16 # Function call print(maxVol(P, A)) # This code is contributed# by Surendra_Gangwar // C# implementation of the above approachusing System; class GFG { // function to return maximum volume static float maxVol(float P, float A) { // calculate length float l = (float)(P - Math.Sqrt(P * P - 24 * A)) / 12; // calculate volume float V = (float)(l * (A / 2.0 - l * (P / 4.0 - l))); // return result return V; } // Driver code public static void Main() { float P = 20, A = 16; // Function call Console.WriteLine(maxVol(P, A)); }} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the above approach // function to return maximum volumefunction maxVol($P, $A){ // calculate length $l = ($P - sqrt($P * $P - 24 * $A)) / 12; // calculate volume $V = $l * ($A / 2.0 - $l * ($P / 4.0 - $l)); // return result return $V;} // Driver code$P = 20;$A = 16; // Function callecho maxVol($P, $A); // This code is contributed by mits?> <script>// javascript implementation of the above approach // function to return maximum volumefunction maxVol( P, A){ // calculate length let l = (P - Math.sqrt(P * P - 24 * A)) / 12; // calculate volume let V = l * (A / 2.0 - l * (P / 4.0 - l)); // return result return V;} // Driver code let P = 20, A = 16; // Function call document.write(maxVol(P, A).toFixed(5)); // This code is contributed by aashish1995 </script> 4.14815 SURENDRA_GANGWAR Kirti_Mangal Akanksha_Rai Mithun Kumar abh1shekk aashish1995 sweetyty area-volume-programs Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Check if two given circles touch or intersect each other Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Sep, 2021" }, { "code": null, "e": 208, "s": 54, "text": "Given a perimeter P and area A, the task is to calculate the maximum volume that can be made in form of cuboid from the given perimeter and surface area." }, { "code": null, "e": 220, "s": 208, "text": "Examples : " }, { "code": null, "e": 285, "s": 220, "text": "Input: P = 24, A = 24\nOutput: 8\n\nInput: P = 20, A = 14\nOutput: 3" }, { "code": null, "e": 521, "s": 285, "text": "Approach: For a given perimeter of cuboid we have P = 4(l+b+h) —(i), for given area of cuboid we have A = 2 (lb+bh+lh) —(ii). Volume of cuboid is V = lbhVolume is dependent on 3 variables l, b, h. Lets make it dependent on only length." }, { "code": null, "e": 900, "s": 521, "text": "as V = lbh, => V = l (A/2-(lb+lh)) {from equation (ii)} => V = lA/2 – l2(b+h) => V = lA/2 – l2(P/4-l) {from equation (i)} => V = lA/2 – l2P/4 + l3 —-(iii)Now differentiate V w.r.t l for finding maximum of volume. dV/dl = A/2 – lP/2 + 3l2 After solving the quadratic in l we have l = (P – (P2-24A)1/2) / 12 Substituting value of l in (iii), we can easily find the maximum volume." }, { "code": null, "e": 951, "s": 900, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 955, "s": 951, "text": "C++" }, { "code": null, "e": 960, "s": 955, "text": "Java" }, { "code": null, "e": 968, "s": 960, "text": "Python3" }, { "code": null, "e": 971, "s": 968, "text": "C#" }, { "code": null, "e": 975, "s": 971, "text": "PHP" }, { "code": null, "e": 986, "s": 975, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // function to return maximum volumefloat maxVol(float P, float A){ // calculate length float l = (P - sqrt(P * P - 24 * A)) / 12; // calculate volume float V = l * (A / 2.0 - l * (P / 4.0 - l)); // return result return V;} // Driver codeint main(){ float P = 20, A = 16; // Function call cout << maxVol(P, A); return 0;}", "e": 1432, "s": 986, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class Geeks { // function to return maximum volume static float maxVol(float P, float A) { // calculate length float l = (float)(P - Math.sqrt(P * P - 24 * A)) / 12; // calculate volume float V = (float)(l * (A / 2.0 - l * (P / 4.0 - l))); // return result return V; } // Driver code public static void main(String args[]) { float P = 20, A = 16; // Function call System.out.println(maxVol(P, A)); }} // This code is contributed by Kirti_Mangal", "e": 2061, "s": 1432, "text": null }, { "code": "# Python3 implementation of the# above approachfrom math import sqrt # function to return maximum volume def maxVol(P, A): # calculate length l = (P - sqrt(P * P - 24 * A)) / 12 # calculate volume V = l * (A / 2.0 - l * (P / 4.0 - l)) # return result return V # Driver codeif __name__ == '__main__': P = 20 A = 16 # Function call print(maxVol(P, A)) # This code is contributed# by Surendra_Gangwar", "e": 2499, "s": 2061, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG { // function to return maximum volume static float maxVol(float P, float A) { // calculate length float l = (float)(P - Math.Sqrt(P * P - 24 * A)) / 12; // calculate volume float V = (float)(l * (A / 2.0 - l * (P / 4.0 - l))); // return result return V; } // Driver code public static void Main() { float P = 20, A = 16; // Function call Console.WriteLine(maxVol(P, A)); }} // This code is contributed// by Akanksha Rai", "e": 3107, "s": 2499, "text": null }, { "code": "<?php// PHP implementation of the above approach // function to return maximum volumefunction maxVol($P, $A){ // calculate length $l = ($P - sqrt($P * $P - 24 * $A)) / 12; // calculate volume $V = $l * ($A / 2.0 - $l * ($P / 4.0 - $l)); // return result return $V;} // Driver code$P = 20;$A = 16; // Function callecho maxVol($P, $A); // This code is contributed by mits?>", "e": 3512, "s": 3107, "text": null }, { "code": "<script>// javascript implementation of the above approach // function to return maximum volumefunction maxVol( P, A){ // calculate length let l = (P - Math.sqrt(P * P - 24 * A)) / 12; // calculate volume let V = l * (A / 2.0 - l * (P / 4.0 - l)); // return result return V;} // Driver code let P = 20, A = 16; // Function call document.write(maxVol(P, A).toFixed(5)); // This code is contributed by aashish1995 </script>", "e": 3976, "s": 3512, "text": null }, { "code": null, "e": 3984, "s": 3976, "text": "4.14815" }, { "code": null, "e": 4001, "s": 3984, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4014, "s": 4001, "text": "Kirti_Mangal" }, { "code": null, "e": 4027, "s": 4014, "text": "Akanksha_Rai" }, { "code": null, "e": 4040, "s": 4027, "text": "Mithun Kumar" }, { "code": null, "e": 4050, "s": 4040, "text": "abh1shekk" }, { "code": null, "e": 4062, "s": 4050, "text": "aashish1995" }, { "code": null, "e": 4071, "s": 4062, "text": "sweetyty" }, { "code": null, "e": 4092, "s": 4071, "text": "area-volume-programs" }, { "code": null, "e": 4102, "s": 4092, "text": "Geometric" }, { "code": null, "e": 4115, "s": 4102, "text": "Mathematical" }, { "code": null, "e": 4128, "s": 4115, "text": "Mathematical" }, { "code": null, "e": 4138, "s": 4128, "text": "Geometric" }, { "code": null, "e": 4236, "s": 4138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4285, "s": 4236, "text": "Program for distance between two points on earth" }, { "code": null, "e": 4338, "s": 4285, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 4395, "s": 4338, "text": "Check if two given circles touch or intersect each other" }, { "code": null, "e": 4448, "s": 4395, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 4499, "s": 4448, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 4529, "s": 4499, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 4572, "s": 4529, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4632, "s": 4572, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4647, "s": 4632, "text": "C++ Data Types" } ]
Two Repeated Elements | Practice | GeeksforGeeks
You are given an array of N+2 integer elements. All elements of the array are in range 1 to N. Also, all elements occur once except two numbers which occur twice. Find the two repeating numbers. Example 1: Input: N = 4 array[] = {1,2,1,3,4,3} Output: 1 3 Explanation: In the given array, 1 and 3 are repeated two times. Example 2: Input: N = 2 array[] = {1,2,2,1} Output: 2 1 Explanation: In the given array, 1 and 2 are repeated two times and second occurence of 2 comes before 1. So the output is 2 1. Your Task: The task is to complete the function repeatedElements() which takes array arr[] and an integer N as inputs (the size of the array is N + 2 and elements are in range[1, N]) and finds the two repeated element in the array and return them in a list. Note: Return the numbers in their order of appearing twice. So, if X and Y are the repeating numbers, and X repeats twice before Y repeating twice, then the order should be (X,Y). Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 2 ≤ N ≤ 105 1 ≤ array[i] ≤ N 0 abhinayabhi141in 8 hours class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { // Your code here vector<int>v; for(int i=0; i<N+2; i++) { if(arr[abs(arr[i])] > 0) { arr[abs(arr[i])] = -arr[abs(arr[i])]; } else { v.push_back(abs(arr[i])); } } return v; }}; 0 sarthakponia0005 hours ago O(n) & O(1) class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { // Your code here vector<int>v; for(int i=0; i<N+2; i++) { if(arr[abs(arr[i])] > 0) { arr[abs(arr[i])] = -arr[abs(arr[i])]; } else { v.push_back(abs(arr[i])); } } return v; } }; 0 prabhatv964 days ago // jAVA public int[] twoRepeated(int arr[], int N) { // Your code here int ans[] = new int[2]; int idx = 0; for(int i = 0; i<N+2; i++){ arr[arr[i]%(N+1)] += N+1; if(arr[arr[i]%(N+1)] / (N+1) == 2){ ans[idx] = arr[i] % (N+1); idx++; } } return ans; } -1 avinav26114 days ago Easy C++ Solution ( 0.33 / 1.72 sec) +1 bhargav3vedi4 days ago Python Solution def twoRepeated(self, arr , N): #Your code here res = [] for i in range(len(arr)): vl = arr[i] nvl = vl*-1 if vl < 0 else vl if arr[nvl] > 0: arr[nvl] *= -1 else: res.append(nvl) return res -1 prasadmohite1 week ago vector<int> twoRepeated (int arr[], int N) { // Your code here int a[N+1]={0}; vector <int>vec; for(int i=0;i<(N+2);i++) { a[arr[i]]++; if(a[arr[i]]==2) { vec.push_back(arr[i]); } } return vec; } +2 karansinghjoshi2 weeks ago Solution WITHOUT EXTRA SPACE , WHITHOUT HASHING or MAPPING concept; Total Time Taken: 0.69/1.83 This is an Interesting problem when you wish to solve it in given constaraint WITHOUT USING HASHING OR MAPPING The key is STORING FREQUENCY of appearing number without using extra space and THIS CAN BE DONE by using the same array to store frequency; We just need to add N to the index (i) of which we need to store frequency, every time we encounter (i) . if we need to store frequency of 5 we may add N to arr[5] and when we do %N we will get the previously stored element; and when we do /N we will get the frequency stored. int j =0; int size = arr.length; int[] out = new int[2]; for(int i =0; i<size; i++){ arr[(arr[i]%size)]+=size; /*arr[i]%size gives the actual number which was earlier stored in ACTUAL ARRAY*/ //arr[i] is now arr[i]+frequency*(size) if(arr[arr[i]%size] / size ==2) out[j++]=(arr[i]%size); } return out; -1 rajreigns19162 weeks ago class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { N = N+2; int m = N - 1; vector<int> ans; for (int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) ans.push_back(arr[i] % m); } return ans; } }; 0 maneshram20Premium2 weeks ago very easy C++ solution class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { unordered_map<int,int> mp; vector<int> ans; for(int i=0;i<N+2;i++){ mp[arr[i]]++; if(mp[arr[i]]==2){ ans.push_back(arr[i]); } } return ans; } }; -1 thakursahabsingh123 weeks ago C++ Solution, class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { // Your code here vector<int>count(N+1,0); vector<int>ans; for(int i=0;i<N+2;i++) { count[arr[i]]+=1; if(count[arr[i]]==2) ans.push_back(arr[i]); } return ans; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 433, "s": 238, "text": "You are given an array of N+2 integer elements. All elements of the array are in range 1 to N. Also, all elements occur once except two numbers which occur twice. Find the two repeating numbers." }, { "code": null, "e": 444, "s": 433, "text": "Example 1:" }, { "code": null, "e": 559, "s": 444, "text": "Input:\nN = 4\narray[] = {1,2,1,3,4,3}\nOutput: 1 3\nExplanation: In the given array, \n1 and 3 are repeated two times." }, { "code": null, "e": 570, "s": 559, "text": "Example 2:" }, { "code": null, "e": 746, "s": 570, "text": "Input:\nN = 2\narray[] = {1,2,2,1}\nOutput: 2 1\nExplanation: In the given array,\n1 and 2 are repeated two times \nand second occurence of 2 comes \nbefore 1. So the output is 2 1.\n" }, { "code": null, "e": 1184, "s": 746, "text": "Your Task:\nThe task is to complete the function repeatedElements() which takes array arr[] and an integer N as inputs (the size of the array is N + 2 and elements are in range[1, N]) and finds the two repeated element in the array and return them in a list.\nNote: Return the numbers in their order of appearing twice. So, if X and Y are the repeating numbers, and X repeats twice before Y repeating twice, then the order should be (X,Y)." }, { "code": null, "e": 1249, "s": 1184, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1). " }, { "code": null, "e": 1292, "s": 1249, "text": "Constraints: \n2 ≤ N ≤ 105\n1 ≤ array[i] ≤ N" }, { "code": null, "e": 1294, "s": 1292, "text": "0" }, { "code": null, "e": 1319, "s": 1294, "text": "abhinayabhi141in 8 hours" }, { "code": null, "e": 1739, "s": 1319, "text": "class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { // Your code here vector<int>v; for(int i=0; i<N+2; i++) { if(arr[abs(arr[i])] > 0) { arr[abs(arr[i])] = -arr[abs(arr[i])]; } else { v.push_back(abs(arr[i])); } } return v; }};" }, { "code": null, "e": 1741, "s": 1739, "text": "0" }, { "code": null, "e": 1768, "s": 1741, "text": "sarthakponia0005 hours ago" }, { "code": null, "e": 1780, "s": 1768, "text": "O(n) & O(1)" }, { "code": null, "e": 2247, "s": 1782, "text": "class Solution {\n public:\n //Function to find two repeated elements.\n vector<int> twoRepeated (int arr[], int N) {\n // Your code here\n vector<int>v;\n for(int i=0; i<N+2; i++)\n {\n if(arr[abs(arr[i])] > 0)\n {\n arr[abs(arr[i])] = -arr[abs(arr[i])];\n }\n else\n {\n v.push_back(abs(arr[i]));\n }\n }\n return v;\n \n }\n};" }, { "code": null, "e": 2251, "s": 2249, "text": "0" }, { "code": null, "e": 2272, "s": 2251, "text": "prabhatv964 days ago" }, { "code": null, "e": 2280, "s": 2272, "text": "// jAVA" }, { "code": null, "e": 2627, "s": 2280, "text": "public int[] twoRepeated(int arr[], int N) { // Your code here int ans[] = new int[2]; int idx = 0; for(int i = 0; i<N+2; i++){ arr[arr[i]%(N+1)] += N+1; if(arr[arr[i]%(N+1)] / (N+1) == 2){ ans[idx] = arr[i] % (N+1); idx++; } } return ans; }" }, { "code": null, "e": 2636, "s": 2633, "text": "-1" }, { "code": null, "e": 2657, "s": 2636, "text": "avinav26114 days ago" }, { "code": null, "e": 2694, "s": 2657, "text": "Easy C++ Solution ( 0.33 / 1.72 sec)" }, { "code": null, "e": 2699, "s": 2696, "text": "+1" }, { "code": null, "e": 2722, "s": 2699, "text": "bhargav3vedi4 days ago" }, { "code": null, "e": 2738, "s": 2722, "text": "Python Solution" }, { "code": null, "e": 3080, "s": 2740, "text": "def twoRepeated(self, arr , N):\n #Your code here\n res = []\n \n for i in range(len(arr)):\n vl = arr[i]\n \n nvl = vl*-1 if vl < 0 else vl\n \n if arr[nvl] > 0:\n arr[nvl] *= -1\n else:\n res.append(nvl)\n \n return res" }, { "code": null, "e": 3083, "s": 3080, "text": "-1" }, { "code": null, "e": 3106, "s": 3083, "text": "prasadmohite1 week ago" }, { "code": null, "e": 3421, "s": 3106, "text": "vector<int> twoRepeated (int arr[], int N) { // Your code here int a[N+1]={0}; vector <int>vec; for(int i=0;i<(N+2);i++) { a[arr[i]]++; if(a[arr[i]]==2) { vec.push_back(arr[i]); } } return vec; }" }, { "code": null, "e": 3424, "s": 3421, "text": "+2" }, { "code": null, "e": 3451, "s": 3424, "text": "karansinghjoshi2 weeks ago" }, { "code": null, "e": 3520, "s": 3451, "text": "Solution WITHOUT EXTRA SPACE , WHITHOUT HASHING or MAPPING concept; " }, { "code": null, "e": 3538, "s": 3520, "text": "Total Time Taken:" }, { "code": null, "e": 3548, "s": 3538, "text": "0.69/1.83" }, { "code": null, "e": 3659, "s": 3548, "text": "This is an Interesting problem when you wish to solve it in given constaraint WITHOUT USING HASHING OR MAPPING" }, { "code": null, "e": 3801, "s": 3661, "text": "The key is STORING FREQUENCY of appearing number without using extra space and THIS CAN BE DONE by using the same array to store frequency;" }, { "code": null, "e": 3907, "s": 3801, "text": "We just need to add N to the index (i) of which we need to store frequency, every time we encounter (i) ." }, { "code": null, "e": 4078, "s": 3907, "text": "if we need to store frequency of 5 we may add N to arr[5] and when we do %N we will get the previously stored element; and when we do /N we will get the frequency stored." }, { "code": null, "e": 4536, "s": 4080, "text": " int j =0;\n int size = arr.length;\n \n int[] out = new int[2];\n \n for(int i =0; i<size; i++){\n \n arr[(arr[i]%size)]+=size; \n \n /*arr[i]%size gives the actual number which was earlier stored in ACTUAL ARRAY*/\n //arr[i] is now arr[i]+frequency*(size)\n \t\t\n if(arr[arr[i]%size] / size ==2) out[j++]=(arr[i]%size);\n }\n \n return out;" }, { "code": null, "e": 4539, "s": 4536, "text": "-1" }, { "code": null, "e": 4564, "s": 4539, "text": "rajreigns19162 weeks ago" }, { "code": null, "e": 5002, "s": 4564, "text": "class Solution {\n public:\n //Function to find two repeated elements.\n vector<int> twoRepeated (int arr[], int N) \n {\n N = N+2;\n int m = N - 1;\n vector<int> ans;\n \n for (int i = 0; i < N; i++) \n {\n arr[arr[i] % m - 1] += m;\n \n if ((arr[arr[i] % m - 1] / m) == 2)\n ans.push_back(arr[i] % m);\n }\n \n return ans;\n }\n};" }, { "code": null, "e": 5004, "s": 5002, "text": "0" }, { "code": null, "e": 5034, "s": 5004, "text": "maneshram20Premium2 weeks ago" }, { "code": null, "e": 5057, "s": 5034, "text": "very easy C++ solution" }, { "code": null, "e": 5420, "s": 5057, "text": "class Solution {\n public:\n //Function to find two repeated elements.\n vector<int> twoRepeated (int arr[], int N) {\n unordered_map<int,int> mp;\n vector<int> ans;\n for(int i=0;i<N+2;i++){\n mp[arr[i]]++;\n if(mp[arr[i]]==2){\n ans.push_back(arr[i]);\n }\n }\n return ans;\n }\n};" }, { "code": null, "e": 5423, "s": 5420, "text": "-1" }, { "code": null, "e": 5453, "s": 5423, "text": "thakursahabsingh123 weeks ago" }, { "code": null, "e": 5467, "s": 5453, "text": "C++ Solution," }, { "code": null, "e": 5797, "s": 5469, "text": "class Solution { public: //Function to find two repeated elements. vector<int> twoRepeated (int arr[], int N) { // Your code here vector<int>count(N+1,0); vector<int>ans; for(int i=0;i<N+2;i++) { count[arr[i]]+=1; if(count[arr[i]]==2) ans.push_back(arr[i]); }" }, { "code": null, "e": 5821, "s": 5797, "text": " return ans; }}; " }, { "code": null, "e": 5967, "s": 5821, "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": 6003, "s": 5967, "text": " Login to access your submissions. " }, { "code": null, "e": 6013, "s": 6003, "text": "\nProblem\n" }, { "code": null, "e": 6023, "s": 6013, "text": "\nContest\n" }, { "code": null, "e": 6086, "s": 6023, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6271, "s": 6086, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6555, "s": 6271, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6701, "s": 6555, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6778, "s": 6701, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6819, "s": 6778, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6847, "s": 6819, "text": "Disable browser extensions." }, { "code": null, "e": 6918, "s": 6847, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7105, "s": 6918, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Ways to paint N paintings such that adjacent paintings don’t have same colors
23 Jun, 2022 Given two integers n and m, where n represent some paintings numbered from 1 to n and m represent some colours 1 to m with unlimited amount. The task is to find the number of ways to paint the paintings such that no two consecutive paintings have the same colors.Note: Answer must be calculated in modulo 10^9 +7 as answer can be very large. Examples: Input: n = 4, m = 2 Output: 2 Input: n = 4, m = 6 Output: 750 Asked in : National InstrumentsApproach: The total number of given color is m and the total paintings are from 1 to n. As per the condition of no two adjacent painting having the same color, first painting can be painted by anyone out of m colors and the rest of any painting can be painted by any of m-1 color except the color used for the painting just preceding that. Hence if we derive the solution for total number of ways, m * (m-1)^(n-1) is the actual answer. Now, this can be either calculated by simple iteration or by the method of efficient power calculation in O(logn) time.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>#define modd 1000000007using namespace std; // Function for finding the powerunsigned long power(unsigned long x, unsigned long y, unsigned long p){ unsigned long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res%p * x%p) % p; // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res;} // Function to calculate the number of waysint ways(int n, int m){ // Answer must be modulo of 10^9 + 7 return power(m - 1, n - 1, modd) * m % modd;} // Driver codeint main(){ int n = 5, m = 5; cout << ways(n, m); return 0;} // Java implementation of the above approach class GFG{ static final int modd = 1000000007; // Function for finding the power static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways static int ways(int n, int m) { // Answer must be modulo of 10^9 + 7 return (int) (power(m - 1, n - 1, modd) * m % modd); } // Driver code public static void main(String[] args) { int n = 5, m = 5; System.out.println(ways(n, m)); }} // This code is contributed by 29AjayKumar # Python3 implementation of the# above approach modd = 1000000007 # Function for finding the powerdef power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res%p * x%p) % p # y must be even now y = y >> 1 # y = y/2 x = (x%p * x%p) % p return res # Function to calculate the number of waysdef ways(n, m): # Answer must be modulo of 10^9 + 7 return power(m - 1, n - 1, modd) * m % modd # Driver coden, m = 5, 5print(ways(n, m)) # This code is contributed# by Mohit Kumar 29 // C# implementation of the above approachusing System; class GFG{ static int modd = 1000000007; // Function for finding the power static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways static int ways(int n, int m) { // Answer must be modulo of 10^9 + 7 return (int) (power(m - 1, n - 1, modd) * m % modd); } // Driver code static public void Main () { int n = 5, m = 5; Console.WriteLine(ways(n, m)); }} // This code is contributed by ajit <?php// PHP implementation of the above approach // Iterative Function to calculate// (x^y)%p in O(log y)function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it is more // than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res % $p * $x % $p) % $p; // y must be even now // y = $y/2 $y = $y >> 1; $x = ($x % $p * $x % $p) % $p; } return $res;} // Function to calculate the number of waysfunction ways($n, $m){ $modd =1000000007; // Answer must be modulo of 10^9 + 7 return (power($m - 1, $n - 1, $modd) * $m ) % $modd;} // Driver code$n = 5;$m = 5;echo ways($n, $m); // This code is contributed// by Arnab Kundu?> <script> // Javascript implementation of the above approach let modd = 1000000007; // Function for finding the power function power(x, y, p) { let res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways function ways(n, m) { // Answer must be modulo of 10^9 + 7 return (power(m - 1, n - 1, modd) * m % modd); } let n = 5, m = 5; document.write(ways(n, m)); </script> 1280 Time Complexity: O(logN)Auxiliary Space: O(1), since no extra space has been taken. mohit kumar 29 29AjayKumar jit_t andrew1234 kumargaurav8 divyeshrabadiya07 pankajsharmagfg ashutoshsinghgeeksforgeeks sushmitamittal1329 maths-power Algorithms Combinatorial Mathematical Mathematical Combinatorial 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 Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) What is Algorithm | Introduction to Algorithms Write a program to print all permutations of a given string Permutation and Combination in Python Program to calculate value of nCr Factorial of a large number
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 406, "s": 52, "text": "Given two integers n and m, where n represent some paintings numbered from 1 to n and m represent some colours 1 to m with unlimited amount. The task is to find the number of ways to paint the paintings such that no two consecutive paintings have the same colors.Note: Answer must be calculated in modulo 10^9 +7 as answer can be very large. Examples: " }, { "code": null, "e": 470, "s": 406, "text": "Input: n = 4, m = 2 \nOutput: 2\n\nInput: n = 4, m = 6\nOutput: 750" }, { "code": null, "e": 903, "s": 472, "text": "Asked in : National InstrumentsApproach: The total number of given color is m and the total paintings are from 1 to n. As per the condition of no two adjacent painting having the same color, first painting can be painted by anyone out of m colors and the rest of any painting can be painted by any of m-1 color except the color used for the painting just preceding that. Hence if we derive the solution for total number of ways, " }, { "code": null, "e": 942, "s": 903, "text": "m * (m-1)^(n-1) is the actual answer. " }, { "code": null, "e": 1114, "s": 942, "text": "Now, this can be either calculated by simple iteration or by the method of efficient power calculation in O(logn) time.Below is the implementation of the above approach: " }, { "code": null, "e": 1118, "s": 1114, "text": "C++" }, { "code": null, "e": 1123, "s": 1118, "text": "Java" }, { "code": null, "e": 1131, "s": 1123, "text": "Python3" }, { "code": null, "e": 1134, "s": 1131, "text": "C#" }, { "code": null, "e": 1138, "s": 1134, "text": "PHP" }, { "code": null, "e": 1149, "s": 1138, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>#define modd 1000000007using namespace std; // Function for finding the powerunsigned long power(unsigned long x, unsigned long y, unsigned long p){ unsigned long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res%p * x%p) % p; // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res;} // Function to calculate the number of waysint ways(int n, int m){ // Answer must be modulo of 10^9 + 7 return power(m - 1, n - 1, modd) * m % modd;} // Driver codeint main(){ int n = 5, m = 5; cout << ways(n, m); return 0;}", "e": 1968, "s": 1149, "text": null }, { "code": "// Java implementation of the above approach class GFG{ static final int modd = 1000000007; // Function for finding the power static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways static int ways(int n, int m) { // Answer must be modulo of 10^9 + 7 return (int) (power(m - 1, n - 1, modd) * m % modd); } // Driver code public static void main(String[] args) { int n = 5, m = 5; System.out.println(ways(n, m)); }} // This code is contributed by 29AjayKumar", "e": 2991, "s": 1968, "text": null }, { "code": "# Python3 implementation of the# above approach modd = 1000000007 # Function for finding the powerdef power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res%p * x%p) % p # y must be even now y = y >> 1 # y = y/2 x = (x%p * x%p) % p return res # Function to calculate the number of waysdef ways(n, m): # Answer must be modulo of 10^9 + 7 return power(m - 1, n - 1, modd) * m % modd # Driver coden, m = 5, 5print(ways(n, m)) # This code is contributed# by Mohit Kumar 29", "e": 3669, "s": 2991, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ static int modd = 1000000007; // Function for finding the power static long power(long x, long y, long p) { long res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways static int ways(int n, int m) { // Answer must be modulo of 10^9 + 7 return (int) (power(m - 1, n - 1, modd) * m % modd); } // Driver code static public void Main () { int n = 5, m = 5; Console.WriteLine(ways(n, m)); }} // This code is contributed by ajit", "e": 4672, "s": 3669, "text": null }, { "code": "<?php// PHP implementation of the above approach // Iterative Function to calculate// (x^y)%p in O(log y)function power($x, $y, $p){ // Initialize result $res = 1; // Update x if it is more // than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res % $p * $x % $p) % $p; // y must be even now // y = $y/2 $y = $y >> 1; $x = ($x % $p * $x % $p) % $p; } return $res;} // Function to calculate the number of waysfunction ways($n, $m){ $modd =1000000007; // Answer must be modulo of 10^9 + 7 return (power($m - 1, $n - 1, $modd) * $m ) % $modd;} // Driver code$n = 5;$m = 5;echo ways($n, $m); // This code is contributed// by Arnab Kundu?>", "e": 5499, "s": 4672, "text": null }, { "code": "<script> // Javascript implementation of the above approach let modd = 1000000007; // Function for finding the power function power(x, y, p) { let res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res%p * x%p) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x%p * x%p) % p; } return res; } // Function to calculate the number of ways function ways(n, m) { // Answer must be modulo of 10^9 + 7 return (power(m - 1, n - 1, modd) * m % modd); } let n = 5, m = 5; document.write(ways(n, m)); </script>", "e": 6350, "s": 5499, "text": null }, { "code": null, "e": 6355, "s": 6350, "text": "1280" }, { "code": null, "e": 6441, "s": 6357, "text": "Time Complexity: O(logN)Auxiliary Space: O(1), since no extra space has been taken." }, { "code": null, "e": 6456, "s": 6441, "text": "mohit kumar 29" }, { "code": null, "e": 6468, "s": 6456, "text": "29AjayKumar" }, { "code": null, "e": 6474, "s": 6468, "text": "jit_t" }, { "code": null, "e": 6485, "s": 6474, "text": "andrew1234" }, { "code": null, "e": 6498, "s": 6485, "text": "kumargaurav8" }, { "code": null, "e": 6516, "s": 6498, "text": "divyeshrabadiya07" }, { "code": null, "e": 6532, "s": 6516, "text": "pankajsharmagfg" }, { "code": null, "e": 6559, "s": 6532, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 6578, "s": 6559, "text": "sushmitamittal1329" }, { "code": null, "e": 6590, "s": 6578, "text": "maths-power" }, { "code": null, "e": 6601, "s": 6590, "text": "Algorithms" }, { "code": null, "e": 6615, "s": 6601, "text": "Combinatorial" }, { "code": null, "e": 6628, "s": 6615, "text": "Mathematical" }, { "code": null, "e": 6641, "s": 6628, "text": "Mathematical" }, { "code": null, "e": 6655, "s": 6641, "text": "Combinatorial" }, { "code": null, "e": 6666, "s": 6655, "text": "Algorithms" }, { "code": null, "e": 6764, "s": 6666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6813, "s": 6764, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6838, "s": 6813, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6905, "s": 6838, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 6968, "s": 6905, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 7015, "s": 6968, "text": "What is Algorithm | Introduction to Algorithms" }, { "code": null, "e": 7075, "s": 7015, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7113, "s": 7075, "text": "Permutation and Combination in Python" }, { "code": null, "e": 7147, "s": 7113, "text": "Program to calculate value of nCr" } ]
Convert String to Character Array in C#
26 May, 2020 Given a string, the task is to convert this string into a character array in C#. Examples: Input: string Output: [s, t, r, i, n, g] Input: GeeksForGeeks Output: [G, e, e, k, s, F, o, r, G, e, e, k, s] Method 1: Naive Approach Step 1: Get the string. Step 2: Create a character array of the same length as of string. Step 3: Traverse over the string to copy character at the i’th index of string to i’th index in the array. Step 4: Return or perform the operation on the character array. Below is the implementation of the above approach: C# // C# program to Convert a string // to a Character array // using Naive Approach using System; public class GFG{ static public void Main () { string str = "GeeksForGeeks"; // Creating array of string length char[] ch = new char[str.Length]; // Copy character by character into array for (int i = 0; i < str.Length; i++) { ch[i] = str[i]; } // Printing content of array foreach (char c in ch) { Console.WriteLine(c); } } } Output: G e e k s F o r G e e k s Method 2: Using toCharArray() Method Step 1: Get the string. Step 2: Create a character array of same length as of string. Step 3: Store the array return by toCharArray() method. Step 4: Return or perform operation on character array. C# // C# program to Convert a string // to a Character array // using ToCharArray method using System; public class GFG{ static public void Main () { string str = "GeeksForGeeks"; // Creating array of string length // Copy character by character into array char[] ch = str.ToCharArray(); // Printing content of array foreach (char c in ch) { Console.WriteLine(c); } } } Output: G e e k s F o r G e e k s CSharp-string C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 109, "s": 28, "text": "Given a string, the task is to convert this string into a character array in C#." }, { "code": null, "e": 119, "s": 109, "text": "Examples:" }, { "code": null, "e": 240, "s": 119, "text": "Input: string \nOutput: [s, t, r, i, n, g]\n \nInput: GeeksForGeeks\nOutput: [G, e, e, k, s, F, o, r, G, e, e, k, s] \n" }, { "code": null, "e": 265, "s": 240, "text": "Method 1: Naive Approach" }, { "code": null, "e": 289, "s": 265, "text": "Step 1: Get the string." }, { "code": null, "e": 355, "s": 289, "text": "Step 2: Create a character array of the same length as of string." }, { "code": null, "e": 462, "s": 355, "text": "Step 3: Traverse over the string to copy character at the i’th index of string to i’th index in the array." }, { "code": null, "e": 526, "s": 462, "text": "Step 4: Return or perform the operation on the character array." }, { "code": null, "e": 577, "s": 526, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 580, "s": 577, "text": "C#" }, { "code": "// C# program to Convert a string // to a Character array // using Naive Approach using System; public class GFG{ static public void Main () { string str = \"GeeksForGeeks\"; // Creating array of string length char[] ch = new char[str.Length]; // Copy character by character into array for (int i = 0; i < str.Length; i++) { ch[i] = str[i]; } // Printing content of array foreach (char c in ch) { Console.WriteLine(c); } } }", "e": 1131, "s": 580, "text": null }, { "code": null, "e": 1139, "s": 1131, "text": "Output:" }, { "code": null, "e": 1166, "s": 1139, "text": "G\ne\ne\nk\ns\nF\no\nr\nG\ne\ne\nk\ns\n" }, { "code": null, "e": 1203, "s": 1166, "text": "Method 2: Using toCharArray() Method" }, { "code": null, "e": 1227, "s": 1203, "text": "Step 1: Get the string." }, { "code": null, "e": 1289, "s": 1227, "text": "Step 2: Create a character array of same length as of string." }, { "code": null, "e": 1345, "s": 1289, "text": "Step 3: Store the array return by toCharArray() method." }, { "code": null, "e": 1401, "s": 1345, "text": "Step 4: Return or perform operation on character array." }, { "code": null, "e": 1404, "s": 1401, "text": "C#" }, { "code": "// C# program to Convert a string // to a Character array // using ToCharArray method using System; public class GFG{ static public void Main () { string str = \"GeeksForGeeks\"; // Creating array of string length // Copy character by character into array char[] ch = str.ToCharArray(); // Printing content of array foreach (char c in ch) { Console.WriteLine(c); } } }", "e": 1866, "s": 1404, "text": null }, { "code": null, "e": 1874, "s": 1866, "text": "Output:" }, { "code": null, "e": 1901, "s": 1874, "text": "G\ne\ne\nk\ns\nF\no\nr\nG\ne\ne\nk\ns\n" }, { "code": null, "e": 1915, "s": 1901, "text": "CSharp-string" }, { "code": null, "e": 1918, "s": 1915, "text": "C#" }, { "code": null, "e": 1930, "s": 1918, "text": "C# Programs" } ]
GATE | GATE CS 2018 | Question 56
09 Mar, 2018 Let G be a graph with 100! vertices, with each vertex labelled by a distinct permutation of the numbers 1, 2, ..., 100. There is an edge between vertices u and v if and only if the label of u can be obtained by swapping two adjacent numbers in the label of v. Let y denote the degree of a vertex in G, and z denote the number of connected components in G. Then y + 10z = _______ . Note –This was Numerical Type question. (A) 109(B) 110(C) 119(D) None of theseAnswer: (A)Explanation: There is an edge between vertices u and v iff the label of u can be obtained by swapping two adjacent numbers in the label of v.Then the set of swapping numbers will be {(1, 2), (2, 3), ...........(9, 9)}There will be 99 such sets, i.e. number of edges = 99and each vertex will have 99 edges corresponding to it. Say graph with 3! vertices, then vertices will be like {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}...Let’s pick vertex {123}, degree will be 2 since it will be connected with two other vertices {213} and {132}. We can conclude that for n, degree will be n-1. SO, degree of each vertex = 99 (as said y)As the vertices are connected together, the number of connected components formed will be 1 (as said z). y+10z = 99+10(1) = 109 Quiz of this Question GATE CS 2018 GATE-GATE CS 2018 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Mar, 2018" }, { "code": null, "e": 433, "s": 52, "text": "Let G be a graph with 100! vertices, with each vertex labelled by a distinct permutation of the numbers 1, 2, ..., 100. There is an edge between vertices u and v if and only if the label of u can be obtained by swapping two adjacent numbers in the label of v. Let y denote the degree of a vertex in G, and z denote the number of connected components in G. Then y + 10z = _______ ." }, { "code": null, "e": 473, "s": 433, "text": "Note –This was Numerical Type question." }, { "code": null, "e": 849, "s": 473, "text": "(A) 109(B) 110(C) 119(D) None of theseAnswer: (A)Explanation: There is an edge between vertices u and v iff the label of u can be obtained by swapping two adjacent numbers in the label of v.Then the set of swapping numbers will be {(1, 2), (2, 3), ...........(9, 9)}There will be 99 such sets, i.e. number of edges = 99and each vertex will have 99 edges corresponding to it. " }, { "code": null, "e": 1059, "s": 849, "text": "Say graph with 3! vertices, then vertices will be like {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}...Let’s pick vertex {123}, degree will be 2 since it will be connected with two other vertices {213} and {132}." }, { "code": null, "e": 1107, "s": 1059, "text": "We can conclude that for n, degree will be n-1." }, { "code": null, "e": 1254, "s": 1107, "text": "SO, degree of each vertex = 99 (as said y)As the vertices are connected together, the number of connected components formed will be 1 (as said z)." }, { "code": null, "e": 1278, "s": 1254, "text": " y+10z = 99+10(1) = 109" }, { "code": null, "e": 1300, "s": 1278, "text": "Quiz of this Question" }, { "code": null, "e": 1313, "s": 1300, "text": "GATE CS 2018" }, { "code": null, "e": 1331, "s": 1313, "text": "GATE-GATE CS 2018" }, { "code": null, "e": 1336, "s": 1331, "text": "GATE" } ]
Name mangling in Python
23 Jan, 2020 In name mangling process any identifier with two leading underscore and one trailing underscore is textually replaced with _classname__identifier where classname is the name of the current class. It means that any identifier of the form __geek (at least two leading underscores or at most one trailing underscore) is replaced with _classname__geek, where classname is the current class name with leading underscore(s) stripped. Example: # Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name def displayName(self): print(self.__name) s1 = Student("Santhosh")s1.displayName() # Raises an errorprint(s1.__name) Output Santhosh Traceback (most recent call last): File "/home/be691046ea08cd2db075d27186ea0493.py", line 14, in print(s1.__name) AttributeError: 'Student' object has no attribute '__name' In the above example, the class variable __name is not accessible outside the class. It can be accessed only within the class. Any modification of the class variable can be done only inside the class. With the help of dir() method, we can see the name mangling process that is done to the class variable. The name mangling process was done by the Interpreter. The dir() method is used by passing the class object and it will return all valid attributes that belong to that object. # Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name s1 = Student("Santhosh")print(dir(s1)) Output [‘_Student__name’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’] The above output shows dir() method returning all valid attributes with the name mangling process that is done to the class variable __name. The name changed from __name to _Student__name. The name mangling process helps to access the class variables from outside the class. The class variables can be accessed by adding _classname to it. The name mangling is closest to private not exactly private. # Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name s1 = Student("Santhosh")print(s1._Student__name) Output Santhosh The above class variable is accessed by adding the _classname to it. The class variable is accessed from outside the class with the name _Student__name. Due to name mangling, there is limited support for a valid use-case for class-private members basically to avoid name clashes of names with names defined by subclasses. Any identifier of the form __geek (at least two leading underscores or at most one trailing underscore) is replaced with _classname__geek, where classname is the current class name with leading underscore(s) stripped. As long as it occurs within the definition of the class, this mangling is done. This is helpful for letting subclasses override methods without breaking intraclass method calls.Let’s look at this example and try to find out how this underscore works: Example: # Python code to illustrate how mangling works # With method overriding class Map: def __init__(self): self.__geek() def geek(self): print("In parent class") # private copy of original geek() method __geek = geek class MapSubclass(Map): # provides new signature for geek() but # does not break __init__() def geek(self): print("In Child class") # Driver's codeobj = MapSubclass()obj.geek() Output: In parent class In Child class python-utility Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jan, 2020" }, { "code": null, "e": 482, "s": 54, "text": "In name mangling process any identifier with two leading underscore and one trailing underscore is textually replaced with _classname__identifier where classname is the name of the current class. It means that any identifier of the form __geek (at least two leading underscores or at most one trailing underscore) is replaced with _classname__geek, where classname is the current class name with leading underscore(s) stripped." }, { "code": null, "e": 491, "s": 482, "text": "Example:" }, { "code": "# Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name def displayName(self): print(self.__name) s1 = Student(\"Santhosh\")s1.displayName() # Raises an errorprint(s1.__name)", "e": 742, "s": 491, "text": null }, { "code": null, "e": 749, "s": 742, "text": "Output" }, { "code": null, "e": 759, "s": 749, "text": "Santhosh\n" }, { "code": null, "e": 940, "s": 759, "text": "Traceback (most recent call last):\n File \"/home/be691046ea08cd2db075d27186ea0493.py\", line 14, in \n print(s1.__name)\nAttributeError: 'Student' object has no attribute '__name'\n" }, { "code": null, "e": 1141, "s": 940, "text": "In the above example, the class variable __name is not accessible outside the class. It can be accessed only within the class. Any modification of the class variable can be done only inside the class." }, { "code": null, "e": 1421, "s": 1141, "text": "With the help of dir() method, we can see the name mangling process that is done to the class variable. The name mangling process was done by the Interpreter. The dir() method is used by passing the class object and it will return all valid attributes that belong to that object." }, { "code": "# Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name s1 = Student(\"Santhosh\")print(dir(s1))", "e": 1581, "s": 1421, "text": null }, { "code": null, "e": 1588, "s": 1581, "text": "Output" }, { "code": null, "e": 1930, "s": 1588, "text": "[‘_Student__name’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’]" }, { "code": null, "e": 2119, "s": 1930, "text": "The above output shows dir() method returning all valid attributes with the name mangling process that is done to the class variable __name. The name changed from __name to _Student__name." }, { "code": null, "e": 2330, "s": 2119, "text": "The name mangling process helps to access the class variables from outside the class. The class variables can be accessed by adding _classname to it. The name mangling is closest to private not exactly private." }, { "code": "# Python program to demonstrate# name mangling class Student: def __init__(self, name): self.__name = name s1 = Student(\"Santhosh\")print(s1._Student__name)", "e": 2500, "s": 2330, "text": null }, { "code": null, "e": 2507, "s": 2500, "text": "Output" }, { "code": null, "e": 2516, "s": 2507, "text": "Santhosh" }, { "code": null, "e": 2669, "s": 2516, "text": "The above class variable is accessed by adding the _classname to it. The class variable is accessed from outside the class with the name _Student__name." }, { "code": null, "e": 3307, "s": 2669, "text": "Due to name mangling, there is limited support for a valid use-case for class-private members basically to avoid name clashes of names with names defined by subclasses. Any identifier of the form __geek (at least two leading underscores or at most one trailing underscore) is replaced with _classname__geek, where classname is the current class name with leading underscore(s) stripped. As long as it occurs within the definition of the class, this mangling is done. This is helpful for letting subclasses override methods without breaking intraclass method calls.Let’s look at this example and try to find out how this underscore works:" }, { "code": null, "e": 3316, "s": 3307, "text": "Example:" }, { "code": "# Python code to illustrate how mangling works # With method overriding class Map: def __init__(self): self.__geek() def geek(self): print(\"In parent class\") # private copy of original geek() method __geek = geek class MapSubclass(Map): # provides new signature for geek() but # does not break __init__() def geek(self): print(\"In Child class\") # Driver's codeobj = MapSubclass()obj.geek()", "e": 3805, "s": 3316, "text": null }, { "code": null, "e": 3813, "s": 3805, "text": "Output:" }, { "code": null, "e": 3845, "s": 3813, "text": "In parent class\nIn Child class\n" }, { "code": null, "e": 3860, "s": 3845, "text": "python-utility" }, { "code": null, "e": 3867, "s": 3860, "text": "Python" }, { "code": null, "e": 3886, "s": 3867, "text": "Technical Scripter" } ]
How to Check the OS Version in Linux?
15 Apr, 2021 When we want to install the software in our system, firstly we must know that whether our current Operating System is supporting this version of the software or not. In Windows, we can easily check it as Windows is totally based on a GUI-based Operating System. But we prefer to use the Command line instead of the GUI in Operating System like Linus/Unix. In this article, we will learn how to check the details of the Operating System we are using in Linux. We will use three simple methods to check the Linux OS version: Using os-release file available in Linux’s etc directoryUsing lsb_release commandUsing version file available in Linux’s proc directory Using os-release file available in Linux’s etc directory Using lsb_release command Using version file available in Linux’s proc directory We can check the Linux Operating System (OS) info by running the below command ~$ cat /etc/os-release Output: LSB Stands for Linux Standard Base, we can check the Linux Operating System (OS) using lsb_release command $ lsb_release -a Output: We can use the below command to check the Linux Operating System (OS) ~$ cat /proc/version Output: How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install and Use NVM on Windows? How to Install Flutter on Visual Studio Code? How to Install Jupyter Notebook on MacOS? How to Install Z Shell(zsh) on Linux? Sed Command in Linux/Unix with examples grep command in Unix/Linux AWK command in Unix/Linux with examples tar command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Apr, 2021" }, { "code": null, "e": 316, "s": 54, "text": "When we want to install the software in our system, firstly we must know that whether our current Operating System is supporting this version of the software or not. In Windows, we can easily check it as Windows is totally based on a GUI-based Operating System." }, { "code": null, "e": 513, "s": 316, "text": "But we prefer to use the Command line instead of the GUI in Operating System like Linus/Unix. In this article, we will learn how to check the details of the Operating System we are using in Linux." }, { "code": null, "e": 577, "s": 513, "text": "We will use three simple methods to check the Linux OS version:" }, { "code": null, "e": 713, "s": 577, "text": "Using os-release file available in Linux’s etc directoryUsing lsb_release commandUsing version file available in Linux’s proc directory" }, { "code": null, "e": 770, "s": 713, "text": "Using os-release file available in Linux’s etc directory" }, { "code": null, "e": 796, "s": 770, "text": "Using lsb_release command" }, { "code": null, "e": 851, "s": 796, "text": "Using version file available in Linux’s proc directory" }, { "code": null, "e": 930, "s": 851, "text": "We can check the Linux Operating System (OS) info by running the below command" }, { "code": null, "e": 954, "s": 930, "text": "~$ cat /etc/os-release " }, { "code": null, "e": 962, "s": 954, "text": "Output:" }, { "code": null, "e": 1070, "s": 962, "text": "LSB Stands for Linux Standard Base, we can check the Linux Operating System (OS) using lsb_release command" }, { "code": null, "e": 1087, "s": 1070, "text": "$ lsb_release -a" }, { "code": null, "e": 1095, "s": 1087, "text": "Output:" }, { "code": null, "e": 1165, "s": 1095, "text": "We can use the below command to check the Linux Operating System (OS)" }, { "code": null, "e": 1186, "s": 1165, "text": "~$ cat /proc/version" }, { "code": null, "e": 1194, "s": 1186, "text": "Output:" }, { "code": null, "e": 1201, "s": 1194, "text": "How To" }, { "code": null, "e": 1212, "s": 1201, "text": "Linux-Unix" }, { "code": null, "e": 1310, "s": 1212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1359, "s": 1310, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 1398, "s": 1359, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 1444, "s": 1398, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 1486, "s": 1444, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 1524, "s": 1486, "text": "How to Install Z Shell(zsh) on Linux?" }, { "code": null, "e": 1564, "s": 1524, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 1591, "s": 1564, "text": "grep command in Unix/Linux" }, { "code": null, "e": 1631, "s": 1591, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 1666, "s": 1631, "text": "tar command in Linux with examples" } ]
C# Multithreading
22 Apr, 2020 Multitasking is the simultaneous execution of multiple tasks or processes over a certain time interval. Windows operating system is an example of multitasking because it is capable of running more than one process at a time like running Google Chrome, Notepad, VLC player, etc. at the same time. The operating system uses a term known as a process to execute all these applications at the same time. A process is a part of an operating system that is responsible for executing an application. Every program that executes on your system is a process and to run the code inside the application a process uses a term known as a thread.A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic. Every program by default carries one thread to executes the logic of the program and the thread is known as the Main Thread, so every program or application is by default single-threaded model. This single-threaded model has a drawback. The single thread runs all the process present in the program in synchronizing manner, means one after another. So, the second process waits until the first process completes its execution, it consumes more time in processing. For example, we have a class named as Geek and this class contains two different methods, i.e method1, method2. Now the main thread is responsible for executing all these methods, so the main thread executes all these methods one by one. Example: // C# program to illustrate the // concept of single threaded modelusing System;using System.Threading; public class Geek { // static method one public static void method1() { // It prints numbers from 0 to 10 for (int I = 0; I <= 10; I++) { Console.WriteLine("Method1 is : {0}", I); // When the value of I is equal to // 5 then this method sleeps for // 6 seconds and after 6 seconds // it resumes its working if (I == 5) { Thread.Sleep(6000); } } } // static method two public static void method2() { // It prints numbers from 0 to 10 for (int J = 0; J <= 10; J++) { Console.WriteLine("Method2 is : {0}", J); } }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Calling static methods Geek.method1(); Geek.method2(); }} Output: Method1 is : 0 Method1 is : 1 Method1 is : 2 Method1 is : 3 Method1 is : 4 Method1 is : 5 Method1 is : 6 Method1 is : 7 Method1 is : 8 Method1 is : 9 Method1 is : 10 Method2 is : 0 Method2 is : 1 Method2 is : 2 Method2 is : 3 Method2 is : 4 Method2 is : 5 Method2 is : 6 Method2 is : 7 Method2 is : 8 Method2 is : 9 Method2 is : 10 Explanation: Here, first of all, method1 executes. In method1 , for loop starts from 0 when the value of i is equal to 5 then the method goes into sleep for 6 seconds and after 6 seconds it resumes its process and print remaining value. Until method2 is in the waiting state. method2 start its working when method1 complete its assigned task. So to overcome the drawback of single threaded model multithreading is introduced. Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread. So the major advantage of multithreading is it works simultaneously, which means multiple tasks execute at the same time. And also maximizing the utilization of the CPU because multithreading works on time-sharing concept mean each thread takes its own time for execution and does not affect the execution of another thread, this time interval is given by the operating system. Example: // C# program to illustrate the// concept of multithreadingusing System;using System.Threading; public class GFG { // static method one public static void method1() { // It prints numbers from 0 to 10 for (int I = 0; I <= 10; I++) { Console.WriteLine("Method1 is : {0}", I); // When the value of I is equal to 5 then // this method sleeps for 6 seconds if (I == 5) { Thread.Sleep(6000); } } } // static method two public static void method2() { // It prints numbers from 0 to 10 for (int J = 0; J <= 10; J++) { Console.WriteLine("Method2 is : {0}", J); } } // Main Method static public void Main() { // Creating and initializing threads Thread thr1 = new Thread(method1); Thread thr2 = new Thread(method2); thr1.Start(); thr2.Start(); }} Output : Method1 is : 0 Method1 is : 1 Method1 is : 2 Method1 is : 3 Method2 is : 0 Method2 is : 1 Method2 is : 2 Method2 is : 3 Method2 is : 4 Method2 is : 5 Method2 is : 6 Method2 is : 7 Method2 is : 8 Method2 is : 9 Method2 is : 10 Method1 is : 4 Method1 is : 5 Method1 is : 6 Method1 is : 7 Method1 is : 8 Method1 is : 9 Method1 is : 10 Explanation: Here, we create and initialize two threads, i.e thr1 and thr2 using Thread class. Now using thr1.Start(); and thr2.Start(); we start the execution of both the threads. Now both thread runs simultaneously and the processing of thr2 does not depend upon the processing of thr1 like in the single threaded model. Note: Output may vary due to context switching. Advantages of Multithreading: It executes multiple process simultaneously. Maximize the utilization of CPU resources. Time sharing between multiple process. CSharp Multithreading C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Apr, 2020" }, { "code": null, "e": 1347, "s": 54, "text": "Multitasking is the simultaneous execution of multiple tasks or processes over a certain time interval. Windows operating system is an example of multitasking because it is capable of running more than one process at a time like running Google Chrome, Notepad, VLC player, etc. at the same time. The operating system uses a term known as a process to execute all these applications at the same time. A process is a part of an operating system that is responsible for executing an application. Every program that executes on your system is a process and to run the code inside the application a process uses a term known as a thread.A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic. Every program by default carries one thread to executes the logic of the program and the thread is known as the Main Thread, so every program or application is by default single-threaded model. This single-threaded model has a drawback. The single thread runs all the process present in the program in synchronizing manner, means one after another. So, the second process waits until the first process completes its execution, it consumes more time in processing." }, { "code": null, "e": 1585, "s": 1347, "text": "For example, we have a class named as Geek and this class contains two different methods, i.e method1, method2. Now the main thread is responsible for executing all these methods, so the main thread executes all these methods one by one." }, { "code": null, "e": 1594, "s": 1585, "text": "Example:" }, { "code": "// C# program to illustrate the // concept of single threaded modelusing System;using System.Threading; public class Geek { // static method one public static void method1() { // It prints numbers from 0 to 10 for (int I = 0; I <= 10; I++) { Console.WriteLine(\"Method1 is : {0}\", I); // When the value of I is equal to // 5 then this method sleeps for // 6 seconds and after 6 seconds // it resumes its working if (I == 5) { Thread.Sleep(6000); } } } // static method two public static void method2() { // It prints numbers from 0 to 10 for (int J = 0; J <= 10; J++) { Console.WriteLine(\"Method2 is : {0}\", J); } }} // Driver Classpublic class GFG { // Main Method static public void Main() { // Calling static methods Geek.method1(); Geek.method2(); }}", "e": 2573, "s": 1594, "text": null }, { "code": null, "e": 2581, "s": 2573, "text": "Output:" }, { "code": null, "e": 2914, "s": 2581, "text": "Method1 is : 0\nMethod1 is : 1\nMethod1 is : 2\nMethod1 is : 3\nMethod1 is : 4\nMethod1 is : 5\nMethod1 is : 6\nMethod1 is : 7\nMethod1 is : 8\nMethod1 is : 9\nMethod1 is : 10\nMethod2 is : 0\nMethod2 is : 1\nMethod2 is : 2\nMethod2 is : 3\nMethod2 is : 4\nMethod2 is : 5\nMethod2 is : 6\nMethod2 is : 7\nMethod2 is : 8\nMethod2 is : 9\nMethod2 is : 10\n" }, { "code": null, "e": 3340, "s": 2914, "text": "Explanation: Here, first of all, method1 executes. In method1 , for loop starts from 0 when the value of i is equal to 5 then the method goes into sleep for 6 seconds and after 6 seconds it resumes its process and print remaining value. Until method2 is in the waiting state. method2 start its working when method1 complete its assigned task. So to overcome the drawback of single threaded model multithreading is introduced." }, { "code": null, "e": 3997, "s": 3340, "text": "Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread. So the major advantage of multithreading is it works simultaneously, which means multiple tasks execute at the same time. And also maximizing the utilization of the CPU because multithreading works on time-sharing concept mean each thread takes its own time for execution and does not affect the execution of another thread, this time interval is given by the operating system." }, { "code": null, "e": 4006, "s": 3997, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of multithreadingusing System;using System.Threading; public class GFG { // static method one public static void method1() { // It prints numbers from 0 to 10 for (int I = 0; I <= 10; I++) { Console.WriteLine(\"Method1 is : {0}\", I); // When the value of I is equal to 5 then // this method sleeps for 6 seconds if (I == 5) { Thread.Sleep(6000); } } } // static method two public static void method2() { // It prints numbers from 0 to 10 for (int J = 0; J <= 10; J++) { Console.WriteLine(\"Method2 is : {0}\", J); } } // Main Method static public void Main() { // Creating and initializing threads Thread thr1 = new Thread(method1); Thread thr2 = new Thread(method2); thr1.Start(); thr2.Start(); }}", "e": 4951, "s": 4006, "text": null }, { "code": null, "e": 4960, "s": 4951, "text": "Output :" }, { "code": null, "e": 5293, "s": 4960, "text": "Method1 is : 0\nMethod1 is : 1\nMethod1 is : 2\nMethod1 is : 3\nMethod2 is : 0\nMethod2 is : 1\nMethod2 is : 2\nMethod2 is : 3\nMethod2 is : 4\nMethod2 is : 5\nMethod2 is : 6\nMethod2 is : 7\nMethod2 is : 8\nMethod2 is : 9\nMethod2 is : 10\nMethod1 is : 4\nMethod1 is : 5\nMethod1 is : 6\nMethod1 is : 7\nMethod1 is : 8\nMethod1 is : 9\nMethod1 is : 10\n" }, { "code": null, "e": 5616, "s": 5293, "text": "Explanation: Here, we create and initialize two threads, i.e thr1 and thr2 using Thread class. Now using thr1.Start(); and thr2.Start(); we start the execution of both the threads. Now both thread runs simultaneously and the processing of thr2 does not depend upon the processing of thr1 like in the single threaded model." }, { "code": null, "e": 5664, "s": 5616, "text": "Note: Output may vary due to context switching." }, { "code": null, "e": 5694, "s": 5664, "text": "Advantages of Multithreading:" }, { "code": null, "e": 5739, "s": 5694, "text": "It executes multiple process simultaneously." }, { "code": null, "e": 5782, "s": 5739, "text": "Maximize the utilization of CPU resources." }, { "code": null, "e": 5821, "s": 5782, "text": "Time sharing between multiple process." }, { "code": null, "e": 5843, "s": 5821, "text": "CSharp Multithreading" }, { "code": null, "e": 5846, "s": 5843, "text": "C#" }, { "code": null, "e": 5944, "s": 5846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5972, "s": 5944, "text": "C# Dictionary with examples" }, { "code": null, "e": 6003, "s": 5972, "text": "Introduction to .NET Framework" }, { "code": null, "e": 6018, "s": 6003, "text": "C# | Delegates" }, { "code": null, "e": 6061, "s": 6018, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6110, "s": 6061, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6133, "s": 6110, "text": "C# | Method Overriding" }, { "code": null, "e": 6149, "s": 6133, "text": "C# | Data Types" }, { "code": null, "e": 6167, "s": 6149, "text": "C# | Constructors" }, { "code": null, "e": 6207, "s": 6167, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Prolog | An Introduction
28 Jun, 2022 Introduction : Prolog is a logic programming language. It has important role in artificial intelligence. Unlike many other programming languages, Prolog is intended primarily as a declarative programming language. In prolog, logic is expressed as relations (called as Facts and Rules). Core heart of prolog lies at the logic being applied. Formulation or Computation is carried out by running a query over these relations. Installation in Linux : Open a terminal (Ctrl+Alt+T) and type: sudo apt-get install swi-prolog Syntax and Basic Fields : In prolog, We declare some facts. These facts constitute the Knowledge Base of the system. We can query against the Knowledge Base. We get output as affirmative if our query is already in the knowledge Base or it is implied by Knowledge Base, otherwise we get output as negative. So, Knowledge Base can be considered similar to database, against which we can query. Prolog facts are expressed in definite pattern. Facts contain entities and their relation. Entities are written within the parenthesis separated by comma (, ). Their relation is expressed at the start and outside the parenthesis. Every fact/rule ends with a dot (.). So, a typical prolog fact goes as follows : Format : relation(entity1, entity2, ....k'th entity). Example : friends(raju, mahesh). singer(sonu). odd_number(5). Explanation : These facts can be interpreted as : raju and mahesh are friends. sonu is a singer. 5 is an odd number. Key Features :1. Unification : The basic idea is, can the given terms be made to represent the same structure.2. Backtracking : When a task fails, prolog traces backwards and tries to satisfy previous task.3. Recursion : Recursion is the basis for any search in program. Running queries :A typical prolog query can be asked as : Query 1 : ?- singer(sonu). Output : Yes. Explanation : As our knowledge base contains the above fact, so output was 'Yes', otherwise it would have been 'No'. Query 2 : ?- odd_number(7). Output : No. Explanation : As our knowledge base does not contain the above fact, so output was 'No'. Advantages :1. Easy to build database. Doesn’t need a lot of programming effort.2. Pattern matching is easy. Search is recursion based.3. It has built in list handling. Makes it easier to play with any algorithm involving lists. Disadvantages :1. LISP (another logic programming language) dominates over prolog with respect to I/O features.2. Sometimes input and output is not easy. Applications : Prolog is highly used in artificial intelligence(AI). Prolog is also used for pattern matching over natural language parse trees. Reference 1: https://en.wikipedia.org/wiki/Prolog Reference 2: http://www.swi-prolog.org/ ManasChhabra2 Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 5 Best Languages for Competitive Programming Top 10 Programming Languages to Learn in 2022 7 Highest Paying Programming Languages For Freelancers in 2022 Decorators with parameters in Python JS++ | Variables and Data Types JS++ | Interfaces JS++ | Event Handlers JS++ | Abstract Classes and Methods SQL using C/C++ and SQLite JS++ | Type System
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 69, "s": 54, "text": "Introduction :" }, { "code": null, "e": 477, "s": 69, "text": "Prolog is a logic programming language. It has important role in artificial intelligence. Unlike many other programming languages, Prolog is intended primarily as a declarative programming language. In prolog, logic is expressed as relations (called as Facts and Rules). Core heart of prolog lies at the logic being applied. Formulation or Computation is carried out by running a query over these relations." }, { "code": null, "e": 501, "s": 477, "text": "Installation in Linux :" }, { "code": null, "e": 540, "s": 501, "text": "Open a terminal (Ctrl+Alt+T) and type:" }, { "code": null, "e": 573, "s": 540, "text": "sudo apt-get install swi-prolog\n" }, { "code": null, "e": 599, "s": 573, "text": "Syntax and Basic Fields :" }, { "code": null, "e": 1276, "s": 599, "text": "In prolog, We declare some facts. These facts constitute the Knowledge Base of the system. We can query against the Knowledge Base. We get output as affirmative if our query is already in the knowledge Base or it is implied by Knowledge Base, otherwise we get output as negative. So, Knowledge Base can be considered similar to database, against which we can query. Prolog facts are expressed in definite pattern. Facts contain entities and their relation. Entities are written within the parenthesis separated by comma (, ). Their relation is expressed at the start and outside the parenthesis. Every fact/rule ends with a dot (.). So, a typical prolog fact goes as follows :" }, { "code": null, "e": 1513, "s": 1276, "text": "Format : relation(entity1, entity2, ....k'th entity).\n\nExample :\nfriends(raju, mahesh).\nsinger(sonu).\nodd_number(5).\n\nExplanation :\nThese facts can be interpreted as :\nraju and mahesh are friends.\nsonu is a singer.\n5 is an odd number.\n\n" }, { "code": null, "e": 1784, "s": 1513, "text": "Key Features :1. Unification : The basic idea is, can the given terms be made to represent the same structure.2. Backtracking : When a task fails, prolog traces backwards and tries to satisfy previous task.3. Recursion : Recursion is the basis for any search in program." }, { "code": null, "e": 1842, "s": 1784, "text": "Running queries :A typical prolog query can be asked as :" }, { "code": null, "e": 2136, "s": 1842, "text": "Query 1 : ?- singer(sonu).\nOutput : Yes.\n\nExplanation : As our knowledge base contains the above fact, so output was 'Yes', otherwise it would have been 'No'. \n\nQuery 2 : ?- odd_number(7).\nOutput : No.\n\nExplanation : As our knowledge base does not contain the above fact, so output was 'No'.\n\n" }, { "code": null, "e": 2365, "s": 2136, "text": "Advantages :1. Easy to build database. Doesn’t need a lot of programming effort.2. Pattern matching is easy. Search is recursion based.3. It has built in list handling. Makes it easier to play with any algorithm involving lists." }, { "code": null, "e": 2519, "s": 2365, "text": "Disadvantages :1. LISP (another logic programming language) dominates over prolog with respect to I/O features.2. Sometimes input and output is not easy." }, { "code": null, "e": 2534, "s": 2519, "text": "Applications :" }, { "code": null, "e": 2664, "s": 2534, "text": "Prolog is highly used in artificial intelligence(AI). Prolog is also used for pattern matching over natural language parse trees." }, { "code": null, "e": 2714, "s": 2664, "text": "Reference 1: https://en.wikipedia.org/wiki/Prolog" }, { "code": null, "e": 2754, "s": 2714, "text": "Reference 2: http://www.swi-prolog.org/" }, { "code": null, "e": 2768, "s": 2754, "text": "ManasChhabra2" }, { "code": null, "e": 2789, "s": 2768, "text": "Programming Language" }, { "code": null, "e": 2887, "s": 2789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2932, "s": 2887, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 2978, "s": 2932, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 3041, "s": 2978, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 3078, "s": 3041, "text": "Decorators with parameters in Python" }, { "code": null, "e": 3110, "s": 3078, "text": "JS++ | Variables and Data Types" }, { "code": null, "e": 3128, "s": 3110, "text": "JS++ | Interfaces" }, { "code": null, "e": 3150, "s": 3128, "text": "JS++ | Event Handlers" }, { "code": null, "e": 3186, "s": 3150, "text": "JS++ | Abstract Classes and Methods" }, { "code": null, "e": 3213, "s": 3186, "text": "SQL using C/C++ and SQLite" } ]
memmove() in C/C++
10 Dec, 2021 memmove() is used to copy a block of memory from a location to another. It is declared in string.h // Copies "numBytes" bytes from address "from" to address "to" void * memmove(void *to, const void *from, size_t numBytes); Below is a sample C program to show the working of memmove(). C /* A C program to demonstrate working of memmove */#include <stdio.h>#include <string.h> int main(){ char str1[] = "Geeks"; // Array of size 100 char str2[] = "Quiz"; // Array of size 5 puts("str1 before memmove "); puts(str1); /* Copies contents of str2 to sr1 */ memmove(str1, str2, sizeof(str2)); puts("\nstr1 after memmove "); puts(str1); return 0;} str1 before memmove Geeks str1 after memmove Quiz How is it different from memcpy()? memcpy() simply copies data one by one from one location to another. On the other hand memmove() copies the data first to an intermediate buffer, then from the buffer to destination.memcpy() leads to problems when strings overlap. For example, consider below program. C // Sample program to show that memcpy() can lose data.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = "Geeksfor"; memcpy(csrc + 5, csrc, strlen(csrc) + 1); printf("%s", csrc); return 0;} GeeksGeeksfor Since the input addresses are overlapping, the above program overwrites the original string and causes data loss. Consider the below program for understanding the difference between the memcpy and memmove function in case of overlapping happens. C // Sample program to show that memmove() is better than// memcpy() when addresses overlap.#include <stdio.h>#include <string.h>int main(){ char str[100] = "Learningisfun"; char *first, *second; first = str; second = str; printf("Original string :%s\n ", str); // when overlap happens then it just ignore it memcpy(first + 8, first, 10); printf("memcpy overlap : %s\n ", str); // when overlap it start from first position memmove(second + 8, first, 10); printf("memmove overlap : %s\n ", str); return 0;} Original string :Learningisfun memcpy overlap : LearningLearningis memmove overlap : LearningLearningLe As you can see clearly with memmove function whenever overlap happens (i.e when the first pointer moves to the character ‘i’) then the first pointer will start to print from the beginning (output Le) but with memcpy function, it just ignores if there is an overlap and just keep moving forward. Write your own memcpy() and memmove()?Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above vermashobhit1994 rkbhola5 CPP-Library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) Bitwise Operators in C/C++ Priority Queue in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Object Oriented Programming in C++ Inheritance in C++ C++ Classes and Objects Sorting a vector in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Dec, 2021" }, { "code": null, "e": 153, "s": 54, "text": "memmove() is used to copy a block of memory from a location to another. It is declared in string.h" }, { "code": null, "e": 278, "s": 153, "text": "// Copies \"numBytes\" bytes from address \"from\" to address \"to\"\nvoid * memmove(void *to, const void *from, size_t numBytes);\n" }, { "code": null, "e": 340, "s": 278, "text": "Below is a sample C program to show the working of memmove()." }, { "code": null, "e": 342, "s": 340, "text": "C" }, { "code": "/* A C program to demonstrate working of memmove */#include <stdio.h>#include <string.h> int main(){ char str1[] = \"Geeks\"; // Array of size 100 char str2[] = \"Quiz\"; // Array of size 5 puts(\"str1 before memmove \"); puts(str1); /* Copies contents of str2 to sr1 */ memmove(str1, str2, sizeof(str2)); puts(\"\\nstr1 after memmove \"); puts(str1); return 0;}", "e": 732, "s": 342, "text": null }, { "code": null, "e": 786, "s": 732, "text": "str1 before memmove \nGeeks\n\nstr1 after memmove \nQuiz\n" }, { "code": null, "e": 822, "s": 786, "text": "How is it different from memcpy()? " }, { "code": null, "e": 1054, "s": 822, "text": "memcpy() simply copies data one by one from one location to another. On the other hand memmove() copies the data first to an intermediate buffer, then from the buffer to destination.memcpy() leads to problems when strings overlap. " }, { "code": null, "e": 1092, "s": 1054, "text": "For example, consider below program. " }, { "code": null, "e": 1094, "s": 1092, "text": "C" }, { "code": "// Sample program to show that memcpy() can lose data.#include <stdio.h>#include <string.h>int main(){ char csrc[100] = \"Geeksfor\"; memcpy(csrc + 5, csrc, strlen(csrc) + 1); printf(\"%s\", csrc); return 0;}", "e": 1311, "s": 1094, "text": null }, { "code": null, "e": 1325, "s": 1311, "text": "GeeksGeeksfor" }, { "code": null, "e": 1440, "s": 1325, "text": "Since the input addresses are overlapping, the above program overwrites the original string and causes data loss. " }, { "code": null, "e": 1572, "s": 1440, "text": "Consider the below program for understanding the difference between the memcpy and memmove function in case of overlapping happens." }, { "code": null, "e": 1574, "s": 1572, "text": "C" }, { "code": "// Sample program to show that memmove() is better than// memcpy() when addresses overlap.#include <stdio.h>#include <string.h>int main(){ char str[100] = \"Learningisfun\"; char *first, *second; first = str; second = str; printf(\"Original string :%s\\n \", str); // when overlap happens then it just ignore it memcpy(first + 8, first, 10); printf(\"memcpy overlap : %s\\n \", str); // when overlap it start from first position memmove(second + 8, first, 10); printf(\"memmove overlap : %s\\n \", str); return 0;}", "e": 2124, "s": 1574, "text": null }, { "code": null, "e": 2232, "s": 2124, "text": "Original string :Learningisfun\n memcpy overlap : LearningLearningis\n memmove overlap : LearningLearningLe\n " }, { "code": null, "e": 2527, "s": 2232, "text": "As you can see clearly with memmove function whenever overlap happens (i.e when the first pointer moves to the character ‘i’) then the first pointer will start to print from the beginning (output Le) but with memcpy function, it just ignores if there is an overlap and just keep moving forward." }, { "code": null, "e": 2690, "s": 2527, "text": "Write your own memcpy() and memmove()?Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 2707, "s": 2690, "text": "vermashobhit1994" }, { "code": null, "e": 2716, "s": 2707, "text": "rkbhola5" }, { "code": null, "e": 2728, "s": 2716, "text": "CPP-Library" }, { "code": null, "e": 2732, "s": 2728, "text": "C++" }, { "code": null, "e": 2736, "s": 2732, "text": "CPP" }, { "code": null, "e": 2834, "s": 2736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2877, "s": 2834, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 2904, "s": 2877, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 2958, "s": 2904, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2992, "s": 2958, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3017, "s": 2992, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3034, "s": 3017, "text": "Substring in C++" }, { "code": null, "e": 3069, "s": 3034, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 3088, "s": 3069, "text": "Inheritance in C++" }, { "code": null, "e": 3112, "s": 3088, "text": "C++ Classes and Objects" } ]
HTML <html> Tag
17 Mar, 2022 The <html> tag in HTML is used to define the root of HTML and XHTML documents. The <html> tag tells the browser that it is an HTML document. It is the second outer container for everything that appears in an HTML document followed by the <!DOCTYPE> tag. The <html> tag requires a starting and end tag.Syntax: <html> HTML Contents... </html> Attribute Value: The <html> tag contains single attribute xmlns whose attribute value is http://www.w3.org/1999/xhtml. It is used to define the namespace attributes.Below examples illustrate the <html> element in HTML:Example 1: HTML <!DOCTYPE html><!-- html tag starts here --><html> <body> <h1>GeeksforGeeks</h1> <h2><html> Tag</h2> </body> </html> <!-- html tag ends here --> Output: Example 2: Using the xmlns attribute inside the <html> tag. HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>html Tag</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2><html> Tag</h2> </body></html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Mar, 2022" }, { "code": null, "e": 364, "s": 53, "text": "The <html> tag in HTML is used to define the root of HTML and XHTML documents. The <html> tag tells the browser that it is an HTML document. It is the second outer container for everything that appears in an HTML document followed by the <!DOCTYPE> tag. The <html> tag requires a starting and end tag.Syntax: " }, { "code": null, "e": 396, "s": 364, "text": "<html> HTML Contents... </html>" }, { "code": null, "e": 627, "s": 396, "text": "Attribute Value: The <html> tag contains single attribute xmlns whose attribute value is http://www.w3.org/1999/xhtml. It is used to define the namespace attributes.Below examples illustrate the <html> element in HTML:Example 1: " }, { "code": null, "e": 632, "s": 627, "text": "HTML" }, { "code": "<!DOCTYPE html><!-- html tag starts here --><html> <body> <h1>GeeksforGeeks</h1> <h2><html> Tag</h2> </body> </html> <!-- html tag ends here -->", "e": 858, "s": 632, "text": null }, { "code": null, "e": 868, "s": 858, "text": "Output: " }, { "code": null, "e": 930, "s": 868, "text": "Example 2: Using the xmlns attribute inside the <html> tag. " }, { "code": null, "e": 935, "s": 930, "text": "HTML" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <title>html Tag</title> <style> h1 { color:green; } body { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2><html> Tag</h2> </body></html> ", "e": 1408, "s": 935, "text": null }, { "code": null, "e": 1418, "s": 1408, "text": "Output: " }, { "code": null, "e": 1439, "s": 1418, "text": "Supported Browsers: " }, { "code": null, "e": 1453, "s": 1439, "text": "Google Chrome" }, { "code": null, "e": 1471, "s": 1453, "text": "Internet Explorer" }, { "code": null, "e": 1479, "s": 1471, "text": "Firefox" }, { "code": null, "e": 1485, "s": 1479, "text": "Opera" }, { "code": null, "e": 1492, "s": 1485, "text": "Safari" }, { "code": null, "e": 1508, "s": 1494, "text": "shubhamyadav4" }, { "code": null, "e": 1518, "s": 1508, "text": "HTML-Tags" }, { "code": null, "e": 1523, "s": 1518, "text": "HTML" }, { "code": null, "e": 1528, "s": 1523, "text": "HTML" }, { "code": null, "e": 1626, "s": 1528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1674, "s": 1626, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1736, "s": 1674, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1786, "s": 1736, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1810, "s": 1786, "text": "REST API (Introduction)" }, { "code": null, "e": 1863, "s": 1810, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1923, "s": 1863, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1984, "s": 1923, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2034, "s": 1984, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2071, "s": 2034, "text": "Types of CSS (Cascading Style Sheet)" } ]
How to clear form after submit in Javascript without using reset?
07 May, 2020 Forms in javascript are used to take the selective or required information from the user. There are various areas and purposes to use forms, i.e, in recruitment, when applying for some kind of jobs, or for asking some types of queries. It is easy to distribute form when it is not online but when it comes to the online field one cannot distribute a form, they have to use the same structure for everyone. In this case, they create one good structure and offer it to every one whosoever wants to go through that particular process and it is easy to proceed further in the online format. Submitting the form is the process after filling the form in which the filled form has to be submitted to the authorities. But it is the work of the designer to play with the programming part of the form. In this section, we will learn about how to clear the form after submitting it in Javascript without using reset? Example: Let’s create an Html form with the help of Tables. Here take some fields in the form, i.e, name, phone number, email, description and a submit button. These fields must have ids along with then. In this code, we are using submit in type by which our form will get submitted but to make it free from the filled date we are calling a function of name fun(). Using this function we will set the value of all fields equal to nothing. This function will be written in javascript and in the script tag. <!DOCTYPE html> <html> <head> <title>Reseting the form without reset method</title> <script> function fun(){ document.getElementById('name').value=''; document.getElementById('mail').value=''; document.getElementById('phone').value=''; } </script> <style> input[type=submit] { position: relative; float: right; } </style></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <b> clear form after submit in Javascript without using reset </b> <form id="d" action="/cgi-bin/test.cgi" name="geek"> <table cellspacing="0" cellpadding="3" border="1"> <tr> <td align="center">Username</td> <td> <input type="text" id="name"/> </td> </tr> <tr> <td align="center">Email</td> <td> <input type="text" id="mail"/> </td> </tr> <tr> <td align="center">Ph no</td> <td> <input type="tel" id="phone"/> </td> </tr> <tr> <td align="center"></td> <td> <input onclick="fun()" type="submit" value="Submit" /> </td> </tr> </table> </form> </center> </body> </html> Output: JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 May, 2020" }, { "code": null, "e": 615, "s": 28, "text": "Forms in javascript are used to take the selective or required information from the user. There are various areas and purposes to use forms, i.e, in recruitment, when applying for some kind of jobs, or for asking some types of queries. It is easy to distribute form when it is not online but when it comes to the online field one cannot distribute a form, they have to use the same structure for everyone. In this case, they create one good structure and offer it to every one whosoever wants to go through that particular process and it is easy to proceed further in the online format." }, { "code": null, "e": 934, "s": 615, "text": "Submitting the form is the process after filling the form in which the filled form has to be submitted to the authorities. But it is the work of the designer to play with the programming part of the form. In this section, we will learn about how to clear the form after submitting it in Javascript without using reset?" }, { "code": null, "e": 1440, "s": 934, "text": "Example: Let’s create an Html form with the help of Tables. Here take some fields in the form, i.e, name, phone number, email, description and a submit button. These fields must have ids along with then. In this code, we are using submit in type by which our form will get submitted but to make it free from the filled date we are calling a function of name fun(). Using this function we will set the value of all fields equal to nothing. This function will be written in javascript and in the script tag." }, { "code": "<!DOCTYPE html> <html> <head> <title>Reseting the form without reset method</title> <script> function fun(){ document.getElementById('name').value=''; document.getElementById('mail').value=''; document.getElementById('phone').value=''; } </script> <style> input[type=submit] { position: relative; float: right; } </style></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <b> clear form after submit in Javascript without using reset </b> <form id=\"d\" action=\"/cgi-bin/test.cgi\" name=\"geek\"> <table cellspacing=\"0\" cellpadding=\"3\" border=\"1\"> <tr> <td align=\"center\">Username</td> <td> <input type=\"text\" id=\"name\"/> </td> </tr> <tr> <td align=\"center\">Email</td> <td> <input type=\"text\" id=\"mail\"/> </td> </tr> <tr> <td align=\"center\">Ph no</td> <td> <input type=\"tel\" id=\"phone\"/> </td> </tr> <tr> <td align=\"center\"></td> <td> <input onclick=\"fun()\" type=\"submit\" value=\"Submit\" /> </td> </tr> </table> </form> </center> </body> </html> ", "e": 3095, "s": 1440, "text": null }, { "code": null, "e": 3103, "s": 3095, "text": "Output:" }, { "code": null, "e": 3119, "s": 3103, "text": "JavaScript-Misc" }, { "code": null, "e": 3124, "s": 3119, "text": "HTML" }, { "code": null, "e": 3135, "s": 3124, "text": "JavaScript" }, { "code": null, "e": 3152, "s": 3135, "text": "Web Technologies" }, { "code": null, "e": 3179, "s": 3152, "text": "Web technologies Questions" }, { "code": null, "e": 3184, "s": 3179, "text": "HTML" } ]
Scala | Multithreading
08 Apr, 2019 A process in which multiple threads executing simultaneously that is called multithreading. It allows you to perform multiple tasks independently. What are Threads in Scala? Threads are lightweight sub-processes which occupy less memory. A multi-threaded program contains two or more threads that can run concurrently and each thread can handle a different task at the same time making optimal use of the available resources specially when your system(computer) has multiple CPUs. Multithreading is used to develop concurrent applications in Scala. Threads in Scala can be created by using two mechanisms : Extending the Thread classExtending the Runnable Interface Extending the Thread class Extending the Runnable Interface Thread creation by extending the Thread classWe create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.// Scala code for thread creation by extending // the Thread class class MyThread extends Thread { override def run() { // Displaying the thread that is running println("Thread " + Thread.currentThread().getName() + " is running.") }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new MyThread() th.setName(x.toString()) th.start() } }}Output :Thread 1 is running. Thread 2 is running. Thread 3 is running. Thread 4 is running. Thread 5 is running. We create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object. // Scala code for thread creation by extending // the Thread class class MyThread extends Thread { override def run() { // Displaying the thread that is running println("Thread " + Thread.currentThread().getName() + " is running.") }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new MyThread() th.setName(x.toString()) th.start() } }} Output : Thread 1 is running. Thread 2 is running. Thread 3 is running. Thread 4 is running. Thread 5 is running. Thread creation by Extending Runnable InterfaceWe create a new class which extends Runnable interface and override run() method. Then we instantiate a Thread object passing the created class to the constructor. We then call start() method on this object.// Scala code for thread creation by implementing // the Runnable Interface class MyThread extends Runnable { override def run() { // Displaying the thread that is running println("Thread " + Thread.currentThread().getName() + " is running.") }} // Creating objectobject MainObject{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new Thread(new MyThread()) th.setName(x.toString()) th.start() } }}Output :Thread 1 is running. Thread 3 is running. Thread 4 is running. Thread 2 is running. Thread 5 is running. We create a new class which extends Runnable interface and override run() method. Then we instantiate a Thread object passing the created class to the constructor. We then call start() method on this object. // Scala code for thread creation by implementing // the Runnable Interface class MyThread extends Runnable { override def run() { // Displaying the thread that is running println("Thread " + Thread.currentThread().getName() + " is running.") }} // Creating objectobject MainObject{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new Thread(new MyThread()) th.setName(x.toString()) th.start() } }} Output : Thread 1 is running. Thread 3 is running. Thread 4 is running. Thread 2 is running. Thread 5 is running. Note : threads need not be running in any sequential order. All the threads run concurrently and independent of each other. In between the period of creation and Termination of a Scala Thread, the thread undergoes various state changes. These constitute the Life Cycle of a Scala Thread. It has the five following states. New : This is the first state when the Thread is just created. Runnable : This is the state when the Thread has been created but the Thread has not got the chance to start running. Running : In this state the Thread is performing its task. Blocked (or Waiting): This is the state when the thread is still alive, but is currently unable to run due to waiting for input or resources. Terminated : A thread is in dead state when its run() method exits. Picked Scala Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Type Casting in Scala Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example How to Install Scala with VSCode?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2019" }, { "code": null, "e": 175, "s": 28, "text": "A process in which multiple threads executing simultaneously that is called multithreading. It allows you to perform multiple tasks independently." }, { "code": null, "e": 202, "s": 175, "text": "What are Threads in Scala?" }, { "code": null, "e": 577, "s": 202, "text": "Threads are lightweight sub-processes which occupy less memory. A multi-threaded program contains two or more threads that can run concurrently and each thread can handle a different task at the same time making optimal use of the available resources specially when your system(computer) has multiple CPUs. Multithreading is used to develop concurrent applications in Scala." }, { "code": null, "e": 635, "s": 577, "text": "Threads in Scala can be created by using two mechanisms :" }, { "code": null, "e": 694, "s": 635, "text": "Extending the Thread classExtending the Runnable Interface" }, { "code": null, "e": 721, "s": 694, "text": "Extending the Thread class" }, { "code": null, "e": 754, "s": 721, "text": "Extending the Runnable Interface" }, { "code": null, "e": 1785, "s": 754, "text": "Thread creation by extending the Thread classWe create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.// Scala code for thread creation by extending // the Thread class class MyThread extends Thread { override def run() { // Displaying the thread that is running println(\"Thread \" + Thread.currentThread().getName() + \" is running.\") }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new MyThread() th.setName(x.toString()) th.start() } }}Output :Thread 1 is running.\nThread 2 is running.\nThread 3 is running.\nThread 4 is running.\nThread 5 is running.\n" }, { "code": null, "e": 2101, "s": 1785, "text": "We create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object." }, { "code": "// Scala code for thread creation by extending // the Thread class class MyThread extends Thread { override def run() { // Displaying the thread that is running println(\"Thread \" + Thread.currentThread().getName() + \" is running.\") }} // Creating objectobject GFG{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new MyThread() th.setName(x.toString()) th.start() } }}", "e": 2659, "s": 2101, "text": null }, { "code": null, "e": 2668, "s": 2659, "text": "Output :" }, { "code": null, "e": 2774, "s": 2668, "text": "Thread 1 is running.\nThread 2 is running.\nThread 3 is running.\nThread 4 is running.\nThread 5 is running.\n" }, { "code": null, "e": 3732, "s": 2774, "text": "Thread creation by Extending Runnable InterfaceWe create a new class which extends Runnable interface and override run() method. Then we instantiate a Thread object passing the created class to the constructor. We then call start() method on this object.// Scala code for thread creation by implementing // the Runnable Interface class MyThread extends Runnable { override def run() { // Displaying the thread that is running println(\"Thread \" + Thread.currentThread().getName() + \" is running.\") }} // Creating objectobject MainObject{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new Thread(new MyThread()) th.setName(x.toString()) th.start() } }}Output :Thread 1 is running.\nThread 3 is running.\nThread 4 is running.\nThread 2 is running.\nThread 5 is running.\n" }, { "code": null, "e": 3940, "s": 3732, "text": "We create a new class which extends Runnable interface and override run() method. Then we instantiate a Thread object passing the created class to the constructor. We then call start() method on this object." }, { "code": "// Scala code for thread creation by implementing // the Runnable Interface class MyThread extends Runnable { override def run() { // Displaying the thread that is running println(\"Thread \" + Thread.currentThread().getName() + \" is running.\") }} // Creating objectobject MainObject{ // Main method def main(args: Array[String]) { for (x <- 1 to 5) { var th = new Thread(new MyThread()) th.setName(x.toString()) th.start() } }}", "e": 4531, "s": 3940, "text": null }, { "code": null, "e": 4540, "s": 4531, "text": "Output :" }, { "code": null, "e": 4646, "s": 4540, "text": "Thread 1 is running.\nThread 3 is running.\nThread 4 is running.\nThread 2 is running.\nThread 5 is running.\n" }, { "code": null, "e": 4770, "s": 4646, "text": "Note : threads need not be running in any sequential order. All the threads run concurrently and independent of each other." }, { "code": null, "e": 4968, "s": 4770, "text": "In between the period of creation and Termination of a Scala Thread, the thread undergoes various state changes. These constitute the Life Cycle of a Scala Thread. It has the five following states." }, { "code": null, "e": 5031, "s": 4968, "text": "New : This is the first state when the Thread is just created." }, { "code": null, "e": 5149, "s": 5031, "text": "Runnable : This is the state when the Thread has been created but the Thread has not got the chance to start running." }, { "code": null, "e": 5208, "s": 5149, "text": "Running : In this state the Thread is performing its task." }, { "code": null, "e": 5350, "s": 5208, "text": "Blocked (or Waiting): This is the state when the thread is still alive, but is currently unable to run due to waiting for input or resources." }, { "code": null, "e": 5418, "s": 5350, "text": "Terminated : A thread is in dead state when its run() method exits." }, { "code": null, "e": 5425, "s": 5418, "text": "Picked" }, { "code": null, "e": 5431, "s": 5425, "text": "Scala" }, { "code": null, "e": 5442, "s": 5431, "text": "Scala-OOPS" }, { "code": null, "e": 5448, "s": 5442, "text": "Scala" }, { "code": null, "e": 5546, "s": 5448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5564, "s": 5546, "text": "For Loop in Scala" }, { "code": null, "e": 5585, "s": 5564, "text": "Scala | map() method" }, { "code": null, "e": 5608, "s": 5585, "text": "Scala | flatMap Method" }, { "code": null, "e": 5638, "s": 5608, "text": "String concatenation in Scala" }, { "code": null, "e": 5664, "s": 5638, "text": "Scala | reduce() Function" }, { "code": null, "e": 5686, "s": 5664, "text": "Type Casting in Scala" }, { "code": null, "e": 5726, "s": 5686, "text": "Scala List filter() method with example" }, { "code": null, "e": 5779, "s": 5726, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 5824, "s": 5779, "text": "Scala String substring() method with example" } ]
enum.auto() in Python
22 Apr, 2020 With the help of enum.auto() method, we can get the assigned integer value automatically by just using enum.auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes. Example #1 :In this example we can see that by using enum.auto() method, we are able to assign the numerical values automatically to the class attributes by using this method. # import enum and autofrom enum import Enum, auto # Using enum.auto() methodclass language(Enum): Java = auto() Python = auto() HTML = auto() print(list(language)) Output : [,, ] Example #2 : # import enum and autofrom enum import Enum, auto # Using enum.auto() methodclass language(Enum): Cpp = auto() JavaScript = auto() Java = auto() Python = auto() HTML = auto() print(list(language)) Output : [,,,, ] Python-enum 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 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 Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 151, "s": 28, "text": "With the help of enum.auto() method, we can get the assigned integer value automatically by just using enum.auto() method." }, { "code": null, "e": 172, "s": 151, "text": "Syntax : enum.auto()" }, { "code": null, "e": 251, "s": 172, "text": "Automatically assign the integer value to the values of enum class attributes." }, { "code": null, "e": 427, "s": 251, "text": "Example #1 :In this example we can see that by using enum.auto() method, we are able to assign the numerical values automatically to the class attributes by using this method." }, { "code": "# import enum and autofrom enum import Enum, auto # Using enum.auto() methodclass language(Enum): Java = auto() Python = auto() HTML = auto() print(list(language))", "e": 602, "s": 427, "text": null }, { "code": null, "e": 611, "s": 602, "text": "Output :" }, { "code": null, "e": 617, "s": 611, "text": "[,, ]" }, { "code": null, "e": 630, "s": 617, "text": "Example #2 :" }, { "code": "# import enum and autofrom enum import Enum, auto # Using enum.auto() methodclass language(Enum): Cpp = auto() JavaScript = auto() Java = auto() Python = auto() HTML = auto() print(list(language))", "e": 844, "s": 630, "text": null }, { "code": null, "e": 853, "s": 844, "text": "Output :" }, { "code": null, "e": 861, "s": 853, "text": "[,,,, ]" }, { "code": null, "e": 873, "s": 861, "text": "Python-enum" }, { "code": null, "e": 880, "s": 873, "text": "Python" }, { "code": null, "e": 978, "s": 880, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 996, "s": 978, "text": "Python Dictionary" }, { "code": null, "e": 1038, "s": 996, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1073, "s": 1038, "text": "Read a file line by line in Python" }, { "code": null, "e": 1099, "s": 1073, "text": "Python String | replace()" }, { "code": null, "e": 1131, "s": 1099, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1160, "s": 1131, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1187, "s": 1160, "text": "Python Classes and Objects" }, { "code": null, "e": 1223, "s": 1187, "text": "Convert integer to string in Python" }, { "code": null, "e": 1254, "s": 1223, "text": "Python | os.path.join() method" } ]
Count of possible subarrays and subsequences using given length of Array
18 Nov, 2021 Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.Examples: Input: N = 5 Output: Count of subarray = 15 Count of subsequence = 32Input: N = 3 Output: Count of subarray = 6 Count of subsequence = 8 Approach: The key observation fact for the count of the subarray is the number of ends position possible for each index elements of the array can be (N – i), Therefore the count of the subarray for an array of size N can be: Count of Sub-arrays = (N) * (N + 1) --------------- 2 The key observation fact for the count of the subsequence possible is each element of the array can be included in a subsequence or not. Therefore, the choice for each element is 2. Count of subsequences = 2N Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ implementation to count// the subarray and subsequence of// given length of the array#include <bits/stdc++.h>using namespace std; // Function to count the subarray// for the given arrayint countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthint countSubsequence(int n){ return pow(2, n);} // Driver Codeint main(){ int n = 5; cout << (countSubarray(n)) << endl; cout << (countSubsequence(n)) << endl; return 0;} // This code is contributed by mohit kumar 29 // Java implementation to count// the subarray and subsequence of// given length of the arrayclass GFG{ // Function to count the subarray// for the given arraystatic int countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthstatic int countSubsequence(int n){ return (int) Math.pow(2, n);} // Driver Codepublic static void main(String[] args){ int n = 5; System.out.print((countSubarray(n)) +"\n"); System.out.print((countSubsequence(n)) +"\n");}} // This code is contributed by Princi Singh # Python implementation to count# the subarray and subsequence of# given length of the array # Function to count the subarray# for the given arraydef countSubarray(n): return ((n)*(n + 1))//2 # Function to count the subsequence# for the given array lengthdef countSubsequence(n): return (2**n) # Driver Code if __name__ == "__main__": n = 5 print(countSubarray(n)) print(countSubsequence(n)) // C# implementation to count// the subarray and subsequence of// given length of the arrayusing System; class GFG{ // Function to count the subarray// for the given arraystatic int countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthstatic int countSubsequence(int n){ return (int) Math.Pow(2, n);} // Driver Codepublic static void Main(String[] args){ int n = 5; Console.Write((countSubarray(n)) +"\n"); Console.Write((countSubsequence(n)) +"\n");}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation to count// the subarray and subsequence of// given length of the array // Function to count the subarray// for the given arrayfunction countSubarray(n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthfunction countSubsequence(n){ return Math.pow(2, n);} // Driver Code let n = 5; document.write((countSubarray(n)) +"<br/>"); document.write((countSubsequence(n)) +"\n"); </script> 15 32 Time Complexity: O(log n) Auxiliary Space: O(1) mohit kumar 29 princi singh Rajput-Ji susmitakundugoaldanga subham348 subarray subsequence Arrays Competitive Programming Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Nov, 2021" }, { "code": null, "e": 226, "s": 53, "text": "Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.Examples: " }, { "code": null, "e": 365, "s": 226, "text": "Input: N = 5 Output: Count of subarray = 15 Count of subsequence = 32Input: N = 3 Output: Count of subarray = 6 Count of subsequence = 8 " }, { "code": null, "e": 593, "s": 367, "text": "Approach: The key observation fact for the count of the subarray is the number of ends position possible for each index elements of the array can be (N – i), Therefore the count of the subarray for an array of size N can be: " }, { "code": null, "e": 696, "s": 593, "text": "Count of Sub-arrays = (N) * (N + 1)\n ---------------\n 2" }, { "code": null, "e": 880, "s": 696, "text": "The key observation fact for the count of the subsequence possible is each element of the array can be included in a subsequence or not. Therefore, the choice for each element is 2. " }, { "code": null, "e": 907, "s": 880, "text": "Count of subsequences = 2N" }, { "code": null, "e": 960, "s": 907, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 964, "s": 960, "text": "C++" }, { "code": null, "e": 969, "s": 964, "text": "Java" }, { "code": null, "e": 976, "s": 969, "text": "Python" }, { "code": null, "e": 979, "s": 976, "text": "C#" }, { "code": null, "e": 990, "s": 979, "text": "Javascript" }, { "code": "// C++ implementation to count// the subarray and subsequence of// given length of the array#include <bits/stdc++.h>using namespace std; // Function to count the subarray// for the given arrayint countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthint countSubsequence(int n){ return pow(2, n);} // Driver Codeint main(){ int n = 5; cout << (countSubarray(n)) << endl; cout << (countSubsequence(n)) << endl; return 0;} // This code is contributed by mohit kumar 29", "e": 1533, "s": 990, "text": null }, { "code": "// Java implementation to count// the subarray and subsequence of// given length of the arrayclass GFG{ // Function to count the subarray// for the given arraystatic int countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthstatic int countSubsequence(int n){ return (int) Math.pow(2, n);} // Driver Codepublic static void main(String[] args){ int n = 5; System.out.print((countSubarray(n)) +\"\\n\"); System.out.print((countSubsequence(n)) +\"\\n\");}} // This code is contributed by Princi Singh", "e": 2102, "s": 1533, "text": null }, { "code": "# Python implementation to count# the subarray and subsequence of# given length of the array # Function to count the subarray# for the given arraydef countSubarray(n): return ((n)*(n + 1))//2 # Function to count the subsequence# for the given array lengthdef countSubsequence(n): return (2**n) # Driver Code if __name__ == \"__main__\": n = 5 print(countSubarray(n)) print(countSubsequence(n))", "e": 2515, "s": 2102, "text": null }, { "code": "// C# implementation to count// the subarray and subsequence of// given length of the arrayusing System; class GFG{ // Function to count the subarray// for the given arraystatic int countSubarray(int n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthstatic int countSubsequence(int n){ return (int) Math.Pow(2, n);} // Driver Codepublic static void Main(String[] args){ int n = 5; Console.Write((countSubarray(n)) +\"\\n\"); Console.Write((countSubsequence(n)) +\"\\n\");}} // This code is contributed by Rajput-Ji", "e": 3089, "s": 2515, "text": null }, { "code": "<script> // JavaScript implementation to count// the subarray and subsequence of// given length of the array // Function to count the subarray// for the given arrayfunction countSubarray(n){ return ((n)*(n + 1))/2;} // Function to count the subsequence// for the given array lengthfunction countSubsequence(n){ return Math.pow(2, n);} // Driver Code let n = 5; document.write((countSubarray(n)) +\"<br/>\"); document.write((countSubsequence(n)) +\"\\n\"); </script>", "e": 3569, "s": 3089, "text": null }, { "code": null, "e": 3575, "s": 3569, "text": "15\n32" }, { "code": null, "e": 3603, "s": 3577, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 3625, "s": 3603, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3640, "s": 3625, "text": "mohit kumar 29" }, { "code": null, "e": 3653, "s": 3640, "text": "princi singh" }, { "code": null, "e": 3663, "s": 3653, "text": "Rajput-Ji" }, { "code": null, "e": 3685, "s": 3663, "text": "susmitakundugoaldanga" }, { "code": null, "e": 3695, "s": 3685, "text": "subham348" }, { "code": null, "e": 3704, "s": 3695, "text": "subarray" }, { "code": null, "e": 3716, "s": 3704, "text": "subsequence" }, { "code": null, "e": 3723, "s": 3716, "text": "Arrays" }, { "code": null, "e": 3747, "s": 3723, "text": "Competitive Programming" }, { "code": null, "e": 3760, "s": 3747, "text": "Mathematical" }, { "code": null, "e": 3767, "s": 3760, "text": "Arrays" }, { "code": null, "e": 3780, "s": 3767, "text": "Mathematical" }, { "code": null, "e": 3878, "s": 3780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3946, "s": 3878, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 3990, "s": 3946, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 4022, "s": 3990, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4070, "s": 4022, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 4084, "s": 4070, "text": "Linear Search" }, { "code": null, "e": 4127, "s": 4084, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 4170, "s": 4127, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 4211, "s": 4170, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 4238, "s": 4211, "text": "Modulo 10^9+7 (1000000007)" } ]
type and isinstance in Python
05 Jul, 2022 In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance(). Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the program in the runtime. The canonical way to check for type in Python is given below: type(object) type(name, bases, dict) In this example, we are trying to check the data type of each variable, such as x, s, and y using type() function. Python3 # Python code type() with a single object parameterx = 5s = "geeksforgeeks"y = [1, 2, 3]print(type(x))print(type(s))print(type(y)) Output: class 'int' class 'str' class 'list' If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It’s because isinstance() function also checks if the given object is an instance of the subclass. Python3 # Python code for type() with a name,# bases and dict parameter o1 = type('X', (object,), dict(a='Foo', b=12)) print(type(o1))print(vars(o1)) class test: a = 'Foo' b = 12 o2 = type('Y', (test,), dict(a='Foo', b=12))print(type(o2))print(vars(o2)) Output: {'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': } {'b': 12, 'a': 'Foo', '__doc__': None} The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument). Syntax: isinstance(object, classinfo) Parameter: object : object to be checked classinfo : class, type, or tuple of classes and types Return: true if the object is an instance or subclass of a class, or any element of the tuple false otherwise. If class info is not a type or tuple of types, a TypeError exception is raised. Example 1: In this example, we will see test isinstance() for the class object. Python3 # Python code for isinstance()class Test: a = 5 TestInstance = Test() print(isinstance(TestInstance, Test))print(isinstance(TestInstance, (list, tuple)))print(isinstance(TestInstance, (list, tuple, Test))) Output: True False True Example 2: In this example, we will see test isinstance() for the integer, float, and string object. Python3 weight = isinstance(17.9, float)print("is a float:", weight) num = isinstance(71, int)print("is an integer:", num) string = isinstance("Geeksforgeeks", str)print("is a string:", string) Output: is a float: True is an integer: True is a string: True Example 3: In this example, we will see test isinstance() for the tuple, list, dictionary, and set object. Python3 tuple1 = isinstance(('A', 'B', 'C'),tuple)print("is a tuple:", tuple1) set1 = isinstance({'A', 'B', 'C'},set)print("is a set:", set1) list1 = isinstance(['A', 'B', 'C'],list)print("is a list:", list1) dict1 = isinstance({"A":"1", "B":"2", "C":"3"},dict)print("is a dict:", dict1) Output: is a tuple: True is a set: True is a list: True is a dict: True One elementary error people make is using the type() function where isinstance() would be more appropriate. If you’re checking to see if an object has a certain type, you want isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Thus, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance. type(), on the other hand, simply returns the type object of an object, and comparing what it returns to another type object will only yield True when you use the exact same type object on both sides. In Python, it’s preferable to use Duck Typing( type checking is deferred to run-time, and is implemented by means of dynamic typing or reflection) rather than inspecting the type of an object. Python3 # Python code to illustrate duck typing class User(object): def __init__(self, firstname): self.firstname = firstname @property def name(self): return self.firstname class Animal(object): pass class Fox(Animal): name = "Fox" class Bear(Animal): name = "Bear" # Use the .name attribute (or property) regardless of the typefor a in [User("Geeksforgeeks"), Fox(), Bear()]: print(a.name) Output: Geeksforgeeks Fox Bear The next reason not to use type() is the lack of support for inheritance. Python3 # python code to illustrate the lack of# support for inheritance in type() class MyDict(dict): """A normal dict, that is always created with an "initial" key""" def __init__(self): self["initial"] = "some data" d = MyDict()print(type(d) == dict)print(type(d) == MyDict) d = dict()print(type(d) == dict)print(type(d) == MyDict) Output: False True True False The MyDict class has all the properties of a dict, without any new methods. It will behave exactly like a dictionary. But type() will not return the expected result. Using isinstance() is preferable in this case because it will give the expected result: Python3 # python code to show isintance() support# inheritanceclass MyDict(dict): """A normal dict, that is always created with an "initial" key""" def __init__(self): self["initial"] = "some data" d = MyDict()print(isinstance(d, MyDict))print(isinstance(d, dict)) d = dict()print(isinstance(d, MyDict))print(isinstance(d, dict)) Output: True True False True surajkumarguptaintern Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 197, "s": 54, "text": "In this article, we will cover about type() and isinstance() function in Python, and what are the differences between type() and isinstance()." }, { "code": null, "e": 411, "s": 197, "text": "Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the program in the runtime. The canonical way to check for type in Python is given below:" }, { "code": null, "e": 448, "s": 411, "text": "type(object)\ntype(name, bases, dict)" }, { "code": null, "e": 563, "s": 448, "text": "In this example, we are trying to check the data type of each variable, such as x, s, and y using type() function." }, { "code": null, "e": 571, "s": 563, "text": "Python3" }, { "code": "# Python code type() with a single object parameterx = 5s = \"geeksforgeeks\"y = [1, 2, 3]print(type(x))print(type(s))print(type(y))", "e": 702, "s": 571, "text": null }, { "code": null, "e": 710, "s": 702, "text": "Output:" }, { "code": null, "e": 747, "s": 710, "text": "class 'int'\nclass 'str'\nclass 'list'" }, { "code": null, "e": 957, "s": 747, "text": "If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It’s because isinstance() function also checks if the given object is an instance of the subclass." }, { "code": null, "e": 965, "s": 957, "text": "Python3" }, { "code": "# Python code for type() with a name,# bases and dict parameter o1 = type('X', (object,), dict(a='Foo', b=12)) print(type(o1))print(vars(o1)) class test: a = 'Foo' b = 12 o2 = type('Y', (test,), dict(a='Foo', b=12))print(type(o2))print(vars(o2))", "e": 1216, "s": 965, "text": null }, { "code": null, "e": 1224, "s": 1216, "text": "Output:" }, { "code": null, "e": 1333, "s": 1224, "text": "{'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': }\n{'b': 12, 'a': 'Foo', '__doc__': None}" }, { "code": null, "e": 1467, "s": 1333, "text": "The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument)." }, { "code": null, "e": 1506, "s": 1467, "text": "Syntax: isinstance(object, classinfo) " }, { "code": null, "e": 1517, "s": 1506, "text": "Parameter:" }, { "code": null, "e": 1547, "s": 1517, "text": "object : object to be checked" }, { "code": null, "e": 1602, "s": 1547, "text": "classinfo : class, type, or tuple of classes and types" }, { "code": null, "e": 1714, "s": 1602, "text": "Return: true if the object is an instance or subclass of a class, or any element of the tuple false otherwise. " }, { "code": null, "e": 1794, "s": 1714, "text": "If class info is not a type or tuple of types, a TypeError exception is raised." }, { "code": null, "e": 1806, "s": 1794, "text": "Example 1: " }, { "code": null, "e": 1875, "s": 1806, "text": "In this example, we will see test isinstance() for the class object." }, { "code": null, "e": 1883, "s": 1875, "text": "Python3" }, { "code": "# Python code for isinstance()class Test: a = 5 TestInstance = Test() print(isinstance(TestInstance, Test))print(isinstance(TestInstance, (list, tuple)))print(isinstance(TestInstance, (list, tuple, Test)))", "e": 2094, "s": 1883, "text": null }, { "code": null, "e": 2102, "s": 2094, "text": "Output:" }, { "code": null, "e": 2118, "s": 2102, "text": "True\nFalse\nTrue" }, { "code": null, "e": 2129, "s": 2118, "text": "Example 2:" }, { "code": null, "e": 2219, "s": 2129, "text": "In this example, we will see test isinstance() for the integer, float, and string object." }, { "code": null, "e": 2227, "s": 2219, "text": "Python3" }, { "code": "weight = isinstance(17.9, float)print(\"is a float:\", weight) num = isinstance(71, int)print(\"is an integer:\", num) string = isinstance(\"Geeksforgeeks\", str)print(\"is a string:\", string)", "e": 2414, "s": 2227, "text": null }, { "code": null, "e": 2422, "s": 2414, "text": "Output:" }, { "code": null, "e": 2477, "s": 2422, "text": "is a float: True\nis an integer: True\nis a string: True" }, { "code": null, "e": 2488, "s": 2477, "text": "Example 3:" }, { "code": null, "e": 2584, "s": 2488, "text": "In this example, we will see test isinstance() for the tuple, list, dictionary, and set object." }, { "code": null, "e": 2592, "s": 2584, "text": "Python3" }, { "code": "tuple1 = isinstance(('A', 'B', 'C'),tuple)print(\"is a tuple:\", tuple1) set1 = isinstance({'A', 'B', 'C'},set)print(\"is a set:\", set1) list1 = isinstance(['A', 'B', 'C'],list)print(\"is a list:\", list1) dict1 = isinstance({\"A\":\"1\", \"B\":\"2\", \"C\":\"3\"},dict)print(\"is a dict:\", dict1)", "e": 2872, "s": 2592, "text": null }, { "code": null, "e": 2880, "s": 2872, "text": "Output:" }, { "code": null, "e": 2944, "s": 2880, "text": "is a tuple: True\nis a set: True\nis a list: True\nis a dict: True" }, { "code": null, "e": 3052, "s": 2944, "text": "One elementary error people make is using the type() function where isinstance() would be more appropriate." }, { "code": null, "e": 3387, "s": 3052, "text": "If you’re checking to see if an object has a certain type, you want isinstance() as it checks to see if the object passed in the first argument is of the type of any of the type objects passed in the second argument. Thus, it works as expected with subclassing and old-style classes, all of which have the legacy type object instance." }, { "code": null, "e": 3782, "s": 3387, "text": "type(), on the other hand, simply returns the type object of an object, and comparing what it returns to another type object will only yield True when you use the exact same type object on both sides. In Python, it’s preferable to use Duck Typing( type checking is deferred to run-time, and is implemented by means of dynamic typing or reflection) rather than inspecting the type of an object. " }, { "code": null, "e": 3790, "s": 3782, "text": "Python3" }, { "code": "# Python code to illustrate duck typing class User(object): def __init__(self, firstname): self.firstname = firstname @property def name(self): return self.firstname class Animal(object): pass class Fox(Animal): name = \"Fox\" class Bear(Animal): name = \"Bear\" # Use the .name attribute (or property) regardless of the typefor a in [User(\"Geeksforgeeks\"), Fox(), Bear()]: print(a.name)", "e": 4215, "s": 3790, "text": null }, { "code": null, "e": 4223, "s": 4215, "text": "Output:" }, { "code": null, "e": 4246, "s": 4223, "text": "Geeksforgeeks\nFox\nBear" }, { "code": null, "e": 4320, "s": 4246, "text": "The next reason not to use type() is the lack of support for inheritance." }, { "code": null, "e": 4328, "s": 4320, "text": "Python3" }, { "code": "# python code to illustrate the lack of# support for inheritance in type() class MyDict(dict): \"\"\"A normal dict, that is always created with an \"initial\" key\"\"\" def __init__(self): self[\"initial\"] = \"some data\" d = MyDict()print(type(d) == dict)print(type(d) == MyDict) d = dict()print(type(d) == dict)print(type(d) == MyDict)", "e": 4671, "s": 4328, "text": null }, { "code": null, "e": 4679, "s": 4671, "text": "Output:" }, { "code": null, "e": 4701, "s": 4679, "text": "False\nTrue\nTrue\nFalse" }, { "code": null, "e": 4956, "s": 4701, "text": "The MyDict class has all the properties of a dict, without any new methods. It will behave exactly like a dictionary. But type() will not return the expected result. Using isinstance() is preferable in this case because it will give the expected result: " }, { "code": null, "e": 4964, "s": 4956, "text": "Python3" }, { "code": "# python code to show isintance() support# inheritanceclass MyDict(dict): \"\"\"A normal dict, that is always created with an \"initial\" key\"\"\" def __init__(self): self[\"initial\"] = \"some data\" d = MyDict()print(isinstance(d, MyDict))print(isinstance(d, dict)) d = dict()print(isinstance(d, MyDict))print(isinstance(d, dict))", "e": 5301, "s": 4964, "text": null }, { "code": null, "e": 5309, "s": 5301, "text": "Output:" }, { "code": null, "e": 5330, "s": 5309, "text": "True\nTrue\nFalse\nTrue" }, { "code": null, "e": 5352, "s": 5330, "text": "surajkumarguptaintern" }, { "code": null, "e": 5378, "s": 5352, "text": "Python-Built-in-functions" }, { "code": null, "e": 5385, "s": 5378, "text": "Python" } ]
JavaScript Anonymous Functions
23 Jun, 2022 In this article we will study in detail about what exactly are Anonymous Functions in JavaScript and how to declare them using normal technique and/or with Arrow Function technique itself. Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name. An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression. Syntax: The below enlightened syntax illustrates the declaration of anonymous function using normal declaration: function() { // Function Body } We may also declare anonymous function using arrow function technique which is shown below: ( () => { // Function Body... } )(); The below examples demonstrate anonymous functions. Example 1: In this example, we define an anonymous function that prints a message to the console. The function is then stored in the greet variable. We can call the function by invoking greet(). Javascript <script>var greet = function () { console.log("Welcome to GeeksforGeeks!");}; greet();</script> Output: Welcome to GeeksforGeeks! Example 2: In this example, we pass arguments to the anonymous function. Javascript <script>var greet = function (platform) { console.log("Welcome to ", platform);}; greet("GeeksforGeeks!");</script> Output: Welcome to GeeksforGeeks! As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout() method. This executes this anonymous function 2000ms later. Javascript <script>setTimeout(function () { console.log("Welcome to GeeksforGeeks!");}, 2000);</script> Output: Welcome to GeeksforGeeks! Another use case of anonymous functions is to invoke the function immediately after initialization, this is also known as Self Executing Function. This can be done by adding parenthesis we can immediately execute the anonymous function. Example 4: In this example, we have created a self-executing function. Javascript <script>(function () { console.log("Welcome to GeeksforGeeks!");})();</script> Output: Welcome to GeeksforGeeks! Arrow functions ES6 introduced a new and shorter way of declaring an anonymous function, which is known as Arrow Functions. In an Arrow function, everything remains the same, except here we don’t need the function keyword also. Here, we define the function by a single parenthesis and then ‘=>’ followed by the function body. Example 5: Javascript <script>var greet = () =>{ console.log("Welcome to GeeksforGeeks!");} greet();</script> Output: Welcome to GeeksforGeeks! If we have only a single statement in the function body, we can even remove the curly braces. Example 6: In this example, we create a self-executing function. Javascript <script> let greet = () => console.log("Welcome to GeeksforGeeks!"); greet();</script> Output: Welcome to Geeksforgeeks! Example-7: In this example we will declare self executing anonymous function (without name itself) and will see how we may declare it as well as how we may call it in order to print the resultant value. Javascript // JavaScript code.. (() => { console.log("GeeksforGeeks");})(); // This code is contributed by Aman Singla... Output: GeeksforGeeks amansingla javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 242, "s": 53, "text": "In this article we will study in detail about what exactly are Anonymous Functions in JavaScript and how to declare them using normal technique and/or with Arrow Function technique itself." }, { "code": null, "e": 528, "s": 242, "text": "Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name." }, { "code": null, "e": 757, "s": 528, "text": "An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression." }, { "code": null, "e": 766, "s": 757, "text": "Syntax: " }, { "code": null, "e": 871, "s": 766, "text": "The below enlightened syntax illustrates the declaration of anonymous function using normal declaration:" }, { "code": null, "e": 908, "s": 871, "text": "function() {\n // Function Body\n }" }, { "code": null, "e": 1000, "s": 908, "text": "We may also declare anonymous function using arrow function technique which is shown below:" }, { "code": null, "e": 1041, "s": 1000, "text": "( () => {\n // Function Body...\n} )();" }, { "code": null, "e": 1093, "s": 1041, "text": "The below examples demonstrate anonymous functions." }, { "code": null, "e": 1288, "s": 1093, "text": "Example 1: In this example, we define an anonymous function that prints a message to the console. The function is then stored in the greet variable. We can call the function by invoking greet()." }, { "code": null, "e": 1299, "s": 1288, "text": "Javascript" }, { "code": "<script>var greet = function () { console.log(\"Welcome to GeeksforGeeks!\");}; greet();</script>", "e": 1398, "s": 1299, "text": null }, { "code": null, "e": 1406, "s": 1398, "text": "Output:" }, { "code": null, "e": 1432, "s": 1406, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 1505, "s": 1432, "text": "Example 2: In this example, we pass arguments to the anonymous function." }, { "code": null, "e": 1516, "s": 1505, "text": "Javascript" }, { "code": "<script>var greet = function (platform) { console.log(\"Welcome to \", platform);}; greet(\"GeeksforGeeks!\");</script>", "e": 1635, "s": 1516, "text": null }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1669, "s": 1643, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 1790, "s": 1669, "text": "As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function." }, { "code": null, "e": 1951, "s": 1790, "text": "Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout() method. This executes this anonymous function 2000ms later." }, { "code": null, "e": 1962, "s": 1951, "text": "Javascript" }, { "code": "<script>setTimeout(function () { console.log(\"Welcome to GeeksforGeeks!\");}, 2000);</script>", "e": 2058, "s": 1962, "text": null }, { "code": null, "e": 2066, "s": 2058, "text": "Output:" }, { "code": null, "e": 2092, "s": 2066, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 2329, "s": 2092, "text": "Another use case of anonymous functions is to invoke the function immediately after initialization, this is also known as Self Executing Function. This can be done by adding parenthesis we can immediately execute the anonymous function." }, { "code": null, "e": 2400, "s": 2329, "text": "Example 4: In this example, we have created a self-executing function." }, { "code": null, "e": 2411, "s": 2400, "text": "Javascript" }, { "code": "<script>(function () { console.log(\"Welcome to GeeksforGeeks!\");})();</script>", "e": 2493, "s": 2411, "text": null }, { "code": null, "e": 2501, "s": 2493, "text": "Output:" }, { "code": null, "e": 2527, "s": 2501, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 2543, "s": 2527, "text": "Arrow functions" }, { "code": null, "e": 2853, "s": 2543, "text": "ES6 introduced a new and shorter way of declaring an anonymous function, which is known as Arrow Functions. In an Arrow function, everything remains the same, except here we don’t need the function keyword also. Here, we define the function by a single parenthesis and then ‘=>’ followed by the function body." }, { "code": null, "e": 2864, "s": 2853, "text": "Example 5:" }, { "code": null, "e": 2875, "s": 2864, "text": "Javascript" }, { "code": "<script>var greet = () =>{ console.log(\"Welcome to GeeksforGeeks!\");} greet();</script>", "e": 2966, "s": 2875, "text": null }, { "code": null, "e": 2974, "s": 2966, "text": "Output:" }, { "code": null, "e": 3000, "s": 2974, "text": "Welcome to GeeksforGeeks!" }, { "code": null, "e": 3094, "s": 3000, "text": "If we have only a single statement in the function body, we can even remove the curly braces." }, { "code": null, "e": 3159, "s": 3094, "text": "Example 6: In this example, we create a self-executing function." }, { "code": null, "e": 3170, "s": 3159, "text": "Javascript" }, { "code": "<script> let greet = () => console.log(\"Welcome to GeeksforGeeks!\"); greet();</script>", "e": 3259, "s": 3170, "text": null }, { "code": null, "e": 3267, "s": 3259, "text": "Output:" }, { "code": null, "e": 3294, "s": 3267, "text": "Welcome to Geeksforgeeks! " }, { "code": null, "e": 3497, "s": 3294, "text": "Example-7: In this example we will declare self executing anonymous function (without name itself) and will see how we may declare it as well as how we may call it in order to print the resultant value." }, { "code": null, "e": 3508, "s": 3497, "text": "Javascript" }, { "code": "// JavaScript code.. (() => { console.log(\"GeeksforGeeks\");})(); // This code is contributed by Aman Singla...", "e": 3620, "s": 3508, "text": null }, { "code": null, "e": 3628, "s": 3620, "text": "Output:" }, { "code": null, "e": 3642, "s": 3628, "text": "GeeksforGeeks" }, { "code": null, "e": 3653, "s": 3642, "text": "amansingla" }, { "code": null, "e": 3674, "s": 3653, "text": "javascript-functions" }, { "code": null, "e": 3685, "s": 3674, "text": "JavaScript" }, { "code": null, "e": 3702, "s": 3685, "text": "Web Technologies" }, { "code": null, "e": 3800, "s": 3702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3861, "s": 3800, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3933, "s": 3861, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3973, "s": 3933, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4014, "s": 3973, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4066, "s": 4014, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 4099, "s": 4066, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4161, "s": 4099, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4222, "s": 4161, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4272, "s": 4222, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Create AlertDialog Box Using SweetAlert Dialog Library?
27 May, 2021 In this article, we will learn about how to add Custom Alert Dialog in an app using SweetAlert Dialog Library. It is a pop-up box which appears in response to any action of the user.AlertBox is very useful when it comes to validation, it can be used to display confirmation messages. Suppose if the user presses the Back Button without saving the changes then for warning it can be used. When the transaction is done in payment apps a short Dialog Box can be shown to the user describing the status of the transaction. Advantages: It provides us a very good user interface which makes the user experience very good. It makes the work very much easier so it is used over Custom Dialog which needs whole layout to be created. It provides many different types of layouts for the dialog box. Approach:Step 1: Add the support Library in build.gradle file and add dependency in the dependencies section. This library has inbuilt alert dialog which can be directly used. XML dependencies { implementation 'com.github.f0ris.sweetalert:library:1.5.1' } Step 2: Now add the following code in activity_main.xml file. This code adds five buttons in the activity. Each button is used to call different style of Alert Dialog Box. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:onClick="showDialog" android:id="@+id/basic_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Basic Dialog" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.452" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.124" /> <Button android:onClick="showDialog" android:id="@+id/error_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Error Dialog" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.452" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.284" /> <Button android:onClick="showDialog" android:id="@+id/warning_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Warning Dialog" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.452" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.45" /> <Button android:onClick="showDialog" android:id="@+id/success_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="256dp" android:text="Success Dialog" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.47" app:layout_constraintStart_toStartOf="parent" /> <Button android:onClick="showDialog" android:id="@+id/custom_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="156dp" android:text="Custom Dialog" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.464" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Add the following code in MainActivity.java file. Now on clicking any button the showDialog() function is started and corresponding Alert Dialog Box is displayed. onClickListner can also be added to the button instead of showDialog function. package org.geeksforgeeks.gfgbottomnav; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import cn.pedant.SweetAlert.SweetAlertDialog; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showDialog(View view){ switch (view.getId()){ case R.id.basic_dialog: new SweetAlertDialog(this) .setTitleText("Here's a message!") .setContentText("This is Basic Dialog") .show(); break; case R.id.error_dialog: new SweetAlertDialog( this, SweetAlertDialog.ERROR_TYPE) .setTitleText("Oops...") .setContentText("Something went wrong!") .show(); break; case R.id.warning_dialog: new SweetAlertDialog( this, SweetAlertDialog.WARNING_TYPE) .setTitleText("Are you sure?") .setContentText("Won't be able to recover this file!") .setConfirmText("Yes, delete it!") .show(); break; case R.id.success_dialog: new SweetAlertDialog( this, SweetAlertDialog.SUCCESS_TYPE) .setTitleText("Great!") .setContentText("You completed this task.") .show(); break; case R.id.custom_dialog: new SweetAlertDialog( this, SweetAlertDialog.CUSTOM_IMAGE_TYPE) .setTitleText("Android") .setContentText("Thi is custom dialog") .setCustomImage(R.drawable.ic_android_black) .show(); break; } } } Output: Reference Link: https://github.com/F0RIS/sweet-alert-dialog varshagumber28 android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components How to Create and Add Data to SQLite Database in Android? Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n27 May, 2021" }, { "code": null, "e": 586, "s": 54, "text": "In this article, we will learn about how to add Custom Alert Dialog in an app using SweetAlert Dialog Library. It is a pop-up box which appears in response to any action of the user.AlertBox is very useful when it comes to validation, it can be used to display confirmation messages. Suppose if the user presses the Back Button without saving the changes then for warning it can be used. When the transaction is done in payment apps a short Dialog Box can be shown to the user describing the status of the transaction. Advantages: " }, { "code": null, "e": 671, "s": 586, "text": "It provides us a very good user interface which makes the user experience very good." }, { "code": null, "e": 779, "s": 671, "text": "It makes the work very much easier so it is used over Custom Dialog which needs whole layout to be created." }, { "code": null, "e": 843, "s": 779, "text": "It provides many different types of layouts for the dialog box." }, { "code": null, "e": 1020, "s": 843, "text": "Approach:Step 1: Add the support Library in build.gradle file and add dependency in the dependencies section. This library has inbuilt alert dialog which can be directly used. " }, { "code": null, "e": 1024, "s": 1020, "text": "XML" }, { "code": "dependencies { implementation 'com.github.f0ris.sweetalert:library:1.5.1' }", "e": 1122, "s": 1024, "text": null }, { "code": null, "e": 1295, "s": 1122, "text": "Step 2: Now add the following code in activity_main.xml file. This code adds five buttons in the activity. Each button is used to call different style of Alert Dialog Box. " }, { "code": null, "e": 4275, "s": 1295, "text": "\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.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 tools:context=\".MainActivity\">\n\n <Button\n android:onClick=\"showDialog\"\n android:id=\"@+id/basic_dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Basic Dialog\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.452\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintVertical_bias=\"0.124\" />\n\n <Button\n android:onClick=\"showDialog\"\n android:id=\"@+id/error_dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Error Dialog\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.452\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintVertical_bias=\"0.284\" />\n\n <Button\n android:onClick=\"showDialog\"\n android:id=\"@+id/warning_dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Warning Dialog\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.452\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintVertical_bias=\"0.45\" />\n\n <Button\n android:onClick=\"showDialog\"\n android:id=\"@+id/success_dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginBottom=\"256dp\"\n android:text=\"Success Dialog\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.47\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n <Button\n android:onClick=\"showDialog\"\n android:id=\"@+id/custom_dialog\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginBottom=\"156dp\"\n android:text=\"Custom Dialog\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintHorizontal_bias=\"0.464\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>\n" }, { "code": null, "e": 4526, "s": 4275, "text": "Step 3: Add the following code in MainActivity.java file. Now on clicking any button the showDialog() function is started and corresponding Alert Dialog Box is displayed. onClickListner can also be added to the button instead of showDialog function. " }, { "code": null, "e": 6696, "s": 4526, "text": "\npackage org.geeksforgeeks.gfgbottomnav;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport cn.pedant.SweetAlert.SweetAlertDialog;\n\n\npublic class MainActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n\n public void showDialog(View view){\n switch (view.getId()){\n case R.id.basic_dialog:\n new SweetAlertDialog(this)\n .setTitleText(\"Here's a message!\")\n .setContentText(\"This is Basic Dialog\")\n .show();\n break;\n case R.id.error_dialog:\n new SweetAlertDialog(\n this, SweetAlertDialog.ERROR_TYPE)\n .setTitleText(\"Oops...\")\n .setContentText(\"Something went wrong!\")\n .show();\n break;\n case R.id.warning_dialog:\n new SweetAlertDialog(\n this, SweetAlertDialog.WARNING_TYPE)\n .setTitleText(\"Are you sure?\")\n .setContentText(\"Won't be able\n to recover this file!\")\n .setConfirmText(\"Yes, delete it!\")\n .show();\n break;\n case R.id.success_dialog:\n new SweetAlertDialog(\n this, SweetAlertDialog.SUCCESS_TYPE)\n .setTitleText(\"Great!\")\n .setContentText(\"You completed this task.\")\n .show();\n break;\n case R.id.custom_dialog:\n new SweetAlertDialog(\n this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)\n .setTitleText(\"Android\")\n .setContentText(\"Thi is custom dialog\")\n .setCustomImage(R.drawable.ic_android_black)\n .show();\n break;\n }\n }\n}\n" }, { "code": null, "e": 6705, "s": 6696, "text": "Output: " }, { "code": null, "e": 6766, "s": 6705, "text": "Reference Link: https://github.com/F0RIS/sweet-alert-dialog " }, { "code": null, "e": 6781, "s": 6766, "text": "varshagumber28" }, { "code": null, "e": 6789, "s": 6781, "text": "android" }, { "code": null, "e": 6797, "s": 6789, "text": "Android" }, { "code": null, "e": 6802, "s": 6797, "text": "Java" }, { "code": null, "e": 6807, "s": 6802, "text": "Java" }, { "code": null, "e": 6815, "s": 6807, "text": "Android" }, { "code": null, "e": 6913, "s": 6815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6982, "s": 6913, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7013, "s": 6982, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 7056, "s": 7013, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 7088, "s": 7056, "text": "Android SDK and it's Components" }, { "code": null, "e": 7146, "s": 7088, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 7161, "s": 7146, "text": "Arrays in Java" }, { "code": null, "e": 7197, "s": 7161, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7241, "s": 7197, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7266, "s": 7241, "text": "Reverse a string in Java" } ]
How to use split () in Android textview?
This example demonstrate about How to use split () in Android textview. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken name as Edit text, when user click on button it will take data and split the data using space regex. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText name; Button button; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.name); button = findViewById(R.id.click); text = findViewById(R.id.textview); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { if (name.getText().toString().length() >= 0) { String[] replace = name.getText().toString().split("\\s"); text.setText(String.valueOf(replace[1])); } } else { name.setError("Plz enter name"); } } }); } } 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 − In the above result, enter the string as “Krishna sai sai” . It splited with space and returned 1st indexed value. Click here to download the project code
[ { "code": null, "e": 1259, "s": 1187, "text": "This example demonstrate about How to use split () in Android textview." }, { "code": null, "e": 1388, "s": 1259, "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": 1453, "s": 1388, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2343, "s": 1453, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2477, "s": 2343, "text": "In the above code, we have taken name as Edit text, when user click on button it will take data and split the data using space regex." }, { "code": null, "e": 2534, "s": 2477, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3655, "s": 2534, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n String[] replace = name.getText().toString().split(\"\\\\s\");\n text.setText(String.valueOf(replace[1]));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 4002, "s": 3655, "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": 4117, "s": 4002, "text": "In the above result, enter the string as “Krishna sai sai” . It splited with space and returned 1st indexed value." }, { "code": null, "e": 4157, "s": 4117, "text": "Click here to download the project code" } ]
SQL Query to Find Names of the Employees Whose Department Have Number of Employees Less than 2
29 Dec, 2021 In SQL, we need to find out the department wise information from the given table containing information about employees. One such data is the name of employee who belong to a department having less than 2(i.e. only 1) employees. We shall use the GROUP BY, IN and COUNT clause to achieve this. This is illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table COMPANY inside the database GeeksForGeeks. This table has 4 columns namely EMPLOYEE_ID, EMPLOYEE_NAME, DEPARTMENT_NAME and SALARY containing the id, name, department and the salary of various employees. Query: CREATE TABLE COMPANY( EMPLOYEE_ID INT PRIMARY KEY, EMPLOYEE_NAME VARCHAR(10), DEPARTMENT_NAME VARCHAR(10), SALARY INT); Output: Step 4: Describe the structure of the table COMPANY. Query: EXEC SP_COLUMNS COMPANY; Output: Step 5: Insert 5 rows into the COMPANY table. Query: INSERT INTO COMPANY VALUES(1,'RAM','HR',10000); INSERT INTO COMPANY VALUES(2,'AMRIT','MRKT',20000); INSERT INTO COMPANY VALUES(3,'RAVI','HR',30000); INSERT INTO COMPANY VALUES(4,'NITIN','MRKT',40000); INSERT INTO COMPANY VALUES(5,'VARUN','IT',50000); Output: Step 6: Display all the rows of the COMPANY table. Query: SELECT * FROM COMPANY; Output: Step 7: Display the name of the employee and of his/her department belonging to a department having less than 2 i.e. 1 employee. We will use the IN clause here to compare the department names obtained from the outer query to department names obtained from the inner query. The inner query uses the GROUP BY clause and COUNT clause to count the number of employees belonging to each department. Then compare this returned count to ensure that the count is less than 2. Syntax: SELECT EMPLOYEE_NAME, DEPARTMENT_NAME FROM COMPANY WHERE DEPARTMENT_NAME IN (SELECT DEPARTMENT_NAME FROM COMPANY GROUP BY DEPARTMENT_NAME HAVING COUNT(*)<2); Query: SELECT EMPLOYEE_NAME, DEPARTMENT_NAME FROM COMPANY WHERE DEPARTMENT_NAME IN (SELECT DEPARTMENT_NAME FROM COMPANY GROUP BY DEPARTMENT_NAME HAVING COUNT(*)<2); Note – This query returns only 1 row i.e. VARUN and IT since IT has only 1 employee. Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Window functions in SQL MySQL | Group_CONCAT() Function SQL | GROUP BY
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 425, "s": 28, "text": "In SQL, we need to find out the department wise information from the given table containing information about employees. One such data is the name of employee who belong to a department having less than 2(i.e. only 1) employees. We shall use the GROUP BY, IN and COUNT clause to achieve this. This is illustrated below. For this article, we will be using the Microsoft SQL Server as our database." }, { "code": null, "e": 525, "s": 425, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 532, "s": 525, "text": "Query:" }, { "code": null, "e": 562, "s": 532, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 570, "s": 562, "text": "Output:" }, { "code": null, "e": 642, "s": 570, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 649, "s": 642, "text": "Query:" }, { "code": null, "e": 667, "s": 649, "text": "USE GeeksForGeeks" }, { "code": null, "e": 675, "s": 667, "text": "Output:" }, { "code": null, "e": 901, "s": 675, "text": "Step 3: Create a table COMPANY inside the database GeeksForGeeks. This table has 4 columns namely EMPLOYEE_ID, EMPLOYEE_NAME, DEPARTMENT_NAME and SALARY containing the id, name, department and the salary of various employees." }, { "code": null, "e": 908, "s": 901, "text": "Query:" }, { "code": null, "e": 1028, "s": 908, "text": "CREATE TABLE COMPANY(\nEMPLOYEE_ID INT PRIMARY KEY,\nEMPLOYEE_NAME VARCHAR(10),\nDEPARTMENT_NAME VARCHAR(10),\nSALARY INT);" }, { "code": null, "e": 1036, "s": 1028, "text": "Output:" }, { "code": null, "e": 1089, "s": 1036, "text": "Step 4: Describe the structure of the table COMPANY." }, { "code": null, "e": 1096, "s": 1089, "text": "Query:" }, { "code": null, "e": 1121, "s": 1096, "text": "EXEC SP_COLUMNS COMPANY;" }, { "code": null, "e": 1129, "s": 1121, "text": "Output:" }, { "code": null, "e": 1175, "s": 1129, "text": "Step 5: Insert 5 rows into the COMPANY table." }, { "code": null, "e": 1182, "s": 1175, "text": "Query:" }, { "code": null, "e": 1433, "s": 1182, "text": "INSERT INTO COMPANY VALUES(1,'RAM','HR',10000);\nINSERT INTO COMPANY VALUES(2,'AMRIT','MRKT',20000);\nINSERT INTO COMPANY VALUES(3,'RAVI','HR',30000);\nINSERT INTO COMPANY VALUES(4,'NITIN','MRKT',40000);\nINSERT INTO COMPANY VALUES(5,'VARUN','IT',50000);" }, { "code": null, "e": 1441, "s": 1433, "text": "Output:" }, { "code": null, "e": 1492, "s": 1441, "text": "Step 6: Display all the rows of the COMPANY table." }, { "code": null, "e": 1499, "s": 1492, "text": "Query:" }, { "code": null, "e": 1522, "s": 1499, "text": "SELECT * FROM COMPANY;" }, { "code": null, "e": 1530, "s": 1522, "text": "Output:" }, { "code": null, "e": 1998, "s": 1530, "text": "Step 7: Display the name of the employee and of his/her department belonging to a department having less than 2 i.e. 1 employee. We will use the IN clause here to compare the department names obtained from the outer query to department names obtained from the inner query. The inner query uses the GROUP BY clause and COUNT clause to count the number of employees belonging to each department. Then compare this returned count to ensure that the count is less than 2." }, { "code": null, "e": 2006, "s": 1998, "text": "Syntax:" }, { "code": null, "e": 2165, "s": 2006, "text": "SELECT EMPLOYEE_NAME, DEPARTMENT_NAME \nFROM COMPANY WHERE DEPARTMENT_NAME IN\n(SELECT DEPARTMENT_NAME FROM COMPANY\nGROUP BY DEPARTMENT_NAME HAVING COUNT(*)<2);" }, { "code": null, "e": 2172, "s": 2165, "text": "Query:" }, { "code": null, "e": 2330, "s": 2172, "text": "SELECT EMPLOYEE_NAME, DEPARTMENT_NAME\nFROM COMPANY WHERE DEPARTMENT_NAME IN\n(SELECT DEPARTMENT_NAME FROM COMPANY GROUP\nBY DEPARTMENT_NAME HAVING COUNT(*)<2);" }, { "code": null, "e": 2415, "s": 2330, "text": "Note – This query returns only 1 row i.e. VARUN and IT since IT has only 1 employee." }, { "code": null, "e": 2423, "s": 2415, "text": "Output:" }, { "code": null, "e": 2430, "s": 2423, "text": "Picked" }, { "code": null, "e": 2440, "s": 2430, "text": "SQL-Query" }, { "code": null, "e": 2451, "s": 2440, "text": "SQL-Server" }, { "code": null, "e": 2455, "s": 2451, "text": "SQL" }, { "code": null, "e": 2459, "s": 2455, "text": "SQL" }, { "code": null, "e": 2557, "s": 2459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2568, "s": 2557, "text": "CTE in SQL" }, { "code": null, "e": 2599, "s": 2568, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2665, "s": 2599, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2689, "s": 2665, "text": "SQL Interview Questions" }, { "code": null, "e": 2701, "s": 2689, "text": "SQL | Views" }, { "code": null, "e": 2746, "s": 2701, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2779, "s": 2746, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 2803, "s": 2779, "text": "Window functions in SQL" }, { "code": null, "e": 2835, "s": 2803, "text": "MySQL | Group_CONCAT() Function" } ]
How to resize Image in Python – Tkinter?
31 Aug, 2021 Prerequisite: Tkinter PIL Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. In this article, we will learn how to resize an image using python in Tkinter. In Tkinter, there is no in-built method or any package to work with images. Here we will use pillow library for images. Let’s Understand step by step implementation:- Import Required Library Python3 # Import Modulefrom tkinter import *from PIL import Image, ImageTk Read the image using the open() method in pillow library Syntax: Image.open("Enter Image File Path", mode='r', **attr) Python3 # Read the Imageimage = Image.open("Image File Path") Resize an image using resize() method. It returns a resized copy of this image. Syntax: Image.resize((width,height) , resample=3, **attr) Python3 # Resize the image using resize() methodresize_image = image.resize((width, height)) Add Label and add resized image Python3 img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack() Below is the implementation: Python3 # Import Modulefrom tkinter import *from PIL import Image, ImageTk # Create Tkinter Objectroot = Tk() # Read the Imageimage = Image.open("Image File Path") # Resize the image using resize() methodresize_image = image.resize((width, height)) img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack() # Execute Tkinterroot.mainloop() Output:- 250×200 In the above example, enter the file name or path at the Image File Path and enter the value of width and height according to your need. abhishek0719kadiyan singghakshay Picked Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 50, "s": 42, "text": "Tkinter" }, { "code": null, "e": 54, "s": 50, "text": "PIL" }, { "code": null, "e": 404, "s": 54, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task." }, { "code": null, "e": 603, "s": 404, "text": "In this article, we will learn how to resize an image using python in Tkinter. In Tkinter, there is no in-built method or any package to work with images. Here we will use pillow library for images." }, { "code": null, "e": 650, "s": 603, "text": "Let’s Understand step by step implementation:-" }, { "code": null, "e": 674, "s": 650, "text": "Import Required Library" }, { "code": null, "e": 682, "s": 674, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import *from PIL import Image, ImageTk", "e": 749, "s": 682, "text": null }, { "code": null, "e": 806, "s": 749, "text": "Read the image using the open() method in pillow library" }, { "code": null, "e": 815, "s": 806, "text": "Syntax: " }, { "code": null, "e": 869, "s": 815, "text": "Image.open(\"Enter Image File Path\", mode='r', **attr)" }, { "code": null, "e": 877, "s": 869, "text": "Python3" }, { "code": "# Read the Imageimage = Image.open(\"Image File Path\")", "e": 931, "s": 877, "text": null }, { "code": null, "e": 1011, "s": 931, "text": "Resize an image using resize() method. It returns a resized copy of this image." }, { "code": null, "e": 1020, "s": 1011, "text": "Syntax: " }, { "code": null, "e": 1070, "s": 1020, "text": "Image.resize((width,height) , resample=3, **attr)" }, { "code": null, "e": 1078, "s": 1070, "text": "Python3" }, { "code": "# Resize the image using resize() methodresize_image = image.resize((width, height))", "e": 1163, "s": 1078, "text": null }, { "code": null, "e": 1195, "s": 1163, "text": "Add Label and add resized image" }, { "code": null, "e": 1203, "s": 1195, "text": "Python3" }, { "code": "img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack()", "e": 1334, "s": 1203, "text": null }, { "code": null, "e": 1364, "s": 1334, "text": "Below is the implementation: " }, { "code": null, "e": 1372, "s": 1364, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import *from PIL import Image, ImageTk # Create Tkinter Objectroot = Tk() # Read the Imageimage = Image.open(\"Image File Path\") # Resize the image using resize() methodresize_image = image.resize((width, height)) img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack() # Execute Tkinterroot.mainloop()", "e": 1777, "s": 1372, "text": null }, { "code": null, "e": 1787, "s": 1777, "text": "Output:- " }, { "code": null, "e": 1795, "s": 1787, "text": "250×200" }, { "code": null, "e": 1933, "s": 1795, "text": "In the above example, enter the file name or path at the Image File Path and enter the value of width and height according to your need. " }, { "code": null, "e": 1955, "s": 1935, "text": "abhishek0719kadiyan" }, { "code": null, "e": 1968, "s": 1955, "text": "singghakshay" }, { "code": null, "e": 1975, "s": 1968, "text": "Picked" }, { "code": null, "e": 2000, "s": 1975, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2015, "s": 2000, "text": "Python-tkinter" }, { "code": null, "e": 2022, "s": 2015, "text": "Python" } ]
Vectorization in Python
04 Oct, 2019 We know that most of the application has to deal with a large number of datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can take result in a model that takes ages to run. To make sure that the code is computationally efficient, we will use vectorization. Time complexity in the execution of any algorithm is very crucial deciding whether an application is reliable or not. To run a large algorithm in as much as optimal time possible is very important when it comes to real-time application of output. To do so, Python has some standard mathematical functions for fast operations on entire arrays of data without having to write loops. One of such library which contains such function is numpy. Let’s see how can we use this standard function in case of vectorization. What is Vectorization ?Vectorization is used to speed up the Python code without using loop. Using such a function can help in minimizing the running time of code efficiently. Various operations are being performed over vector such as dot product of vectors which is also known as scalar product as it produces single output, outer products which results in square matrix of dimension equal to length X length of the vectors, Element wise multiplication which products the element of same indexes and dimension of the matrix remain unchanged. We will see how the classic methods are more time consuming than using some standard function by calculating their processing time. outer(a, b): Compute the outer product of two vectors.multiply(a, b): Matrix product of two arrays.dot(a, b): Dot product of two arrays.zeros((n, m)): Return a matrix of given shape and type, filled with zeros.process_time(): Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. Dot Product:Dot product is an algebraic operation in which two equal length vectors are being multiplied such that it produces a single number. Dot Product often called as inner product. This product results in a scalar number. Let’s consider two matrix a and b of same length, the dot product is done by taking the transpose of first matrix and then mathematical matrix multiplication of a’(transpose of a) and b is followed as shown in the figure below. Pictorial representation of dot product – Below is the Python code: # Dot productimport timeimport numpyimport array # 8 bytes size inta = array.array('q')for i in range(100000): a.append(i); b = array.array('q')for i in range(100000, 200000): b.append(i) # classic dot product of vectors implementation tic = time.process_time()dot = 0.0; for i in range(len(a)): dot += a[i] * b[i] toc = time.process_time() print("dot_product = "+ str(dot));print("Computation time = " + str(1000*(toc - tic )) + "ms") n_tic = time.process_time()n_dot_product = numpy.dot(a, b)n_toc = time.process_time() print("\nn_dot_product = "+str(n_dot_product))print("Computation time = "+str(1000*(n_toc - n_tic ))+"ms") Output: dot_product = 833323333350000.0 Computation time = 35.59449199999999ms n_dot_product = 833323333350000 Computation time = 0.1559900000000225ms Outer Product:The tensor product of two coordinate vectors is termed as Outer product. Let’s consider two vectors a and b with dimension n x 1 and m x 1 then the outer product of the vector results in a rectangular matrix of n x m. If two vectors have same dimension then the resultant matrix will be a square matrix as shown in the figure. Pictorial representation of outer product – Below is the Python code: # Outer productimport timeimport numpyimport array a = array.array('i')for i in range(200): a.append(i); b = array.array('i')for i in range(200, 400): b.append(i) # classic outer product of vectors implementation tic = time.process_time()outer_product = numpy.zeros((200, 200)) for i in range(len(a)): for j in range(len(b)): outer_product[i][j]= a[i]*b[j] toc = time.process_time() print("outer_product = "+ str(outer_product));print("Computation time = "+str(1000*(toc - tic ))+"ms") n_tic = time.process_time()outer_product = numpy.outer(a, b)n_toc = time.process_time() print("outer_product = "+str(outer_product));print("\nComputation time = "+str(1000*(n_toc - n_tic ))+"ms") Output: outer_product = [[ 0. 0. 0. ..., 0. 0. 0.] [ 200. 201. 202. ..., 397. 398. 399.] [ 400. 402. 404. ..., 794. 796. 798.] ..., [ 39400. 39597. 39794. ..., 78209. 78406. 78603.] [ 39600. 39798. 39996. ..., 78606. 78804. 79002.] [ 39800. 39999. 40198. ..., 79003. 79202. 79401.]] Computation time = 39.821617ms outer_product = [[ 0 0 0 ..., 0 0 0] [ 200 201 202 ..., 397 398 399] [ 400 402 404 ..., 794 796 798] ..., [39400 39597 39794 ..., 78209 78406 78603] [39600 39798 39996 ..., 78606 78804 79002] [39800 39999 40198 ..., 79003 79202 79401]] Computation time = 0.2809480000000031ms Element wise Product:Element-wise multiplication of two matrices is the algebraic operation in which each element of first matrix is multiplied by its corresponding element in the later matrix. Dimension of the matrices should be same.Consider two matrices a and b, index of an element in a is i and j then a(i, j) is multiplied with b(i, j) respectively as shown in the figure below. Pictorial representation of Element wise product – Below is the Python code: # Element-wise multiplicationimport timeimport numpyimport array a = array.array('i')for i in range(50000): a.append(i); b = array.array('i')for i in range(50000, 100000): b.append(i) # classic element wise product of vectors implementation vector = numpy.zeros((50000)) tic = time.process_time() for i in range(len(a)): vector[i]= a[i]*b[i] toc = time.process_time() print("Element wise Product = "+ str(vector));print("\nComputation time = "+str(1000*(toc - tic ))+"ms") n_tic = time.process_time()vector = numpy.multiply(a, b)n_toc = time.process_time() print("Element wise Product = "+str(vector));print("\nComputation time = "+str(1000*(n_toc - n_tic ))+"ms") Output: Element wise Product = [ 0.00000000e+00 5.00010000e+04 1.00004000e+05 ..., 4.99955001e+09 4.99970000e+09 4.99985000e+09] Computation time = 23.516678000000013ms Element wise Product = [ 0 50001 100004 ..., 704582713 704732708 704882705] Computation time = 0.2250640000000248ms nidhi_biet data-science Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Oct, 2019" }, { "code": null, "e": 368, "s": 54, "text": "We know that most of the application has to deal with a large number of datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can take result in a model that takes ages to run. To make sure that the code is computationally efficient, we will use vectorization." }, { "code": null, "e": 882, "s": 368, "text": "Time complexity in the execution of any algorithm is very crucial deciding whether an application is reliable or not. To run a large algorithm in as much as optimal time possible is very important when it comes to real-time application of output. To do so, Python has some standard mathematical functions for fast operations on entire arrays of data without having to write loops. One of such library which contains such function is numpy. Let’s see how can we use this standard function in case of vectorization." }, { "code": null, "e": 1425, "s": 882, "text": "What is Vectorization ?Vectorization is used to speed up the Python code without using loop. Using such a function can help in minimizing the running time of code efficiently. Various operations are being performed over vector such as dot product of vectors which is also known as scalar product as it produces single output, outer products which results in square matrix of dimension equal to length X length of the vectors, Element wise multiplication which products the element of same indexes and dimension of the matrix remain unchanged." }, { "code": null, "e": 1557, "s": 1425, "text": "We will see how the classic methods are more time consuming than using some standard function by calculating their processing time." }, { "code": null, "e": 1938, "s": 1557, "text": "outer(a, b): Compute the outer product of two vectors.multiply(a, b): Matrix product of two arrays.dot(a, b): Dot product of two arrays.zeros((n, m)): Return a matrix of given shape and type, filled with zeros.process_time(): Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep." }, { "code": null, "e": 2394, "s": 1938, "text": "Dot Product:Dot product is an algebraic operation in which two equal length vectors are being multiplied such that it produces a single number. Dot Product often called as inner product. This product results in a scalar number. Let’s consider two matrix a and b of same length, the dot product is done by taking the transpose of first matrix and then mathematical matrix multiplication of a’(transpose of a) and b is followed as shown in the figure below." }, { "code": null, "e": 2436, "s": 2394, "text": "Pictorial representation of dot product –" }, { "code": null, "e": 2462, "s": 2436, "text": "Below is the Python code:" }, { "code": "# Dot productimport timeimport numpyimport array # 8 bytes size inta = array.array('q')for i in range(100000): a.append(i); b = array.array('q')for i in range(100000, 200000): b.append(i) # classic dot product of vectors implementation tic = time.process_time()dot = 0.0; for i in range(len(a)): dot += a[i] * b[i] toc = time.process_time() print(\"dot_product = \"+ str(dot));print(\"Computation time = \" + str(1000*(toc - tic )) + \"ms\") n_tic = time.process_time()n_dot_product = numpy.dot(a, b)n_toc = time.process_time() print(\"\\nn_dot_product = \"+str(n_dot_product))print(\"Computation time = \"+str(1000*(n_toc - n_tic ))+\"ms\")", "e": 3113, "s": 2462, "text": null }, { "code": null, "e": 3121, "s": 3113, "text": "Output:" }, { "code": null, "e": 3266, "s": 3121, "text": "dot_product = 833323333350000.0\nComputation time = 35.59449199999999ms\n\nn_dot_product = 833323333350000\nComputation time = 0.1559900000000225ms\n" }, { "code": null, "e": 3608, "s": 3266, "text": " Outer Product:The tensor product of two coordinate vectors is termed as Outer product. Let’s consider two vectors a and b with dimension n x 1 and m x 1 then the outer product of the vector results in a rectangular matrix of n x m. If two vectors have same dimension then the resultant matrix will be a square matrix as shown in the figure." }, { "code": null, "e": 3652, "s": 3608, "text": "Pictorial representation of outer product –" }, { "code": null, "e": 3678, "s": 3652, "text": "Below is the Python code:" }, { "code": "# Outer productimport timeimport numpyimport array a = array.array('i')for i in range(200): a.append(i); b = array.array('i')for i in range(200, 400): b.append(i) # classic outer product of vectors implementation tic = time.process_time()outer_product = numpy.zeros((200, 200)) for i in range(len(a)): for j in range(len(b)): outer_product[i][j]= a[i]*b[j] toc = time.process_time() print(\"outer_product = \"+ str(outer_product));print(\"Computation time = \"+str(1000*(toc - tic ))+\"ms\") n_tic = time.process_time()outer_product = numpy.outer(a, b)n_toc = time.process_time() print(\"outer_product = \"+str(outer_product));print(\"\\nComputation time = \"+str(1000*(n_toc - n_tic ))+\"ms\") ", "e": 4384, "s": 3678, "text": null }, { "code": null, "e": 4392, "s": 4384, "text": "Output:" }, { "code": null, "e": 5115, "s": 4392, "text": "outer_product = [[ 0. 0. 0. ..., 0. 0. 0.]\n [ 200. 201. 202. ..., 397. 398. 399.]\n [ 400. 402. 404. ..., 794. 796. 798.]\n ..., \n [ 39400. 39597. 39794. ..., 78209. 78406. 78603.]\n [ 39600. 39798. 39996. ..., 78606. 78804. 79002.]\n [ 39800. 39999. 40198. ..., 79003. 79202. 79401.]]\n\nComputation time = 39.821617ms\n\nouter_product = [[ 0 0 0 ..., 0 0 0]\n [ 200 201 202 ..., 397 398 399]\n [ 400 402 404 ..., 794 796 798]\n ..., \n [39400 39597 39794 ..., 78209 78406 78603]\n [39600 39798 39996 ..., 78606 78804 79002]\n [39800 39999 40198 ..., 79003 79202 79401]]\n\nComputation time = 0.2809480000000031ms\n" }, { "code": null, "e": 5501, "s": 5115, "text": " Element wise Product:Element-wise multiplication of two matrices is the algebraic operation in which each element of first matrix is multiplied by its corresponding element in the later matrix. Dimension of the matrices should be same.Consider two matrices a and b, index of an element in a is i and j then a(i, j) is multiplied with b(i, j) respectively as shown in the figure below." }, { "code": null, "e": 5552, "s": 5501, "text": "Pictorial representation of Element wise product –" }, { "code": null, "e": 5578, "s": 5552, "text": "Below is the Python code:" }, { "code": "# Element-wise multiplicationimport timeimport numpyimport array a = array.array('i')for i in range(50000): a.append(i); b = array.array('i')for i in range(50000, 100000): b.append(i) # classic element wise product of vectors implementation vector = numpy.zeros((50000)) tic = time.process_time() for i in range(len(a)): vector[i]= a[i]*b[i] toc = time.process_time() print(\"Element wise Product = \"+ str(vector));print(\"\\nComputation time = \"+str(1000*(toc - tic ))+\"ms\") n_tic = time.process_time()vector = numpy.multiply(a, b)n_toc = time.process_time() print(\"Element wise Product = \"+str(vector));print(\"\\nComputation time = \"+str(1000*(n_toc - n_tic ))+\"ms\")", "e": 6266, "s": 5578, "text": null }, { "code": null, "e": 6274, "s": 6266, "text": "Output:" }, { "code": null, "e": 6580, "s": 6274, "text": "Element wise Product = [ 0.00000000e+00 5.00010000e+04 1.00004000e+05 ..., 4.99955001e+09\n 4.99970000e+09 4.99985000e+09]\n\nComputation time = 23.516678000000013ms\n\nElement wise Product = [ 0 50001 100004 ..., 704582713 704732708 704882705]\nComputation time = 0.2250640000000248ms\n" }, { "code": null, "e": 6591, "s": 6580, "text": "nidhi_biet" }, { "code": null, "e": 6604, "s": 6591, "text": "data-science" }, { "code": null, "e": 6611, "s": 6604, "text": "Python" }, { "code": null, "e": 6709, "s": 6611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6727, "s": 6709, "text": "Python Dictionary" }, { "code": null, "e": 6769, "s": 6727, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6791, "s": 6769, "text": "Enumerate() in Python" }, { "code": null, "e": 6826, "s": 6791, "text": "Read a file line by line in Python" }, { "code": null, "e": 6852, "s": 6826, "text": "Python String | replace()" }, { "code": null, "e": 6884, "s": 6852, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6913, "s": 6884, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6940, "s": 6913, "text": "Python Classes and Objects" }, { "code": null, "e": 6970, "s": 6940, "text": "Iterate over a list in Python" } ]
Iterative HeapSort
Difficulty Level : Medium HeapSort is a comparison based sorting technique where we first build Max Heap and then swaps the root element with last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15 5 19 Output: 5 5 6 7 11 12 13 15 19 In first Example, first we have to build Max Heap. So, we will start from 20 as child and check for its parent. Here 10 is smaller, so we will swap these two. Now, 20 10 15 17 9 21 Now, child 17 is greater than its parent 10. So, both will be swapped and order will be 20 17 15 10 9 21 Now, child 21 is greater than parent 15. So, both will be swapped. 20 17 21 10 9 15 Now, again 21 is bigger than parent 20. So, 21 17 20 10 9 15 This is Max Heap. Now, we have to apply sorting. Here, we have to swap first element with last one and we have to maintain Max Heap property. So, after first swapping : 15 17 20 10 9 21 It clearly violates Max Heap property. So, we have to maintain it. So, order will be 20 17 15 10 9 21 17 10 15 9 20 21 15 10 9 17 20 21 10 9 15 17 20 21 9 10 15 17 20 21 Here, underlined part is sorted part. C++ Java Python3 C# C // C++ program for implementation// of Iterative Heap Sort#include <bits/stdc++.h>using namespace std; // function build Max Heap where value// of each child is always smaller// than value of their parentvoid buildMaxHeap(int arr[], int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr[j], arr[(j - 1) / 2]); j = (j - 1) / 2; } } }} void heapSort(int arr[], int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr[0], arr[i]); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (arr[index] < arr[index + 1] && index < (i - 1)) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (arr[j] < arr[index] && index < i) swap(arr[j], arr[index]); j = index; } while (index < i); }} // Driver Code to test aboveint main(){ int arr[] = {10, 20, 15, 17, 9, 21}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n\n"); heapSort(arr, n); // print array after sorting printf("Sorted array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} // Java implementation of Iterative Heap Sortpublic class HeapSort { // function build Max Heap where value // of each child is always smaller // than value of their parent static void buildMaxHeap(int arr[], int n) { for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr, j, (j - 1) / 2); j = (j - 1) / 2; } } } } static void heapSort(int arr[], int n) { buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr, 0, i); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (index < (i - 1) && arr[index] < arr[index + 1]) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (index < i && arr[j] < arr[index]) swap(arr, j, index); j = index; } while (index < i); } } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i]=a[j]; a[j] = temp; } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver program public static void main(String args[]) { int arr[] = {10, 20, 15, 17, 9, 21}; int n = arr.length; System.out.print("Given array: "); printArray(arr); heapSort(arr, n); System.out.print("Sorted array: "); printArray(arr); }} # Python3 program for implementation# of Iterative Heap Sort # function build Max Heap where value# of each child is always smaller# than value of their parentdef buildMaxHeap(arr, n): for i in range(n): # if child is bigger than parent if arr[i] > arr[int((i - 1) / 2)]: j = i # swap child and parent until # parent is smaller while arr[j] > arr[int((j - 1) / 2)]: (arr[j], arr[int((j - 1) / 2)]) = (arr[int((j - 1) / 2)], arr[j]) j = int((j - 1) / 2) def heapSort(arr, n): buildMaxHeap(arr, n) for i in range(n - 1, 0, -1): # swap value of first indexed # with last indexed arr[0], arr[i] = arr[i], arr[0] # maintaining heap property # after each swapping j, index = 0, 0 while True: index = 2 * j + 1 # if left child is smaller than # right child point index variable # to right child if (index < (i - 1) and arr[index] < arr[index + 1]): index += 1 # if parent is smaller than child # then swapping parent with child # having higher value if index < i and arr[j] < arr[index]: arr[j], arr[index] = arr[index], arr[j] j = index if index >= i: break # Driver Codeif __name__ == '__main__': arr = [10, 20, 15, 17, 9, 21] n = len(arr) print("Given array: ") for i in range(n): print(arr[i], end = " ") print() heapSort(arr, n) # print array after sorting print("Sorted array: ") for i in range(n): print(arr[i], end = " ") # This code is contributed by PranchalK // C# implementation of Iterative Heap Sortusing System; class HeapSort{ // function build Max Heap where value// of each child is always smaller// than value of their parentstatic void buildMaxHeap(int []arr, int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr, j, (j - 1) / 2); j = (j - 1) / 2; } } }} static void heapSort(int []arr, int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr, 0, i); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (index < (i - 1) && arr[index] < arr[index + 1]) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (index < i && arr[j] < arr[index]) swap(arr, j, index); j = index; } while (index < i); }} public static void swap(int[] a, int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp;} /* A utility function to print array of size n */static void printArray(int []arr){ int n = arr.Length; for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine();} // Driver Codepublic static void Main(String []args){ int []arr = {10, 20, 15, 17, 9, 21}; int n = arr.Length; Console.Write("Given array: "); printArray(arr); heapSort(arr, n); Console.Write("Sorted array: "); printArray(arr);}} // This code is contributed by Princi Singh // C program for implementation// of Iterative Heap Sort#include <stdio.h> // function build Max Heap where value// of each child is always smaller// than value of their parentvoid buildMaxHeap(int arr[], int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { int temp=arr[j]; arr[j]=arr[(j-1)/2]; arr[(j-1)/2]=temp; j = (j - 1) / 2; } } }} void heapSort(int arr[], int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed int temp=arr[0]; arr[0]=arr[i]; arr[i]=temp; // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (arr[index] < arr[index + 1] && index < (i - 1)) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (arr[j] < arr[index] && index < i) { int tem1=arr[j]; arr[j]=arr[index]; arr[index]=tem1; } j = index; } while (index < i); }} // Driver Code to test aboveint main(){ int arr[] = {10, 20, 15, 17, 9, 21}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n\n"); heapSort(arr, n); // print array after sorting printf("Sorted array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} Output : Given array: 10 20 15 17 9 21 Sorted array: 9 10 15 17 20 21 Here, both function buildMaxHeap and heapSort runs in O(nlogn) time. So, overall time complexity is O(nlogn) PranchalKatiyar vreflect Rajput-Ji rexomkar Heap Sorting Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k) Count Inversions in an array | Set 1 (Using Merge Sort) Merge two sorted arrays Sort an array of 0s, 1s and 2s | Dutch National Flag problem Chocolate Distribution Problem Find a triplet that sum to a given value
[ { "code": null, "e": 26, "s": 0, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 238, "s": 26, "text": "HeapSort is a comparison based sorting technique where we first build Max Heap and then swaps the root element with last element (size times) and maintains the heap property each time to finally make it sorted. " }, { "code": null, "e": 248, "s": 238, "text": "Examples:" }, { "code": null, "e": 365, "s": 248, "text": "Input : 10 20 15 17 9 21\nOutput : 9 10 15 17 20 21 \n\nInput: 12 11 13 5 6 7 15 5 19\nOutput: 5 5 6 7 11 12 13 15 19 " }, { "code": null, "e": 417, "s": 365, "text": "In first Example, first we have to build Max Heap. " }, { "code": null, "e": 526, "s": 417, "text": "So, we will start from 20 as child and check for its parent. Here 10 is smaller, so we will swap these two. " }, { "code": null, "e": 549, "s": 526, "text": "Now, 20 10 15 17 9 21 " }, { "code": null, "e": 655, "s": 549, "text": "Now, child 17 is greater than its parent 10. So, both will be swapped and order will be 20 17 15 10 9 21 " }, { "code": null, "e": 723, "s": 655, "text": "Now, child 21 is greater than parent 15. So, both will be swapped. " }, { "code": null, "e": 741, "s": 723, "text": "20 17 21 10 9 15 " }, { "code": null, "e": 803, "s": 741, "text": "Now, again 21 is bigger than parent 20. So, 21 17 20 10 9 15 " }, { "code": null, "e": 822, "s": 803, "text": "This is Max Heap. " }, { "code": null, "e": 1030, "s": 822, "text": "Now, we have to apply sorting. Here, we have to swap first element with last one and we have to maintain Max Heap property. So, after first swapping : 15 17 20 10 9 21 It clearly violates Max Heap property. " }, { "code": null, "e": 1077, "s": 1030, "text": "So, we have to maintain it. So, order will be " }, { "code": null, "e": 1095, "s": 1077, "text": "20 17 15 10 9 21 " }, { "code": null, "e": 1113, "s": 1095, "text": "17 10 15 9 20 21 " }, { "code": null, "e": 1131, "s": 1113, "text": "15 10 9 17 20 21 " }, { "code": null, "e": 1149, "s": 1131, "text": "10 9 15 17 20 21 " }, { "code": null, "e": 1167, "s": 1149, "text": "9 10 15 17 20 21 " }, { "code": null, "e": 1205, "s": 1167, "text": "Here, underlined part is sorted part." }, { "code": null, "e": 1209, "s": 1205, "text": "C++" }, { "code": null, "e": 1214, "s": 1209, "text": "Java" }, { "code": null, "e": 1222, "s": 1214, "text": "Python3" }, { "code": null, "e": 1225, "s": 1222, "text": "C#" }, { "code": null, "e": 1227, "s": 1225, "text": "C" }, { "code": "// C++ program for implementation// of Iterative Heap Sort#include <bits/stdc++.h>using namespace std; // function build Max Heap where value// of each child is always smaller// than value of their parentvoid buildMaxHeap(int arr[], int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr[j], arr[(j - 1) / 2]); j = (j - 1) / 2; } } }} void heapSort(int arr[], int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr[0], arr[i]); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (arr[index] < arr[index + 1] && index < (i - 1)) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (arr[j] < arr[index] && index < i) swap(arr[j], arr[index]); j = index; } while (index < i); }} // Driver Code to test aboveint main(){ int arr[] = {10, 20, 15, 17, 9, 21}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Given array: \"); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\\n\"); heapSort(arr, n); // print array after sorting printf(\"Sorted array: \"); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}", "e": 3161, "s": 1227, "text": null }, { "code": "// Java implementation of Iterative Heap Sortpublic class HeapSort { // function build Max Heap where value // of each child is always smaller // than value of their parent static void buildMaxHeap(int arr[], int n) { for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr, j, (j - 1) / 2); j = (j - 1) / 2; } } } } static void heapSort(int arr[], int n) { buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr, 0, i); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (index < (i - 1) && arr[index] < arr[index + 1]) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (index < i && arr[j] < arr[index]) swap(arr, j, index); j = index; } while (index < i); } } public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i]=a[j]; a[j] = temp; } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver program public static void main(String args[]) { int arr[] = {10, 20, 15, 17, 9, 21}; int n = arr.length; System.out.print(\"Given array: \"); printArray(arr); heapSort(arr, n); System.out.print(\"Sorted array: \"); printArray(arr); }}", "e": 5062, "s": 3161, "text": null }, { "code": "# Python3 program for implementation# of Iterative Heap Sort # function build Max Heap where value# of each child is always smaller# than value of their parentdef buildMaxHeap(arr, n): for i in range(n): # if child is bigger than parent if arr[i] > arr[int((i - 1) / 2)]: j = i # swap child and parent until # parent is smaller while arr[j] > arr[int((j - 1) / 2)]: (arr[j], arr[int((j - 1) / 2)]) = (arr[int((j - 1) / 2)], arr[j]) j = int((j - 1) / 2) def heapSort(arr, n): buildMaxHeap(arr, n) for i in range(n - 1, 0, -1): # swap value of first indexed # with last indexed arr[0], arr[i] = arr[i], arr[0] # maintaining heap property # after each swapping j, index = 0, 0 while True: index = 2 * j + 1 # if left child is smaller than # right child point index variable # to right child if (index < (i - 1) and arr[index] < arr[index + 1]): index += 1 # if parent is smaller than child # then swapping parent with child # having higher value if index < i and arr[j] < arr[index]: arr[j], arr[index] = arr[index], arr[j] j = index if index >= i: break # Driver Codeif __name__ == '__main__': arr = [10, 20, 15, 17, 9, 21] n = len(arr) print(\"Given array: \") for i in range(n): print(arr[i], end = \" \") print() heapSort(arr, n) # print array after sorting print(\"Sorted array: \") for i in range(n): print(arr[i], end = \" \") # This code is contributed by PranchalK", "e": 6938, "s": 5062, "text": null }, { "code": "// C# implementation of Iterative Heap Sortusing System; class HeapSort{ // function build Max Heap where value// of each child is always smaller// than value of their parentstatic void buildMaxHeap(int []arr, int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { swap(arr, j, (j - 1) / 2); j = (j - 1) / 2; } } }} static void heapSort(int []arr, int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed swap(arr, 0, i); // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (index < (i - 1) && arr[index] < arr[index + 1]) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (index < i && arr[j] < arr[index]) swap(arr, j, index); j = index; } while (index < i); }} public static void swap(int[] a, int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp;} /* A utility function to print array of size n */static void printArray(int []arr){ int n = arr.Length; for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine();} // Driver Codepublic static void Main(String []args){ int []arr = {10, 20, 15, 17, 9, 21}; int n = arr.Length; Console.Write(\"Given array: \"); printArray(arr); heapSort(arr, n); Console.Write(\"Sorted array: \"); printArray(arr);}} // This code is contributed by Princi Singh", "e": 9020, "s": 6938, "text": null }, { "code": "// C program for implementation// of Iterative Heap Sort#include <stdio.h> // function build Max Heap where value// of each child is always smaller// than value of their parentvoid buildMaxHeap(int arr[], int n){ for (int i = 1; i < n; i++) { // if child is bigger than parent if (arr[i] > arr[(i - 1) / 2]) { int j = i; // swap child and parent until // parent is smaller while (arr[j] > arr[(j - 1) / 2]) { int temp=arr[j]; arr[j]=arr[(j-1)/2]; arr[(j-1)/2]=temp; j = (j - 1) / 2; } } }} void heapSort(int arr[], int n){ buildMaxHeap(arr, n); for (int i = n - 1; i > 0; i--) { // swap value of first indexed // with last indexed int temp=arr[0]; arr[0]=arr[i]; arr[i]=temp; // maintaining heap property // after each swapping int j = 0, index; do { index = (2 * j + 1); // if left child is smaller than // right child point index variable // to right child if (arr[index] < arr[index + 1] && index < (i - 1)) index++; // if parent is smaller than child // then swapping parent with child // having higher value if (arr[j] < arr[index] && index < i) { int tem1=arr[j]; arr[j]=arr[index]; arr[index]=tem1; } j = index; } while (index < i); }} // Driver Code to test aboveint main(){ int arr[] = {10, 20, 15, 17, 9, 21}; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Given array: \"); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\\n\"); heapSort(arr, n); // print array after sorting printf(\"Sorted array: \"); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}", "e": 11101, "s": 9020, "text": null }, { "code": null, "e": 11110, "s": 11101, "text": "Output :" }, { "code": null, "e": 11174, "s": 11110, "text": "Given array: 10 20 15 17 9 21 \n\nSorted array: 9 10 15 17 20 21 " }, { "code": null, "e": 11283, "s": 11174, "text": "Here, both function buildMaxHeap and heapSort runs in O(nlogn) time. So, overall time complexity is O(nlogn)" }, { "code": null, "e": 11299, "s": 11283, "text": "PranchalKatiyar" }, { "code": null, "e": 11308, "s": 11299, "text": "vreflect" }, { "code": null, "e": 11318, "s": 11308, "text": "Rajput-Ji" }, { "code": null, "e": 11327, "s": 11318, "text": "rexomkar" }, { "code": null, "e": 11332, "s": 11327, "text": "Heap" }, { "code": null, "e": 11340, "s": 11332, "text": "Sorting" }, { "code": null, "e": 11348, "s": 11340, "text": "Sorting" }, { "code": null, "e": 11353, "s": 11348, "text": "Heap" }, { "code": null, "e": 11451, "s": 11353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11507, "s": 11451, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 11519, "s": 11507, "text": "Binary Heap" }, { "code": null, "e": 11551, "s": 11519, "text": "Introduction to Data Structures" }, { "code": null, "e": 11582, "s": 11551, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 11642, "s": 11582, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 11698, "s": 11642, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 11722, "s": 11698, "text": "Merge two sorted arrays" }, { "code": null, "e": 11783, "s": 11722, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 11814, "s": 11783, "text": "Chocolate Distribution Problem" } ]
TreeView in Android with Example
18 Feb, 2021 If you are looking for the new UI designs for the representation of huge data, then there are so many ways for the representation of this type of data. You can use pie charts, graphs, and many more view types for the implementation of these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it is having a parent node and inside that parent node, you can create multiple nodes according to requirement. In this example, we can take a look at creating a TreeView in your Android application. Now we will move towards the implementation of Tree View. Note that we are going to implement this project using the Java language. TreeView is a pattern for the representation of data in the form of the tree so that it becomes easier for users to understand the organization of data in our app. A sample image is given below to get an idea of how TreeView looks like. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency to build.gradle(Module:app) Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘de.blox.treeview:treeview:0.1.0’ After adding this dependency sync your project and now we will move towards its implementation. Step 3: Modify the strings.xml file Below is the code for the strings.xml file. XML <resources> <string name="app_name">GFG App</string> <string name="my_node">Node</string></resources> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><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" tools:context=".MainActivity"> <!--Below is the code for tree view--> <de.blox.treeview.TreeView android:id="@+id/idTreeView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 5: Create a new XML file After adding this TreeView create a new XML file for your node which we have to display inside our TreeView. For creating a new XML file navigate to the app > res > layout > Right-click > New > Layout Resource file. Give a name to your file (Here we have given tree_view_node) and click on create. After creating this file add the below code to it. Below is the code for the tree_view_node.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/idTvnode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="@color/purple_500" android:padding="8dp" android:text="@string/my_node" android:textColor="@color/white" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 6: Create a new Java class Now create a new Java class as View Holder for handling our nodes in Tree View. To create a new java class please refer to the How to Create Classes in Android Studio. After creating a new java class add the below code to it. Here we have named the class as Viewholder. Below is the code for the Viewholder.java file. Java import android.view.View;import android.widget.TextView; public class Viewholder { TextView textView; Viewholder(View view) { textView = view.findViewById(R.id.idTvnode); }} After creating the Viewholder class then we will move towards the implementation of TreeView in our MainActivity.java file. Step 7: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import de.blox.treeview.BaseTreeAdapter;import de.blox.treeview.TreeNode;import de.blox.treeview.TreeView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for tree view. TreeView treeView = findViewById(R.id.idTreeView); // creating adapter class for our treeview using basetree adapter. // inside base tree adapter you have to pass viewholder class along // with context and your layout file for treeview node. BaseTreeAdapter<Viewholder> adapter = new BaseTreeAdapter<Viewholder>(this, R.layout.tree_view_node) { @NonNull @Override public Viewholder onCreateViewHolder(View view) { return new Viewholder(view); } @Override public void onBindViewHolder(Viewholder viewHolder, Object data, int position) { // inside our on bind view holder method we // are setting data from object to text view. viewHolder.textView.setText(data.toString()); } }; // below line is setting adapter for our tree. treeView.setAdapter(adapter); // below tree node is a parent node of our tree // node which is Geeks for Geeks. TreeNode root = new TreeNode("Geeks for Geeks"); // below node is the first child node of our root node ie Geeks for Geeks. TreeNode DSAchildNode = new TreeNode("DSA"); // below node is the second child of our // root node ie Geeks for Geeks. TreeNode AlgoChildNode = new TreeNode("Algorithm"); // below node is the third child of our // root node ie Geeks for Geeks. TreeNode languageNode = new TreeNode("Language"); // below node is the first child of our language node. TreeNode CchildNode = new TreeNode("C++"); // below node is the second child of our language node. TreeNode javaChildNode = new TreeNode("Java"); // below node is the first child of our DSA node. TreeNode arrayChild = new TreeNode("Arrays"); // below node is the second child of our DSA node. TreeNode stringChild = new TreeNode("Strings"); // below node is the first child of our Algorithm node. TreeNode sortingChildNode = new TreeNode("Sorting"); // below lines is used for adding child // nodes to our root nodes. root.addChild(DSAchildNode); root.addChild(languageNode); root.addChild(AlgoChildNode); // below lines is used to add languages // to our Language node. we are adding c++, // java to our language node. languageNode.addChild(CchildNode); languageNode.addChild(javaChildNode); // below line isused to add arrays, // strings to our dsa node. we are // adding Arrays,Strings to our DSA node. DSAchildNode.addChild(arrayChild); DSAchildNode.addChild(stringChild); // below line is used for adding sorting // algo to our Algorithm node. AlgoChildNode.addChild(sortingChildNode); // below line is for setting our root node. // Inside our root node we are passing "root" // as our root node. adapter.setRootNode(root); }} android Android-View Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2021" }, { "code": null, "e": 723, "s": 28, "text": "If you are looking for the new UI designs for the representation of huge data, then there are so many ways for the representation of this type of data. You can use pie charts, graphs, and many more view types for the implementation of these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it is having a parent node and inside that parent node, you can create multiple nodes according to requirement. In this example, we can take a look at creating a TreeView in your Android application. Now we will move towards the implementation of Tree View. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 960, "s": 723, "text": "TreeView is a pattern for the representation of data in the form of the tree so that it becomes easier for users to understand the organization of data in our app. A sample image is given below to get an idea of how TreeView looks like." }, { "code": null, "e": 989, "s": 960, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1151, "s": 989, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1202, "s": 1151, "text": "Step 2: Add dependency to build.gradle(Module:app)" }, { "code": null, "e": 1322, "s": 1202, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 1371, "s": 1322, "text": "implementation ‘de.blox.treeview:treeview:0.1.0’" }, { "code": null, "e": 1468, "s": 1371, "text": "After adding this dependency sync your project and now we will move towards its implementation. " }, { "code": null, "e": 1504, "s": 1468, "text": "Step 3: Modify the strings.xml file" }, { "code": null, "e": 1548, "s": 1504, "text": "Below is the code for the strings.xml file." }, { "code": null, "e": 1552, "s": 1548, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">GFG App</string> <string name=\"my_node\">Node</string></resources>", "e": 1660, "s": 1552, "text": null }, { "code": null, "e": 1708, "s": 1660, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 1853, "s": 1708, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1857, "s": 1853, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Below is the code for tree view--> <de.blox.treeview.TreeView android:id=\"@+id/idTreeView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>", "e": 2360, "s": 1857, "text": null }, { "code": null, "e": 2390, "s": 2360, "text": "Step 5: Create a new XML file" }, { "code": null, "e": 2791, "s": 2390, "text": "After adding this TreeView create a new XML file for your node which we have to display inside our TreeView. For creating a new XML file navigate to the app > res > layout > Right-click > New > Layout Resource file. Give a name to your file (Here we have given tree_view_node) and click on create. After creating this file add the below code to it. Below is the code for the tree_view_node.xml file. " }, { "code": null, "e": 2795, "s": 2791, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\"> <TextView android:id=\"@+id/idTvnode\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:background=\"@color/purple_500\" android:padding=\"8dp\" android:text=\"@string/my_node\" android:textColor=\"@color/white\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 3401, "s": 2795, "text": null }, { "code": null, "e": 3434, "s": 3401, "text": "Step 6: Create a new Java class " }, { "code": null, "e": 3753, "s": 3434, "text": "Now create a new Java class as View Holder for handling our nodes in Tree View. To create a new java class please refer to the How to Create Classes in Android Studio. After creating a new java class add the below code to it. Here we have named the class as Viewholder. Below is the code for the Viewholder.java file. " }, { "code": null, "e": 3758, "s": 3753, "text": "Java" }, { "code": "import android.view.View;import android.widget.TextView; public class Viewholder { TextView textView; Viewholder(View view) { textView = view.findViewById(R.id.idTvnode); }}", "e": 3957, "s": 3758, "text": null }, { "code": null, "e": 4082, "s": 3957, "text": "After creating the Viewholder class then we will move towards the implementation of TreeView in our MainActivity.java file. " }, { "code": null, "e": 4130, "s": 4082, "text": "Step 7: Working with the MainActivity.java file" }, { "code": null, "e": 4320, "s": 4130, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4325, "s": 4320, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import de.blox.treeview.BaseTreeAdapter;import de.blox.treeview.TreeNode;import de.blox.treeview.TreeView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating a variable for tree view. TreeView treeView = findViewById(R.id.idTreeView); // creating adapter class for our treeview using basetree adapter. // inside base tree adapter you have to pass viewholder class along // with context and your layout file for treeview node. BaseTreeAdapter<Viewholder> adapter = new BaseTreeAdapter<Viewholder>(this, R.layout.tree_view_node) { @NonNull @Override public Viewholder onCreateViewHolder(View view) { return new Viewholder(view); } @Override public void onBindViewHolder(Viewholder viewHolder, Object data, int position) { // inside our on bind view holder method we // are setting data from object to text view. viewHolder.textView.setText(data.toString()); } }; // below line is setting adapter for our tree. treeView.setAdapter(adapter); // below tree node is a parent node of our tree // node which is Geeks for Geeks. TreeNode root = new TreeNode(\"Geeks for Geeks\"); // below node is the first child node of our root node ie Geeks for Geeks. TreeNode DSAchildNode = new TreeNode(\"DSA\"); // below node is the second child of our // root node ie Geeks for Geeks. TreeNode AlgoChildNode = new TreeNode(\"Algorithm\"); // below node is the third child of our // root node ie Geeks for Geeks. TreeNode languageNode = new TreeNode(\"Language\"); // below node is the first child of our language node. TreeNode CchildNode = new TreeNode(\"C++\"); // below node is the second child of our language node. TreeNode javaChildNode = new TreeNode(\"Java\"); // below node is the first child of our DSA node. TreeNode arrayChild = new TreeNode(\"Arrays\"); // below node is the second child of our DSA node. TreeNode stringChild = new TreeNode(\"Strings\"); // below node is the first child of our Algorithm node. TreeNode sortingChildNode = new TreeNode(\"Sorting\"); // below lines is used for adding child // nodes to our root nodes. root.addChild(DSAchildNode); root.addChild(languageNode); root.addChild(AlgoChildNode); // below lines is used to add languages // to our Language node. we are adding c++, // java to our language node. languageNode.addChild(CchildNode); languageNode.addChild(javaChildNode); // below line isused to add arrays, // strings to our dsa node. we are // adding Arrays,Strings to our DSA node. DSAchildNode.addChild(arrayChild); DSAchildNode.addChild(stringChild); // below line is used for adding sorting // algo to our Algorithm node. AlgoChildNode.addChild(sortingChildNode); // below line is for setting our root node. // Inside our root node we are passing \"root\" // as our root node. adapter.setRootNode(root); }}", "e": 8031, "s": 4325, "text": null }, { "code": null, "e": 8039, "s": 8031, "text": "android" }, { "code": null, "e": 8052, "s": 8039, "text": "Android-View" }, { "code": null, "e": 8076, "s": 8052, "text": "Technical Scripter 2020" }, { "code": null, "e": 8084, "s": 8076, "text": "Android" }, { "code": null, "e": 8089, "s": 8084, "text": "Java" }, { "code": null, "e": 8108, "s": 8089, "text": "Technical Scripter" }, { "code": null, "e": 8113, "s": 8108, "text": "Java" }, { "code": null, "e": 8121, "s": 8113, "text": "Android" }, { "code": null, "e": 8219, "s": 8121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8288, "s": 8219, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8320, "s": 8288, "text": "Android SDK and it's Components" }, { "code": null, "e": 8359, "s": 8320, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8408, "s": 8359, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8450, "s": 8408, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8465, "s": 8450, "text": "Arrays in Java" }, { "code": null, "e": 8501, "s": 8465, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8545, "s": 8501, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8570, "s": 8545, "text": "Reverse a string in Java" } ]
Print all Hamiltonian Cycles in an Undirected Graph
25 Oct, 2021 Given an undirected Graph consisting of N nodes in the form of an adjacency matrix graph[][] of size N*N, the task is to print all Hamiltonian cycles possible in the given undirected Graph (taking starting vertex as ‘0’). A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path. Examples: Input: graph[][] = {{0, 1, 1, 0, 0, 1}, {1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 1}, {1, 1, 0, 0, 1, 0}}Output: 0 1 2 3 4 5 0 0 1 5 4 3 2 0 0 2 3 4 1 5 0 0 2 3 4 5 1 0 0 5 1 4 3 2 0 0 5 4 3 2 1 0 Explanation:All Possible Hamiltonian Cycles for the following graph (with the starting vertex as 0) are {0 → 1 → 2 → 3 → 4 → 5 → 0}{0 → 1 → 5 → 4 → 3 → 2 → 0}{0 → 2 → 3 → 4 → 1 → 5 → 0}{0 → 2 → 3 → 4 → 5 → 1 → 0}{0 → 5 → 1 → 4 → 3 → 2 → 0}{0 → 5 → 4 → 3 → 2 → 1 → 0} {0 → 1 → 2 → 3 → 4 → 5 → 0} {0 → 1 → 5 → 4 → 3 → 2 → 0} {0 → 2 → 3 → 4 → 1 → 5 → 0} {0 → 2 → 3 → 4 → 5 → 1 → 0} {0 → 5 → 1 → 4 → 3 → 2 → 0} {0 → 5 → 4 → 3 → 2 → 1 → 0} Input: graph[][] = {{0, 1, 0, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1}, {0, 0, 1, 0, 0, 1, 0}}Output: No Hamiltonian Cycle possibleExplanation:For the given graph, no Hamiltonian Cycle is possible: Approach: The given problem can be solved by using Backtracking to generate all possible Hamiltonian Cycles. Follow the steps below to solve the problem: Create an auxiliary array, say path[] to store the order of traversal of nodes and a boolean array visited[] to keep track of vertices included in the current path. Initially, add the source vertex (in this case ‘0’) to the path. Now, recursively add vertices to path one by one to find the cycle. Before adding a vertex to path, check whether the vertex being considered is adjacent to the previously added vertex or not and is not already in path. If such a vertex is found, then add it to the path and mark its value as true in the visited[] array. If the length of path becomes equal to N, and there is an edge from the last vertex in path to 0, then print the path array. After completing the above steps, if there exists no such path, then print No Hamiltonian Cycle possible. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include<bits/stdc++.h>using namespace std; // To check if there exists// at least 1 hamiltonian cyclebool hasCycle; // Function to check if a vertex v// can be added at index pos in// the Hamiltonian Cyclebool isSafe(int v, int graph[][6], vector<int> path, int pos){ // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1]][v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true;} // Recursive function to find all// hamiltonian cyclesvoid FindHamCycle(int graph[][6], int pos, vector<int> path, bool visited[], int N){ // If all vertices are included // in Hamiltonian Cycle if (pos == N) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.size() - 1]][path[0]] != 0) { // Include source vertex // into the path and // print the path path.push_back(0); for (int i = 0; i < path.size(); i++) { cout << path[i] << " "; } cout << endl; // Remove the source // vertex added path.pop_back(); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < N; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.push_back(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited, N); // Remove current vertex // from path and process // other vertices visited[v] = false; path.pop_back(); } }} // Function to find all possible// hamiltonian cyclesvoid hamCycle(int graph[][6], int N){ // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path vector<int> path; path.push_back(0); // Keeps the track of the // visited vertices bool visited[N]; for (int i = 0; i < N; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited, N); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph cout << "No Hamiltonian Cycle" << "possible " << endl; return; }} int main(){ int graph[][6] = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamCycle(graph, 6); return 0;} // This code is contributed by rameshtravel07. // Java program for the above approach import java.util.ArrayList;class GFG { // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle boolean isSafe(int v, int graph[][], ArrayList<Integer> path, int pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path.get(pos - 1)][v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path.get(i) == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle boolean hasCycle; // Function to find all possible // hamiltonian cycles void hamCycle(int graph[][]) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path ArrayList<Integer> path = new ArrayList<>(); path.add(0); // Keeps the track of the // visited vertices boolean[] visited = new boolean[graph.length]; for (int i = 0; i < visited.length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph System.out.println( "No Hamiltonian Cycle" + "possible "); return; } } // Recursive function to find all // hamiltonian cycles void FindHamCycle(int graph[][], int pos, ArrayList<Integer> path, boolean[] visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.length) { // If there is an edge // from the last vertex to // the source vertex if (graph[path.get(path.size() - 1)] [path.get(0)] != 0) { // Include source vertex // into the path and // print the path path.add(0); for (int i = 0; i < path.size(); i++) { System.out.print( path.get(i) + " "); } System.out.println(); // Remove the source // vertex added path.remove(path.size() - 1); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < graph.length; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.add(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle( graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.remove( path.size() - 1); } } } // Driver Code public static void main(String args[]) { GFG hamiltonian = new GFG(); /* Input Graph: (0) - - -- (2) | \ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ int[][] graph = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamiltonian.hamCycle(graph); }} # Python3 program for the above approach # Function to check if a vertex v# can be added at index pos in# the Hamiltonian Cycledef isSafe(v, graph, path, pos): # If the vertex is adjacent to # the vertex of the previously # added vertex if graph[path[pos - 1]][v] == 0: return False # If the vertex has already # been included in the path for i in range(pos): if path[i] == v: return False # Both the above conditions are # not true, return true return True # To check if there exists# at least 1 hamiltonian cyclehasCycle = False # Function to find all possible# hamiltonian cyclesdef hamCycle(graph): global hasCycle # Initially value of boolean # flag is false hasCycle = False # Store the resultant path path = [] path.append(0) # Keeps the track of the # visited vertices visited = [False]*(len(graph)) for i in range(len(visited)): visited[i] = False visited[0] = True # Function call to find all # hamiltonian cycles FindHamCycle(graph, 1, path, visited) if hasCycle: # If no Hamiltonian Cycle # is possible for the # given graph print("No Hamiltonian Cycle" + "possible ") return # Recursive function to find all# hamiltonian cyclesdef FindHamCycle(graph, pos, path, visited): # If all vertices are included # in Hamiltonian Cycle if pos == len(graph): # If there is an edge # from the last vertex to # the source vertex if graph[path[-1]][path[0]] != 0: # Include source vertex # into the path and # print the path path.append(0) for i in range(len(path)): print(path[i], end = " ") print() # Remove the source # vertex added path.pop() # Update the hasCycle # as true hasCycle = True return # Try different vertices # as the next vertex for v in range(len(graph)): # Check if this vertex can # be added to Cycle if isSafe(v, graph, path, pos) and not visited[v]: path.append(v) visited[v] = True # Recur to construct # rest of the path FindHamCycle(graph, pos + 1, path, visited) # Remove current vertex # from path and process # other vertices visited[v] = False path.pop() """ Input Graph: (0) - - -- (2) | \ / | | (1) | | / | | | / | | (5)----(4)--(3)""" graph = [ [ 0, 1, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1 ], [ 1, 1, 0, 1, 0, 0 ], [ 0, 0, 1, 0, 1, 0 ], [ 0, 1, 0, 1, 0, 1 ], [ 1, 1, 0, 0, 1, 0 ],]hamCycle(graph) # This code is contributed by divyesh072019. // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle static bool isSafe(int v, int[,] graph, List<int> path, int pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1],v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle static bool hasCycle; // Function to find all possible // hamiltonian cycles static void hamCycle(int[,] graph) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path List<int> path = new List<int>(); path.Add(0); // Keeps the track of the // visited vertices bool[] visited = new bool[graph.GetLength(0)]; for (int i = 0; i < visited.Length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph Console.WriteLine("No Hamiltonian Cycle" + "possible "); return; } } // Recursive function to find all // hamiltonian cycles static void FindHamCycle(int[,] graph, int pos, List<int> path, bool[] visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.GetLength(0)) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.Count - 1], path[0]] != 0) { // Include source vertex // into the path and // print the path path.Add(0); for (int i = 0; i < path.Count; i++) { Console.Write(path[i] + " "); } Console.WriteLine(); // Remove the source // vertex added path.RemoveAt(path.Count - 1); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < graph.GetLength(0); v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.Add(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.RemoveAt(path.Count - 1); } } } static void Main() { /* Input Graph: (0) - - -- (2) | \ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ int[,] graph = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamCycle(graph); }} // This code is contributed by suresh07. <script> // Javascript program for the above approach // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle function isSafe(v, graph, path, pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1]][v] == 0) return false; // If the vertex has already // been included in the path for (let i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle let hasCycle; // Function to find all possible // hamiltonian cycles function hamCycle(graph) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path let path = []; path.push(0); // Keeps the track of the // visited vertices let visited = new Array(graph.length); for (let i = 0; i < visited.length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph document.write("No Hamiltonian Cycle" + "possible "); return; } } // Recursive function to find all // hamiltonian cycles function FindHamCycle(graph, pos, path, visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.length) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.length - 1]][path[0]] != 0) { // Include source vertex // into the path and // print the path path.push(0); for (let i = 0; i < path.length; i++) { document.write(path[i] + " "); } document.write("</br>"); // Remove the source // vertex added path.pop(); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (let v = 0; v < graph.length; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.push(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.pop(); } } } /* Input Graph: (0) - - -- (2) | \ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ let graph = [ [ 0, 1, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1 ], [ 1, 1, 0, 1, 0, 0 ], [ 0, 0, 1, 0, 1, 0 ], [ 0, 1, 0, 1, 0, 1 ], [ 1, 1, 0, 0, 1, 0 ], ]; hamCycle(graph); // This code is contributed by divyeshrabadiya07.</script> 0 1 2 3 4 5 0 0 1 5 4 3 2 0 0 2 3 4 1 5 0 0 2 3 4 5 1 0 0 5 1 4 3 2 0 0 5 4 3 2 1 0 Time Complexity: O(N!)Auxiliary Space: O(N) suresh07 divyeshrabadiya07 divyesh072019 rameshtravel07 Graph Traversals graph-connectivity graph-cycle Backtracking Graph Recursion Recursion Graph Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path of more than k length from a source Find shortest safe route in a path with landmines Longest Possible Route in a Matrix with Hurdles Difference between Backtracking and Branch-N-Bound technique Top 20 Backtracking Algorithm Interview Questions Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Oct, 2021" }, { "code": null, "e": 276, "s": 54, "text": "Given an undirected Graph consisting of N nodes in the form of an adjacency matrix graph[][] of size N*N, the task is to print all Hamiltonian cycles possible in the given undirected Graph (taking starting vertex as ‘0’)." }, { "code": null, "e": 451, "s": 276, "text": "A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path." }, { "code": null, "e": 461, "s": 451, "text": "Examples:" }, { "code": null, "e": 797, "s": 461, "text": "Input: graph[][] = {{0, 1, 1, 0, 0, 1}, {1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 1}, {1, 1, 0, 0, 1, 0}}Output: 0 1 2 3 4 5 0 0 1 5 4 3 2 0 0 2 3 4 1 5 0 0 2 3 4 5 1 0 0 5 1 4 3 2 0 0 5 4 3 2 1 0 Explanation:All Possible Hamiltonian Cycles for the following graph (with the starting vertex as 0) are " }, { "code": null, "e": 960, "s": 797, "text": "{0 → 1 → 2 → 3 → 4 → 5 → 0}{0 → 1 → 5 → 4 → 3 → 2 → 0}{0 → 2 → 3 → 4 → 1 → 5 → 0}{0 → 2 → 3 → 4 → 5 → 1 → 0}{0 → 5 → 1 → 4 → 3 → 2 → 0}{0 → 5 → 4 → 3 → 2 → 1 → 0}" }, { "code": null, "e": 988, "s": 960, "text": "{0 → 1 → 2 → 3 → 4 → 5 → 0}" }, { "code": null, "e": 1016, "s": 988, "text": "{0 → 1 → 5 → 4 → 3 → 2 → 0}" }, { "code": null, "e": 1044, "s": 1016, "text": "{0 → 2 → 3 → 4 → 1 → 5 → 0}" }, { "code": null, "e": 1072, "s": 1044, "text": "{0 → 2 → 3 → 4 → 5 → 1 → 0}" }, { "code": null, "e": 1100, "s": 1072, "text": "{0 → 5 → 1 → 4 → 3 → 2 → 0}" }, { "code": null, "e": 1128, "s": 1100, "text": "{0 → 5 → 4 → 3 → 2 → 1 → 0}" }, { "code": null, "e": 1413, "s": 1128, "text": "Input: graph[][] = {{0, 1, 0, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1}, {0, 0, 1, 0, 0, 1, 0}}Output: No Hamiltonian Cycle possibleExplanation:For the given graph, no Hamiltonian Cycle is possible: " }, { "code": null, "e": 1567, "s": 1413, "text": "Approach: The given problem can be solved by using Backtracking to generate all possible Hamiltonian Cycles. Follow the steps below to solve the problem:" }, { "code": null, "e": 1732, "s": 1567, "text": "Create an auxiliary array, say path[] to store the order of traversal of nodes and a boolean array visited[] to keep track of vertices included in the current path." }, { "code": null, "e": 1797, "s": 1732, "text": "Initially, add the source vertex (in this case ‘0’) to the path." }, { "code": null, "e": 1865, "s": 1797, "text": "Now, recursively add vertices to path one by one to find the cycle." }, { "code": null, "e": 2119, "s": 1865, "text": "Before adding a vertex to path, check whether the vertex being considered is adjacent to the previously added vertex or not and is not already in path. If such a vertex is found, then add it to the path and mark its value as true in the visited[] array." }, { "code": null, "e": 2244, "s": 2119, "text": "If the length of path becomes equal to N, and there is an edge from the last vertex in path to 0, then print the path array." }, { "code": null, "e": 2350, "s": 2244, "text": "After completing the above steps, if there exists no such path, then print No Hamiltonian Cycle possible." }, { "code": null, "e": 2401, "s": 2350, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2405, "s": 2401, "text": "C++" }, { "code": null, "e": 2410, "s": 2405, "text": "Java" }, { "code": null, "e": 2418, "s": 2410, "text": "Python3" }, { "code": null, "e": 2421, "s": 2418, "text": "C#" }, { "code": null, "e": 2432, "s": 2421, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // To check if there exists// at least 1 hamiltonian cyclebool hasCycle; // Function to check if a vertex v// can be added at index pos in// the Hamiltonian Cyclebool isSafe(int v, int graph[][6], vector<int> path, int pos){ // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1]][v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true;} // Recursive function to find all// hamiltonian cyclesvoid FindHamCycle(int graph[][6], int pos, vector<int> path, bool visited[], int N){ // If all vertices are included // in Hamiltonian Cycle if (pos == N) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.size() - 1]][path[0]] != 0) { // Include source vertex // into the path and // print the path path.push_back(0); for (int i = 0; i < path.size(); i++) { cout << path[i] << \" \"; } cout << endl; // Remove the source // vertex added path.pop_back(); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < N; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.push_back(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited, N); // Remove current vertex // from path and process // other vertices visited[v] = false; path.pop_back(); } }} // Function to find all possible// hamiltonian cyclesvoid hamCycle(int graph[][6], int N){ // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path vector<int> path; path.push_back(0); // Keeps the track of the // visited vertices bool visited[N]; for (int i = 0; i < N; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited, N); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph cout << \"No Hamiltonian Cycle\" << \"possible \" << endl; return; }} int main(){ int graph[][6] = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamCycle(graph, 6); return 0;} // This code is contributed by rameshtravel07.", "e": 5536, "s": 2432, "text": null }, { "code": "// Java program for the above approach import java.util.ArrayList;class GFG { // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle boolean isSafe(int v, int graph[][], ArrayList<Integer> path, int pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path.get(pos - 1)][v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path.get(i) == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle boolean hasCycle; // Function to find all possible // hamiltonian cycles void hamCycle(int graph[][]) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path ArrayList<Integer> path = new ArrayList<>(); path.add(0); // Keeps the track of the // visited vertices boolean[] visited = new boolean[graph.length]; for (int i = 0; i < visited.length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph System.out.println( \"No Hamiltonian Cycle\" + \"possible \"); return; } } // Recursive function to find all // hamiltonian cycles void FindHamCycle(int graph[][], int pos, ArrayList<Integer> path, boolean[] visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.length) { // If there is an edge // from the last vertex to // the source vertex if (graph[path.get(path.size() - 1)] [path.get(0)] != 0) { // Include source vertex // into the path and // print the path path.add(0); for (int i = 0; i < path.size(); i++) { System.out.print( path.get(i) + \" \"); } System.out.println(); // Remove the source // vertex added path.remove(path.size() - 1); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < graph.length; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.add(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle( graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.remove( path.size() - 1); } } } // Driver Code public static void main(String args[]) { GFG hamiltonian = new GFG(); /* Input Graph: (0) - - -- (2) | \\ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ int[][] graph = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamiltonian.hamCycle(graph); }}", "e": 9718, "s": 5536, "text": null }, { "code": "# Python3 program for the above approach # Function to check if a vertex v# can be added at index pos in# the Hamiltonian Cycledef isSafe(v, graph, path, pos): # If the vertex is adjacent to # the vertex of the previously # added vertex if graph[path[pos - 1]][v] == 0: return False # If the vertex has already # been included in the path for i in range(pos): if path[i] == v: return False # Both the above conditions are # not true, return true return True # To check if there exists# at least 1 hamiltonian cyclehasCycle = False # Function to find all possible# hamiltonian cyclesdef hamCycle(graph): global hasCycle # Initially value of boolean # flag is false hasCycle = False # Store the resultant path path = [] path.append(0) # Keeps the track of the # visited vertices visited = [False]*(len(graph)) for i in range(len(visited)): visited[i] = False visited[0] = True # Function call to find all # hamiltonian cycles FindHamCycle(graph, 1, path, visited) if hasCycle: # If no Hamiltonian Cycle # is possible for the # given graph print(\"No Hamiltonian Cycle\" + \"possible \") return # Recursive function to find all# hamiltonian cyclesdef FindHamCycle(graph, pos, path, visited): # If all vertices are included # in Hamiltonian Cycle if pos == len(graph): # If there is an edge # from the last vertex to # the source vertex if graph[path[-1]][path[0]] != 0: # Include source vertex # into the path and # print the path path.append(0) for i in range(len(path)): print(path[i], end = \" \") print() # Remove the source # vertex added path.pop() # Update the hasCycle # as true hasCycle = True return # Try different vertices # as the next vertex for v in range(len(graph)): # Check if this vertex can # be added to Cycle if isSafe(v, graph, path, pos) and not visited[v]: path.append(v) visited[v] = True # Recur to construct # rest of the path FindHamCycle(graph, pos + 1, path, visited) # Remove current vertex # from path and process # other vertices visited[v] = False path.pop() \"\"\" Input Graph: (0) - - -- (2) | \\ / | | (1) | | / | | | / | | (5)----(4)--(3)\"\"\" graph = [ [ 0, 1, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1 ], [ 1, 1, 0, 1, 0, 0 ], [ 0, 0, 1, 0, 1, 0 ], [ 0, 1, 0, 1, 0, 1 ], [ 1, 1, 0, 0, 1, 0 ],]hamCycle(graph) # This code is contributed by divyesh072019.", "e": 12568, "s": 9718, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle static bool isSafe(int v, int[,] graph, List<int> path, int pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1],v] == 0) return false; // If the vertex has already // been included in the path for (int i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle static bool hasCycle; // Function to find all possible // hamiltonian cycles static void hamCycle(int[,] graph) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path List<int> path = new List<int>(); path.Add(0); // Keeps the track of the // visited vertices bool[] visited = new bool[graph.GetLength(0)]; for (int i = 0; i < visited.Length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph Console.WriteLine(\"No Hamiltonian Cycle\" + \"possible \"); return; } } // Recursive function to find all // hamiltonian cycles static void FindHamCycle(int[,] graph, int pos, List<int> path, bool[] visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.GetLength(0)) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.Count - 1], path[0]] != 0) { // Include source vertex // into the path and // print the path path.Add(0); for (int i = 0; i < path.Count; i++) { Console.Write(path[i] + \" \"); } Console.WriteLine(); // Remove the source // vertex added path.RemoveAt(path.Count - 1); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (int v = 0; v < graph.GetLength(0); v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.Add(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.RemoveAt(path.Count - 1); } } } static void Main() { /* Input Graph: (0) - - -- (2) | \\ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ int[,] graph = { { 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 1 }, { 1, 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1 }, { 1, 1, 0, 0, 1, 0 }, }; hamCycle(graph); }} // This code is contributed by suresh07.", "e": 16329, "s": 12568, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to check if a vertex v // can be added at index pos in // the Hamiltonian Cycle function isSafe(v, graph, path, pos) { // If the vertex is adjacent to // the vertex of the previously // added vertex if (graph[path[pos - 1]][v] == 0) return false; // If the vertex has already // been included in the path for (let i = 0; i < pos; i++) if (path[i] == v) return false; // Both the above conditions are // not true, return true return true; } // To check if there exists // at least 1 hamiltonian cycle let hasCycle; // Function to find all possible // hamiltonian cycles function hamCycle(graph) { // Initially value of boolean // flag is false hasCycle = false; // Store the resultant path let path = []; path.push(0); // Keeps the track of the // visited vertices let visited = new Array(graph.length); for (let i = 0; i < visited.length; i++) visited[i] = false; visited[0] = true; // Function call to find all // hamiltonian cycles FindHamCycle(graph, 1, path, visited); if (!hasCycle) { // If no Hamiltonian Cycle // is possible for the // given graph document.write(\"No Hamiltonian Cycle\" + \"possible \"); return; } } // Recursive function to find all // hamiltonian cycles function FindHamCycle(graph, pos, path, visited) { // If all vertices are included // in Hamiltonian Cycle if (pos == graph.length) { // If there is an edge // from the last vertex to // the source vertex if (graph[path[path.length - 1]][path[0]] != 0) { // Include source vertex // into the path and // print the path path.push(0); for (let i = 0; i < path.length; i++) { document.write(path[i] + \" \"); } document.write(\"</br>\"); // Remove the source // vertex added path.pop(); // Update the hasCycle // as true hasCycle = true; } return; } // Try different vertices // as the next vertex for (let v = 0; v < graph.length; v++) { // Check if this vertex can // be added to Cycle if (isSafe(v, graph, path, pos) && !visited[v]) { path.push(v); visited[v] = true; // Recur to construct // rest of the path FindHamCycle(graph, pos + 1, path, visited); // Remove current vertex // from path and process // other vertices visited[v] = false; path.pop(); } } } /* Input Graph: (0) - - -- (2) | \\ / | | (1) | | / | | | / | | (5)----(4)--(3)*/ let graph = [ [ 0, 1, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1 ], [ 1, 1, 0, 1, 0, 0 ], [ 0, 0, 1, 0, 1, 0 ], [ 0, 1, 0, 1, 0, 1 ], [ 1, 1, 0, 0, 1, 0 ], ]; hamCycle(graph); // This code is contributed by divyeshrabadiya07.</script>", "e": 19927, "s": 16329, "text": null }, { "code": null, "e": 20016, "s": 19927, "text": "0 1 2 3 4 5 0 \n0 1 5 4 3 2 0 \n0 2 3 4 1 5 0 \n0 2 3 4 5 1 0 \n0 5 1 4 3 2 0 \n0 5 4 3 2 1 0" }, { "code": null, "e": 20062, "s": 20018, "text": "Time Complexity: O(N!)Auxiliary Space: O(N)" }, { "code": null, "e": 20071, "s": 20062, "text": "suresh07" }, { "code": null, "e": 20089, "s": 20071, "text": "divyeshrabadiya07" }, { "code": null, "e": 20103, "s": 20089, "text": "divyesh072019" }, { "code": null, "e": 20118, "s": 20103, "text": "rameshtravel07" }, { "code": null, "e": 20135, "s": 20118, "text": "Graph Traversals" }, { "code": null, "e": 20154, "s": 20135, "text": "graph-connectivity" }, { "code": null, "e": 20166, "s": 20154, "text": "graph-cycle" }, { "code": null, "e": 20179, "s": 20166, "text": "Backtracking" }, { "code": null, "e": 20185, "s": 20179, "text": "Graph" }, { "code": null, "e": 20195, "s": 20185, "text": "Recursion" }, { "code": null, "e": 20205, "s": 20195, "text": "Recursion" }, { "code": null, "e": 20211, "s": 20205, "text": "Graph" }, { "code": null, "e": 20224, "s": 20211, "text": "Backtracking" }, { "code": null, "e": 20322, "s": 20224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20382, "s": 20322, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 20432, "s": 20382, "text": "Find shortest safe route in a path with landmines" }, { "code": null, "e": 20480, "s": 20432, "text": "Longest Possible Route in a Matrix with Hurdles" }, { "code": null, "e": 20541, "s": 20480, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 20591, "s": 20541, "text": "Top 20 Backtracking Algorithm Interview Questions" }, { "code": null, "e": 20631, "s": 20591, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 20669, "s": 20631, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 20720, "s": 20669, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 20771, "s": 20720, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
R - Normal Distribution
In a random collection of data from independent sources, it is generally observed that the distribution of data is normal. Which means, on plotting a graph with the value of the variable in the horizontal axis and the count of the values in the vertical axis we get a bell shape curve. The center of the curve represents the mean of the data set. In the graph, fifty percent of values lie to the left of the mean and the other fifty percent lie to the right of the graph. This is referred as normal distribution in statistics. R has four in built functions to generate normal distribution. They are described below. dnorm(x, mean, sd) pnorm(x, mean, sd) qnorm(p, mean, sd) rnorm(n, mean, sd) Following is the description of the parameters used in above functions − x is a vector of numbers. x is a vector of numbers. p is a vector of probabilities. p is a vector of probabilities. n is number of observations(sample size). n is number of observations(sample size). mean is the mean value of the sample data. It's default value is zero. mean is the mean value of the sample data. It's default value is zero. sd is the standard deviation. It's default value is 1. sd is the standard deviation. It's default value is 1. This function gives height of the probability distribution at each point for a given mean and standard deviation. # Create a sequence of numbers between -10 and 10 incrementing by 0.1. x <- seq(-10, 10, by = .1) # Choose the mean as 2.5 and standard deviation as 0.5. y <- dnorm(x, mean = 2.5, sd = 0.5) # Give the chart file a name. png(file = "dnorm.png") plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function gives the probability of a normally distributed random number to be less that the value of a given number. It is also called "Cumulative Distribution Function". # Create a sequence of numbers between -10 and 10 incrementing by 0.2. x <- seq(-10,10,by = .2) # Choose the mean as 2.5 and standard deviation as 2. y <- pnorm(x, mean = 2.5, sd = 2) # Give the chart file a name. png(file = "pnorm.png") # Plot the graph. plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function takes the probability value and gives a number whose cumulative value matches the probability value. # Create a sequence of probability values incrementing by 0.02. x <- seq(0, 1, by = 0.02) # Choose the mean as 2 and standard deviation as 3. y <- qnorm(x, mean = 2, sd = 1) # Give the chart file a name. png(file = "qnorm.png") # Plot the graph. plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function is used to generate random numbers whose distribution is normal. It takes the sample size as input and generates that many random numbers. We draw a histogram to show the distribution of the generated numbers. # Create a sample of 50 numbers which are normally distributed. y <- rnorm(50) # Give the chart file a name. png(file = "rnorm.png") # Plot the histogram for this sample. hist(y, main = "Normal DIstribution") # Save the file. dev.off() When we execute the above code, it produces the following result −
[ { "code": null, "e": 3063, "s": 2536, "text": "In a random collection of data from independent sources, it is generally observed that the distribution of data is normal. Which means, on plotting a graph with the value of the variable in the horizontal axis and the count of the values in the vertical axis we get a bell shape curve. The center of the curve represents the mean of the data set. In the graph, fifty percent of values lie to the left of the mean and the other fifty percent lie to the right of the graph. This is referred as normal distribution in statistics." }, { "code": null, "e": 3152, "s": 3063, "text": "R has four in built functions to generate normal distribution. They are described below." }, { "code": null, "e": 3229, "s": 3152, "text": "dnorm(x, mean, sd)\npnorm(x, mean, sd)\nqnorm(p, mean, sd)\nrnorm(n, mean, sd)\n" }, { "code": null, "e": 3302, "s": 3229, "text": "Following is the description of the parameters used in above functions −" }, { "code": null, "e": 3328, "s": 3302, "text": "x is a vector of numbers." }, { "code": null, "e": 3354, "s": 3328, "text": "x is a vector of numbers." }, { "code": null, "e": 3386, "s": 3354, "text": "p is a vector of probabilities." }, { "code": null, "e": 3418, "s": 3386, "text": "p is a vector of probabilities." }, { "code": null, "e": 3460, "s": 3418, "text": "n is number of observations(sample size)." }, { "code": null, "e": 3502, "s": 3460, "text": "n is number of observations(sample size)." }, { "code": null, "e": 3573, "s": 3502, "text": "mean is the mean value of the sample data. It's default value is zero." }, { "code": null, "e": 3644, "s": 3573, "text": "mean is the mean value of the sample data. It's default value is zero." }, { "code": null, "e": 3699, "s": 3644, "text": "sd is the standard deviation. It's default value is 1." }, { "code": null, "e": 3754, "s": 3699, "text": "sd is the standard deviation. It's default value is 1." }, { "code": null, "e": 3868, "s": 3754, "text": "This function gives height of the probability distribution at each point for a given mean and standard deviation." }, { "code": null, "e": 4153, "s": 3868, "text": "# Create a sequence of numbers between -10 and 10 incrementing by 0.1.\nx <- seq(-10, 10, by = .1)\n\n# Choose the mean as 2.5 and standard deviation as 0.5.\ny <- dnorm(x, mean = 2.5, sd = 0.5)\n\n# Give the chart file a name.\npng(file = \"dnorm.png\")\n\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 4220, "s": 4153, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 4395, "s": 4220, "text": "This function gives the probability of a normally distributed random number to be less that the value of a given number. It is also called \"Cumulative Distribution Function\"." }, { "code": null, "e": 4694, "s": 4395, "text": "# Create a sequence of numbers between -10 and 10 incrementing by 0.2.\nx <- seq(-10,10,by = .2)\n \n# Choose the mean as 2.5 and standard deviation as 2. \ny <- pnorm(x, mean = 2.5, sd = 2)\n\n# Give the chart file a name.\npng(file = \"pnorm.png\")\n\n# Plot the graph.\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 4761, "s": 4694, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 4876, "s": 4761, "text": "This function takes the probability value and gives a number whose cumulative value matches the probability value." }, { "code": null, "e": 5163, "s": 4876, "text": "# Create a sequence of probability values incrementing by 0.02.\nx <- seq(0, 1, by = 0.02)\n\n# Choose the mean as 2 and standard deviation as 3.\ny <- qnorm(x, mean = 2, sd = 1)\n\n# Give the chart file a name.\npng(file = \"qnorm.png\")\n\n# Plot the graph.\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 5230, "s": 5163, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5454, "s": 5230, "text": "This function is used to generate random numbers whose distribution is normal. It takes the sample size as input and generates that many random numbers. We draw a histogram to show the distribution of the generated numbers." }, { "code": null, "e": 5693, "s": 5454, "text": "# Create a sample of 50 numbers which are normally distributed.\ny <- rnorm(50)\n\n# Give the chart file a name.\npng(file = \"rnorm.png\")\n\n# Plot the histogram for this sample.\nhist(y, main = \"Normal DIstribution\")\n\n# Save the file.\ndev.off()" } ]
Method overloading and null error in Java
18 Apr, 2022 In Java it is very common to overload methods. Below is an interesting Java program. Java public class Test{ // Overloaded methods public void fun(Integer i) { System.out.println("fun(Integer ) "); } public void fun(String name) { System.out.println("fun(String ) "); } // Driver code public static void main(String [] args) { Test mv = new Test(); // This line causes error mv.fun(null); }} Output : 22: error: reference to fun is ambiguous mv.fun(null); ^ both method fun(Integer) in Test and method fun(String) in Test match 1 error The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding. Java public class Test{ // Overloaded methods public void fun(Integer i) { System.out.println("fun(Integer ) "); } public void fun(String name) { System.out.println("fun(String ) "); } // Driver code public static void main(String [] args) { Test mv = new Test(); Integer arg = null; // No compiler error mv.fun(arg); }} Output : fun(Integer ) In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that. Note: This problem wouldn’t persist when the overridden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it. This article is contributed by Nageswara Rao Maridu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. imeenalgrover simmytarika5 Java-Overloading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Apr, 2022" }, { "code": null, "e": 138, "s": 52, "text": "In Java it is very common to overload methods. Below is an interesting Java program. " }, { "code": null, "e": 143, "s": 138, "text": "Java" }, { "code": "public class Test{ // Overloaded methods public void fun(Integer i) { System.out.println(\"fun(Integer ) \"); } public void fun(String name) { System.out.println(\"fun(String ) \"); } // Driver code public static void main(String [] args) { Test mv = new Test(); // This line causes error mv.fun(null); }}", "e": 515, "s": 143, "text": null }, { "code": null, "e": 524, "s": 515, "text": "Output :" }, { "code": null, "e": 679, "s": 524, "text": "22: error: reference to fun is ambiguous\n mv.fun(null);\n ^\n both method fun(Integer) in Test and method fun(String) in Test match\n1 error" }, { "code": null, "e": 1158, "s": 679, "text": "The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding. " }, { "code": null, "e": 1163, "s": 1158, "text": "Java" }, { "code": "public class Test{ // Overloaded methods public void fun(Integer i) { System.out.println(\"fun(Integer ) \"); } public void fun(String name) { System.out.println(\"fun(String ) \"); } // Driver code public static void main(String [] args) { Test mv = new Test(); Integer arg = null; // No compiler error mv.fun(arg); }}", "e": 1565, "s": 1163, "text": null }, { "code": null, "e": 1574, "s": 1565, "text": "Output :" }, { "code": null, "e": 1589, "s": 1574, "text": "fun(Integer ) " }, { "code": null, "e": 2512, "s": 1589, "text": "In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that. Note: This problem wouldn’t persist when the overridden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it. This article is contributed by Nageswara Rao Maridu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2526, "s": 2512, "text": "imeenalgrover" }, { "code": null, "e": 2539, "s": 2526, "text": "simmytarika5" }, { "code": null, "e": 2556, "s": 2539, "text": "Java-Overloading" }, { "code": null, "e": 2561, "s": 2556, "text": "Java" }, { "code": null, "e": 2566, "s": 2561, "text": "Java" }, { "code": null, "e": 2664, "s": 2566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2679, "s": 2664, "text": "Arrays in Java" }, { "code": null, "e": 2723, "s": 2679, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2759, "s": 2723, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2784, "s": 2759, "text": "Reverse a string in Java" }, { "code": null, "e": 2835, "s": 2784, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2857, "s": 2835, "text": "For-each loop in Java" }, { "code": null, "e": 2888, "s": 2857, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2907, "s": 2888, "text": "Interfaces in Java" }, { "code": null, "e": 2937, "s": 2907, "text": "HashMap in Java with Examples" } ]
mkdir() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <sys/stat.h> #include <sys/types.h> int mkdir(const char *pathname, mode_t mode); int mkdir(const char *pathname, mode_t mode); The parameter mode specifies the permissions to use. It is modified by the process’s umask in the usual way: the permissions of the created directory are (mode & ~umask & 0777). Other mode bits of the created directory depend on the operating system. For Linux, see below. The newly created directory will be owned by the effective user ID of the process. If the directory containing the file has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics, the new directory will inherit the group ownership from its parent; otherwise it will be owned by the effective group ID of the process. If the parent directory has the set-group-ID bit set then so will the newly created directory. There are many infelicities in the protocol underlying NFS. Some of these affect mkdir(). mkdir (1) mkdir (1) chmod (2) chmod (2) mkdirat (2) mkdirat (2) mknod (2) mknod (2) mount (2) mount (2) path_resolution (2) path_resolution (2) rmdir (2) rmdir (2) stat (2) stat (2) umask (2) umask (2) unlink (2) unlink (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2415, "s": 2319, "text": "#include <sys/stat.h> \n#include <sys/types.h> \n\nint mkdir(const char *pathname, mode_t mode); \n" }, { "code": null, "e": 2464, "s": 2415, "text": "\nint mkdir(const char *pathname, mode_t mode); \n" }, { "code": null, "e": 2739, "s": 2464, "text": "\nThe parameter\nmode specifies the permissions to use. It is modified by the process’s\numask in the usual way: the permissions of the created directory are\n(mode & ~umask & 0777). Other mode bits of the created directory depend on the operating system.\nFor Linux, see below.\n" }, { "code": null, "e": 3087, "s": 2739, "text": "\nThe newly created directory will be owned by the effective user ID of the\nprocess. If the directory containing the file has the set-group-ID\nbit set, or if the filesystem is mounted with BSD group semantics, the\nnew directory will inherit the group ownership from its parent;\notherwise it will be owned by the effective group ID of the process.\n" }, { "code": null, "e": 3184, "s": 3087, "text": "\nIf the parent directory has the set-group-ID bit set then so will the\nnewly created directory.\n" }, { "code": null, "e": 3279, "s": 3186, "text": "\nThere are many infelicities in the protocol underlying NFS. Some\nof these affect\nmkdir(). " }, { "code": null, "e": 3289, "s": 3279, "text": "mkdir (1)" }, { "code": null, "e": 3299, "s": 3289, "text": "mkdir (1)" }, { "code": null, "e": 3309, "s": 3299, "text": "chmod (2)" }, { "code": null, "e": 3319, "s": 3309, "text": "chmod (2)" }, { "code": null, "e": 3331, "s": 3319, "text": "mkdirat (2)" }, { "code": null, "e": 3343, "s": 3331, "text": "mkdirat (2)" }, { "code": null, "e": 3353, "s": 3343, "text": "mknod (2)" }, { "code": null, "e": 3363, "s": 3353, "text": "mknod (2)" }, { "code": null, "e": 3373, "s": 3363, "text": "mount (2)" }, { "code": null, "e": 3383, "s": 3373, "text": "mount (2)" }, { "code": null, "e": 3403, "s": 3383, "text": "path_resolution (2)" }, { "code": null, "e": 3423, "s": 3403, "text": "path_resolution (2)" }, { "code": null, "e": 3433, "s": 3423, "text": "rmdir (2)" }, { "code": null, "e": 3443, "s": 3433, "text": "rmdir (2)" }, { "code": null, "e": 3452, "s": 3443, "text": "stat (2)" }, { "code": null, "e": 3461, "s": 3452, "text": "stat (2)" }, { "code": null, "e": 3471, "s": 3461, "text": "umask (2)" }, { "code": null, "e": 3481, "s": 3471, "text": "umask (2)" }, { "code": null, "e": 3492, "s": 3481, "text": "unlink (2)" }, { "code": null, "e": 3503, "s": 3492, "text": "unlink (2)" }, { "code": null, "e": 3520, "s": 3503, "text": "\nAdvertisements\n" }, { "code": null, "e": 3555, "s": 3520, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3583, "s": 3555, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3617, "s": 3583, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3634, "s": 3617, "text": " Frahaan Hussain" }, { "code": null, "e": 3667, "s": 3634, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3678, "s": 3667, "text": " Pradeep D" }, { "code": null, "e": 3713, "s": 3678, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3729, "s": 3713, "text": " Musab Zayadneh" }, { "code": null, "e": 3762, "s": 3729, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 3774, "s": 3762, "text": " GUHARAJANM" }, { "code": null, "e": 3806, "s": 3774, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 3814, "s": 3806, "text": " Uplatz" }, { "code": null, "e": 3821, "s": 3814, "text": " Print" }, { "code": null, "e": 3832, "s": 3821, "text": " Add Notes" } ]
Java Program for Radix Sort
Radix sort is a sorting technique that sorts the elements based on every digit in every element (or number). Based on the ones place digit (which is also known as least significant digit) and tens place digit (which is also known as most significant digit), hundreds place digit, and so on, the elements are sorted. Following is an example for Radix Sort in Java − Live Demo import java.util.*; public class my_radix_sorting { static int get_max_val(int my_arr[], int arr_len) { int max_val = my_arr[0]; for (int i = 1; i < arr_len; i++) if (my_arr[i] > max_val) max_val = my_arr[i]; return max_val; } static void countSort(int my_arr[], int arr_len, int exp) { int result[] = new int[arr_len]; int i; int count[] = new int[10]; Arrays.fill(count,0); for (i = 0; i < arr_len; i++) count[ (my_arr[i]/exp)%10 ]++; for (i = 1; i < 10; i++) count[i] += count[i - 1]; for (i = arr_len - 1; i >= 0; i--) { result[count[ (my_arr[i]/exp)%10 ] - 1] = my_arr[i]; count[ (my_arr[i]/exp)%10 ]--; } for (i = 0; i < arr_len; i++) my_arr[i] = result[i]; } static void radix_sort(int my_arr[], int arr_len) { int m = get_max_val(my_arr, arr_len); for (int exp = 1; m/exp > 0; exp *= 10) countSort(my_arr, arr_len, exp); } public static void main (String[] args) { int my_arr[] = {56, 78, 102, 345, 67, 90, 102, 45, 78}; int arr_len = my_arr.length; System.out.println("The array after performing radix sort is "); radix_sort(my_arr, arr_len); for (int i=0; i<arr_len; i++) System.out.print(my_arr[i]+" "); } } The array after performing radix sort is 45 56 67 78 78 90 102 102 345 In radix sort, every element is sorted based on its digit, wherein the least significant digit in every element is sorted first, and the most significant digit is sorted in the end. It uses counting sort as a sub-function to perform its sorting functions. Given an array of elements, the first step is that the elements are sorted based on the least significant place’s digit, i.e ones place. Next the elements in the array are sorted based on tens place digits. Then, the elements are sorted based on hundreds place digit and so on. This is done with the help of ‘get_max_val’ function. In the main function, the array is defined, and the array is passed as a parameter to the ‘radix_sort’ function.
[ { "code": null, "e": 1378, "s": 1062, "text": "Radix sort is a sorting technique that sorts the elements based on every digit in every element (or number). Based on the ones place digit (which is also known as least significant digit) and tens place digit (which is also known as most significant digit), hundreds place digit, and so on, the elements are sorted." }, { "code": null, "e": 1427, "s": 1378, "text": "Following is an example for Radix Sort in Java −" }, { "code": null, "e": 1438, "s": 1427, "text": " Live Demo" }, { "code": null, "e": 2770, "s": 1438, "text": "import java.util.*;\npublic class my_radix_sorting {\n static int get_max_val(int my_arr[], int arr_len) {\n int max_val = my_arr[0];\n for (int i = 1; i < arr_len; i++)\n if (my_arr[i] > max_val)\n max_val = my_arr[i];\n return max_val;\n }\n static void countSort(int my_arr[], int arr_len, int exp) {\n int result[] = new int[arr_len];\n int i;\n int count[] = new int[10];\n Arrays.fill(count,0);\n for (i = 0; i < arr_len; i++)\n count[ (my_arr[i]/exp)%10 ]++;\n for (i = 1; i < 10; i++)\n count[i] += count[i - 1];\n for (i = arr_len - 1; i >= 0; i--) {\n result[count[ (my_arr[i]/exp)%10 ] - 1] = my_arr[i];\n count[ (my_arr[i]/exp)%10 ]--;\n }\n for (i = 0; i < arr_len; i++)\n my_arr[i] = result[i];\n }\n static void radix_sort(int my_arr[], int arr_len) {\n int m = get_max_val(my_arr, arr_len);\n for (int exp = 1; m/exp > 0; exp *= 10)\n countSort(my_arr, arr_len, exp);\n }\n public static void main (String[] args) {\n int my_arr[] = {56, 78, 102, 345, 67, 90, 102, 45, 78};\n int arr_len = my_arr.length;\n System.out.println(\"The array after performing radix sort is \");\n radix_sort(my_arr, arr_len);\n for (int i=0; i<arr_len; i++)\n System.out.print(my_arr[i]+\" \");\n }\n}" }, { "code": null, "e": 2841, "s": 2770, "text": "The array after performing radix sort is\n45 56 67 78 78 90 102 102 345" }, { "code": null, "e": 3097, "s": 2841, "text": "In radix sort, every element is sorted based on its digit, wherein the least significant digit in every element is sorted first, and the most significant digit is sorted in the end. It uses counting sort as a sub-function to perform its sorting functions." }, { "code": null, "e": 3542, "s": 3097, "text": "Given an array of elements, the first step is that the elements are sorted based on the least significant place’s digit, i.e ones place. Next the elements in the array are sorted based on tens place digits. Then, the elements are sorted based on hundreds place digit and so on. This is done with the help of ‘get_max_val’ function. In the main function, the array is defined, and the array is passed as a parameter to the ‘radix_sort’ function." } ]
Find smallest and largest element from square matrix diagonals - GeeksforGeeks
11 Sep, 2021 Given a square matrix of order n*n, find the smallest and largest elements from both diagonals of the given matrix. Examples: Input : matrix = { {1, 2, 3, 4, -10}, {5, 6, 7, 8, 6}, {1, 2, 11, 3, 4}, {5, 6, 70, 5, 8}, {4, 9, 7, 1, 5}}; Output : Principal Diagonal Smallest Element: 1 Principal Diagonal Greatest Element :11 Secondary Diagonal Smallest Element: -10 Secondary Diagonal Greatest Element: 11 The idea behind solving this problem is, First check traverse matrix and reach all diagonals elements (for principle diagonal i == j and secondary diagonal i+j = size_of_matrix-1) and compare diagonal element with min and max variable and take new min and max values. and same thing for secondary diagonals. Here is implementation of above approach: Example 1: With O(n^2) Complexity: C++ Java Python3 C# PHP Javascript // CPP program to find smallest and// largest elements of both diagonals#include<bits/stdc++.h>using namespace std; // Function to find smallest and largest element// from principal and secondary diagonalvoid diagonalsMinMax(int mat[5][5]){ // take length of matrix int n = sizeof(*mat) / 4; if (n == 0) return; // declare and initialize variables // with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } cout << ("Principal Diagonal Smallest Element: ") << principalMin << endl; cout << ("Principal Diagonal Greatest Element : ") << principalMax << endl; cout << ("Secondary Diagonal Smallest Element: ") << secondaryMin << endl; cout << ("Secondary Diagonal Greatest Element: ") << secondaryMax << endl;} // Driver codeint main(){ // Declare and initialize 5X5 matrix int matrix[5][5] = {{ 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 }}; diagonalsMinMax(matrix);} // This code is contributed by// Shashank_Sharma // Java program to find// smallest and largest elements of both diagonals public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[][] mat) { // take length of matrix int n = mat.length; if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } System.out.println("Principal Diagonal Smallest Element: " + principalMin); System.out.println("Principal Diagonal Greatest Element : " + principalMax); System.out.println("Secondary Diagonal Smallest Element: " + secondaryMin); System.out.println("Secondary Diagonal Greatest Element: " + secondaryMax); } // Driver code static public void main(String[] args) { // Declare and initialize 5X5 matrix int[][] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }} # Python3 program to find smallest and# largest elements of both diagonals # Function to find smallest and largest element# from principal and secondary diagonaldef diagonalsMinMax(mat): # take length of matrix n = len(mat) if (n == 0): return # declare and initialize variables # with appropriate value principalMin = mat[0][0] principalMax = mat[0][0] secondaryMin = mat[0][n-1] secondaryMax = mat[0][n-1] for i in range(1, n): for j in range(1, n): # Condition for principal # diagonal if (i == j): # take new smallest value if (mat[i][j] < principalMin): principalMin = mat[i][j] # take new largest value if (mat[i][j] > principalMax): principalMax = mat[i][j] # Condition for secondary # diagonal if ((i + j) == (n - 1)): # take new smallest value if (mat[i][j] < secondaryMin): secondaryMin = mat[i][j] # take new largest value if (mat[i][j] > secondaryMax): secondaryMax = mat[i][j] print("Principal Diagonal Smallest Element: ", principalMin) print("Principal Diagonal Greatest Element : ", principalMax) print("Secondary Diagonal Smallest Element: ", secondaryMin) print("Secondary Diagonal Greatest Element: ", secondaryMax) # Driver code # Declare and initialize 5X5 matrixmatrix = [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]]diagonalsMinMax(matrix) # This code is contributed by Mohit kumar 29 // C# program to find smallest and largest// elements of both diagonalsusing System; public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[,] mat) { // take length of square matrix int n = mat.GetLength(0); if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0,0], principalMax = mat[0,0]; int secondaryMin = mat[n-1,0], secondaryMax = mat[n-1,0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i,j] < principalMin) { principalMin = mat[i,j]; } // take new largest value if (mat[i,j] > principalMax) { principalMax = mat[i,j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i,j] < secondaryMin) { secondaryMin = mat[i,j]; } // take new largest value if (mat[i,j] > secondaryMax) { secondaryMax = mat[i,j]; } } } } Console.WriteLine("Principal Diagonal Smallest Element: " + principalMin); Console.WriteLine("Principal Diagonal Greatest Element : " + principalMax); Console.WriteLine("Secondary Diagonal Smallest Element: " + secondaryMin); Console.WriteLine("Secondary Diagonal Greatest Element: " + secondaryMax); } // Driver code static void Main() { // Declare and initialize 5X5 matrix int[,] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); } // This code is contributed by Ryuga} <?php// PHP program to find smallest and// largest elements of both diagonals // Function to find smallest and largest element// from principal and secondary diagonalfunction diagonalsMinMax($mat){ // take length of $matrix $n = count($mat); if ($n == 0) return; // declare and initialize variables // with appropriate value $principalMin = $mat[0][0]; $principalMax = $mat[0][0]; $secondaryMin = $mat[$n - 1][0]; $secondaryMax = $mat[$n - 1][0]; for ($i = 1; $i < $n; $i++) { for ($j = 1; $j < $n; $j++) { // Condition for principal // diagonal if ($i == $j) { // take new smallest value if ($mat[$i][$j] < $principalMin) { $principalMin = $mat[$i][$j]; } // take new largest value if ($mat[$i][$j] > $principalMax) { $principalMax = $mat[$i][$j]; } } // Condition for secondary // diagonal if (($i + $j) == ($n - 1)) { // take new smallest value if ($mat[$i][$j] < $secondaryMin) { $secondaryMin = $mat[$i][$j]; } // take new largest value if ($mat[$i][$j] > $secondaryMax) { $secondaryMax = $mat[$i][$j]; } } } } echo "Principal Diagonal Smallest Element: ", $principalMin, "\n"; echo "Principal Diagonal Greatest Element : ", $principalMax, "\n"; echo "Secondary Diagonal Smallest Element: ", $secondaryMin, "\n"; echo "Secondary Diagonal Greatest Element: ", $secondaryMax, "\n";} // Driver code // Declare and initialize 5X5 matrix$matrix = array(array ( 1, 2, 3, 4, -10 ), array ( 5, 6, 7, 8, 6 ), array ( 1, 2, 11, 3, 4 ), array ( 5, 6, 70, 5, 8 ), array ( 4, 9, 7, 1, -5 ));diagonalsMinMax($matrix); // This code is contributed by// ihritik?> <script>// Javascript program to find smallest and// largest elements of both diagonals // Function to find smallest and largest element// from principal and secondary diagonalfunction diagonalsMinMax(mat){ // take length of matrix let n = mat.length; if (n == 0) return; // declare and initialize variables // with appropriate value let principalMin = mat[0][0], principalMax = mat[0][0]; let secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (let i = 1; i < n; i++) { for (let j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } document.write("Principal Diagonal Smallest Element: " + principalMin + "<br>"); document.write("Principal Diagonal Greatest Element : " + principalMax + "<br>"); document.write("Secondary Diagonal Smallest Element: " + secondaryMin + "<br>"); document.write("Secondary Diagonal Greatest Element: " + secondaryMax + "<br>");} // Driver code // Declare and initialize 5X5 matrix let matrix = [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]]; diagonalsMinMax(matrix); // This code is contributed by subham348.</script> Principal Diagonal Smallest Element: -5 Principal Diagonal Greatest Element : 11 Secondary Diagonal Smallest Element: 4 Secondary Diagonal Greatest Element: 11 Example 2: With O(n) Complexity: C++ Java Python C# Javascript // C++ program to find// smallest and largest elements of both diagonals#include<bits/stdc++.h>using namespace std; const int n = 5; // Function to find smallest and largest element// from principal and secondary diagonalvoid diagonalsMinMax(int mat [n][n]){ // take length of matrix if (n == 0) return; // declare and initialize variables // with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } cout << "Principal Diagonal Smallest Element: " << principalMin << "\n"; cout << "Principal Diagonal Greatest Element : " << principalMax << "\n"; cout << "Secondary Diagonal Smallest Element: " << secondaryMin << "\n"; cout << "Secondary Diagonal Greatest Element: " << secondaryMax;} // Driver codeint main(){ // Declare and initialize 5X5 matrix int matrix [n][n] = {{ 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 }}; diagonalsMinMax(matrix);} // This code is contributed by ihritik // Java program to find// smallest and largest elements of both diagonals public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[][] mat) { // take length of matrix int n = mat.length; if (n == 0) return; // declare and initialism variables with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } System.out.println("Principal Diagonal Smallest Element: " + principalMin); System.out.println("Principal Diagonal Greatest Element : " + principalMax); System.out.println("Secondary Diagonal Smallest Element: " + secondaryMin); System.out.println("Secondary Diagonal Greatest Element: " + secondaryMax); } // Driver code static public void main(String[] args) { // Declare and initialize 5X5 matrix int[][] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }} # Python3 program to find smallest and# largest elements of both diagonals n = 5 # Function to find smallest and largest element# from principal and secondary diagonaldef diagonalsMinMax(mat): # take length of matrix if (n == 0): return # declare and initialize variables # with appropriate value principalMin = mat[0][0] principalMax = mat[0][0] secondaryMin = mat[n - 1][0] secondaryMax = mat[n - 1][0] for i in range(n): # Condition for principal # diagonal mat[i][i] # take new smallest value if (mat[i][i] < principalMin): principalMin = mat[i][i] # take new largest value if (mat[i][i] > principalMax): principalMax = mat[i][i] # Condition for secondary # diagonal is mat[n-1-i][i] # take new smallest value if (mat[n - 1 - i][i] < secondaryMin): secondaryMin = mat[n - 1 - i][i] # take new largest value if (mat[n - 1 - i][i] > secondaryMax): secondaryMax = mat[n - 1 - i][i] print("Principal Diagonal Smallest Element: ",principalMin) print("Principal Diagonal Greatest Element : ",principalMax) print("Secondary Diagonal Smallest Element: ",secondaryMin) print("Secondary Diagonal Greatest Element: ",secondaryMax) # Driver code # Declare and initialize 5X5 matrixmatrix= [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]] diagonalsMinMax(matrix) # This code is contributed by mohit kumar 29 // C# program to find smallest and largest// elements of both diagonalsusing System; public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[,] mat) { // take length of square matrix int n = mat.GetLength(0); if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0,0], principalMax = mat[0,0]; int secondaryMin = mat[n-1,0], secondaryMax = mat[n-1,0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i,i] < principalMin) { principalMin = mat[i,i]; } // take new largest value if (mat[i,i] > principalMax) { principalMax = mat[i,i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i,i] < secondaryMin) { secondaryMin = mat[n - 1 - i,i]; } // take new largest value if (mat[n - 1 - i,i] > secondaryMax) { secondaryMax = mat[n - 1 - i,i]; } } Console.WriteLine("Principal Diagonal Smallest Element: " + principalMin); Console.WriteLine("Principal Diagonal Greatest Element : " + principalMax); Console.WriteLine("Secondary Diagonal Smallest Element: " + secondaryMin); Console.WriteLine("Secondary Diagonal Greatest Element: " + secondaryMax); } // Driver code public static void Main() { // Declare and initialize 5X5 matrix int[,] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }} /*This code is contributed by 29AjayKumar*/ <script> // JavaScript program to find// smallest and largest elements// of both diagonals // Function to find smallest // and largest element from // principal and secondary diagonal function diagonalsMinMax(mat) { // take length of matrix let n = mat.length; if (n == 0) return; // declare and initialism variables // with appropriate value let principalMin = mat[0][0], principalMax = mat[0][0]; let secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (let i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } document.write("Principal Diagonal Smallest Element: " + principalMin+"<br>"); document.write("Principal Diagonal Greatest Element : " + principalMax+"<br>"); document.write("Secondary Diagonal Smallest Element: " + secondaryMin+"<br>"); document.write("Secondary Diagonal Greatest Element: " + secondaryMax+"<br>"); } // Driver code // Declare and initialize 5X5 matrix let matrix = [ [ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ] ]; diagonalsMinMax(matrix); // This code is contributed by sravan kumar </script> Principal Diagonal Smallest Element: -5 Principal Diagonal Greatest Element : 11 Secondary Diagonal Smallest Element: -10 Secondary Diagonal Greatest Element: 11 ankthon 29AjayKumar Shashank_Sharma mohit kumar 29 ihritik user_n13p subham348 sravankumar8128 surinderdawra388 Technical Scripter 2018 Java Programs Matrix Searching Technical Scripter Searching Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Iterate through List in Java Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Java program to count the occurrence of each character in a string using Hashmap Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
[ { "code": null, "e": 24904, "s": 24876, "text": "\n11 Sep, 2021" }, { "code": null, "e": 25021, "s": 24904, "text": "Given a square matrix of order n*n, find the smallest and largest elements from both diagonals of the given matrix. " }, { "code": null, "e": 25032, "s": 25021, "text": "Examples: " }, { "code": null, "e": 25371, "s": 25032, "text": "Input : matrix = {\n {1, 2, 3, 4, -10},\n {5, 6, 7, 8, 6},\n {1, 2, 11, 3, 4},\n {5, 6, 70, 5, 8},\n {4, 9, 7, 1, 5}};\nOutput :\nPrincipal Diagonal Smallest Element: 1\nPrincipal Diagonal Greatest Element :11\nSecondary Diagonal Smallest Element: -10\nSecondary Diagonal Greatest Element: 11" }, { "code": null, "e": 25679, "s": 25371, "text": "The idea behind solving this problem is, First check traverse matrix and reach all diagonals elements (for principle diagonal i == j and secondary diagonal i+j = size_of_matrix-1) and compare diagonal element with min and max variable and take new min and max values. and same thing for secondary diagonals." }, { "code": null, "e": 25722, "s": 25679, "text": "Here is implementation of above approach: " }, { "code": null, "e": 25759, "s": 25722, "text": "Example 1: With O(n^2) Complexity: " }, { "code": null, "e": 25763, "s": 25759, "text": "C++" }, { "code": null, "e": 25768, "s": 25763, "text": "Java" }, { "code": null, "e": 25776, "s": 25768, "text": "Python3" }, { "code": null, "e": 25779, "s": 25776, "text": "C#" }, { "code": null, "e": 25783, "s": 25779, "text": "PHP" }, { "code": null, "e": 25794, "s": 25783, "text": "Javascript" }, { "code": "// CPP program to find smallest and// largest elements of both diagonals#include<bits/stdc++.h>using namespace std; // Function to find smallest and largest element// from principal and secondary diagonalvoid diagonalsMinMax(int mat[5][5]){ // take length of matrix int n = sizeof(*mat) / 4; if (n == 0) return; // declare and initialize variables // with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } cout << (\"Principal Diagonal Smallest Element: \") << principalMin << endl; cout << (\"Principal Diagonal Greatest Element : \") << principalMax << endl; cout << (\"Secondary Diagonal Smallest Element: \") << secondaryMin << endl; cout << (\"Secondary Diagonal Greatest Element: \") << secondaryMax << endl;} // Driver codeint main(){ // Declare and initialize 5X5 matrix int matrix[5][5] = {{ 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 }}; diagonalsMinMax(matrix);} // This code is contributed by// Shashank_Sharma", "e": 28030, "s": 25794, "text": null }, { "code": "// Java program to find// smallest and largest elements of both diagonals public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[][] mat) { // take length of matrix int n = mat.length; if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } System.out.println(\"Principal Diagonal Smallest Element: \" + principalMin); System.out.println(\"Principal Diagonal Greatest Element : \" + principalMax); System.out.println(\"Secondary Diagonal Smallest Element: \" + secondaryMin); System.out.println(\"Secondary Diagonal Greatest Element: \" + secondaryMax); } // Driver code static public void main(String[] args) { // Declare and initialize 5X5 matrix int[][] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }}", "e": 30361, "s": 28030, "text": null }, { "code": "# Python3 program to find smallest and# largest elements of both diagonals # Function to find smallest and largest element# from principal and secondary diagonaldef diagonalsMinMax(mat): # take length of matrix n = len(mat) if (n == 0): return # declare and initialize variables # with appropriate value principalMin = mat[0][0] principalMax = mat[0][0] secondaryMin = mat[0][n-1] secondaryMax = mat[0][n-1] for i in range(1, n): for j in range(1, n): # Condition for principal # diagonal if (i == j): # take new smallest value if (mat[i][j] < principalMin): principalMin = mat[i][j] # take new largest value if (mat[i][j] > principalMax): principalMax = mat[i][j] # Condition for secondary # diagonal if ((i + j) == (n - 1)): # take new smallest value if (mat[i][j] < secondaryMin): secondaryMin = mat[i][j] # take new largest value if (mat[i][j] > secondaryMax): secondaryMax = mat[i][j] print(\"Principal Diagonal Smallest Element: \", principalMin) print(\"Principal Diagonal Greatest Element : \", principalMax) print(\"Secondary Diagonal Smallest Element: \", secondaryMin) print(\"Secondary Diagonal Greatest Element: \", secondaryMax) # Driver code # Declare and initialize 5X5 matrixmatrix = [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]]diagonalsMinMax(matrix) # This code is contributed by Mohit kumar 29", "e": 32402, "s": 30361, "text": null }, { "code": "// C# program to find smallest and largest// elements of both diagonalsusing System; public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[,] mat) { // take length of square matrix int n = mat.GetLength(0); if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0,0], principalMax = mat[0,0]; int secondaryMin = mat[n-1,0], secondaryMax = mat[n-1,0]; for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i,j] < principalMin) { principalMin = mat[i,j]; } // take new largest value if (mat[i,j] > principalMax) { principalMax = mat[i,j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i,j] < secondaryMin) { secondaryMin = mat[i,j]; } // take new largest value if (mat[i,j] > secondaryMax) { secondaryMax = mat[i,j]; } } } } Console.WriteLine(\"Principal Diagonal Smallest Element: \" + principalMin); Console.WriteLine(\"Principal Diagonal Greatest Element : \" + principalMax); Console.WriteLine(\"Secondary Diagonal Smallest Element: \" + secondaryMin); Console.WriteLine(\"Secondary Diagonal Greatest Element: \" + secondaryMax); } // Driver code static void Main() { // Declare and initialize 5X5 matrix int[,] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); } // This code is contributed by Ryuga}", "e": 34744, "s": 32402, "text": null }, { "code": "<?php// PHP program to find smallest and// largest elements of both diagonals // Function to find smallest and largest element// from principal and secondary diagonalfunction diagonalsMinMax($mat){ // take length of $matrix $n = count($mat); if ($n == 0) return; // declare and initialize variables // with appropriate value $principalMin = $mat[0][0]; $principalMax = $mat[0][0]; $secondaryMin = $mat[$n - 1][0]; $secondaryMax = $mat[$n - 1][0]; for ($i = 1; $i < $n; $i++) { for ($j = 1; $j < $n; $j++) { // Condition for principal // diagonal if ($i == $j) { // take new smallest value if ($mat[$i][$j] < $principalMin) { $principalMin = $mat[$i][$j]; } // take new largest value if ($mat[$i][$j] > $principalMax) { $principalMax = $mat[$i][$j]; } } // Condition for secondary // diagonal if (($i + $j) == ($n - 1)) { // take new smallest value if ($mat[$i][$j] < $secondaryMin) { $secondaryMin = $mat[$i][$j]; } // take new largest value if ($mat[$i][$j] > $secondaryMax) { $secondaryMax = $mat[$i][$j]; } } } } echo \"Principal Diagonal Smallest Element: \", $principalMin, \"\\n\"; echo \"Principal Diagonal Greatest Element : \", $principalMax, \"\\n\"; echo \"Secondary Diagonal Smallest Element: \", $secondaryMin, \"\\n\"; echo \"Secondary Diagonal Greatest Element: \", $secondaryMax, \"\\n\";} // Driver code // Declare and initialize 5X5 matrix$matrix = array(array ( 1, 2, 3, 4, -10 ), array ( 5, 6, 7, 8, 6 ), array ( 1, 2, 11, 3, 4 ), array ( 5, 6, 70, 5, 8 ), array ( 4, 9, 7, 1, -5 ));diagonalsMinMax($matrix); // This code is contributed by// ihritik?>", "e": 36981, "s": 34744, "text": null }, { "code": "<script>// Javascript program to find smallest and// largest elements of both diagonals // Function to find smallest and largest element// from principal and secondary diagonalfunction diagonalsMinMax(mat){ // take length of matrix let n = mat.length; if (n == 0) return; // declare and initialize variables // with appropriate value let principalMin = mat[0][0], principalMax = mat[0][0]; let secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (let i = 1; i < n; i++) { for (let j = 1; j < n; j++) { // Condition for principal // diagonal if (i == j) { // take new smallest value if (mat[i][j] < principalMin) { principalMin = mat[i][j]; } // take new largest value if (mat[i][j] > principalMax) { principalMax = mat[i][j]; } } // Condition for secondary // diagonal if ((i + j) == (n - 1)) { // take new smallest value if (mat[i][j] < secondaryMin) { secondaryMin = mat[i][j]; } // take new largest value if (mat[i][j] > secondaryMax) { secondaryMax = mat[i][j]; } } } } document.write(\"Principal Diagonal Smallest Element: \" + principalMin + \"<br>\"); document.write(\"Principal Diagonal Greatest Element : \" + principalMax + \"<br>\"); document.write(\"Secondary Diagonal Smallest Element: \" + secondaryMin + \"<br>\"); document.write(\"Secondary Diagonal Greatest Element: \" + secondaryMax + \"<br>\");} // Driver code // Declare and initialize 5X5 matrix let matrix = [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]]; diagonalsMinMax(matrix); // This code is contributed by subham348.</script>", "e": 39185, "s": 36981, "text": null }, { "code": null, "e": 39346, "s": 39185, "text": "Principal Diagonal Smallest Element: -5\nPrincipal Diagonal Greatest Element : 11\nSecondary Diagonal Smallest Element: 4\nSecondary Diagonal Greatest Element: 11" }, { "code": null, "e": 39382, "s": 39348, "text": "Example 2: With O(n) Complexity: " }, { "code": null, "e": 39386, "s": 39382, "text": "C++" }, { "code": null, "e": 39391, "s": 39386, "text": "Java" }, { "code": null, "e": 39398, "s": 39391, "text": "Python" }, { "code": null, "e": 39401, "s": 39398, "text": "C#" }, { "code": null, "e": 39412, "s": 39401, "text": "Javascript" }, { "code": "// C++ program to find// smallest and largest elements of both diagonals#include<bits/stdc++.h>using namespace std; const int n = 5; // Function to find smallest and largest element// from principal and secondary diagonalvoid diagonalsMinMax(int mat [n][n]){ // take length of matrix if (n == 0) return; // declare and initialize variables // with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n - 1][0], secondaryMax = mat[n - 1][0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } cout << \"Principal Diagonal Smallest Element: \" << principalMin << \"\\n\"; cout << \"Principal Diagonal Greatest Element : \" << principalMax << \"\\n\"; cout << \"Secondary Diagonal Smallest Element: \" << secondaryMin << \"\\n\"; cout << \"Secondary Diagonal Greatest Element: \" << secondaryMax;} // Driver codeint main(){ // Declare and initialize 5X5 matrix int matrix [n][n] = {{ 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 }}; diagonalsMinMax(matrix);} // This code is contributed by ihritik", "e": 41356, "s": 39412, "text": null }, { "code": "// Java program to find// smallest and largest elements of both diagonals public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[][] mat) { // take length of matrix int n = mat.length; if (n == 0) return; // declare and initialism variables with appropriate value int principalMin = mat[0][0], principalMax = mat[0][0]; int secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } System.out.println(\"Principal Diagonal Smallest Element: \" + principalMin); System.out.println(\"Principal Diagonal Greatest Element : \" + principalMax); System.out.println(\"Secondary Diagonal Smallest Element: \" + secondaryMin); System.out.println(\"Secondary Diagonal Greatest Element: \" + secondaryMax); } // Driver code static public void main(String[] args) { // Declare and initialize 5X5 matrix int[][] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }}", "e": 43441, "s": 41356, "text": null }, { "code": "# Python3 program to find smallest and# largest elements of both diagonals n = 5 # Function to find smallest and largest element# from principal and secondary diagonaldef diagonalsMinMax(mat): # take length of matrix if (n == 0): return # declare and initialize variables # with appropriate value principalMin = mat[0][0] principalMax = mat[0][0] secondaryMin = mat[n - 1][0] secondaryMax = mat[n - 1][0] for i in range(n): # Condition for principal # diagonal mat[i][i] # take new smallest value if (mat[i][i] < principalMin): principalMin = mat[i][i] # take new largest value if (mat[i][i] > principalMax): principalMax = mat[i][i] # Condition for secondary # diagonal is mat[n-1-i][i] # take new smallest value if (mat[n - 1 - i][i] < secondaryMin): secondaryMin = mat[n - 1 - i][i] # take new largest value if (mat[n - 1 - i][i] > secondaryMax): secondaryMax = mat[n - 1 - i][i] print(\"Principal Diagonal Smallest Element: \",principalMin) print(\"Principal Diagonal Greatest Element : \",principalMax) print(\"Secondary Diagonal Smallest Element: \",secondaryMin) print(\"Secondary Diagonal Greatest Element: \",secondaryMax) # Driver code # Declare and initialize 5X5 matrixmatrix= [[ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ]] diagonalsMinMax(matrix) # This code is contributed by mohit kumar 29", "e": 45008, "s": 43441, "text": null }, { "code": "// C# program to find smallest and largest// elements of both diagonalsusing System; public class GFG { // Function to find smallest and largest element from // principal and secondary diagonal static void diagonalsMinMax(int[,] mat) { // take length of square matrix int n = mat.GetLength(0); if (n == 0) return; // declare and initialize variables with appropriate value int principalMin = mat[0,0], principalMax = mat[0,0]; int secondaryMin = mat[n-1,0], secondaryMax = mat[n-1,0]; for (int i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i,i] < principalMin) { principalMin = mat[i,i]; } // take new largest value if (mat[i,i] > principalMax) { principalMax = mat[i,i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i,i] < secondaryMin) { secondaryMin = mat[n - 1 - i,i]; } // take new largest value if (mat[n - 1 - i,i] > secondaryMax) { secondaryMax = mat[n - 1 - i,i]; } } Console.WriteLine(\"Principal Diagonal Smallest Element: \" + principalMin); Console.WriteLine(\"Principal Diagonal Greatest Element : \" + principalMax); Console.WriteLine(\"Secondary Diagonal Smallest Element: \" + secondaryMin); Console.WriteLine(\"Secondary Diagonal Greatest Element: \" + secondaryMax); } // Driver code public static void Main() { // Declare and initialize 5X5 matrix int[,] matrix = { { 1, 2, 3, 4, -10 }, { 5, 6, 7, 8, 6 }, { 1, 2, 11, 3, 4 }, { 5, 6, 70, 5, 8 }, { 4, 9, 7, 1, -5 } }; diagonalsMinMax(matrix); }} /*This code is contributed by 29AjayKumar*/", "e": 47129, "s": 45008, "text": null }, { "code": "<script> // JavaScript program to find// smallest and largest elements// of both diagonals // Function to find smallest // and largest element from // principal and secondary diagonal function diagonalsMinMax(mat) { // take length of matrix let n = mat.length; if (n == 0) return; // declare and initialism variables // with appropriate value let principalMin = mat[0][0], principalMax = mat[0][0]; let secondaryMin = mat[n-1][0], secondaryMax = mat[n-1][0]; for (let i = 0; i < n; i++) { // Condition for principal // diagonal mat[i][i] // take new smallest value if (mat[i][i] < principalMin) { principalMin = mat[i][i]; } // take new largest value if (mat[i][i] > principalMax) { principalMax = mat[i][i]; } // Condition for secondary // diagonal is mat[n-1-i][i] // take new smallest value if (mat[n - 1 - i][i] < secondaryMin) { secondaryMin = mat[n - 1 - i][i]; } // take new largest value if (mat[n - 1 - i][i] > secondaryMax) { secondaryMax = mat[n - 1 - i][i]; } } document.write(\"Principal Diagonal Smallest Element: \" + principalMin+\"<br>\"); document.write(\"Principal Diagonal Greatest Element : \" + principalMax+\"<br>\"); document.write(\"Secondary Diagonal Smallest Element: \" + secondaryMin+\"<br>\"); document.write(\"Secondary Diagonal Greatest Element: \" + secondaryMax+\"<br>\"); } // Driver code // Declare and initialize 5X5 matrix let matrix = [ [ 1, 2, 3, 4, -10 ], [ 5, 6, 7, 8, 6 ], [ 1, 2, 11, 3, 4 ], [ 5, 6, 70, 5, 8 ], [ 4, 9, 7, 1, -5 ] ]; diagonalsMinMax(matrix); // This code is contributed by sravan kumar </script>", "e": 49238, "s": 47129, "text": null }, { "code": null, "e": 49401, "s": 49238, "text": "Principal Diagonal Smallest Element: -5\nPrincipal Diagonal Greatest Element : 11\nSecondary Diagonal Smallest Element: -10\nSecondary Diagonal Greatest Element: 11" }, { "code": null, "e": 49411, "s": 49403, "text": "ankthon" }, { "code": null, "e": 49423, "s": 49411, "text": "29AjayKumar" }, { "code": null, "e": 49439, "s": 49423, "text": "Shashank_Sharma" }, { "code": null, "e": 49454, "s": 49439, "text": "mohit kumar 29" }, { "code": null, "e": 49462, "s": 49454, "text": "ihritik" }, { "code": null, "e": 49472, "s": 49462, "text": "user_n13p" }, { "code": null, "e": 49482, "s": 49472, "text": "subham348" }, { "code": null, "e": 49498, "s": 49482, "text": "sravankumar8128" }, { "code": null, "e": 49515, "s": 49498, "text": "surinderdawra388" }, { "code": null, "e": 49539, "s": 49515, "text": "Technical Scripter 2018" }, { "code": null, "e": 49553, "s": 49539, "text": "Java Programs" }, { "code": null, "e": 49560, "s": 49553, "text": "Matrix" }, { "code": null, "e": 49570, "s": 49560, "text": "Searching" }, { "code": null, "e": 49589, "s": 49570, "text": "Technical Scripter" }, { "code": null, "e": 49599, "s": 49589, "text": "Searching" }, { "code": null, "e": 49606, "s": 49599, "text": "Matrix" }, { "code": null, "e": 49704, "s": 49606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49736, "s": 49704, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 49765, "s": 49736, "text": "Iterate through List in Java" }, { "code": null, "e": 49803, "s": 49765, "text": "Factory method design pattern in Java" }, { "code": null, "e": 49860, "s": 49803, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 49941, "s": 49860, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 49976, "s": 49941, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 50020, "s": 49976, "text": "Program to find largest element in an array" }, { "code": null, "e": 50051, "s": 50020, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 50075, "s": 50051, "text": "Sudoku | Backtracking-7" } ]
COBOL - String Handling
String handling statements in COBOL are used to do multiple functional operations on strings. Following are the string handling statements − Inspect String Unstring Inspect verb is used to count or replace the characters in a string. String operations can be performed on alphanumeric, numeric, or alphabetic values. Inspect operations are performed from left to right. The options used for the string operations are as follows − Tallying option is used to count the string characters. Syntax Following is the syntax of Tallying option − INSPECT input-string TALLYING output-count FOR ALL CHARACTERS The parameters used are − input-string − The string whose characters are to be counted. output-count − Data item to hold the count of characters. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-CNT1 PIC 9(2) VALUE 0. 01 WS-CNT2 PIC 9(2) VALUE 0. 01 WS-STRING PIC X(15) VALUE 'ABCDACDADEAAAFF'. PROCEDURE DIVISION. INSPECT WS-STRING TALLYING WS-CNT1 FOR CHARACTER. DISPLAY "WS-CNT1 : "WS-CNT1. INSPECT WS-STRING TALLYING WS-CNT2 FOR ALL 'A'. DISPLAY "WS-CNT2 : "WS-CNT2 STOP RUN. JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-CNT1 : 15 WS-CNT2 : 06 Replacing option is used to replace the string characters. Syntax Following is the syntax of Replacing option − INSPECT input-string REPLACING ALL char1 BY char2. The parameter used is − input-string − The string whose characters are to be replaced from char1 to char2. input-string − The string whose characters are to be replaced from char1 to char2. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STRING PIC X(15) VALUE 'ABCDACDADEAAAFF'. PROCEDURE DIVISION. DISPLAY "OLD STRING : "WS-STRING. INSPECT WS-STRING REPLACING ALL 'A' BY 'X'. DISPLAY "NEW STRING : "WS-STRING. STOP RUN. JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − OLD STRING : ABCDACDADEAAAFF NEW STRING : XBCDXCDXDEXXXFF String verb is used to concatenate the strings. Using STRING statement, two or more strings of characters can be combined to form a longer string. ‘Delimited By’ clause is compulsory. Syntax Following is the syntax of String verb − STRING ws-string1 DELIMITED BY SPACE ws-string2 DELIMITED BY SIZE INTO ws-destination-string WITH POINTER ws-count ON OVERFLOW DISPLAY message1 NOT ON OVERFLOW DISPLAY message2 END-STRING. Following are the details of the used parameters − ws-string1 and ws-string2 : Input strings to be concatenated ws-string : Output string ws-count : Used to count the length of new concatenated string Delimited specifies the end of string Pointer and Overflow are optional Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STRING PIC A(30). 01 WS-STR1 PIC A(15) VALUE 'Tutorialspoint'. 01 WS-STR2 PIC A(7) VALUE 'Welcome'. 01 WS-STR3 PIC A(7) VALUE 'To AND'. 01 WS-COUNT PIC 99 VALUE 1. PROCEDURE DIVISION. STRING WS-STR2 DELIMITED BY SIZE WS-STR3 DELIMITED BY SPACE WS-STR1 DELIMITED BY SIZE INTO WS-STRING WITH POINTER WS-COUNT ON OVERFLOW DISPLAY 'OVERFLOW!' END-STRING. DISPLAY 'WS-STRING : 'WS-STRING. DISPLAY 'WS-COUNT : 'WS-COUNT. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-STRING : WelcomeToTutorialspoint WS-COUNT : 25 Unstring verb is used to split one string into multiple sub-strings. Delimited By clause is compulsory. Syntax Following is the syntax of Unstring verb − UNSTRING ws-string DELIMITED BY SPACE INTO ws-str1, ws-str2 WITH POINTER ws-count ON OVERFLOW DISPLAY message NOT ON OVERFLOW DISPLAY message END-UNSTRING. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STRING PIC A(30) VALUE 'WELCOME TO TUTORIALSPOINT'. 01 WS-STR1 PIC A(7). 01 WS-STR2 PIC A(2). 01 WS-STR3 PIC A(15). 01 WS-COUNT PIC 99 VALUE 1. PROCEDURE DIVISION. UNSTRING WS-STRING DELIMITED BY SPACE INTO WS-STR1, WS-STR2, WS-STR3 END-UNSTRING. DISPLAY 'WS-STR1 : 'WS-STR1. DISPLAY 'WS-STR2 : 'WS-STR2. DISPLAY 'WS-STR3 : 'WS-STR3. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-STR1 : WELCOME WS-STR2 : TO WS-STR3 : TUTORIALSPOINT 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2163, "s": 2022, "text": "String handling statements in COBOL are used to do multiple functional operations on strings. Following are the string handling statements −" }, { "code": null, "e": 2171, "s": 2163, "text": "Inspect" }, { "code": null, "e": 2178, "s": 2171, "text": "String" }, { "code": null, "e": 2187, "s": 2178, "text": "Unstring" }, { "code": null, "e": 2452, "s": 2187, "text": "Inspect verb is used to count or replace the characters in a string. String operations can be performed on alphanumeric, numeric, or alphabetic values. Inspect operations are performed from left to right. The options used for the string operations are as follows −" }, { "code": null, "e": 2508, "s": 2452, "text": "Tallying option is used to count the string characters." }, { "code": null, "e": 2515, "s": 2508, "text": "Syntax" }, { "code": null, "e": 2560, "s": 2515, "text": "Following is the syntax of Tallying option −" }, { "code": null, "e": 2623, "s": 2560, "text": "INSPECT input-string\nTALLYING output-count FOR ALL CHARACTERS\n" }, { "code": null, "e": 2649, "s": 2623, "text": "The parameters used are −" }, { "code": null, "e": 2711, "s": 2649, "text": "input-string − The string whose characters are to be counted." }, { "code": null, "e": 2769, "s": 2711, "text": "output-count − Data item to hold the count of characters." }, { "code": null, "e": 2777, "s": 2769, "text": "Example" }, { "code": null, "e": 3185, "s": 2777, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-CNT1 PIC 9(2) VALUE 0.\n 01 WS-CNT2 PIC 9(2) VALUE 0.\n 01 WS-STRING PIC X(15) VALUE 'ABCDACDADEAAAFF'.\n \nPROCEDURE DIVISION.\n INSPECT WS-STRING TALLYING WS-CNT1 FOR CHARACTER.\n DISPLAY \"WS-CNT1 : \"WS-CNT1.\n INSPECT WS-STRING TALLYING WS-CNT2 FOR ALL 'A'.\n DISPLAY \"WS-CNT2 : \"WS-CNT2\n \nSTOP RUN." }, { "code": null, "e": 3225, "s": 3185, "text": "JCL to execute the above COBOL program." }, { "code": null, "e": 3302, "s": 3225, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 3385, "s": 3302, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 3412, "s": 3385, "text": "WS-CNT1 : 15\nWS-CNT2 : 06\n" }, { "code": null, "e": 3471, "s": 3412, "text": "Replacing option is used to replace the string characters." }, { "code": null, "e": 3478, "s": 3471, "text": "Syntax" }, { "code": null, "e": 3524, "s": 3478, "text": "Following is the syntax of Replacing option −" }, { "code": null, "e": 3576, "s": 3524, "text": "INSPECT input-string REPLACING ALL char1 BY char2.\n" }, { "code": null, "e": 3600, "s": 3576, "text": "The parameter used is −" }, { "code": null, "e": 3683, "s": 3600, "text": "input-string − The string whose characters are to be replaced from char1 to char2." }, { "code": null, "e": 3766, "s": 3683, "text": "input-string − The string whose characters are to be replaced from char1 to char2." }, { "code": null, "e": 3774, "s": 3766, "text": "Example" }, { "code": null, "e": 4069, "s": 3774, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STRING PIC X(15) VALUE 'ABCDACDADEAAAFF'.\n\nPROCEDURE DIVISION.\n DISPLAY \"OLD STRING : \"WS-STRING.\n INSPECT WS-STRING REPLACING ALL 'A' BY 'X'.\n DISPLAY \"NEW STRING : \"WS-STRING.\n \nSTOP RUN." }, { "code": null, "e": 4109, "s": 4069, "text": "JCL to execute the above COBOL program." }, { "code": null, "e": 4186, "s": 4109, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 4269, "s": 4186, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 4328, "s": 4269, "text": "OLD STRING : ABCDACDADEAAAFF\nNEW STRING : XBCDXCDXDEXXXFF\n" }, { "code": null, "e": 4512, "s": 4328, "text": "String verb is used to concatenate the strings. Using STRING statement, two or more strings of characters can be combined to form a longer string. ‘Delimited By’ clause is compulsory." }, { "code": null, "e": 4519, "s": 4512, "text": "Syntax" }, { "code": null, "e": 4560, "s": 4519, "text": "Following is the syntax of String verb −" }, { "code": null, "e": 4764, "s": 4560, "text": "STRING ws-string1 DELIMITED BY SPACE\n ws-string2 DELIMITED BY SIZE\n INTO ws-destination-string\n WITH POINTER ws-count\n ON OVERFLOW DISPLAY message1\n NOT ON OVERFLOW DISPLAY message2\nEND-STRING." }, { "code": null, "e": 4815, "s": 4764, "text": "Following are the details of the used parameters −" }, { "code": null, "e": 4876, "s": 4815, "text": "ws-string1 and ws-string2 : Input strings to be concatenated" }, { "code": null, "e": 4902, "s": 4876, "text": "ws-string : Output string" }, { "code": null, "e": 4965, "s": 4902, "text": "ws-count : Used to count the length of new concatenated string" }, { "code": null, "e": 5003, "s": 4965, "text": "Delimited specifies the end of string" }, { "code": null, "e": 5037, "s": 5003, "text": "Pointer and Overflow are optional" }, { "code": null, "e": 5045, "s": 5037, "text": "Example" }, { "code": null, "e": 5629, "s": 5045, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STRING PIC A(30).\n 01 WS-STR1 PIC A(15) VALUE 'Tutorialspoint'.\n 01 WS-STR2 PIC A(7) VALUE 'Welcome'.\n 01 WS-STR3 PIC A(7) VALUE 'To AND'.\n 01 WS-COUNT PIC 99 VALUE 1.\n\nPROCEDURE DIVISION.\n STRING WS-STR2 DELIMITED BY SIZE\n WS-STR3 DELIMITED BY SPACE\n WS-STR1 DELIMITED BY SIZE\n INTO WS-STRING \n WITH POINTER WS-COUNT\n ON OVERFLOW DISPLAY 'OVERFLOW!' \n END-STRING.\n \n DISPLAY 'WS-STRING : 'WS-STRING.\n DISPLAY 'WS-COUNT : 'WS-COUNT.\n\nSTOP RUN." }, { "code": null, "e": 5670, "s": 5629, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 5747, "s": 5670, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 5830, "s": 5747, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5888, "s": 5830, "text": "WS-STRING : WelcomeToTutorialspoint \nWS-COUNT : 25\n" }, { "code": null, "e": 5992, "s": 5888, "text": "Unstring verb is used to split one string into multiple sub-strings. Delimited By clause is compulsory." }, { "code": null, "e": 5999, "s": 5992, "text": "Syntax" }, { "code": null, "e": 6042, "s": 5999, "text": "Following is the syntax of Unstring verb −" }, { "code": null, "e": 6198, "s": 6042, "text": "UNSTRING ws-string DELIMITED BY SPACE\nINTO ws-str1, ws-str2\nWITH POINTER ws-count\nON OVERFLOW DISPLAY message\nNOT ON OVERFLOW DISPLAY message\nEND-UNSTRING." }, { "code": null, "e": 6206, "s": 6198, "text": "Example" }, { "code": null, "e": 6689, "s": 6206, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STRING PIC A(30) VALUE 'WELCOME TO TUTORIALSPOINT'.\n 01 WS-STR1 PIC A(7).\n 01 WS-STR2 PIC A(2).\n 01 WS-STR3 PIC A(15).\n 01 WS-COUNT PIC 99 VALUE 1.\n\nPROCEDURE DIVISION.\n UNSTRING WS-STRING DELIMITED BY SPACE\n INTO WS-STR1, WS-STR2, WS-STR3\n END-UNSTRING.\n \n DISPLAY 'WS-STR1 : 'WS-STR1.\n DISPLAY 'WS-STR2 : 'WS-STR2.\n DISPLAY 'WS-STR3 : 'WS-STR3.\n \nSTOP RUN." }, { "code": null, "e": 6730, "s": 6689, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 6807, "s": 6730, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 6890, "s": 6807, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6948, "s": 6890, "text": "WS-STR1 : WELCOME\nWS-STR2 : TO\nWS-STR3 : TUTORIALSPOINT \n" }, { "code": null, "e": 6983, "s": 6948, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6998, "s": 6983, "text": " Nishant Malik" }, { "code": null, "e": 7033, "s": 6998, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7057, "s": 7033, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 7064, "s": 7057, "text": " Print" }, { "code": null, "e": 7075, "s": 7064, "text": " Add Notes" } ]
Can Enum implements an interface in Java?
Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version. The Enums are constants, by default they are static and final so the names of an enum type fields are in uppercase letters. interface EnumInterface { int calculate(int first, int second); } enum EnumClassOperator implements EnumInterface { // An Enum implements an interface ADD { @Override public int calculate(int first, int second) { return first + second; } }, SUBTRACT { @Override public int calculate(int first, int second) { return first - second; } }; } class Operation { private int first, second; private EnumClassOperator operator; public Operation(int first, int second, EnumClassOperator operator) { this.first = first; this.second = second; this.operator = operator; } public int calculate() { return operator.calculate(first, second); } } // Main Class public class EnumTest { public static void main (String [] args) { Operation add = new Operation(20, 10, EnumClassOperator.ADD); Operation subtract = new Operation(20, 10, EnumClassOperator.SUBTRACT); System.out.println("Addition: " + add.calculate()); System.out.println("Subtraction: " + subtract.calculate()); } } Addition: 30 Subtraction: 10
[ { "code": null, "e": 1441, "s": 1062, "text": "Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version. The Enums are constants, by default they are static and final so the names of an enum type fields are in uppercase letters." }, { "code": null, "e": 2543, "s": 1441, "text": "interface EnumInterface {\n int calculate(int first, int second);\n}\nenum EnumClassOperator implements EnumInterface { // An Enum implements an interface\n ADD {\n @Override\n public int calculate(int first, int second) {\n return first + second;\n }\n },\n SUBTRACT {\n @Override\n public int calculate(int first, int second) {\n return first - second;\n }\n };\n}\nclass Operation {\n private int first, second;\n private EnumClassOperator operator;\n public Operation(int first, int second, EnumClassOperator operator) {\n this.first = first;\n this.second = second;\n this.operator = operator;\n }\n public int calculate() {\n return operator.calculate(first, second);\n }\n}\n// Main Class\npublic class EnumTest {\n public static void main (String [] args) {\n Operation add = new Operation(20, 10, EnumClassOperator.ADD);\n Operation subtract = new Operation(20, 10, EnumClassOperator.SUBTRACT);\n System.out.println(\"Addition: \" + add.calculate());\n System.out.println(\"Subtraction: \" + subtract.calculate());\n }\n}" }, { "code": null, "e": 2572, "s": 2543, "text": "Addition: 30\nSubtraction: 10" } ]
Count the number of non-reachable nodes - GeeksforGeeks
09 Mar, 2022 Given an undirected graph and a set of vertices, we have to count the number of non-reachable nodes from the given head node using a depth-first search. Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes. Hence their count is 2. Example: Input : 5 0 1 0 2 1 2 3 4 Output : 2 We can either use BFS or DFS for this purpose. In the below implementation, DFS is used. We do DFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in DFS. In DFS, if we start from the head node it will mark all the nodes connected to the head node as visited. Then after traversing the graph, we count the number of nodes that are not marked as visited from the head node. C++ Java Python3 C# Javascript // C++ program to count non-reachable nodes// from a given source using DFS.#include <iostream>#include <list>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph { int V; // No. of vertices // Pointer to an array containing // adjacency lists list<int>* adj; // A recursive function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v int countNotReach(int v);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Add v to w's list.} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int Graph::countNotReach(int v){ // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for (int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} int main(){ // Create a graph given in the above diagram Graph g(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); cout << g.countNotReach(2); return 0;} // Java program to count non-reachable nodes// from a given source using DFS.import java.util.*; // Graph class represents a directed graph// using adjacency list representation@SuppressWarnings("unchecked")class Graph{ // No. of vertices public int V; // Pointer to an array containing// adjacency listspublic ArrayList []adj; public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} void addEdge(int v, int w){ // add w to v’s list. adj[v].add(w); // add v to w's list. adj[w].add(v);} void DFSUtil(int v, boolean []visited){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex for(int i : (ArrayList<Integer>)adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int countNotReach(int v){ // Mark all the vertices as not visited boolean []visited = new boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for(int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} // Driver Codepublic static void main(String []args){ // Create a graph given in the above diagram Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); System.out.print(g.countNotReach(2));}} // This code is contributed by Pratham76 # Python3 program to count non-reachable# nodes from a given source using DFS. # Graph class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, v, w): self.adj[v].append(w) # Add w to v’s list. self.adj[w].append(v) # Add v to w's list. def DFSUtil(self, v, visited): # Mark the current node as # visited and print it visited[v] = True # Recur for all the vertices # adjacent to this vertex i = self.adj[v][0] for i in self.adj[v]: if (not visited[i]): self.DFSUtil(i, visited) # Returns count of not reachable # nodes from vertex v. # It uses recursive DFSUtil() def countNotReach(self, v): # Mark all the vertices as not visited visited = [False] * self.V # Call the recursive helper # function to print DFS traversal self.DFSUtil(v, visited) # Return count of not visited nodes count = 0 for i in range(self.V): if (visited[i] == False): count += 1 return count # Driver Codeif __name__ == '__main__': # Create a graph given in the # above diagram g = Graph(8) g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(3, 4) g.addEdge(4, 5) g.addEdge(6, 7) print(g.countNotReach(2)) # This code is contributed by PranchalK // C# program to count non-reachable nodes// from a given source using DFS.using System;using System.Collections;using System.Collections.Generic; // Graph class represents a directed graph// using adjacency list representationclass Graph{ // No. of vertices public int V; // Pointer to an array containing// adjacency listspublic ArrayList []adj; public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} void addEdge(int v, int w){ // Add w to v’s list. adj[v].Add(w); // Add v to w's list. adj[w].Add(v);} void DFSUtil(int v, bool []visited){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex foreach(int i in (ArrayList)adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int countNotReach(int v){ // Mark all the vertices as not visited bool []visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for(int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} // Driver Codestatic void Main(string []args){ // Create a graph given in the above diagram Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); Console.Write(g.countNotReach(2));}} // This code is contributed by rutvik_56 <script> // Javascript program to count non-reachable nodes // from a given source using DFS. // Graph class represents a directed graph // using adjacency list representation let V = 8; let adj = []; for(let i = 0; i < V; i++) { adj.push([]); } function addEdge(v, w) { // Add w to v’s list. adj[v].push(w); // Add v to w's list. adj[w].push(v); } function DFSUtil(v, visited) { // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex for(let i = 0; i < adj[v].length; i++) { if (!visited[adj[v][i]]) DFSUtil(adj[v][i], visited); } } // Returns count of not reachable nodes from // vertex v. // It uses recursive DFSUtil() function countNotReach(v) { // Mark all the vertices as not visited let visited = new Array(V); for(let i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes let count = 0; for(let i = 0; i < V; i++) { if (visited[i] == false) count++; } return count; } // Create a graph given in the above diagram addEdge(0, 1); addEdge(0, 2); addEdge(1, 2); addEdge(3, 4); addEdge(4, 5); addEdge(6, 7); document.write(countNotReach(2)); // This code is contributed by suresh07.</script> Output: 5 YouTubeGeeksforGeeks500K subscribersCount the number of non-reachable nodes | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=54avWHVxDwg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> PranchalKatiyar Akanksha_Rai niteshkumarrai1234 rutvik_56 pratham76 suresh07 simmytarika5 DFS graph-connectivity Graph DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Best First Search (Informed Search) Longest Path in a Directed Acyclic Graph Graph Coloring | Set 2 (Greedy Algorithm) Snake and Ladder Problem Find if there is a path between two vertices in a directed graph Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Tree, Back, Edge and Cross Edges in DFS of Graph Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS) Check if a given graph is tree or not Real-time application of Data Structures
[ { "code": null, "e": 24699, "s": 24671, "text": "\n09 Mar, 2022" }, { "code": null, "e": 24852, "s": 24699, "text": "Given an undirected graph and a set of vertices, we have to count the number of non-reachable nodes from the given head node using a depth-first search." }, { "code": null, "e": 24918, "s": 24852, "text": "Consider below undirected graph with two disconnected components:" }, { "code": null, "e": 25165, "s": 24918, "text": "In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes. Hence their count is 2." }, { "code": null, "e": 25176, "s": 25165, "text": "Example: " }, { "code": null, "e": 25255, "s": 25176, "text": "Input : 5\n 0 1\n 0 2\n 1 2\n 3 4\nOutput : 2" }, { "code": null, "e": 25827, "s": 25255, "text": "We can either use BFS or DFS for this purpose. In the below implementation, DFS is used. We do DFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in DFS. In DFS, if we start from the head node it will mark all the nodes connected to the head node as visited. Then after traversing the graph, we count the number of nodes that are not marked as visited from the head node." }, { "code": null, "e": 25831, "s": 25827, "text": "C++" }, { "code": null, "e": 25836, "s": 25831, "text": "Java" }, { "code": null, "e": 25844, "s": 25836, "text": "Python3" }, { "code": null, "e": 25847, "s": 25844, "text": "C#" }, { "code": null, "e": 25858, "s": 25847, "text": "Javascript" }, { "code": "// C++ program to count non-reachable nodes// from a given source using DFS.#include <iostream>#include <list>using namespace std; // Graph class represents a directed graph// using adjacency list representationclass Graph { int V; // No. of vertices // Pointer to an array containing // adjacency lists list<int>* adj; // A recursive function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v int countNotReach(int v);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Add v to w's list.} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int Graph::countNotReach(int v){ // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for (int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} int main(){ // Create a graph given in the above diagram Graph g(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); cout << g.countNotReach(2); return 0;}", "e": 27747, "s": 25858, "text": null }, { "code": "// Java program to count non-reachable nodes// from a given source using DFS.import java.util.*; // Graph class represents a directed graph// using adjacency list representation@SuppressWarnings(\"unchecked\")class Graph{ // No. of vertices public int V; // Pointer to an array containing// adjacency listspublic ArrayList []adj; public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} void addEdge(int v, int w){ // add w to v’s list. adj[v].add(w); // add v to w's list. adj[w].add(v);} void DFSUtil(int v, boolean []visited){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex for(int i : (ArrayList<Integer>)adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int countNotReach(int v){ // Mark all the vertices as not visited boolean []visited = new boolean[V]; for(int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for(int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} // Driver Codepublic static void main(String []args){ // Create a graph given in the above diagram Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); System.out.print(g.countNotReach(2));}} // This code is contributed by Pratham76", "e": 29534, "s": 27747, "text": null }, { "code": "# Python3 program to count non-reachable# nodes from a given source using DFS. # Graph class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, v, w): self.adj[v].append(w) # Add w to v’s list. self.adj[w].append(v) # Add v to w's list. def DFSUtil(self, v, visited): # Mark the current node as # visited and print it visited[v] = True # Recur for all the vertices # adjacent to this vertex i = self.adj[v][0] for i in self.adj[v]: if (not visited[i]): self.DFSUtil(i, visited) # Returns count of not reachable # nodes from vertex v. # It uses recursive DFSUtil() def countNotReach(self, v): # Mark all the vertices as not visited visited = [False] * self.V # Call the recursive helper # function to print DFS traversal self.DFSUtil(v, visited) # Return count of not visited nodes count = 0 for i in range(self.V): if (visited[i] == False): count += 1 return count # Driver Codeif __name__ == '__main__': # Create a graph given in the # above diagram g = Graph(8) g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(1, 2) g.addEdge(3, 4) g.addEdge(4, 5) g.addEdge(6, 7) print(g.countNotReach(2)) # This code is contributed by PranchalK", "e": 31061, "s": 29534, "text": null }, { "code": "// C# program to count non-reachable nodes// from a given source using DFS.using System;using System.Collections;using System.Collections.Generic; // Graph class represents a directed graph// using adjacency list representationclass Graph{ // No. of vertices public int V; // Pointer to an array containing// adjacency listspublic ArrayList []adj; public Graph(int V){ this.V = V; adj = new ArrayList[V]; for(int i = 0; i < V; i++) { adj[i] = new ArrayList(); }} void addEdge(int v, int w){ // Add w to v’s list. adj[v].Add(w); // Add v to w's list. adj[w].Add(v);} void DFSUtil(int v, bool []visited){ // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex foreach(int i in (ArrayList)adj[v]) { if (!visited[i]) DFSUtil(i, visited); }} // Returns count of not reachable nodes from// vertex v.// It uses recursive DFSUtil()int countNotReach(int v){ // Mark all the vertices as not visited bool []visited = new bool[V]; for(int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes int count = 0; for(int i = 0; i < V; i++) { if (visited[i] == false) count++; } return count;} // Driver Codestatic void Main(string []args){ // Create a graph given in the above diagram Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(6, 7); Console.Write(g.countNotReach(2));}} // This code is contributed by rutvik_56", "e": 32827, "s": 31061, "text": null }, { "code": "<script> // Javascript program to count non-reachable nodes // from a given source using DFS. // Graph class represents a directed graph // using adjacency list representation let V = 8; let adj = []; for(let i = 0; i < V; i++) { adj.push([]); } function addEdge(v, w) { // Add w to v’s list. adj[v].push(w); // Add v to w's list. adj[w].push(v); } function DFSUtil(v, visited) { // Mark the current node as visited and // print it visited[v] = true; // Recur for all the vertices adjacent // to this vertex for(let i = 0; i < adj[v].length; i++) { if (!visited[adj[v][i]]) DFSUtil(adj[v][i], visited); } } // Returns count of not reachable nodes from // vertex v. // It uses recursive DFSUtil() function countNotReach(v) { // Mark all the vertices as not visited let visited = new Array(V); for(let i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function // to print DFS traversal DFSUtil(v, visited); // Return count of not visited nodes let count = 0; for(let i = 0; i < V; i++) { if (visited[i] == false) count++; } return count; } // Create a graph given in the above diagram addEdge(0, 1); addEdge(0, 2); addEdge(1, 2); addEdge(3, 4); addEdge(4, 5); addEdge(6, 7); document.write(countNotReach(2)); // This code is contributed by suresh07.</script>", "e": 34462, "s": 32827, "text": null }, { "code": null, "e": 34472, "s": 34462, "text": "Output: " }, { "code": null, "e": 34475, "s": 34472, "text": " 5" }, { "code": null, "e": 35315, "s": 34477, "text": "YouTubeGeeksforGeeks500K subscribersCount the number of non-reachable nodes | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=54avWHVxDwg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35333, "s": 35317, "text": "PranchalKatiyar" }, { "code": null, "e": 35346, "s": 35333, "text": "Akanksha_Rai" }, { "code": null, "e": 35365, "s": 35346, "text": "niteshkumarrai1234" }, { "code": null, "e": 35375, "s": 35365, "text": "rutvik_56" }, { "code": null, "e": 35385, "s": 35375, "text": "pratham76" }, { "code": null, "e": 35394, "s": 35385, "text": "suresh07" }, { "code": null, "e": 35407, "s": 35394, "text": "simmytarika5" }, { "code": null, "e": 35411, "s": 35407, "text": "DFS" }, { "code": null, "e": 35430, "s": 35411, "text": "graph-connectivity" }, { "code": null, "e": 35436, "s": 35430, "text": "Graph" }, { "code": null, "e": 35440, "s": 35436, "text": "DFS" }, { "code": null, "e": 35446, "s": 35440, "text": "Graph" }, { "code": null, "e": 35544, "s": 35446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35553, "s": 35544, "text": "Comments" }, { "code": null, "e": 35566, "s": 35553, "text": "Old Comments" }, { "code": null, "e": 35602, "s": 35566, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 35643, "s": 35602, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 35685, "s": 35643, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 35710, "s": 35685, "text": "Snake and Ladder Problem" }, { "code": null, "e": 35775, "s": 35710, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 35845, "s": 35775, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 35894, "s": 35845, "text": "Tree, Back, Edge and Cross Edges in DFS of Graph" }, { "code": null, "e": 35975, "s": 35894, "text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)" }, { "code": null, "e": 36013, "s": 35975, "text": "Check if a given graph is tree or not" } ]
R Markdown Parameters | Drew Seewald | Towards Data Science
We’ve all been in a meeting where someone asks, “can you run that analysis again for a different time period,” or, “can you run it for group B instead of group A,” or, “can you send me that analysis so that I can play around with it?” There are some problems that we often encounter when trying to fulfill those requests. Changing the source of an analysis can be difficult, whether it is from one .csv to another or from the testing database to the production database. If the connection or file to import is defined in multiple places, it can be easy to miss one and have invalid output. We run into the same issue when switching the analysis from a group A to a group B or changing the time frame of the analysis data. It could be in multiple filters that all need to get changed. Giving an analysis out can also be troublesome. When working on some ad hoc analysis, it is common to leave database passwords in the code while working out the details of the analysis. Giving out that R Markdown file or leaving it on a shared network drive raises security concerns. While dotenv is an option, it requires slightly more setup to work correctly. towardsdatascience.com Luckily R Markdown has a feature called parameters which provide solutions to all of these problems. Parameters in an R Markdown document are very simple to use. In the yaml header (the section at the top of the markdown document), you just have to add a couple new lines for your parameters to hardcode them in. Once they’re coded in, they will be available in the params object for use in the rest of the analysis. By referencing the parameters from the yaml header, any updates to them that need to be made will only require one change. For this example, we’ll look at the gapminder data set. This is a data set available from the gapminder package. It has a subset of the indicators collected by the Gapminder foundation. Check out Hans Rosling’s (one of the Gapminder founders) TED talk, or the Gapminder website for more information. # Setup# install.packages("gapminder")library(gapminder)# The data framegapminder The gapminder data set contains 6 variables: country, continent, year, lifeExp (life expectancy), pop (population), and gdpPercap (gross domestic product per capita). We’ll start by filtering the data frame for the year 2002. Using the tidyverse, that code looks like this: library(tidyverse)gapminder %>% filter(year == 2002) %>% head() We might want to run this report for a different year, making this a good candidate to create a parameter for. In our yaml header, we will add another item called params and underneath it, with 2 spaces in front, we’ll create a year parameter. When running an R Markdown, a params object will be created, and the named parameters will be available for our use. ---title: "Hardcoded Parameters"author: "RealDrewData"date: "7/6/2021"output: html_documentparams: year: 2002--- Now we can return to our filtering code. We’ll replace 2002 with the year parameter we just created. library(tidyverse)gapminder %>% filter(year == params$year) %>% head() We can also use the year parameter in other places in the code, such as a label in a plot. Let’s create a scatter plot with GDP per capita on the x axis, life expectancy on the y axis, population for the size of the points, and continent for color. In our labels, we can use the paste() function and our params$year to build a title for the plot that updates with the parameter. gapminder %>% filter(year == params$year) %>% ggplot(aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) + geom_point() + labs(title = paste("Life Expectancy and GDP for", params$year), x = "GPD Per Capita", y = "Life Expectancy") Markdown sections are where we have the plain text. We can run code inline to return values and have them display in the output text. For example, we may have a section header that says: ## Gapminder Analysis for 2002 This will not update when we change our parameter. To correct this, we can use inline code to grab the year from the params object. The r is there to say we are going to use R code. When knitting the document, this will be exactly the same as the previous code, assuming the year parameter is still set to 2002. ## Gapminder Analysis for 'r params$year' Parameters don’t have to be numeric, they can also be boolean. One common example of this is to create switches to modify the behavior when the Markdown is knitting. One example is whether or not to print code in the final output. When showing something to a manager or executive, you may not want to see code, but when reviewing with the team, code can be more important. towardsdatascience.com For this, we’ll create another parameter under year: show_code. ---title: "Hardcoded Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams: year: 2002 show_code: FALSE--- Usually in the setup chunk knitting options are defined. In our case, we want to set the echo option equal to show_code. Since we set this to FALSE, it will prevent our code from showing up in the final output. knitr::opts_chunk$set(echo = params$show_code) Hardcoding parameters in Markdown clearly adds some major benefits. What if someone who isn’t as familiar with Markdown wants to modify a report or you want to quickly rerun for a different period? Dynamic parameters can be helpful here. With the gapminder data frame, there is some nuance in the data available. Every 5 years is in the data frame, starting at 1952 and ending in 2007. For someone who doesn’t know the data, they could easily change the parameter to 1953 and be very confused when no data shows up. To change that, we can add a custom prompt by modifying the year parameter in the yaml header. We’ll add another sub level under year with the settings that we want. In this case we want the label to be called year, the default value to be 2002, and for the input to be a slider. We can also specify minimum and maximum values, and how many steps are between each value. ---title: "Dynamic Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams: year: label: "Year" value: 2002 input: slider min: 1952 max: 2007 step: 5 sep: "" show_code: FALSE To get the prompt to appear, click the arrow next to the knit button. Click on knit with parameters. This will bring up a window with a slider labelled year. This slider will have the restrictions we set above. Sliding the slider to 1977 and clicking knit is the same as changing the value of year in the yaml header. The added benefit is that we know that the input will be the correct type and we can limit the options that can be chosen to make sure that data appears on the final output. You’ll also notice that a check box input was created for the show_code parameter. This is the default for boolean parameters. Again, we aren’t limited to just numeric and boolean types. If I have a call to a database where the code needs a username and password, we can create parameters for those as well. The username can be a text field. That input is denoted by the text input. The value is the value to default to, in this case blank. placeholder is the text displayed in the text box when it is blank. For the password input, we can use the password variant of the text input. This will obfuscate the text that is typed into it, much like when you are logging into a website. ---title: "Dynamic Parameters"author: "RealDrewData"date: "6/19/2021"output: html_documentparams: year: label: "Year" value: 2002 input: slider min: 1952 max: 2007 step: 5 sep: "" show_code: FALSE username: label: "username" value: "" input: text placeholder: "username" password: label: "PWD" value: "" input: password placeholder: "password"--- When we click knit with parameters, we now see a text box input and a password input. This is by no means best practice, but it gives you an example of what you can do with dynamic parameters. There are many other options for inputs you can use to set your parameters. A more comprehensive list can be found in the Shiny Widget Gallery. Parameters serve multiple purposes in R Markdown. They allow you to make a single change in a document that impacts the entire document. They make it easy to run the same report for a different period, or event a different audience. They also can aid in sharing analysis with others, but there may be better options for this particular use case. R Markdown: The Definitive Guide, by Yihui Xie, J. J. Allaire, Garrett Grolemund. Written by members of the RStudio team, this covers everything you could ever want to know about R Markdown. It is available online for free here, but you can also purchase a hardcopy Shiny Widget Gallery: interactive examples of all the shiny widgets that can be used to dynamically set the parameters in an R Markdown document. Hans Rosling TED Talk: Hans Rosling is one of the founders of the Gapminder Foundation. This TED talk gives some background on the data used in the examples. It always gets me fired up and ready to do some data analysis!
[ { "code": null, "e": 406, "s": 171, "text": "We’ve all been in a meeting where someone asks, “can you run that analysis again for a different time period,” or, “can you run it for group B instead of group A,” or, “can you send me that analysis so that I can play around with it?”" }, { "code": null, "e": 955, "s": 406, "text": "There are some problems that we often encounter when trying to fulfill those requests. Changing the source of an analysis can be difficult, whether it is from one .csv to another or from the testing database to the production database. If the connection or file to import is defined in multiple places, it can be easy to miss one and have invalid output. We run into the same issue when switching the analysis from a group A to a group B or changing the time frame of the analysis data. It could be in multiple filters that all need to get changed." }, { "code": null, "e": 1317, "s": 955, "text": "Giving an analysis out can also be troublesome. When working on some ad hoc analysis, it is common to leave database passwords in the code while working out the details of the analysis. Giving out that R Markdown file or leaving it on a shared network drive raises security concerns. While dotenv is an option, it requires slightly more setup to work correctly." }, { "code": null, "e": 1340, "s": 1317, "text": "towardsdatascience.com" }, { "code": null, "e": 1441, "s": 1340, "text": "Luckily R Markdown has a feature called parameters which provide solutions to all of these problems." }, { "code": null, "e": 1880, "s": 1441, "text": "Parameters in an R Markdown document are very simple to use. In the yaml header (the section at the top of the markdown document), you just have to add a couple new lines for your parameters to hardcode them in. Once they’re coded in, they will be available in the params object for use in the rest of the analysis. By referencing the parameters from the yaml header, any updates to them that need to be made will only require one change." }, { "code": null, "e": 2180, "s": 1880, "text": "For this example, we’ll look at the gapminder data set. This is a data set available from the gapminder package. It has a subset of the indicators collected by the Gapminder foundation. Check out Hans Rosling’s (one of the Gapminder founders) TED talk, or the Gapminder website for more information." }, { "code": null, "e": 2262, "s": 2180, "text": "# Setup# install.packages(\"gapminder\")library(gapminder)# The data framegapminder" }, { "code": null, "e": 2429, "s": 2262, "text": "The gapminder data set contains 6 variables: country, continent, year, lifeExp (life expectancy), pop (population), and gdpPercap (gross domestic product per capita)." }, { "code": null, "e": 2536, "s": 2429, "text": "We’ll start by filtering the data frame for the year 2002. Using the tidyverse, that code looks like this:" }, { "code": null, "e": 2606, "s": 2536, "text": "library(tidyverse)gapminder %>% filter(year == 2002) %>% head()" }, { "code": null, "e": 2967, "s": 2606, "text": "We might want to run this report for a different year, making this a good candidate to create a parameter for. In our yaml header, we will add another item called params and underneath it, with 2 spaces in front, we’ll create a year parameter. When running an R Markdown, a params object will be created, and the named parameters will be available for our use." }, { "code": null, "e": 3081, "s": 2967, "text": "---title: \"Hardcoded Parameters\"author: \"RealDrewData\"date: \"7/6/2021\"output: html_documentparams: year: 2002---" }, { "code": null, "e": 3182, "s": 3081, "text": "Now we can return to our filtering code. We’ll replace 2002 with the year parameter we just created." }, { "code": null, "e": 3253, "s": 3182, "text": "library(tidyverse)gapminder %>% filter(year == params$year) %>% head()" }, { "code": null, "e": 3632, "s": 3253, "text": "We can also use the year parameter in other places in the code, such as a label in a plot. Let’s create a scatter plot with GDP per capita on the x axis, life expectancy on the y axis, population for the size of the points, and continent for color. In our labels, we can use the paste() function and our params$year to build a title for the plot that updates with the parameter." }, { "code": null, "e": 3887, "s": 3632, "text": "gapminder %>% filter(year == params$year) %>% ggplot(aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) + geom_point() + labs(title = paste(\"Life Expectancy and GDP for\", params$year), x = \"GPD Per Capita\", y = \"Life Expectancy\")" }, { "code": null, "e": 4074, "s": 3887, "text": "Markdown sections are where we have the plain text. We can run code inline to return values and have them display in the output text. For example, we may have a section header that says:" }, { "code": null, "e": 4105, "s": 4074, "text": "## Gapminder Analysis for 2002" }, { "code": null, "e": 4417, "s": 4105, "text": "This will not update when we change our parameter. To correct this, we can use inline code to grab the year from the params object. The r is there to say we are going to use R code. When knitting the document, this will be exactly the same as the previous code, assuming the year parameter is still set to 2002." }, { "code": null, "e": 4459, "s": 4417, "text": "## Gapminder Analysis for 'r params$year'" }, { "code": null, "e": 4832, "s": 4459, "text": "Parameters don’t have to be numeric, they can also be boolean. One common example of this is to create switches to modify the behavior when the Markdown is knitting. One example is whether or not to print code in the final output. When showing something to a manager or executive, you may not want to see code, but when reviewing with the team, code can be more important." }, { "code": null, "e": 4855, "s": 4832, "text": "towardsdatascience.com" }, { "code": null, "e": 4919, "s": 4855, "text": "For this, we’ll create another parameter under year: show_code." }, { "code": null, "e": 5052, "s": 4919, "text": "---title: \"Hardcoded Parameters\"author: \"RealDrewData\"date: \"6/19/2021\"output: html_documentparams: year: 2002 show_code: FALSE---" }, { "code": null, "e": 5263, "s": 5052, "text": "Usually in the setup chunk knitting options are defined. In our case, we want to set the echo option equal to show_code. Since we set this to FALSE, it will prevent our code from showing up in the final output." }, { "code": null, "e": 5310, "s": 5263, "text": "knitr::opts_chunk$set(echo = params$show_code)" }, { "code": null, "e": 5548, "s": 5310, "text": "Hardcoding parameters in Markdown clearly adds some major benefits. What if someone who isn’t as familiar with Markdown wants to modify a report or you want to quickly rerun for a different period? Dynamic parameters can be helpful here." }, { "code": null, "e": 5921, "s": 5548, "text": "With the gapminder data frame, there is some nuance in the data available. Every 5 years is in the data frame, starting at 1952 and ending in 2007. For someone who doesn’t know the data, they could easily change the parameter to 1953 and be very confused when no data shows up. To change that, we can add a custom prompt by modifying the year parameter in the yaml header." }, { "code": null, "e": 6197, "s": 5921, "text": "We’ll add another sub level under year with the settings that we want. In this case we want the label to be called year, the default value to be 2002, and for the input to be a slider. We can also specify minimum and maximum values, and how many steps are between each value." }, { "code": null, "e": 6417, "s": 6197, "text": "---title: \"Dynamic Parameters\"author: \"RealDrewData\"date: \"6/19/2021\"output: html_documentparams: year: label: \"Year\" value: 2002 input: slider min: 1952 max: 2007 step: 5 sep: \"\" show_code: FALSE" }, { "code": null, "e": 6518, "s": 6417, "text": "To get the prompt to appear, click the arrow next to the knit button. Click on knit with parameters." }, { "code": null, "e": 6909, "s": 6518, "text": "This will bring up a window with a slider labelled year. This slider will have the restrictions we set above. Sliding the slider to 1977 and clicking knit is the same as changing the value of year in the yaml header. The added benefit is that we know that the input will be the correct type and we can limit the options that can be chosen to make sure that data appears on the final output." }, { "code": null, "e": 7036, "s": 6909, "text": "You’ll also notice that a check box input was created for the show_code parameter. This is the default for boolean parameters." }, { "code": null, "e": 7217, "s": 7036, "text": "Again, we aren’t limited to just numeric and boolean types. If I have a call to a database where the code needs a username and password, we can create parameters for those as well." }, { "code": null, "e": 7592, "s": 7217, "text": "The username can be a text field. That input is denoted by the text input. The value is the value to default to, in this case blank. placeholder is the text displayed in the text box when it is blank. For the password input, we can use the password variant of the text input. This will obfuscate the text that is typed into it, much like when you are logging into a website." }, { "code": null, "e": 7988, "s": 7592, "text": "---title: \"Dynamic Parameters\"author: \"RealDrewData\"date: \"6/19/2021\"output: html_documentparams: year: label: \"Year\" value: 2002 input: slider min: 1952 max: 2007 step: 5 sep: \"\" show_code: FALSE username: label: \"username\" value: \"\" input: text placeholder: \"username\" password: label: \"PWD\" value: \"\" input: password placeholder: \"password\"---" }, { "code": null, "e": 8181, "s": 7988, "text": "When we click knit with parameters, we now see a text box input and a password input. This is by no means best practice, but it gives you an example of what you can do with dynamic parameters." }, { "code": null, "e": 8325, "s": 8181, "text": "There are many other options for inputs you can use to set your parameters. A more comprehensive list can be found in the Shiny Widget Gallery." }, { "code": null, "e": 8671, "s": 8325, "text": "Parameters serve multiple purposes in R Markdown. They allow you to make a single change in a document that impacts the entire document. They make it easy to run the same report for a different period, or event a different audience. They also can aid in sharing analysis with others, but there may be better options for this particular use case." }, { "code": null, "e": 8937, "s": 8671, "text": "R Markdown: The Definitive Guide, by Yihui Xie, J. J. Allaire, Garrett Grolemund. Written by members of the RStudio team, this covers everything you could ever want to know about R Markdown. It is available online for free here, but you can also purchase a hardcopy" }, { "code": null, "e": 9083, "s": 8937, "text": "Shiny Widget Gallery: interactive examples of all the shiny widgets that can be used to dynamically set the parameters in an R Markdown document." } ]
3D Plots in MATLAB - GeeksforGeeks
09 May, 2021 In MATLAB, we can plot different types of modules like 2d plotting and 3d plotting. In this article, we will see what are the various types of 3D plotting. Mesh Plot: A mesh plot is a 3d surface that creates different types of meshes for different types of expression. To create mesh we have to give the values x and y for z, (z= f(x, y)). For plotting the mesh plot it has mesh() which will generate the 3d surface. It has solid edge color but no face color. Syntax: mesh(Z) Example: Matlab % give the input of x and y.[x,y]= meshgrid(0:0.1:5); % give the expression for x % and y for the output in zz= sin(x).*cos(y); % mesh() is used for 3D plottingmesh(z); Output: Surface plot: A surface plot is a 3d surface that creates different types of surfaces for different expressions. To create a surface we have to give the values x and y for z, (z= f(x, y)). For plotting the surface plot it has surf() which will generate the 3d surface. It has solid edge color and solid face color Syntax: surf(Z) Example: Matlab % give the input for x and y[x,y]= meshgrid(0:0.1:5); % give the expression for % x and y for the value of z.z= sin(x).*cos(y); % use surf() for the plotting surf(z) Output: Surface plot(with shading): A surface plot that creates a three-dimensional surface plot that has solid edge colors and solid face colors and also has shading. In surface with shading, we have to give the values x and y for z, (z= f(x, y)). For plotting the surface plot it has surf(z) is used for 3d plotting. Syntax: surfl(z) There are three types of shading available: shading flatshading facetedshading interp shading flat shading faceted shading interp Example: Matlab % give the input for x and y[x,y]= meshgrid(0:0.1:5); % give the expression for x and y % for the value of zz= sin(x).*cos(y); % use surfl() for the plotting % shading faceted is by defaultsurfl(z)shading facetedtitle('Faceted Shading') % use shading flat for each mesh% line segment and face has a % constant color surfl(z)shading flattitle('Flat Shading') % use shading flat for varies the % color in each line segment and % face by interpolatingsurfl(z)shading interptitle('Interpolated Shading') Output: Contour plot: A contour plot is also called a line plot. To plot contour it has x, y variables which are used to give the values for z, (z=f(x, y)). The x and y variables are usually in a grid called meshgrid. Syntax: contour(Z) Example: Matlab % enter the inputs of x and y[x,y]= meshgrid(0:0.1:5); % enter the expression using% x and y z= sin(x).*cos(y); % use contour() for plotting contour3(z,50) Output: Quiver plot: A quiver plot or vector plot is a type of plotting that gives directional components of u, v, w using the cartesian components x, y, and z. For plotting of quiver plot use quiver3(). Syntax: quiver3(X, Y, Z, U, V, W) Example: Matlab % give the input value for x,% y and z[x,y,z]= meshgrid(0:0.1:5); % using x, y and z give the % values for u,v and w u= sin(x).*cos(y);v= sin(x).*cos(y);w= sin(x).*cos(y); %use quiver3() for 3d plottingquiver3(x,y,z,u,v,w); Output: MATLAB-graphs Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Differential or Derivatives in MATLAB Boundary Extraction of image using MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB Laplacian of Gaussian Filter in MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Apply Median Filter For RGB Image in MATLAB? How to Normalize a Histogram in MATLAB? Laplace Transform in MATLAB What is Upsampling in MATLAB?
[ { "code": null, "e": 24528, "s": 24500, "text": "\n09 May, 2021" }, { "code": null, "e": 24684, "s": 24528, "text": "In MATLAB, we can plot different types of modules like 2d plotting and 3d plotting. In this article, we will see what are the various types of 3D plotting." }, { "code": null, "e": 24988, "s": 24684, "text": "Mesh Plot: A mesh plot is a 3d surface that creates different types of meshes for different types of expression. To create mesh we have to give the values x and y for z, (z= f(x, y)). For plotting the mesh plot it has mesh() which will generate the 3d surface. It has solid edge color but no face color." }, { "code": null, "e": 24996, "s": 24988, "text": "Syntax:" }, { "code": null, "e": 25004, "s": 24996, "text": "mesh(Z)" }, { "code": null, "e": 25013, "s": 25004, "text": "Example:" }, { "code": null, "e": 25020, "s": 25013, "text": "Matlab" }, { "code": "% give the input of x and y.[x,y]= meshgrid(0:0.1:5); % give the expression for x % and y for the output in zz= sin(x).*cos(y); % mesh() is used for 3D plottingmesh(z);", "e": 25191, "s": 25020, "text": null }, { "code": null, "e": 25199, "s": 25191, "text": "Output:" }, { "code": null, "e": 25513, "s": 25199, "text": "Surface plot: A surface plot is a 3d surface that creates different types of surfaces for different expressions. To create a surface we have to give the values x and y for z, (z= f(x, y)). For plotting the surface plot it has surf() which will generate the 3d surface. It has solid edge color and solid face color" }, { "code": null, "e": 25521, "s": 25513, "text": "Syntax:" }, { "code": null, "e": 25529, "s": 25521, "text": "surf(Z)" }, { "code": null, "e": 25538, "s": 25529, "text": "Example:" }, { "code": null, "e": 25545, "s": 25538, "text": "Matlab" }, { "code": "% give the input for x and y[x,y]= meshgrid(0:0.1:5); % give the expression for % x and y for the value of z.z= sin(x).*cos(y); % use surf() for the plotting surf(z)", "e": 25713, "s": 25545, "text": null }, { "code": null, "e": 25721, "s": 25713, "text": "Output:" }, { "code": null, "e": 26033, "s": 25721, "text": "Surface plot(with shading): A surface plot that creates a three-dimensional surface plot that has solid edge colors and solid face colors and also has shading. In surface with shading, we have to give the values x and y for z, (z= f(x, y)). For plotting the surface plot it has surf(z) is used for 3d plotting." }, { "code": null, "e": 26041, "s": 26033, "text": "Syntax:" }, { "code": null, "e": 26050, "s": 26041, "text": "surfl(z)" }, { "code": null, "e": 26094, "s": 26050, "text": "There are three types of shading available:" }, { "code": null, "e": 26136, "s": 26094, "text": "shading flatshading facetedshading interp" }, { "code": null, "e": 26149, "s": 26136, "text": "shading flat" }, { "code": null, "e": 26165, "s": 26149, "text": "shading faceted" }, { "code": null, "e": 26180, "s": 26165, "text": "shading interp" }, { "code": null, "e": 26189, "s": 26180, "text": "Example:" }, { "code": null, "e": 26196, "s": 26189, "text": "Matlab" }, { "code": "% give the input for x and y[x,y]= meshgrid(0:0.1:5); % give the expression for x and y % for the value of zz= sin(x).*cos(y); % use surfl() for the plotting % shading faceted is by defaultsurfl(z)shading facetedtitle('Faceted Shading') % use shading flat for each mesh% line segment and face has a % constant color surfl(z)shading flattitle('Flat Shading') % use shading flat for varies the % color in each line segment and % face by interpolatingsurfl(z)shading interptitle('Interpolated Shading')", "e": 26700, "s": 26196, "text": null }, { "code": null, "e": 26708, "s": 26700, "text": "Output:" }, { "code": null, "e": 26918, "s": 26708, "text": "Contour plot: A contour plot is also called a line plot. To plot contour it has x, y variables which are used to give the values for z, (z=f(x, y)). The x and y variables are usually in a grid called meshgrid." }, { "code": null, "e": 26926, "s": 26918, "text": "Syntax:" }, { "code": null, "e": 26937, "s": 26926, "text": "contour(Z)" }, { "code": null, "e": 26946, "s": 26937, "text": "Example:" }, { "code": null, "e": 26953, "s": 26946, "text": "Matlab" }, { "code": "% enter the inputs of x and y[x,y]= meshgrid(0:0.1:5); % enter the expression using% x and y z= sin(x).*cos(y); % use contour() for plotting contour3(z,50)", "e": 27111, "s": 26953, "text": null }, { "code": null, "e": 27119, "s": 27111, "text": "Output:" }, { "code": null, "e": 27315, "s": 27119, "text": "Quiver plot: A quiver plot or vector plot is a type of plotting that gives directional components of u, v, w using the cartesian components x, y, and z. For plotting of quiver plot use quiver3()." }, { "code": null, "e": 27323, "s": 27315, "text": "Syntax:" }, { "code": null, "e": 27349, "s": 27323, "text": "quiver3(X, Y, Z, U, V, W)" }, { "code": null, "e": 27358, "s": 27349, "text": "Example:" }, { "code": null, "e": 27365, "s": 27358, "text": "Matlab" }, { "code": "% give the input value for x,% y and z[x,y,z]= meshgrid(0:0.1:5); % using x, y and z give the % values for u,v and w u= sin(x).*cos(y);v= sin(x).*cos(y);w= sin(x).*cos(y); %use quiver3() for 3d plottingquiver3(x,y,z,u,v,w);", "e": 27591, "s": 27365, "text": null }, { "code": null, "e": 27599, "s": 27591, "text": "Output:" }, { "code": null, "e": 27613, "s": 27599, "text": "MATLAB-graphs" }, { "code": null, "e": 27620, "s": 27613, "text": "Picked" }, { "code": null, "e": 27627, "s": 27620, "text": "MATLAB" }, { "code": null, "e": 27725, "s": 27627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27734, "s": 27725, "text": "Comments" }, { "code": null, "e": 27747, "s": 27734, "text": "Old Comments" }, { "code": null, "e": 27820, "s": 27747, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 27858, "s": 27820, "text": "Differential or Derivatives in MATLAB" }, { "code": null, "e": 27900, "s": 27858, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 27960, "s": 27900, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 27999, "s": 27960, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 28064, "s": 27999, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 28116, "s": 28064, "text": "How to Apply Median Filter For RGB Image in MATLAB?" }, { "code": null, "e": 28156, "s": 28116, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 28184, "s": 28156, "text": "Laplace Transform in MATLAB" } ]
C# - Miscellaneous Operators
There are few other important operators including sizeof and ? : supported by C#. StringReader r = obj as StringReader; using System; namespace OperatorsAppl { class Program { static void Main(string[] args) { /* example of sizeof operator */ Console.WriteLine("The size of int is {0}", sizeof(int)); Console.WriteLine("The size of short is {0}", sizeof(short)); Console.WriteLine("The size of double is {0}", sizeof(double)); /* example of ternary operator */ int a, b; a = 10; b = (a == 1) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); b = (a == 10) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − The size of int is 4 The size of short is 2 The size of double is 8 Value of b is 30 Value of b is 20 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2353, "s": 2270, "text": "There are few other important operators including sizeof and ? : supported by C#." }, { "code": null, "e": 2391, "s": 2353, "text": "StringReader r = obj as StringReader;" }, { "code": null, "e": 3054, "s": 2391, "text": "using System;\n\nnamespace OperatorsAppl {\n\n class Program {\n \n static void Main(string[] args) {\n /* example of sizeof operator */\n Console.WriteLine(\"The size of int is {0}\", sizeof(int));\n Console.WriteLine(\"The size of short is {0}\", sizeof(short));\n Console.WriteLine(\"The size of double is {0}\", sizeof(double));\n \n /* example of ternary operator */\n int a, b;\n a = 10;\n b = (a == 1) ? 20 : 30;\n Console.WriteLine(\"Value of b is {0}\", b);\n\n b = (a == 10) ? 20 : 30;\n Console.WriteLine(\"Value of b is {0}\", b);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3135, "s": 3054, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3238, "s": 3135, "text": "The size of int is 4\nThe size of short is 2\nThe size of double is 8\nValue of b is 30\nValue of b is 20\n" }, { "code": null, "e": 3275, "s": 3238, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 3288, "s": 3275, "text": " Raja Biswas" }, { "code": null, "e": 3322, "s": 3288, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3340, "s": 3322, "text": " Trevoir Williams" }, { "code": null, "e": 3373, "s": 3340, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3387, "s": 3373, "text": " Peter Jepson" }, { "code": null, "e": 3424, "s": 3387, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 3439, "s": 3424, "text": " Ebenezer Ogbu" }, { "code": null, "e": 3474, "s": 3439, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 3489, "s": 3474, "text": " Arnold Higuit" }, { "code": null, "e": 3524, "s": 3489, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3536, "s": 3524, "text": " Eric Frick" }, { "code": null, "e": 3543, "s": 3536, "text": " Print" }, { "code": null, "e": 3554, "s": 3543, "text": " Add Notes" } ]
The Nice Way To Use Docker With VSCode | by Yash Prakash | Towards Data Science
Your next project might contain a lot of complex machine learning code with numerous different libraries and their versions threatening to wreak havoc on your machine. Next comes the process of making sure your colleague can also run your app with the right dependencies installed. This brings forward a new round of headaches. It does not have to be this way. Developing inside a docker container can save you a lot of time, and help smooth out the process of deployment of your app in the long run. In another article, I’ve discussed the complete set of steps to manually build and run a docker image for your project. You can find it here. But there’s a simpler way to automate the setup of Docker for your next project and it comes built-in with VSCode. In this story, let me show you how I learned to start a new development environment within a container in a few simple steps. Here we go 👇 The VSCode Docker extension is the backbone of all your Docker workflows. Make sure you have it installed by visiting the extensions marketplace or simply go to this URL: Docker Extension. Now, go ahed and start up Docker Desktop on your machine. This extension makes it trivial to build, run, and deploy containerised applications, all without leaving your code editor! Make sure Docker Desktop is running before moving on to the next step. The purpose of this tutorial is to demonstrate how easy it is to develop an app in a dockerised manner. Keeping this in mind, I’ll show a simple example on using FastApi to build a HelloWorld app. To get started, make a new file called helloworld.py and paste this block of code within it: from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"} This will make sure we have a simple API that displays ‘Hello World’ message at the exposed URL. Now comes the part where we play with Docker. First, you need to make a requirements.txt file that will contain all the dependencies for the app we’re building. Owing to the simplicity of this test application, we only have these two for now: fastapi[all]==0.63.0uvicorn[standard]==0.13.4 Finally, press CMD + Shift + P or CTRL + Shift + P to open up the command pallete of VSCode. Type in and select “Add Docker Files...” The below window will pop up, select the FastApi option. This process significantly simplifies our workflow. So, even if we hadn’t placed our FastApi dependency in the requirements.txt file, it would’ve added it anyway. Ain’t that neat? Now go ahead and select the port option like in the below screenshot too. The default should work just fine. Change it to your requirement, if you wish. Finally, the step to build your Docker Image is here. Go ahead and right click the Dockerfile generated and select Build Image. You should now get the following files in your Editor: Excellent! We can now move to the last step in order to test our API! Now that we have the image ready, you can go ahead and switch to the Docker tab on your left hand side of VSCode sidebar. Here, you’ll see a list of images you already have in your system. The new image we built just now will also show up here like this: This is great. Now you only need to right click the ‘latest’ under your image name and select the Run option. You can view the startup logs by right clicking the built container and clicking on ‘View logs’ option. This should produce the output like so: This means our API is running. Fire up your web browser and navigate to the above URL or simply: 0.0.0.0:8000. You should now see the Hello World message! Great! You should now be able to build your own project centred around this very process. This article, I hope, serves as a good starting point to get you up to speed on the convenient way to use Docker for your Python apps. I would recommend you experiment with the other features of Docker in VSCode by reading up on this official documentation on the same. I know I will. 😃 If you find this article helpful, follow me here as I do write every week, to make sure you never miss another article ever again. Also, the codebase and resources for all my data science articles is located here. Happy learning! Here are a couple other stories of mine that might interest you:
[ { "code": null, "e": 500, "s": 172, "text": "Your next project might contain a lot of complex machine learning code with numerous different libraries and their versions threatening to wreak havoc on your machine. Next comes the process of making sure your colleague can also run your app with the right dependencies installed. This brings forward a new round of headaches." }, { "code": null, "e": 533, "s": 500, "text": "It does not have to be this way." }, { "code": null, "e": 815, "s": 533, "text": "Developing inside a docker container can save you a lot of time, and help smooth out the process of deployment of your app in the long run. In another article, I’ve discussed the complete set of steps to manually build and run a docker image for your project. You can find it here." }, { "code": null, "e": 930, "s": 815, "text": "But there’s a simpler way to automate the setup of Docker for your next project and it comes built-in with VSCode." }, { "code": null, "e": 1056, "s": 930, "text": "In this story, let me show you how I learned to start a new development environment within a container in a few simple steps." }, { "code": null, "e": 1069, "s": 1056, "text": "Here we go 👇" }, { "code": null, "e": 1258, "s": 1069, "text": "The VSCode Docker extension is the backbone of all your Docker workflows. Make sure you have it installed by visiting the extensions marketplace or simply go to this URL: Docker Extension." }, { "code": null, "e": 1316, "s": 1258, "text": "Now, go ahed and start up Docker Desktop on your machine." }, { "code": null, "e": 1440, "s": 1316, "text": "This extension makes it trivial to build, run, and deploy containerised applications, all without leaving your code editor!" }, { "code": null, "e": 1511, "s": 1440, "text": "Make sure Docker Desktop is running before moving on to the next step." }, { "code": null, "e": 1708, "s": 1511, "text": "The purpose of this tutorial is to demonstrate how easy it is to develop an app in a dockerised manner. Keeping this in mind, I’ll show a simple example on using FastApi to build a HelloWorld app." }, { "code": null, "e": 1801, "s": 1708, "text": "To get started, make a new file called helloworld.py and paste this block of code within it:" }, { "code": null, "e": 1911, "s": 1801, "text": "from fastapi import FastAPIapp = FastAPI()@app.get(\"/\")async def root(): return {\"message\": \"Hello World\"}" }, { "code": null, "e": 2008, "s": 1911, "text": "This will make sure we have a simple API that displays ‘Hello World’ message at the exposed URL." }, { "code": null, "e": 2054, "s": 2008, "text": "Now comes the part where we play with Docker." }, { "code": null, "e": 2169, "s": 2054, "text": "First, you need to make a requirements.txt file that will contain all the dependencies for the app we’re building." }, { "code": null, "e": 2251, "s": 2169, "text": "Owing to the simplicity of this test application, we only have these two for now:" }, { "code": null, "e": 2297, "s": 2251, "text": "fastapi[all]==0.63.0uvicorn[standard]==0.13.4" }, { "code": null, "e": 2431, "s": 2297, "text": "Finally, press CMD + Shift + P or CTRL + Shift + P to open up the command pallete of VSCode. Type in and select “Add Docker Files...”" }, { "code": null, "e": 2488, "s": 2431, "text": "The below window will pop up, select the FastApi option." }, { "code": null, "e": 2540, "s": 2488, "text": "This process significantly simplifies our workflow." }, { "code": null, "e": 2668, "s": 2540, "text": "So, even if we hadn’t placed our FastApi dependency in the requirements.txt file, it would’ve added it anyway. Ain’t that neat?" }, { "code": null, "e": 2821, "s": 2668, "text": "Now go ahead and select the port option like in the below screenshot too. The default should work just fine. Change it to your requirement, if you wish." }, { "code": null, "e": 2949, "s": 2821, "text": "Finally, the step to build your Docker Image is here. Go ahead and right click the Dockerfile generated and select Build Image." }, { "code": null, "e": 3004, "s": 2949, "text": "You should now get the following files in your Editor:" }, { "code": null, "e": 3074, "s": 3004, "text": "Excellent! We can now move to the last step in order to test our API!" }, { "code": null, "e": 3196, "s": 3074, "text": "Now that we have the image ready, you can go ahead and switch to the Docker tab on your left hand side of VSCode sidebar." }, { "code": null, "e": 3329, "s": 3196, "text": "Here, you’ll see a list of images you already have in your system. The new image we built just now will also show up here like this:" }, { "code": null, "e": 3439, "s": 3329, "text": "This is great. Now you only need to right click the ‘latest’ under your image name and select the Run option." }, { "code": null, "e": 3583, "s": 3439, "text": "You can view the startup logs by right clicking the built container and clicking on ‘View logs’ option. This should produce the output like so:" }, { "code": null, "e": 3614, "s": 3583, "text": "This means our API is running." }, { "code": null, "e": 3738, "s": 3614, "text": "Fire up your web browser and navigate to the above URL or simply: 0.0.0.0:8000. You should now see the Hello World message!" }, { "code": null, "e": 3828, "s": 3738, "text": "Great! You should now be able to build your own project centred around this very process." }, { "code": null, "e": 4115, "s": 3828, "text": "This article, I hope, serves as a good starting point to get you up to speed on the convenient way to use Docker for your Python apps. I would recommend you experiment with the other features of Docker in VSCode by reading up on this official documentation on the same. I know I will. 😃" }, { "code": null, "e": 4246, "s": 4115, "text": "If you find this article helpful, follow me here as I do write every week, to make sure you never miss another article ever again." }, { "code": null, "e": 4345, "s": 4246, "text": "Also, the codebase and resources for all my data science articles is located here. Happy learning!" } ]
Behave - Installation
Behave installation can be done by the following ways − For Behave installation, we should have pip – the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9). To install pip, run the below mentioned command − pip install pip To install pip with Behave, run the command given below − pip install behave The following screen will appear on your computer − We can update an existing version of Behave with the following command − pip install –U behave We can also use the easy_install for the Behave installation. To install Setuptools, run the below mentioned command− pip install setuptools Now, for the Behave installation, run the command stated below: easy_install behave We can update an existing version of behave with the command given below: easy_install –U behave Post unpacking of the source distribution of Behave, type the new generated directory 'behave-<version>' and execute the below mentioned command − python setup.py install We should first have the pip installed in the system. Later on, to install the latest version of Behave with Git repository, run the below mentioned command − pip install git+https://github.com/behave/behave If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it. Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2296, "text": "Behave installation can be done by the following ways −" }, { "code": null, "e": 2555, "s": 2352, "text": "For Behave installation, we should have pip – the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9)." }, { "code": null, "e": 2605, "s": 2555, "text": "To install pip, run the below mentioned command −" }, { "code": null, "e": 2622, "s": 2605, "text": "pip install pip\n" }, { "code": null, "e": 2680, "s": 2622, "text": "To install pip with Behave, run the command given below −" }, { "code": null, "e": 2700, "s": 2680, "text": "pip install behave\n" }, { "code": null, "e": 2752, "s": 2700, "text": "The following screen will appear on your computer −" }, { "code": null, "e": 2825, "s": 2752, "text": "We can update an existing version of Behave with the following command −" }, { "code": null, "e": 2848, "s": 2825, "text": "pip install –U behave\n" }, { "code": null, "e": 2910, "s": 2848, "text": "We can also use the easy_install for the Behave installation." }, { "code": null, "e": 2966, "s": 2910, "text": "To install Setuptools, run the below mentioned command−" }, { "code": null, "e": 2990, "s": 2966, "text": "pip install setuptools\n" }, { "code": null, "e": 3054, "s": 2990, "text": "Now, for the Behave installation, run the command stated below:" }, { "code": null, "e": 3075, "s": 3054, "text": "easy_install behave\n" }, { "code": null, "e": 3149, "s": 3075, "text": "We can update an existing version of behave with the command given below:" }, { "code": null, "e": 3173, "s": 3149, "text": "easy_install –U behave\n" }, { "code": null, "e": 3320, "s": 3173, "text": "Post unpacking of the source distribution of Behave, type the new generated directory 'behave-<version>' and execute the below mentioned command −" }, { "code": null, "e": 3345, "s": 3320, "text": "python setup.py install\n" }, { "code": null, "e": 3399, "s": 3345, "text": "We should first have the pip installed in the system." }, { "code": null, "e": 3504, "s": 3399, "text": "Later on, to install the latest version of Behave with Git repository, run the below mentioned command −" }, { "code": null, "e": 3554, "s": 3504, "text": "pip install git+https://github.com/behave/behave\n" }, { "code": null, "e": 3712, "s": 3554, "text": "If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it." }, { "code": null, "e": 3719, "s": 3712, "text": " Print" }, { "code": null, "e": 3730, "s": 3719, "text": " Add Notes" } ]
fillpoly() function in C
Now the header file graphics.h contains fillpoly() function which is implemented to draw and fill a polygon such as triangle, rectangle, pentagon, hexagon etc. So this function require same arguments as drawpoly(). void fillpoly( int number, int *polypoints ); In this case,number indicates (n + 1) number of points where, n is the number of vertices in a polygon and polypoints points to a sequence of (n*2) integers. Input arr[] = {320, 150, 400, 250, 250, 350, 320, 150}; Output Explanation So the declaration of fillpoly() contains two arguments: number specifies (n + 1) number of points where n is indicated as the number of vertices in a polygon.The second argument, such as, polypoints points to a sequence of (n * 2) integers. As a result of this,each pair of integers provides x and y coordinates of a point on the polygon. So we indicate (n + 1) points because first point coordinates should be equal to (n + 1)th for drawing a complete figure. // C Implementation for fillpoly() #include <graphics.h> // driver code intmain(){ // Here gm1 is Graphics mode which is a computer display mode that // produces image using pixels. DETECT is a macro defined in // "graphics.h" header file intgd1 = DETECT, gm1; // Different coordinates for polygon intarr1[] = {320, 150, 400, 250, 250, 350, 320, 150}; // Here initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd1, &gm1, ""); // fillpoly function fillpoly(4, arr1); getch(); // Here closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return0; }
[ { "code": null, "e": 1277, "s": 1062, "text": "Now the header file graphics.h contains fillpoly() function which is implemented to draw and fill a polygon such as triangle, rectangle, pentagon, hexagon etc. So this function require same arguments as drawpoly()." }, { "code": null, "e": 1323, "s": 1277, "text": "void fillpoly( int number, int *polypoints );" }, { "code": null, "e": 1481, "s": 1323, "text": "In this case,number indicates (n + 1) number of points where, n is the number of vertices in a polygon and polypoints points to a sequence of (n*2) integers." }, { "code": null, "e": 1488, "s": 1481, "text": "Input " }, { "code": null, "e": 1538, "s": 1488, "text": "arr[] = {320, 150, 400, 250, 250, 350, 320, 150};" }, { "code": null, "e": 1546, "s": 1538, "text": "Output " }, { "code": null, "e": 1559, "s": 1546, "text": "Explanation " }, { "code": null, "e": 2021, "s": 1559, "text": "So the declaration of fillpoly() contains two arguments: number specifies (n + 1) number of points where n is indicated as the number of vertices in a polygon.The second argument, such as, polypoints points to a sequence of (n * 2) integers. As a result of this,each pair of integers provides x and y coordinates of a point on the polygon. So we indicate (n + 1) points because first point coordinates should be equal to (n + 1)th for drawing a complete figure." }, { "code": null, "e": 2746, "s": 2021, "text": "// C Implementation for fillpoly()\n#include <graphics.h>\n// driver code\nintmain(){\n // Here gm1 is Graphics mode which is a computer display mode that\n // produces image using pixels. DETECT is a macro defined in\n // \"graphics.h\" header file\n intgd1 = DETECT, gm1;\n // Different coordinates for polygon\n intarr1[] = {320, 150, 400, 250, 250, 350, 320, 150};\n // Here initgraph initializes the\n // graphics system by loading a\n // graphics driver from disk\n initgraph(&gd1, &gm1, \"\");\n // fillpoly function\n fillpoly(4, arr1);\n getch();\n // Here closegraph function closes the\n // graphics mode and deallocates\n // all memory allocated by\n // graphics system .\n closegraph();\n return0;\n}" } ]
Transformers in NLP: A beginner friendly explanation | Towards Data Science
No, this article is not about the American sci-fi action movie series — no Optimus Prime here. It is also not about the electrical device that is used to transfer energy from one electrical circuit to another. What is this about then, you ask? It is about the one in the most sci-fi fields of all time, Artificial Intelligence — Natural Language Processing in particular and it is pretty optimal at transferring information and primely used. (See what I did there. :P) This post is based on the paper: Attention is All You Need. P.S. the authors were not kidding when they chose that title because you will need all the attention at your disposal for this one. But don’t let that scare you, it is SO SO worth it!! The Transformer in NLP is a novel architecture that aims to solve sequence-to-sequence tasks while handling long-range dependencies with ease. It relies entirely on self-attention to compute representations of its input and output WITHOUT using sequence-aligned RNNs or convolution. 🤯 If you recall my previous post, Understanding Attention In Deep Learning, we discussed how and why many models fell short when it came to handling long-range dependencies. The concept of attention somewhat allowed us to overcome that problem and now in Transformers we will build on top of attention and unleash its full potential. towardsdatascience.com Let us start with revisiting what attention is in the NLP universe? Understanding Attention In Deep Learning. (I apologize for these blatant self-advertisements, but seriously give it a read. It will help you under Transformers much better. I promise.) Attention allowed us to focus on parts of our input sequence while we predicted our output sequence. If our model predicted the word “rouge” [French translation for the color red], we are very likely to find a high weight-age for the word “red” in our input sequence. So attention, in a way, allowed us to map some connection/correlation between the input word “rouge” and the output word “red”. Self attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. In simpler terms, self attention helps us create similar connections but within the same sentence. Look at the following example: “I poured water from the bottle into the cup until it was full.”it => cup“I poured water from the bottle into the cup until it was empty.”it=> bottle By changing one word “full” — > “empty” the reference object for “it” changed. If we are translating such a sentence, we will want to know the word “it” refers to. Encoder-Decoder Attention: Attention between the input sequence and the output sequence.Self attention in the input sequence: Attends to all the words in the input sequence.Self attention in the output sequence: One thing we should be wary of here is that the scope of self attention is limited to the words that occur before a given word. This prevents any information leaks during the training of the model. This is done by masking the words that occur after it for each step. So for step 1, only the first word of the output sequence is NOT masked, for step 2, the first two words are NOT masked and so on. Encoder-Decoder Attention: Attention between the input sequence and the output sequence. Self attention in the input sequence: Attends to all the words in the input sequence. Self attention in the output sequence: One thing we should be wary of here is that the scope of self attention is limited to the words that occur before a given word. This prevents any information leaks during the training of the model. This is done by masking the words that occur after it for each step. So for step 1, only the first word of the output sequence is NOT masked, for step 2, the first two words are NOT masked and so on. The three random words I just threw at you in this heading are vectors created as abstractions are useful for calculating self attention, more details on each below. These are calculated by multiplying your input vector(X) with weight matrices that are learnt while training. Query Vector: q= X * Wq. Think of this as the current word. Key Vector: k= X * Wk. Think of this as an indexing mechanism for Value vector. Similar to how we have key-value pairs in hash maps, where keys are used to uniquely index the values. Value Vector: v= X * Wv. Think of this as the information in the input word. What we want to do is take query q and find the most similar key k, by doing a dot product for q and k. The closest query-key product will have the highest value, followed by a softmax that will drive the q.k with smaller values close to 0 and q.k with larger values towards 1. This softmax distribution is multiplied with v. The value vectors multiplied with ~1 will get more attention while the ones ~0 will get less. The sizes of these q, k and v vectors are referred to as “hidden size” by various implementations. All these matrices Wq, Wk and Wv are learnt while being jointly trained during the model training. If we are calculating self attention for #i input word, Step 1: Multiply qi by the kj key vector of word. Step 2: Then divide this product by the square root of the dimension of key vector. This step is done for better gradient flow which is specially important in cases when the value of the dot product in previous step is too big. As using them directly might push the softmax into regions with very little gradient flow. Step 3: Once we have scores for all js, we pass these through a softmax. We get normalized value for each j. Step 4: Multiply softmax scores for each j with vi vector. The idea/purpose here is, very similar attention, to keep preserve only the values v of the input word(s) we want to focus on by multiplying them with high probability scores from softmax ~1, and remove the rest by driving them towards 0, i.e. making them very small by multiplying them with the low probability scores ~0 from softmax. ⚠️ A word of caution: the contents of this image may appear exponentially more complicated than they are. We will break this scary beast down into small baby beasts and it will all make sense. (I promise #2) Encoder: The encoder maps an input sequence of symbol representations (x1, ..., xn) to a sequence of representations z = (z1, ..., zn). Think of them as the outputs from self attention with some post-processing. Each encoder has two sub-layers. A multi-head self attention mechanism on the input vectors (Think parallelized and efficient sibling of self attention).A simple, position-wise fully connected feed-forward network (Think post-processing). A multi-head self attention mechanism on the input vectors (Think parallelized and efficient sibling of self attention). A simple, position-wise fully connected feed-forward network (Think post-processing). Check out this absolute bomb 3D diagram of the Encoder block used in BERT. Seriously you can’t miss this!!! It is like a whole new level of understanding. Decoder: Given z, the decoder then generates an output sequence (y1, ..., ym) of symbols one element at a time. Each decoder has three sub-layers. A masked multi-head self attention mechanism on the output vectors of the previous iteration.A multi-head attention mechanism on the output from encoder and masked multi-headed attention in decoder.A simple, position-wise fully connected feed-forward network (think post-processing). A masked multi-head self attention mechanism on the output vectors of the previous iteration. A multi-head attention mechanism on the output from encoder and masked multi-headed attention in decoder. A simple, position-wise fully connected feed-forward network (think post-processing). A few additional points: In the original paper, 6 layers were present in the encoder stack (2 sub-layer version) and 6 in the decoder stack (3 sub-layer version). All sub-layers in the model, as well as the embedding layers, produce outputs of the same dimension. This is done to facilitate the residual connections. We just noted that the output of each sub-layer needs to be of the same dimension which is 512 in our paper.=> zi needs to be of 512 dimensions. => vi needs to be of 512 dimensions as zi are just sort of weighted sums of vis. Additionally, we want to allow the model to focus on different positions is by calculating self attention multiple times with different sets of q, k and v vectors, then take an average of all those outputs to get our final z. So instead of dealing with these humongous vectors and averaging multiple outputs, we reduce the size of our k,q and v vectors to some smaller dimension — reduces size of Wq, Wk, and Wv matrices as well. We keep the multiple sets (h) of k,q and v and refer to each set as an “attention head”, hence the name multi-headed attention. And lastly, instead of averaging to get final z, we concatenate them. The size of the concatenated vector will be too large to be fed to the next sub-layer, so we scale it down by multiplying it with another learnt matrix Wo. Multiple attention heads allowed the model to jointly attend to information from different representation sub-spaces at different positions which was inhibited by averaging in a single attention head. The input words are represented using some form of embedding. This is done for both encoder and decoder. Word embedding on their own lack any positional information which is achieved in RNNs by virtue of their sequential nature. Meanwhile in self-attention, due to softmax, any such positional information is lost. To preserve the positional information, the transformer injects a vector to individual input embeddings (could be using word embeddings for corresponding to the input words). These vectors follow a specific periodic function (Example: combination of various sines/cosines having different frequency, in short not in sync with each other) that the model learns and is able to determine the position of individual word wrt each other based on the values . This injected vector is called “positional encoding” and are added to the input embeddings at the bottoms of both encoder and decoder stacks. The output of the decoder stack at each step is fed back to the decoder in the next time step — pretty similar to how outputs from previous steps in RNNs were used as next hidden states. And just as we did with the encoder inputs, we embed and add positional encoding to those decoder inputs to preserve the position of each word. This positional encoding + word embedding combo is then fed into a masked multi-headed self attention. This self-attention sub-layer in the decoder stack is modified to prevent positions from attending to subsequent positions — you can’t look at future words. This masking ensures that the predictions for position i can depend only on the known outputs at positions less than i. The outputs from the encoder stack are then used as multiple sets of key vectors k and value vectors v, for the “encoder decoder attention” — shown in green in the diagram — layer. It helps the decoder focus on the contextually relevant parts in the input sequence for that step. (The part similar to global attention vectors.) The q vector comes from the “output self attention” layer. Once we get the output from the decoder, we do a softmax again to select the final probabilities of words. Let’s finish with a quick wrap-up revision. We started with understanding what self attention is and how to calculate self-attention from these v, k ,q vectors. Multi-headed attention is an efficient modification of self attention that uses multiple smaller sets of v, k ,q and concatenates the outputs from each set to get the final z. Then we saw how and where the three kinds of self attention are used in the model. Followed by the pre-processing done on the inputs for the encoder and decoder stacks. Understanding Deep Attention in Deep Learning if you faced issues around attention. The Illustrated Transformer — Has great visualizations along with the explanations. https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/ YouTube video #1: A great resource to get the model intuition. Specially if you want to learn more about positional encoding. YouTube video#2: Talk by Lukasz Kaiser on this paper explaining self attention — . P.S. He is one of the authors for this paper. I’m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖 If you liked this article, do check out my other ones here. If you want to reach out to me, my medium of choice would be Twitter.
[ { "code": null, "e": 416, "s": 172, "text": "No, this article is not about the American sci-fi action movie series — no Optimus Prime here. It is also not about the electrical device that is used to transfer energy from one electrical circuit to another. What is this about then, you ask?" }, { "code": null, "e": 641, "s": 416, "text": "It is about the one in the most sci-fi fields of all time, Artificial Intelligence — Natural Language Processing in particular and it is pretty optimal at transferring information and primely used. (See what I did there. :P)" }, { "code": null, "e": 886, "s": 641, "text": "This post is based on the paper: Attention is All You Need. P.S. the authors were not kidding when they chose that title because you will need all the attention at your disposal for this one. But don’t let that scare you, it is SO SO worth it!!" }, { "code": null, "e": 1171, "s": 886, "text": "The Transformer in NLP is a novel architecture that aims to solve sequence-to-sequence tasks while handling long-range dependencies with ease. It relies entirely on self-attention to compute representations of its input and output WITHOUT using sequence-aligned RNNs or convolution. 🤯" }, { "code": null, "e": 1503, "s": 1171, "text": "If you recall my previous post, Understanding Attention In Deep Learning, we discussed how and why many models fell short when it came to handling long-range dependencies. The concept of attention somewhat allowed us to overcome that problem and now in Transformers we will build on top of attention and unleash its full potential." }, { "code": null, "e": 1526, "s": 1503, "text": "towardsdatascience.com" }, { "code": null, "e": 1779, "s": 1526, "text": "Let us start with revisiting what attention is in the NLP universe? Understanding Attention In Deep Learning. (I apologize for these blatant self-advertisements, but seriously give it a read. It will help you under Transformers much better. I promise.)" }, { "code": null, "e": 2175, "s": 1779, "text": "Attention allowed us to focus on parts of our input sequence while we predicted our output sequence. If our model predicted the word “rouge” [French translation for the color red], we are very likely to find a high weight-age for the word “red” in our input sequence. So attention, in a way, allowed us to map some connection/correlation between the input word “rouge” and the output word “red”." }, { "code": null, "e": 2354, "s": 2175, "text": "Self attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence." }, { "code": null, "e": 2484, "s": 2354, "text": "In simpler terms, self attention helps us create similar connections but within the same sentence. Look at the following example:" }, { "code": null, "e": 2634, "s": 2484, "text": "“I poured water from the bottle into the cup until it was full.”it => cup“I poured water from the bottle into the cup until it was empty.”it=> bottle" }, { "code": null, "e": 2798, "s": 2634, "text": "By changing one word “full” — > “empty” the reference object for “it” changed. If we are translating such a sentence, we will want to know the word “it” refers to." }, { "code": null, "e": 3408, "s": 2798, "text": "Encoder-Decoder Attention: Attention between the input sequence and the output sequence.Self attention in the input sequence: Attends to all the words in the input sequence.Self attention in the output sequence: One thing we should be wary of here is that the scope of self attention is limited to the words that occur before a given word. This prevents any information leaks during the training of the model. This is done by masking the words that occur after it for each step. So for step 1, only the first word of the output sequence is NOT masked, for step 2, the first two words are NOT masked and so on." }, { "code": null, "e": 3497, "s": 3408, "text": "Encoder-Decoder Attention: Attention between the input sequence and the output sequence." }, { "code": null, "e": 3583, "s": 3497, "text": "Self attention in the input sequence: Attends to all the words in the input sequence." }, { "code": null, "e": 4020, "s": 3583, "text": "Self attention in the output sequence: One thing we should be wary of here is that the scope of self attention is limited to the words that occur before a given word. This prevents any information leaks during the training of the model. This is done by masking the words that occur after it for each step. So for step 1, only the first word of the output sequence is NOT masked, for step 2, the first two words are NOT masked and so on." }, { "code": null, "e": 4296, "s": 4020, "text": "The three random words I just threw at you in this heading are vectors created as abstractions are useful for calculating self attention, more details on each below. These are calculated by multiplying your input vector(X) with weight matrices that are learnt while training." }, { "code": null, "e": 4356, "s": 4296, "text": "Query Vector: q= X * Wq. Think of this as the current word." }, { "code": null, "e": 4539, "s": 4356, "text": "Key Vector: k= X * Wk. Think of this as an indexing mechanism for Value vector. Similar to how we have key-value pairs in hash maps, where keys are used to uniquely index the values." }, { "code": null, "e": 4616, "s": 4539, "text": "Value Vector: v= X * Wv. Think of this as the information in the input word." }, { "code": null, "e": 5135, "s": 4616, "text": "What we want to do is take query q and find the most similar key k, by doing a dot product for q and k. The closest query-key product will have the highest value, followed by a softmax that will drive the q.k with smaller values close to 0 and q.k with larger values towards 1. This softmax distribution is multiplied with v. The value vectors multiplied with ~1 will get more attention while the ones ~0 will get less. The sizes of these q, k and v vectors are referred to as “hidden size” by various implementations." }, { "code": null, "e": 5234, "s": 5135, "text": "All these matrices Wq, Wk and Wv are learnt while being jointly trained during the model training." }, { "code": null, "e": 5290, "s": 5234, "text": "If we are calculating self attention for #i input word," }, { "code": null, "e": 5340, "s": 5290, "text": "Step 1: Multiply qi by the kj key vector of word." }, { "code": null, "e": 5659, "s": 5340, "text": "Step 2: Then divide this product by the square root of the dimension of key vector. This step is done for better gradient flow which is specially important in cases when the value of the dot product in previous step is too big. As using them directly might push the softmax into regions with very little gradient flow." }, { "code": null, "e": 5768, "s": 5659, "text": "Step 3: Once we have scores for all js, we pass these through a softmax. We get normalized value for each j." }, { "code": null, "e": 6163, "s": 5768, "text": "Step 4: Multiply softmax scores for each j with vi vector. The idea/purpose here is, very similar attention, to keep preserve only the values v of the input word(s) we want to focus on by multiplying them with high probability scores from softmax ~1, and remove the rest by driving them towards 0, i.e. making them very small by multiplying them with the low probability scores ~0 from softmax." }, { "code": null, "e": 6371, "s": 6163, "text": "⚠️ A word of caution: the contents of this image may appear exponentially more complicated than they are. We will break this scary beast down into small baby beasts and it will all make sense. (I promise #2)" }, { "code": null, "e": 6583, "s": 6371, "text": "Encoder: The encoder maps an input sequence of symbol representations (x1, ..., xn) to a sequence of representations z = (z1, ..., zn). Think of them as the outputs from self attention with some post-processing." }, { "code": null, "e": 6616, "s": 6583, "text": "Each encoder has two sub-layers." }, { "code": null, "e": 6822, "s": 6616, "text": "A multi-head self attention mechanism on the input vectors (Think parallelized and efficient sibling of self attention).A simple, position-wise fully connected feed-forward network (Think post-processing)." }, { "code": null, "e": 6943, "s": 6822, "text": "A multi-head self attention mechanism on the input vectors (Think parallelized and efficient sibling of self attention)." }, { "code": null, "e": 7029, "s": 6943, "text": "A simple, position-wise fully connected feed-forward network (Think post-processing)." }, { "code": null, "e": 7184, "s": 7029, "text": "Check out this absolute bomb 3D diagram of the Encoder block used in BERT. Seriously you can’t miss this!!! It is like a whole new level of understanding." }, { "code": null, "e": 7296, "s": 7184, "text": "Decoder: Given z, the decoder then generates an output sequence (y1, ..., ym) of symbols one element at a time." }, { "code": null, "e": 7331, "s": 7296, "text": "Each decoder has three sub-layers." }, { "code": null, "e": 7615, "s": 7331, "text": "A masked multi-head self attention mechanism on the output vectors of the previous iteration.A multi-head attention mechanism on the output from encoder and masked multi-headed attention in decoder.A simple, position-wise fully connected feed-forward network (think post-processing)." }, { "code": null, "e": 7709, "s": 7615, "text": "A masked multi-head self attention mechanism on the output vectors of the previous iteration." }, { "code": null, "e": 7815, "s": 7709, "text": "A multi-head attention mechanism on the output from encoder and masked multi-headed attention in decoder." }, { "code": null, "e": 7901, "s": 7815, "text": "A simple, position-wise fully connected feed-forward network (think post-processing)." }, { "code": null, "e": 7926, "s": 7901, "text": "A few additional points:" }, { "code": null, "e": 8064, "s": 7926, "text": "In the original paper, 6 layers were present in the encoder stack (2 sub-layer version) and 6 in the decoder stack (3 sub-layer version)." }, { "code": null, "e": 8218, "s": 8064, "text": "All sub-layers in the model, as well as the embedding layers, produce outputs of the same dimension. This is done to facilitate the residual connections." }, { "code": null, "e": 8444, "s": 8218, "text": "We just noted that the output of each sub-layer needs to be of the same dimension which is 512 in our paper.=> zi needs to be of 512 dimensions. => vi needs to be of 512 dimensions as zi are just sort of weighted sums of vis." }, { "code": null, "e": 8670, "s": 8444, "text": "Additionally, we want to allow the model to focus on different positions is by calculating self attention multiple times with different sets of q, k and v vectors, then take an average of all those outputs to get our final z." }, { "code": null, "e": 9072, "s": 8670, "text": "So instead of dealing with these humongous vectors and averaging multiple outputs, we reduce the size of our k,q and v vectors to some smaller dimension — reduces size of Wq, Wk, and Wv matrices as well. We keep the multiple sets (h) of k,q and v and refer to each set as an “attention head”, hence the name multi-headed attention. And lastly, instead of averaging to get final z, we concatenate them." }, { "code": null, "e": 9228, "s": 9072, "text": "The size of the concatenated vector will be too large to be fed to the next sub-layer, so we scale it down by multiplying it with another learnt matrix Wo." }, { "code": null, "e": 9429, "s": 9228, "text": "Multiple attention heads allowed the model to jointly attend to information from different representation sub-spaces at different positions which was inhibited by averaging in a single attention head." }, { "code": null, "e": 9534, "s": 9429, "text": "The input words are represented using some form of embedding. This is done for both encoder and decoder." }, { "code": null, "e": 9744, "s": 9534, "text": "Word embedding on their own lack any positional information which is achieved in RNNs by virtue of their sequential nature. Meanwhile in self-attention, due to softmax, any such positional information is lost." }, { "code": null, "e": 10198, "s": 9744, "text": "To preserve the positional information, the transformer injects a vector to individual input embeddings (could be using word embeddings for corresponding to the input words). These vectors follow a specific periodic function (Example: combination of various sines/cosines having different frequency, in short not in sync with each other) that the model learns and is able to determine the position of individual word wrt each other based on the values ." }, { "code": null, "e": 10340, "s": 10198, "text": "This injected vector is called “positional encoding” and are added to the input embeddings at the bottoms of both encoder and decoder stacks." }, { "code": null, "e": 10774, "s": 10340, "text": "The output of the decoder stack at each step is fed back to the decoder in the next time step — pretty similar to how outputs from previous steps in RNNs were used as next hidden states. And just as we did with the encoder inputs, we embed and add positional encoding to those decoder inputs to preserve the position of each word. This positional encoding + word embedding combo is then fed into a masked multi-headed self attention." }, { "code": null, "e": 11051, "s": 10774, "text": "This self-attention sub-layer in the decoder stack is modified to prevent positions from attending to subsequent positions — you can’t look at future words. This masking ensures that the predictions for position i can depend only on the known outputs at positions less than i." }, { "code": null, "e": 11438, "s": 11051, "text": "The outputs from the encoder stack are then used as multiple sets of key vectors k and value vectors v, for the “encoder decoder attention” — shown in green in the diagram — layer. It helps the decoder focus on the contextually relevant parts in the input sequence for that step. (The part similar to global attention vectors.) The q vector comes from the “output self attention” layer." }, { "code": null, "e": 11545, "s": 11438, "text": "Once we get the output from the decoder, we do a softmax again to select the final probabilities of words." }, { "code": null, "e": 11589, "s": 11545, "text": "Let’s finish with a quick wrap-up revision." }, { "code": null, "e": 11706, "s": 11589, "text": "We started with understanding what self attention is and how to calculate self-attention from these v, k ,q vectors." }, { "code": null, "e": 11882, "s": 11706, "text": "Multi-headed attention is an efficient modification of self attention that uses multiple smaller sets of v, k ,q and concatenates the outputs from each set to get the final z." }, { "code": null, "e": 11965, "s": 11882, "text": "Then we saw how and where the three kinds of self attention are used in the model." }, { "code": null, "e": 12051, "s": 11965, "text": "Followed by the pre-processing done on the inputs for the encoder and decoder stacks." }, { "code": null, "e": 12135, "s": 12051, "text": "Understanding Deep Attention in Deep Learning if you faced issues around attention." }, { "code": null, "e": 12219, "s": 12135, "text": "The Illustrated Transformer — Has great visualizations along with the explanations." }, { "code": null, "e": 12320, "s": 12219, "text": "https://www.analyticsvidhya.com/blog/2019/06/understanding-transformers-nlp-state-of-the-art-models/" }, { "code": null, "e": 12446, "s": 12320, "text": "YouTube video #1: A great resource to get the model intuition. Specially if you want to learn more about positional encoding." }, { "code": null, "e": 12575, "s": 12446, "text": "YouTube video#2: Talk by Lukasz Kaiser on this paper explaining self attention — . P.S. He is one of the authors for this paper." }, { "code": null, "e": 12708, "s": 12575, "text": "I’m glad you made it till the end of this article. 🎉I hope your reading experience was as enriching as the one I had writing this. 💖" }, { "code": null, "e": 12768, "s": 12708, "text": "If you liked this article, do check out my other ones here." } ]
Jupyter Notebook - IPyWidgets
IPyWidgets is a Python library of HTML interactive widgets for Jupyter notebook. Each UI element in the library can respond to events and invokes specified event handler functions. They enhance the interactive feature of Jupyter notebook application. In order to incorporate widgets in the notebook, we have to import the following module as shown below − from ipywidgets import widgets Some basic IPyWidgets are explained here − The widgets.text() function renders widgets in the notebook. It is similar to text box form element in HTML. The object of this widget has on_submit() method which listens to activity of the text field and can invoke event handler given as an argument to it. This widget is similar to HTML button. When it is clicked, the event is registered by on_click() method which calls the click event handler. A slider control which displays the incrementing integer values. There is also a FloatSlider and IntRangeSlider (changing integer between a range) This widget is useful to display non editable text in the notebook. This function from ipywidgets module renders the widget object in notebook’s input cell. This function automatically renders a widget depending upon type of data argument given to it. First argument to this function is the event handler and second is a value passed to event handler itself. Following example shows three label widgets, two text widgets and a button with ‘add’ caption. When the button is clicked, sum of numbers in two text input fields is displayed on the lowermost label. 22 Lectures 49 mins Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2911, "s": 2660, "text": "IPyWidgets is a Python library of HTML interactive widgets for Jupyter notebook. Each UI element in the library can respond to events and invokes specified event handler functions. They enhance the interactive feature of Jupyter notebook application." }, { "code": null, "e": 3016, "s": 2911, "text": "In order to incorporate widgets in the notebook, we have to import the following module as shown below −" }, { "code": null, "e": 3048, "s": 3016, "text": "from ipywidgets import widgets\n" }, { "code": null, "e": 3091, "s": 3048, "text": "Some basic IPyWidgets are explained here −" }, { "code": null, "e": 3350, "s": 3091, "text": "The widgets.text() function renders widgets in the notebook. It is similar to text box form element in HTML. The object of this widget has on_submit() method which listens to activity of the text field and can invoke event handler given as an argument to it." }, { "code": null, "e": 3491, "s": 3350, "text": "This widget is similar to HTML button. When it is clicked, the event is registered by on_click() method which calls the click event handler." }, { "code": null, "e": 3638, "s": 3491, "text": "A slider control which displays the incrementing integer values. There is also a FloatSlider and IntRangeSlider (changing integer between a range)" }, { "code": null, "e": 3706, "s": 3638, "text": "This widget is useful to display non editable text in the notebook." }, { "code": null, "e": 3795, "s": 3706, "text": "This function from ipywidgets module renders the widget object in notebook’s input cell." }, { "code": null, "e": 3997, "s": 3795, "text": "This function automatically renders a widget depending upon type of data argument given to it. First argument to this function is the event handler and second is a value passed to event handler itself." }, { "code": null, "e": 4197, "s": 3997, "text": "Following example shows three label widgets, two text widgets and a button with ‘add’ caption. When the button is clicked, sum of numbers in two text input fields is displayed on the lowermost label." }, { "code": null, "e": 4229, "s": 4197, "text": "\n 22 Lectures \n 49 mins\n" }, { "code": null, "e": 4247, "s": 4229, "text": " Bigdata Engineer" }, { "code": null, "e": 4254, "s": 4247, "text": " Print" }, { "code": null, "e": 4265, "s": 4254, "text": " Add Notes" } ]
Using Python's matplotlib to visualise spatial data | Towards Data Science
As part of a project to predict house prices, I was handed a large dataset of housing data from King County, Washington, USA. This dataset contained a wide range of house-related data, including the latitude and longitude of each house sold within a one-year period. As latitude and longitude are both continuous numerical data, these are potentially useful features to use in a multiple linear regression model. However, even before getting to that stage of the project, seeing latitude and longitude in a dataset is a sign that the exciting world of spatial data mapping is also available to you. Several free or low-cost GUI-based spreadsheet programs with semi-functional mapping capabilities do exist — from the cumbersome Excel Power Map, to the limited Google My Maps, to the sadly soon-to-be discontinued Google Fusion Tables. However, with just a few lines of code you can create informative map-like visualisations using Python much more quickly, with far more options for customisation. And you don’t even need knowledge of niche geospatial analysis libraries to do it — as long as you have latitude and longitude in your dataset, you can visualise it using everyone’s favourite graphing buddy matplotlib. Histograms are a great way to visualise the distribution of a variable in a dataset, by showing the number of entries in your dataset that lie in particular value ranges, or bins. The code below produces simple (one-dimensional) histograms for latitude and longitude in the King County (‘kc’) dataset: import matplotlib.pyplot as pltfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))fig.suptitle(‘Distributions of latitude and longitude in the King County housing dataset’, fontsize=16)ax1.hist(kc.lat)ax1.set_xlabel(‘Latitude’, fontsize=13)ax1.set_ylabel(‘Frequency’, fontsize=13)ax2.hist(kc.long)ax2.set_xlabel(‘Longitude’, fontsize=13)ax2.set_ylabel(‘Frequency’, fontsize=13); These work fine as a way to show the distribution of each individual variable, but they don’t really give you a sense of what this looks like geographically. What we want is a map. Luckily enough, we can achieve this with a two-dimensional histogram. This is essentially combining a histogram along the x axis (longitude) with a histogram along the y axis (latitude). Instead of the bins being the width of the bars (i.e. a single dimension) they are now essentially a grid (i.e. a square of two dimensions). We can add a colorbar with plt.colorbar() to help us visualise this as a kind of heatmap: plt.figure(figsize = (10,8))plt.hist2d(kc.long, kc.lat, bins=150, cmap=’hot’)plt.colorbar().set_label(‘Number of properties’)plt.xlabel(‘Longitude’, fontsize=14)plt.ylabel(‘Latitude’, fontsize=14)plt.title(‘Number of properties in each area of King County, Washington’, fontsize=17)plt.show() And if you look closely and squint a bit, you can make out the shape of King County with Seattle towards the top left, and the shape of the Puget Sound. One other way of plotting spatial data with matplotlib is by using scatterplots. Scatterplots visualise the relationship between two variables, one on the x axis and one on the y axis, by plotting points for each datapoint at the values for its x and y variables. Matplotlib allows us to go one step further, and use a third variable to change the colour (or shape, or size) of each point in accordance with the datapoint’s value for this third variable. The King County database contains, among other things, the price at which each house was sold and the size of the living space of each house. From looking at the 2D histogram above, it’s clear that a lot of properties are found in and around Seattle, but that the dataset also includes properties further away from the city. Lot size is likely to vary in a non-random way, with smaller lots in the city and larger lots in the country. Therefore, a better metric to compare like-for-like is to compare price per square foot. In this scatterplot, longitude and latitude are plotted, and points are coloured by their price per square foot to produce a map of how expensive each area is: plt.figure(figsize = (10,8))plt.scatter(kc.long, kc.lat ,c=kc.price_per_sqft, cmap = ‘hot’, s=1)plt.colorbar().set_label(‘Price per square foot ($)’, fontsize=14)plt.xlabel(‘Longitude’, fontsize=14)plt.ylabel(‘Latitude’, fontsize=14)plt.title(‘House prices in King County, Washington’, fontsize=17)plt.show() Not surprisingly, the most expensive properties (in terms of price per square foot) are found in Bellevue and Medina — home of tech billionaires Bill Gates and Jeff Bezos, as well as some of the most expensive zipcodes in the country. So there we are — two methods for creating map-like viualisations using matplotlib. The next time you find yourself in possession of a dataset including latitude and longitude, why not give them a try!
[ { "code": null, "e": 770, "s": 171, "text": "As part of a project to predict house prices, I was handed a large dataset of housing data from King County, Washington, USA. This dataset contained a wide range of house-related data, including the latitude and longitude of each house sold within a one-year period. As latitude and longitude are both continuous numerical data, these are potentially useful features to use in a multiple linear regression model. However, even before getting to that stage of the project, seeing latitude and longitude in a dataset is a sign that the exciting world of spatial data mapping is also available to you." }, { "code": null, "e": 1388, "s": 770, "text": "Several free or low-cost GUI-based spreadsheet programs with semi-functional mapping capabilities do exist — from the cumbersome Excel Power Map, to the limited Google My Maps, to the sadly soon-to-be discontinued Google Fusion Tables. However, with just a few lines of code you can create informative map-like visualisations using Python much more quickly, with far more options for customisation. And you don’t even need knowledge of niche geospatial analysis libraries to do it — as long as you have latitude and longitude in your dataset, you can visualise it using everyone’s favourite graphing buddy matplotlib." }, { "code": null, "e": 1690, "s": 1388, "text": "Histograms are a great way to visualise the distribution of a variable in a dataset, by showing the number of entries in your dataset that lie in particular value ranges, or bins. The code below produces simple (one-dimensional) histograms for latitude and longitude in the King County (‘kc’) dataset:" }, { "code": null, "e": 2071, "s": 1690, "text": "import matplotlib.pyplot as pltfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))fig.suptitle(‘Distributions of latitude and longitude in the King County housing dataset’, fontsize=16)ax1.hist(kc.lat)ax1.set_xlabel(‘Latitude’, fontsize=13)ax1.set_ylabel(‘Frequency’, fontsize=13)ax2.hist(kc.long)ax2.set_xlabel(‘Longitude’, fontsize=13)ax2.set_ylabel(‘Frequency’, fontsize=13);" }, { "code": null, "e": 2670, "s": 2071, "text": "These work fine as a way to show the distribution of each individual variable, but they don’t really give you a sense of what this looks like geographically. What we want is a map. Luckily enough, we can achieve this with a two-dimensional histogram. This is essentially combining a histogram along the x axis (longitude) with a histogram along the y axis (latitude). Instead of the bins being the width of the bars (i.e. a single dimension) they are now essentially a grid (i.e. a square of two dimensions). We can add a colorbar with plt.colorbar() to help us visualise this as a kind of heatmap:" }, { "code": null, "e": 2963, "s": 2670, "text": "plt.figure(figsize = (10,8))plt.hist2d(kc.long, kc.lat, bins=150, cmap=’hot’)plt.colorbar().set_label(‘Number of properties’)plt.xlabel(‘Longitude’, fontsize=14)plt.ylabel(‘Latitude’, fontsize=14)plt.title(‘Number of properties in each area of King County, Washington’, fontsize=17)plt.show()" }, { "code": null, "e": 3116, "s": 2963, "text": "And if you look closely and squint a bit, you can make out the shape of King County with Seattle towards the top left, and the shape of the Puget Sound." }, { "code": null, "e": 3571, "s": 3116, "text": "One other way of plotting spatial data with matplotlib is by using scatterplots. Scatterplots visualise the relationship between two variables, one on the x axis and one on the y axis, by plotting points for each datapoint at the values for its x and y variables. Matplotlib allows us to go one step further, and use a third variable to change the colour (or shape, or size) of each point in accordance with the datapoint’s value for this third variable." }, { "code": null, "e": 4095, "s": 3571, "text": "The King County database contains, among other things, the price at which each house was sold and the size of the living space of each house. From looking at the 2D histogram above, it’s clear that a lot of properties are found in and around Seattle, but that the dataset also includes properties further away from the city. Lot size is likely to vary in a non-random way, with smaller lots in the city and larger lots in the country. Therefore, a better metric to compare like-for-like is to compare price per square foot." }, { "code": null, "e": 4255, "s": 4095, "text": "In this scatterplot, longitude and latitude are plotted, and points are coloured by their price per square foot to produce a map of how expensive each area is:" }, { "code": null, "e": 4564, "s": 4255, "text": "plt.figure(figsize = (10,8))plt.scatter(kc.long, kc.lat ,c=kc.price_per_sqft, cmap = ‘hot’, s=1)plt.colorbar().set_label(‘Price per square foot ($)’, fontsize=14)plt.xlabel(‘Longitude’, fontsize=14)plt.ylabel(‘Latitude’, fontsize=14)plt.title(‘House prices in King County, Washington’, fontsize=17)plt.show()" }, { "code": null, "e": 4799, "s": 4564, "text": "Not surprisingly, the most expensive properties (in terms of price per square foot) are found in Bellevue and Medina — home of tech billionaires Bill Gates and Jeff Bezos, as well as some of the most expensive zipcodes in the country." } ]
Introduction to PonyGE2 for Grammatical Evolution | by Peter Adam | Towards Data Science
Grammatical Evolution is a powerful method for algorithm optimisation. Given an objective function and a search space (grammar), it is possible to use evolutionary computing methods to evolve an algorithm to optimally (or at least efficiently) maximise the objective function. PonyGE2 is a Python3 implementation which makes GE easy. This walkthrough discusses the pros and cons of GE and provides an example of how to evolve your own algorithms with GE. A paper describing fully the operation of PonyGE2 can be found here. Unfortunately, Grammatical Evolution with PonyGE2 on current computers isn’t fast enough to evolve functions from large grammars in a reasonable time quite yet, but this technique is definitely one to keep an eye on in the future. The method was first proposed by Dr. Michael O’Neill (paywall) in 2001 as a way to apply evolutionary computing methods to problems with a Formal Grammatical Structure, such as algorithms. A Formal Grammar can be thought of as the set of rules that define a language, or just an official way of setting out what combination of words makes sense. In English, we learn these from our parents when learning to speak, and in school. When learning a second language, it can generally be broken down into two steps: Learn vocabularyLearn the grammar Learn vocabulary Learn the grammar Programming isn’t much different, and the major difference between programming languages isn’t what you’re trying to achieve, but how you tell them computer to do that. So then how do we teach grammar to computers? And how are these words then used in evolutionary optimisation? The process works something like this: Define a Backus Naur Form (BNF) representation of the grammar;Randomly generate linear chromosomes to encode information;Evaluate the fitness of chromosomes by mapping the grammar to the chromosome and testing against the fitness function;Use Genetic Operators such as Crossover, Mutation and Reproduction to generate next generation of chromosomes;Repeat steps 3 and 4 for a certain number of generations. Define a Backus Naur Form (BNF) representation of the grammar; Randomly generate linear chromosomes to encode information; Evaluate the fitness of chromosomes by mapping the grammar to the chromosome and testing against the fitness function; Use Genetic Operators such as Crossover, Mutation and Reproduction to generate next generation of chromosomes; Repeat steps 3 and 4 for a certain number of generations. A BNF grammar is a way of writing grammar that computers can understand (context free). In Python, it is represented by a tuple containing 4 sets: T: The terminal Set N: The non-terminal set P: Set of production rules S: Start symbol (which is a member of N). This probably doesn’t clear things up, but it’s good to keep in mind. Let’s look at an example: T = {+, -, /, *, x, y} So the terminal set is the set of all operators and variables you want to use in your program. N = {<e>, <o>, <v>} The non-terminal set is the set of all production activities that the program can undertake. In this situation, <e> is an expression, <o> is an operator, and <v> is a variable. P then is the set of production rules: <e> ::= <e><o><e> | <v><o> ::= + | - | / | *<v> ::= x | y Notice that all entries inP are entries of either T or N . The pipe operator | represents or . So when an <e> is encountered in the chromosome, it is either replaced with <e><o><e> , or <v> , and likewise for <o> and <v> . Finally, the start symbol: S = <e> This is probably still quite confusing, but the reason for representing the grammar in this form becomes apparent when evaluating a chromosome. The simplest way of describing chromosomes is as a non-negative integer array. The values don’t matter much, but the length does (more on this later). So for our example, let us call our chromosome: C: [4, 15, 75, 8, 41, 12] Now everything comes together. Remember our starting symbol was: <e> Now, according to our Production Rules P , when a <e> is encountered, it is either replaced with <e><o><e> or <v> . But how do we know which one? Well, the chromosome tells us. The first value of the chromosome is 4 , and there are 2 options for <e> in the production rules. 4 mod 2 is 0 , so we take the 0-th (zero-indexed, so really the 1-st entry) option from the production rules, <e><o><e> . So now our expression has expanded to <e><o><e> , and we’re evaluating the first entry <e>(as it’s not a member of the terminal set, we keep evaluating each entry until it is replaced with a member of the terminal set). We know there are 2 options for <e> in the Production Rules, so we take the 2nd entry in the chromosome, 15 , and 15 mod 2 gives 1, so we take the 1st (zero-indexed, so really the 2nd entry) option from the production rules, <v> . We continue with the following steps: Full Expression: <v><o><e> Current Expression: <v> Number of <v> options in Grammar: 2 Chromosome value: 75 75 mod 2 = 1 Replace <v> with y Full Expression: y <o><e> Current Expression: <o> Number of <o> options in Grammar: 4Chromosome value: 88 mod 4 = 0Replace <o> with + Full Expression: y + <e> Current Expression: <e> Number of <e> options in Grammar: 2 Chromosome value: 4141 mod 2 = 1 Replace <e> with <v> Full Expression: y + <v> Current Expression: <v> Number of <v> options in Grammar: 2 Chromosome value: 1212 mod 2 = 0Replace <v> with x Final Expression: y + x So we’ve turned our chromosome (array) into a function using our grammatical representation! Feel free to re-read this a few times, as it takes a while to understand where the expressions and operators come from. Now we have a grammatically correct function, we can evaluate the performance of this function against some fitness function. Those functions that perform well are then given a greater chance of passing on their DNA to the next generation of chromosomes. From this point, GE doesn’t differ greatly from other genetic algorithms, as the chromosomes are crossed-over and mutated to generate the next generation of chromosomes, which are then mapped to the grammar and tested against the fitness function. This continues for a user-specified number of generations, at the conclusion of which the most efficient (best score on the fitness function) algorithm is returned to you. Now that you (hopefully) have a bit more of an understanding of what Grammatical Evolution involves, you might be asking why it’s so good? First of all, it’s fast, really fast. By passing down information from generation to generation, it vastly improves on random search. Secondly, because the grammar is written by you, you can easily encode domain knowledge into the function. You might hear this a lot, and ask ‘What does that actually mean?’ (I know I do). Here are some examples: Allow access to all information you have, regardless of whether it’s useful. This can be achieved using a <v> expression in the grammar and include all variables you want. Make the program as complicated or simple as required. Including lots of options in the <e> (including duplicated options to alter the chance of a specific operator being chosen) allows easy manipulation of the complexity of the evolved program. Define level of accuracy of constants by setting <n> ::= 0|1|2|3|4|5|6|7|8|9 and then <const> ::= <n><n><n>.<n><n><n> to set constants between 0 and 999 with 3 decimal places of accuracy. Include functions with expressions include <fn>(<e>) and <fn> ::= sin | max This is all pretty cool, but GE does have some drawbacks. First of all, as mentioned above, the length of the chromosome does result in invalid programs. For the example above, if the second to last entry in the chromosome was 42 instead of 41, the <e> would’ve been replaced with <e><o><e> , but with no chromosome data left to evaluate these expressions. As this chromosome is invalid, it can’t be evaluated against the fitness function. So while a chromosome may contain close to a good solution, it will never be known. The converse of this is when the program is evolved without using the entire chromosome. The leftover data is known as a tail, and can be ignored. As such, it is generally better to construct chromosomes to have long tails, as this reduces the chance of invalid solutions occurring. Probably the biggest drawback however, is that grammar must be very very carefully constructed, and there is a bit of an art to constructing appropriate grammars and fitness functions for a problem. On top of this, ‘large’ grammars can take a long time to evolve. Grammars that include single-level for loops, if statements, list functions and dictionary operations can take upwards of 12 hours to evolve. Hopefully this improves in the future, but is the main thing stopping Grammatical Evolution from being a replacement for human code optimisers... So now you hopefully have a bit more of an understanding on how Grammatical Evolution, we can have a go at implementing a simple example in PonyGE2. PonyGE2 can be cloned or forked from here. There’s no setup required, and the evolution will run from the command line with the appropriate arguments. The best way to explore the package is to work through an example. We’ll try to evolve a function to find the maximum value in a list. This is easily achieved in Python with max() or functionally: for val in list: if val >= current_max: current_max = val The first step is to create a fitness function, or what we want to maximise or minimise. The terminology here is a little confusing, as we’re evolving a function, the result of which will optimise the fitness function. For now we’re just talking about the fitness function. All my code for these examples is contained at https://github.com/Padam-0/NC-GA There are a bunch of examples in PonyGE2/src/fitness , and to run your own, create a file called max_in_list.py in that folder, with a structure something like this: from fitness.base_ff_classes.base_ff import base_ffimport randomimport timeclass max_in_list(base_ff): def __init__(self): # Initialise base fitness function class. super().__init__() def evaluate(self, ind, **kwargs): p = ind.phenotype print("\n" + p) fitness = 0 for trial in range(50): self.test_list = generate_list() m = max(self.test_list) d = {'test_list': self.test_list} try: t0 = time.time() exec(p, d) t1 = time.time() guess = d['return_val'] fitness += len(p) v = abs(m - guess) if v <= 10**6: fitness += v else: fitness = self.default_fitness break if t1 - t0 < 10: fitness = self.default_fitness break else: fitness += (t1 - t0) * 1000 except: fitness = self.default_fitness break return fitnessdef generate_list(): return [random.randint(0, round(random.random() * 90 + 10, 0)) for i in range(9)] Let’s step through it line by line. Lines 1–3: Imports. base-ff is the class we’ll inherit from, random is used to generate the random list, and time to track execution time Line 5: Define the class, max_in_list , inheriting from base_ff . This needs to have the same name as the file you’re working in (which is max_in_list.py in this case). Line 6–9: Instance initialisation information for the class. Line 10: Create evaluate function with three parameters, self, ind, and kwargs. Up to this point, this is standard for each fitness function. What comes next is independent for each algorithm being evolved. Line 11–13: Returns the current algorithm from the evolution as p . We can print this to the command line (as we do in line 13), and see it. Line 15: Initialise fitness to 0 Line 17: Set a for loop to run 50 times. If we don’t do this, each algorithm will run on the same ‘random’ list, and may evolve a line such as m=49 which is then returned. 49 may happen to be in that list and the maximum value, so the computer thinks it has found the perfect algorithm. Short, fast and correct! But overfit to that one example. On any other list, where 49 is not in it (or not the maximum value), the algorithm would be wrong. So we give the fitness function 50 lists to look at, all with different values (and indeed maximum possible values) to avoid overfitting. Line 18: Create the random list self.test_list from the function generate_list() Jumping forward to the last few lines, this function generates 10 random integers between 0 , and some number between 10 and 100. This is best to avoid overfitting. Line 19: Find the maximum of the current list being used. It’s important to do this here and not after the algorithm has been executed, as the list may change during the execution (if list operations have been included in the grammar), so the correct result may not be returned. At this point you may (correctly) be asking, what’s the point of doing all this if we already have a function to find the maximum value of a list? That’s an excellent question, and the point of GE is to find a potentially more efficient way of doing this. For simple functions it’s not really worth it, but is a good learning exercise. Line 21: Create a dictionary d with one entry test_list that holds the current list. This will make more sense when we write the grammar. Line 23 / 45–47: Try/Except statement. Generally it’s not a good idea to have an open ended Except statement, as you’ll never catch errors, but in this case, all errors can feasibly occur within the evolved algorithm (because it’s just putting words together at semi-random, so there’s no way they’re all going to be perfect code) so the statement is justified. If an error is returned, the fitness for that algorithm is set to the default (NA) and the loop broken out of, and the next algorithm tested. Line 24: Get the start time. Line 25: Execute the algorithm p and pass the parameters within d so they can be accessed. This is where the algorithm is actually evaluated. The value that is returned is written to the dictionary d as return_val (we define this in the grammar). Line 26: Get the end time. Line 28: Retrieve the maximum value guess from the current algorithm. Line 30: Increase the current fitness score by the length of the algorithm. This is to avoid bloat and unnecessary if statements. The evolution tries to keep things as short as possible. Line 32: Find the difference between the actual maximum value of the list and the guess. Best case scenario this is 0, but if not, it is a proxy for how close the algorithm was to getting the right answer. Line 33–37: There are some algorithms which may produce completely outsize guesses which will crash the evolution, so it’s best to keep an if statement to check the value isn’t above some large (but not too large) number that would never be feasible. Again, if this check fails, set the fitness to NA and move onto the next algorithm. Otherwise, add the difference between the guess and correct value to the current fitness score. Line 39–43: Some algorithms (with multi-level for loops, or for i in range(1000) statements) take a very long time to evaluate. Unless this is expected, this indicates an error, so an if statement to catch those which take more than some time (10 seconds in this case) is recommended. If the algorithm takes less than this, the time can be added to the fitness score, so that algorithms that work faster are rewarded with a lower fitness. Because the time-scale is so small, scaling this part of the score up by a factor of 100 or 1000 is recommended. Line 49: Return the fitness, and we’re done! That was a lot to take in, and a few bits may not make sense, but we’ll push on a write the grammar, and hopefully with the full picture it will be a bit clearer. This is the difficult part, as you have to be very precise and thoughtful with what you write. We’ll step through the base grammar required to evolve our max function, but grammar extensions that include additional logic, list functions, and dictionary functions are available at https://github.com/Padam-0/NC-GA. Once again, PonyGE2 provides grammar examples in the PonyGE2/grammars directory. Create yours in there (it can be called anything, but give it the extensions .pybnf ). The first line contains the starting point for the program: <fc> ::= <deff>{::}<callf> In English, this says: <fc> is the starting symbol, which contains one option: <deff> followed by a newline ({::} represents a newline, {: is an indent (tab or 4 spaces) and :} closes the indent), followed by <callf> . The next line, we define <deff> : <deff> ::= def fun(li):{:m = 0{::}<code>{::}return m:} This looks a bit more like Python. We can see we have a function definition of a function called fun() with one argument li . Next we open an indent (like Python requires), initialise our variable m=0 , start a new line, write some <code> , start a new line, return m , then close the indent. Again, there is only one option for <deff> , so this will definitely be written. Next, <callf> : <callf> ::= return_val = fun(test_list) Again, this looks more like Python. And only one option, so regardless of the chromosome, our algorithm will always look something like this: def fun(li): m = 0 <code> return mreturn_val = fun(test_list) The <code> section is where the evolution gets done, but in most cases we’ll now have a working function. Cool hey! It gets cooler. Remember in our fitness function, we gave our dictionary d a key called test_list? Well, because we call exec(p, d) , the program can see the contents of that dictionary d , so when it sees test_list in the algorithm, it replaces it with the value corresponding to test_list in the dictionary d , or in our case, the random list we want to find the maximum of! Cool huh, now we have a way of passing data from our fitness function into our evolved function. And again, in our fitness function, we set guess = d['return_val'] ? Well it turns out not only can we read from d , we can write to it, and the value returned from fun(test_list) is passed to d as return_val , so then we can access the returned value of the evolved algorithm in the fitness function, so we can access its fitness! So we now can send data in both directions, I recommend going and re-reading the section on the fitness function to see if this all makes a bit more sense now. It definitely does for me. As for the rest of our grammar: <code> ::= <stmt> | <stmt>{::}<code> Code is either a single statement, or a statement followed by some more code on a new line. This way we can give ourselves multi-line functions! This recursive nature of the grammar is very useful, and will come up quite a lot to enable us to add complexity to the evolution. <stmt> ::= <var> = <expr> | <for> | <if> A statement is then either assigning an expression to a variable, a for loop, or an if statement. Let’s look at these in reverse order: <if> ::= if <cond>:<if-opt><if-opt> ::= {:<code>:} | {:<code>:}else:{:<code>:} | {:<code>:}elif <cond>:{:<if-opt>:}<cond> ::= <expr> <c-op> <expr><c-op> ::= ">=" | "<=" | ">" | "<" So the if statement takes a condition, and then an option. The condition takes the form of an expression, an operator, and an expression. To make this clearer, it’s worth discussing the <expr> tag now: <expr> ::= <number> | <var> | <expr> <op> <expr> So an expression is either a number, a variable, or an operation (more on all of these later). Back to our if statement, our condition takes the form if <cond>: which expands to: if <expr> <c-op> <expr>: Which can then expand to something like: if <var> >= <number>: And we have an if statement we recognise. The <if-opt> are a little more complex, as they have to include elif and else functionality, but they all boil down to an if statement, a condition, and then some <code> being written inside them. Next, for loops: <for> ::= for i in <list-var>:{:<fl-code>:}<fl-stmt> ::= <var> = <expr> | <fl-if><fl-code> ::= <fl-stmt> | <fl-stmt>{::}<fl-code> So the for loop takes the form for i in list: then creates an indent (on a new line) for some statement. The statement itself could just be our <stmt> from above, but this would allow nested for loops, which can exponentially increase evaluation time. Unless you think nested for loops are absolutely necessary, avoid them (this is a pretty good rule for programming in general). So our <fl-stmt> only includes variable assignment, and a special if statement, <fl-if> : <fl-if> ::= if <cond>:<fl-if-opt><fl-if-opt> ::= {:<fl-code>:} | {:<fl-code>:}else:{:<fl-code>:} | {:<fl-code>:}elif <cond>:{:<fl-if-opt>:} This is actually identical to the if statement grammar above, but instead of calling <code> , it calls <fl-code> , basically to avoid for loops inside if statements inside for loops. A little cumbersome, but better than allowing nested for loops! Finally, variable assignment. We’ve already looked at <expr> , so let’s look at parts that make it up: <var> ::= m | i<list-var> ::= li<number> ::= <num><num><num> | <num><num> | <num><num> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9<op> ::= + | - | * | / | // | % This should be pretty straightforward. Our variables are m which we initialised at the beginning, and i which is initialised if a for-loop is run. Numbers can go from 0 to 999, and we have all the python operators (except exponential, which can cause integer overflow and a whole bunch of very slow to execute algorithms. Like the nested for loops, only include it if you need it). And believe it or not, that’s our grammar done! Let’s see how we can go from a <code> tag to our final function. A chromosome like: [0, 1, 0, 1, 0, 1, 1, 2, 1, 0, 0, 0, 0, 1, 1] Mapped out, this gives us: def fun(li): for i in li: if i > m: m = ireturn_val = fun(test_list) Sweet! Now that we have our fitness function and our grammar, how can we run this with PonyGE2? Well, if the fitness function is in PonyGE2/src/fitness (and has the same filename as the class it holds, max_in_list in this case), and the grammar is in PonyGE2/grammars, we can run from the command line: python ponyge.py --fitness_function max_in_list --grammar_file max_in_list.pybnf This will run your evolution with your grammar and fitness function, with default parameters for other options. There are a lot, and it’s worth reading the reference documentation, but the two really important ones are Population size and Number of generations. The population size is the number of chromosomes generated at the beginning, and evolved at each generation. The larger this number, the wider the search, but the slower the evolution time. The number of generations is the number of evolutions that the chromosomes go through. Again, it widens the search but at the cost of evolution speed. You can set these parameters with: python ponyge.py --fitness_function max_in_list --grammar_file MIL_e2.pybnf --population_size 500 --generations 100 Now for simple grammars, values for these parameters in the range of 100–500 is sufficient, but as the grammars get more complex, they require more population and generations to ensure a sufficient algorithm is evolved. A good test is to add complexity to your grammar, and run it with the same fitness function as above. If you get a function which finds the maximum in a list, you can be confident that your parameters are appropriate, and then turn it onto your other fitness function for the problem you’re trying to solve. Unfortunately, run times get large quite quickly. For me, a population of 2000 and 750 generations took around 6 and a half hours, and that wasn’t enough to evolve an appropriate algorithm with the grammar above (but also including list and dictionary operations). And herein lies the issue with GE. The promise is that if you can write a fitness function, and a robust grammar that encompasses a wide range of Python operations, then GE will be able to evolve a more efficient way of doing things. Unfortunately, the processing power and time this takes at present is infeasible on public machines. Regardless, this is a field to watch, as if we’re going to teach machines to code, there’s a good bet that Grammatical Evolution will have something to do with it. The team at UCD Natural Computing Research and Applications Group are the cutting edge of this research, and have published many great papers showing the power of GE (albeit on supercomputers). Some include: A Search for Improved Performance in Regular Expressions; Optimising complex pylon structures with grammatical evolution; and Combining structural analysis and multi-objective criteria for evolutionary architectural design. If you liked this post, please click the ❤ button to let your followers know, or let me know your thoughts below or on Twitter @padams02.
[ { "code": null, "e": 448, "s": 171, "text": "Grammatical Evolution is a powerful method for algorithm optimisation. Given an objective function and a search space (grammar), it is possible to use evolutionary computing methods to evolve an algorithm to optimally (or at least efficiently) maximise the objective function." }, { "code": null, "e": 695, "s": 448, "text": "PonyGE2 is a Python3 implementation which makes GE easy. This walkthrough discusses the pros and cons of GE and provides an example of how to evolve your own algorithms with GE. A paper describing fully the operation of PonyGE2 can be found here." }, { "code": null, "e": 926, "s": 695, "text": "Unfortunately, Grammatical Evolution with PonyGE2 on current computers isn’t fast enough to evolve functions from large grammars in a reasonable time quite yet, but this technique is definitely one to keep an eye on in the future." }, { "code": null, "e": 1115, "s": 926, "text": "The method was first proposed by Dr. Michael O’Neill (paywall) in 2001 as a way to apply evolutionary computing methods to problems with a Formal Grammatical Structure, such as algorithms." }, { "code": null, "e": 1436, "s": 1115, "text": "A Formal Grammar can be thought of as the set of rules that define a language, or just an official way of setting out what combination of words makes sense. In English, we learn these from our parents when learning to speak, and in school. When learning a second language, it can generally be broken down into two steps:" }, { "code": null, "e": 1470, "s": 1436, "text": "Learn vocabularyLearn the grammar" }, { "code": null, "e": 1487, "s": 1470, "text": "Learn vocabulary" }, { "code": null, "e": 1505, "s": 1487, "text": "Learn the grammar" }, { "code": null, "e": 1674, "s": 1505, "text": "Programming isn’t much different, and the major difference between programming languages isn’t what you’re trying to achieve, but how you tell them computer to do that." }, { "code": null, "e": 1784, "s": 1674, "text": "So then how do we teach grammar to computers? And how are these words then used in evolutionary optimisation?" }, { "code": null, "e": 1823, "s": 1784, "text": "The process works something like this:" }, { "code": null, "e": 2230, "s": 1823, "text": "Define a Backus Naur Form (BNF) representation of the grammar;Randomly generate linear chromosomes to encode information;Evaluate the fitness of chromosomes by mapping the grammar to the chromosome and testing against the fitness function;Use Genetic Operators such as Crossover, Mutation and Reproduction to generate next generation of chromosomes;Repeat steps 3 and 4 for a certain number of generations." }, { "code": null, "e": 2293, "s": 2230, "text": "Define a Backus Naur Form (BNF) representation of the grammar;" }, { "code": null, "e": 2353, "s": 2293, "text": "Randomly generate linear chromosomes to encode information;" }, { "code": null, "e": 2472, "s": 2353, "text": "Evaluate the fitness of chromosomes by mapping the grammar to the chromosome and testing against the fitness function;" }, { "code": null, "e": 2583, "s": 2472, "text": "Use Genetic Operators such as Crossover, Mutation and Reproduction to generate next generation of chromosomes;" }, { "code": null, "e": 2641, "s": 2583, "text": "Repeat steps 3 and 4 for a certain number of generations." }, { "code": null, "e": 2788, "s": 2641, "text": "A BNF grammar is a way of writing grammar that computers can understand (context free). In Python, it is represented by a tuple containing 4 sets:" }, { "code": null, "e": 2808, "s": 2788, "text": "T: The terminal Set" }, { "code": null, "e": 2832, "s": 2808, "text": "N: The non-terminal set" }, { "code": null, "e": 2859, "s": 2832, "text": "P: Set of production rules" }, { "code": null, "e": 2901, "s": 2859, "text": "S: Start symbol (which is a member of N)." }, { "code": null, "e": 2997, "s": 2901, "text": "This probably doesn’t clear things up, but it’s good to keep in mind. Let’s look at an example:" }, { "code": null, "e": 3020, "s": 2997, "text": "T = {+, -, /, *, x, y}" }, { "code": null, "e": 3115, "s": 3020, "text": "So the terminal set is the set of all operators and variables you want to use in your program." }, { "code": null, "e": 3135, "s": 3115, "text": "N = {<e>, <o>, <v>}" }, { "code": null, "e": 3312, "s": 3135, "text": "The non-terminal set is the set of all production activities that the program can undertake. In this situation, <e> is an expression, <o> is an operator, and <v> is a variable." }, { "code": null, "e": 3351, "s": 3312, "text": "P then is the set of production rules:" }, { "code": null, "e": 3409, "s": 3351, "text": "<e> ::= <e><o><e> | <v><o> ::= + | - | / | *<v> ::= x | y" }, { "code": null, "e": 3632, "s": 3409, "text": "Notice that all entries inP are entries of either T or N . The pipe operator | represents or . So when an <e> is encountered in the chromosome, it is either replaced with <e><o><e> , or <v> , and likewise for <o> and <v> ." }, { "code": null, "e": 3659, "s": 3632, "text": "Finally, the start symbol:" }, { "code": null, "e": 3667, "s": 3659, "text": "S = <e>" }, { "code": null, "e": 3811, "s": 3667, "text": "This is probably still quite confusing, but the reason for representing the grammar in this form becomes apparent when evaluating a chromosome." }, { "code": null, "e": 3962, "s": 3811, "text": "The simplest way of describing chromosomes is as a non-negative integer array. The values don’t matter much, but the length does (more on this later)." }, { "code": null, "e": 4010, "s": 3962, "text": "So for our example, let us call our chromosome:" }, { "code": null, "e": 4036, "s": 4010, "text": "C: [4, 15, 75, 8, 41, 12]" }, { "code": null, "e": 4101, "s": 4036, "text": "Now everything comes together. Remember our starting symbol was:" }, { "code": null, "e": 4105, "s": 4101, "text": "<e>" }, { "code": null, "e": 4502, "s": 4105, "text": "Now, according to our Production Rules P , when a <e> is encountered, it is either replaced with <e><o><e> or <v> . But how do we know which one? Well, the chromosome tells us. The first value of the chromosome is 4 , and there are 2 options for <e> in the production rules. 4 mod 2 is 0 , so we take the 0-th (zero-indexed, so really the 1-st entry) option from the production rules, <e><o><e> ." }, { "code": null, "e": 4722, "s": 4502, "text": "So now our expression has expanded to <e><o><e> , and we’re evaluating the first entry <e>(as it’s not a member of the terminal set, we keep evaluating each entry until it is replaced with a member of the terminal set)." }, { "code": null, "e": 4953, "s": 4722, "text": "We know there are 2 options for <e> in the Production Rules, so we take the 2nd entry in the chromosome, 15 , and 15 mod 2 gives 1, so we take the 1st (zero-indexed, so really the 2nd entry) option from the production rules, <v> ." }, { "code": null, "e": 4991, "s": 4953, "text": "We continue with the following steps:" }, { "code": null, "e": 5131, "s": 4991, "text": "Full Expression: <v><o><e> Current Expression: <v> Number of <v> options in Grammar: 2 Chromosome value: 75 75 mod 2 = 1 Replace <v> with y" }, { "code": null, "e": 5265, "s": 5131, "text": "Full Expression: y <o><e> Current Expression: <o> Number of <o> options in Grammar: 4Chromosome value: 88 mod 4 = 0Replace <o> with +" }, { "code": null, "e": 5404, "s": 5265, "text": "Full Expression: y + <e> Current Expression: <e> Number of <e> options in Grammar: 2 Chromosome value: 4141 mod 2 = 1 Replace <e> with <v>" }, { "code": null, "e": 5540, "s": 5404, "text": "Full Expression: y + <v> Current Expression: <v> Number of <v> options in Grammar: 2 Chromosome value: 1212 mod 2 = 0Replace <v> with x" }, { "code": null, "e": 5564, "s": 5540, "text": "Final Expression: y + x" }, { "code": null, "e": 5777, "s": 5564, "text": "So we’ve turned our chromosome (array) into a function using our grammatical representation! Feel free to re-read this a few times, as it takes a while to understand where the expressions and operators come from." }, { "code": null, "e": 6280, "s": 5777, "text": "Now we have a grammatically correct function, we can evaluate the performance of this function against some fitness function. Those functions that perform well are then given a greater chance of passing on their DNA to the next generation of chromosomes. From this point, GE doesn’t differ greatly from other genetic algorithms, as the chromosomes are crossed-over and mutated to generate the next generation of chromosomes, which are then mapped to the grammar and tested against the fitness function." }, { "code": null, "e": 6452, "s": 6280, "text": "This continues for a user-specified number of generations, at the conclusion of which the most efficient (best score on the fitness function) algorithm is returned to you." }, { "code": null, "e": 6591, "s": 6452, "text": "Now that you (hopefully) have a bit more of an understanding of what Grammatical Evolution involves, you might be asking why it’s so good?" }, { "code": null, "e": 6725, "s": 6591, "text": "First of all, it’s fast, really fast. By passing down information from generation to generation, it vastly improves on random search." }, { "code": null, "e": 6938, "s": 6725, "text": "Secondly, because the grammar is written by you, you can easily encode domain knowledge into the function. You might hear this a lot, and ask ‘What does that actually mean?’ (I know I do). Here are some examples:" }, { "code": null, "e": 7110, "s": 6938, "text": "Allow access to all information you have, regardless of whether it’s useful. This can be achieved using a <v> expression in the grammar and include all variables you want." }, { "code": null, "e": 7356, "s": 7110, "text": "Make the program as complicated or simple as required. Including lots of options in the <e> (including duplicated options to alter the chance of a specific operator being chosen) allows easy manipulation of the complexity of the evolved program." }, { "code": null, "e": 7544, "s": 7356, "text": "Define level of accuracy of constants by setting <n> ::= 0|1|2|3|4|5|6|7|8|9 and then <const> ::= <n><n><n>.<n><n><n> to set constants between 0 and 999 with 3 decimal places of accuracy." }, { "code": null, "e": 7620, "s": 7544, "text": "Include functions with expressions include <fn>(<e>) and <fn> ::= sin | max" }, { "code": null, "e": 8144, "s": 7620, "text": "This is all pretty cool, but GE does have some drawbacks. First of all, as mentioned above, the length of the chromosome does result in invalid programs. For the example above, if the second to last entry in the chromosome was 42 instead of 41, the <e> would’ve been replaced with <e><o><e> , but with no chromosome data left to evaluate these expressions. As this chromosome is invalid, it can’t be evaluated against the fitness function. So while a chromosome may contain close to a good solution, it will never be known." }, { "code": null, "e": 8427, "s": 8144, "text": "The converse of this is when the program is evolved without using the entire chromosome. The leftover data is known as a tail, and can be ignored. As such, it is generally better to construct chromosomes to have long tails, as this reduces the chance of invalid solutions occurring." }, { "code": null, "e": 8979, "s": 8427, "text": "Probably the biggest drawback however, is that grammar must be very very carefully constructed, and there is a bit of an art to constructing appropriate grammars and fitness functions for a problem. On top of this, ‘large’ grammars can take a long time to evolve. Grammars that include single-level for loops, if statements, list functions and dictionary operations can take upwards of 12 hours to evolve. Hopefully this improves in the future, but is the main thing stopping Grammatical Evolution from being a replacement for human code optimisers..." }, { "code": null, "e": 9128, "s": 8979, "text": "So now you hopefully have a bit more of an understanding on how Grammatical Evolution, we can have a go at implementing a simple example in PonyGE2." }, { "code": null, "e": 9279, "s": 9128, "text": "PonyGE2 can be cloned or forked from here. There’s no setup required, and the evolution will run from the command line with the appropriate arguments." }, { "code": null, "e": 9476, "s": 9279, "text": "The best way to explore the package is to work through an example. We’ll try to evolve a function to find the maximum value in a list. This is easily achieved in Python with max() or functionally:" }, { "code": null, "e": 9544, "s": 9476, "text": "for val in list: if val >= current_max: current_max = val" }, { "code": null, "e": 9818, "s": 9544, "text": "The first step is to create a fitness function, or what we want to maximise or minimise. The terminology here is a little confusing, as we’re evolving a function, the result of which will optimise the fitness function. For now we’re just talking about the fitness function." }, { "code": null, "e": 9898, "s": 9818, "text": "All my code for these examples is contained at https://github.com/Padam-0/NC-GA" }, { "code": null, "e": 10064, "s": 9898, "text": "There are a bunch of examples in PonyGE2/src/fitness , and to run your own, create a file called max_in_list.py in that folder, with a structure something like this:" }, { "code": null, "e": 11283, "s": 10064, "text": "from fitness.base_ff_classes.base_ff import base_ffimport randomimport timeclass max_in_list(base_ff): def __init__(self): # Initialise base fitness function class. super().__init__() def evaluate(self, ind, **kwargs): p = ind.phenotype print(\"\\n\" + p) fitness = 0 for trial in range(50): self.test_list = generate_list() m = max(self.test_list) d = {'test_list': self.test_list} try: t0 = time.time() exec(p, d) t1 = time.time() guess = d['return_val'] fitness += len(p) v = abs(m - guess) if v <= 10**6: fitness += v else: fitness = self.default_fitness break if t1 - t0 < 10: fitness = self.default_fitness break else: fitness += (t1 - t0) * 1000 except: fitness = self.default_fitness break return fitnessdef generate_list(): return [random.randint(0, round(random.random() * 90 + 10, 0)) for i in range(9)]" }, { "code": null, "e": 11319, "s": 11283, "text": "Let’s step through it line by line." }, { "code": null, "e": 11330, "s": 11319, "text": "Lines 1–3:" }, { "code": null, "e": 11457, "s": 11330, "text": "Imports. base-ff is the class we’ll inherit from, random is used to generate the random list, and time to track execution time" }, { "code": null, "e": 11465, "s": 11457, "text": "Line 5:" }, { "code": null, "e": 11626, "s": 11465, "text": "Define the class, max_in_list , inheriting from base_ff . This needs to have the same name as the file you’re working in (which is max_in_list.py in this case)." }, { "code": null, "e": 11636, "s": 11626, "text": "Line 6–9:" }, { "code": null, "e": 11687, "s": 11636, "text": "Instance initialisation information for the class." }, { "code": null, "e": 11696, "s": 11687, "text": "Line 10:" }, { "code": null, "e": 11767, "s": 11696, "text": "Create evaluate function with three parameters, self, ind, and kwargs." }, { "code": null, "e": 11894, "s": 11767, "text": "Up to this point, this is standard for each fitness function. What comes next is independent for each algorithm being evolved." }, { "code": null, "e": 11906, "s": 11894, "text": "Line 11–13:" }, { "code": null, "e": 12035, "s": 11906, "text": "Returns the current algorithm from the evolution as p . We can print this to the command line (as we do in line 13), and see it." }, { "code": null, "e": 12044, "s": 12035, "text": "Line 15:" }, { "code": null, "e": 12068, "s": 12044, "text": "Initialise fitness to 0" }, { "code": null, "e": 12077, "s": 12068, "text": "Line 17:" }, { "code": null, "e": 12650, "s": 12077, "text": "Set a for loop to run 50 times. If we don’t do this, each algorithm will run on the same ‘random’ list, and may evolve a line such as m=49 which is then returned. 49 may happen to be in that list and the maximum value, so the computer thinks it has found the perfect algorithm. Short, fast and correct! But overfit to that one example. On any other list, where 49 is not in it (or not the maximum value), the algorithm would be wrong. So we give the fitness function 50 lists to look at, all with different values (and indeed maximum possible values) to avoid overfitting." }, { "code": null, "e": 12659, "s": 12650, "text": "Line 18:" }, { "code": null, "e": 12731, "s": 12659, "text": "Create the random list self.test_list from the function generate_list()" }, { "code": null, "e": 12896, "s": 12731, "text": "Jumping forward to the last few lines, this function generates 10 random integers between 0 , and some number between 10 and 100. This is best to avoid overfitting." }, { "code": null, "e": 12905, "s": 12896, "text": "Line 19:" }, { "code": null, "e": 13175, "s": 12905, "text": "Find the maximum of the current list being used. It’s important to do this here and not after the algorithm has been executed, as the list may change during the execution (if list operations have been included in the grammar), so the correct result may not be returned." }, { "code": null, "e": 13511, "s": 13175, "text": "At this point you may (correctly) be asking, what’s the point of doing all this if we already have a function to find the maximum value of a list? That’s an excellent question, and the point of GE is to find a potentially more efficient way of doing this. For simple functions it’s not really worth it, but is a good learning exercise." }, { "code": null, "e": 13520, "s": 13511, "text": "Line 21:" }, { "code": null, "e": 13649, "s": 13520, "text": "Create a dictionary d with one entry test_list that holds the current list. This will make more sense when we write the grammar." }, { "code": null, "e": 13666, "s": 13649, "text": "Line 23 / 45–47:" }, { "code": null, "e": 14011, "s": 13666, "text": "Try/Except statement. Generally it’s not a good idea to have an open ended Except statement, as you’ll never catch errors, but in this case, all errors can feasibly occur within the evolved algorithm (because it’s just putting words together at semi-random, so there’s no way they’re all going to be perfect code) so the statement is justified." }, { "code": null, "e": 14153, "s": 14011, "text": "If an error is returned, the fitness for that algorithm is set to the default (NA) and the loop broken out of, and the next algorithm tested." }, { "code": null, "e": 14162, "s": 14153, "text": "Line 24:" }, { "code": null, "e": 14182, "s": 14162, "text": "Get the start time." }, { "code": null, "e": 14191, "s": 14182, "text": "Line 25:" }, { "code": null, "e": 14429, "s": 14191, "text": "Execute the algorithm p and pass the parameters within d so they can be accessed. This is where the algorithm is actually evaluated. The value that is returned is written to the dictionary d as return_val (we define this in the grammar)." }, { "code": null, "e": 14438, "s": 14429, "text": "Line 26:" }, { "code": null, "e": 14456, "s": 14438, "text": "Get the end time." }, { "code": null, "e": 14465, "s": 14456, "text": "Line 28:" }, { "code": null, "e": 14526, "s": 14465, "text": "Retrieve the maximum value guess from the current algorithm." }, { "code": null, "e": 14535, "s": 14526, "text": "Line 30:" }, { "code": null, "e": 14713, "s": 14535, "text": "Increase the current fitness score by the length of the algorithm. This is to avoid bloat and unnecessary if statements. The evolution tries to keep things as short as possible." }, { "code": null, "e": 14722, "s": 14713, "text": "Line 32:" }, { "code": null, "e": 14919, "s": 14722, "text": "Find the difference between the actual maximum value of the list and the guess. Best case scenario this is 0, but if not, it is a proxy for how close the algorithm was to getting the right answer." }, { "code": null, "e": 14931, "s": 14919, "text": "Line 33–37:" }, { "code": null, "e": 15170, "s": 14931, "text": "There are some algorithms which may produce completely outsize guesses which will crash the evolution, so it’s best to keep an if statement to check the value isn’t above some large (but not too large) number that would never be feasible." }, { "code": null, "e": 15350, "s": 15170, "text": "Again, if this check fails, set the fitness to NA and move onto the next algorithm. Otherwise, add the difference between the guess and correct value to the current fitness score." }, { "code": null, "e": 15362, "s": 15350, "text": "Line 39–43:" }, { "code": null, "e": 15635, "s": 15362, "text": "Some algorithms (with multi-level for loops, or for i in range(1000) statements) take a very long time to evaluate. Unless this is expected, this indicates an error, so an if statement to catch those which take more than some time (10 seconds in this case) is recommended." }, { "code": null, "e": 15902, "s": 15635, "text": "If the algorithm takes less than this, the time can be added to the fitness score, so that algorithms that work faster are rewarded with a lower fitness. Because the time-scale is so small, scaling this part of the score up by a factor of 100 or 1000 is recommended." }, { "code": null, "e": 15911, "s": 15902, "text": "Line 49:" }, { "code": null, "e": 15947, "s": 15911, "text": "Return the fitness, and we’re done!" }, { "code": null, "e": 16110, "s": 15947, "text": "That was a lot to take in, and a few bits may not make sense, but we’ll push on a write the grammar, and hopefully with the full picture it will be a bit clearer." }, { "code": null, "e": 16424, "s": 16110, "text": "This is the difficult part, as you have to be very precise and thoughtful with what you write. We’ll step through the base grammar required to evolve our max function, but grammar extensions that include additional logic, list functions, and dictionary functions are available at https://github.com/Padam-0/NC-GA." }, { "code": null, "e": 16592, "s": 16424, "text": "Once again, PonyGE2 provides grammar examples in the PonyGE2/grammars directory. Create yours in there (it can be called anything, but give it the extensions .pybnf )." }, { "code": null, "e": 16652, "s": 16592, "text": "The first line contains the starting point for the program:" }, { "code": null, "e": 16679, "s": 16652, "text": "<fc> ::= <deff>{::}<callf>" }, { "code": null, "e": 16702, "s": 16679, "text": "In English, this says:" }, { "code": null, "e": 16898, "s": 16702, "text": "<fc> is the starting symbol, which contains one option: <deff> followed by a newline ({::} represents a newline, {: is an indent (tab or 4 spaces) and :} closes the indent), followed by <callf> ." }, { "code": null, "e": 16932, "s": 16898, "text": "The next line, we define <deff> :" }, { "code": null, "e": 16987, "s": 16932, "text": "<deff> ::= def fun(li):{:m = 0{::}<code>{::}return m:}" }, { "code": null, "e": 17113, "s": 16987, "text": "This looks a bit more like Python. We can see we have a function definition of a function called fun() with one argument li ." }, { "code": null, "e": 17280, "s": 17113, "text": "Next we open an indent (like Python requires), initialise our variable m=0 , start a new line, write some <code> , start a new line, return m , then close the indent." }, { "code": null, "e": 17377, "s": 17280, "text": "Again, there is only one option for <deff> , so this will definitely be written. Next, <callf> :" }, { "code": null, "e": 17417, "s": 17377, "text": "<callf> ::= return_val = fun(test_list)" }, { "code": null, "e": 17559, "s": 17417, "text": "Again, this looks more like Python. And only one option, so regardless of the chromosome, our algorithm will always look something like this:" }, { "code": null, "e": 17630, "s": 17559, "text": "def fun(li): m = 0 <code> return mreturn_val = fun(test_list)" }, { "code": null, "e": 17762, "s": 17630, "text": "The <code> section is where the evolution gets done, but in most cases we’ll now have a working function. Cool hey! It gets cooler." }, { "code": null, "e": 18220, "s": 17762, "text": "Remember in our fitness function, we gave our dictionary d a key called test_list? Well, because we call exec(p, d) , the program can see the contents of that dictionary d , so when it sees test_list in the algorithm, it replaces it with the value corresponding to test_list in the dictionary d , or in our case, the random list we want to find the maximum of! Cool huh, now we have a way of passing data from our fitness function into our evolved function." }, { "code": null, "e": 18552, "s": 18220, "text": "And again, in our fitness function, we set guess = d['return_val'] ? Well it turns out not only can we read from d , we can write to it, and the value returned from fun(test_list) is passed to d as return_val , so then we can access the returned value of the evolved algorithm in the fitness function, so we can access its fitness!" }, { "code": null, "e": 18739, "s": 18552, "text": "So we now can send data in both directions, I recommend going and re-reading the section on the fitness function to see if this all makes a bit more sense now. It definitely does for me." }, { "code": null, "e": 18771, "s": 18739, "text": "As for the rest of our grammar:" }, { "code": null, "e": 18808, "s": 18771, "text": "<code> ::= <stmt> | <stmt>{::}<code>" }, { "code": null, "e": 19084, "s": 18808, "text": "Code is either a single statement, or a statement followed by some more code on a new line. This way we can give ourselves multi-line functions! This recursive nature of the grammar is very useful, and will come up quite a lot to enable us to add complexity to the evolution." }, { "code": null, "e": 19125, "s": 19084, "text": "<stmt> ::= <var> = <expr> | <for> | <if>" }, { "code": null, "e": 19261, "s": 19125, "text": "A statement is then either assigning an expression to a variable, a for loop, or an if statement. Let’s look at these in reverse order:" }, { "code": null, "e": 19442, "s": 19261, "text": "<if> ::= if <cond>:<if-opt><if-opt> ::= {:<code>:} | {:<code>:}else:{:<code>:} | {:<code>:}elif <cond>:{:<if-opt>:}<cond> ::= <expr> <c-op> <expr><c-op> ::= \">=\" | \"<=\" | \">\" | \"<\"" }, { "code": null, "e": 19580, "s": 19442, "text": "So the if statement takes a condition, and then an option. The condition takes the form of an expression, an operator, and an expression." }, { "code": null, "e": 19644, "s": 19580, "text": "To make this clearer, it’s worth discussing the <expr> tag now:" }, { "code": null, "e": 19693, "s": 19644, "text": "<expr> ::= <number> | <var> | <expr> <op> <expr>" }, { "code": null, "e": 19788, "s": 19693, "text": "So an expression is either a number, a variable, or an operation (more on all of these later)." }, { "code": null, "e": 19872, "s": 19788, "text": "Back to our if statement, our condition takes the form if <cond>: which expands to:" }, { "code": null, "e": 19897, "s": 19872, "text": "if <expr> <c-op> <expr>:" }, { "code": null, "e": 19938, "s": 19897, "text": "Which can then expand to something like:" }, { "code": null, "e": 19960, "s": 19938, "text": "if <var> >= <number>:" }, { "code": null, "e": 20199, "s": 19960, "text": "And we have an if statement we recognise. The <if-opt> are a little more complex, as they have to include elif and else functionality, but they all boil down to an if statement, a condition, and then some <code> being written inside them." }, { "code": null, "e": 20216, "s": 20199, "text": "Next, for loops:" }, { "code": null, "e": 20346, "s": 20216, "text": "<for> ::= for i in <list-var>:{:<fl-code>:}<fl-stmt> ::= <var> = <expr> | <fl-if><fl-code> ::= <fl-stmt> | <fl-stmt>{::}<fl-code>" }, { "code": null, "e": 20726, "s": 20346, "text": "So the for loop takes the form for i in list: then creates an indent (on a new line) for some statement. The statement itself could just be our <stmt> from above, but this would allow nested for loops, which can exponentially increase evaluation time. Unless you think nested for loops are absolutely necessary, avoid them (this is a pretty good rule for programming in general)." }, { "code": null, "e": 20816, "s": 20726, "text": "So our <fl-stmt> only includes variable assignment, and a special if statement, <fl-if> :" }, { "code": null, "e": 20956, "s": 20816, "text": "<fl-if> ::= if <cond>:<fl-if-opt><fl-if-opt> ::= {:<fl-code>:} | {:<fl-code>:}else:{:<fl-code>:} | {:<fl-code>:}elif <cond>:{:<fl-if-opt>:}" }, { "code": null, "e": 21203, "s": 20956, "text": "This is actually identical to the if statement grammar above, but instead of calling <code> , it calls <fl-code> , basically to avoid for loops inside if statements inside for loops. A little cumbersome, but better than allowing nested for loops!" }, { "code": null, "e": 21306, "s": 21203, "text": "Finally, variable assignment. We’ve already looked at <expr> , so let’s look at parts that make it up:" }, { "code": null, "e": 21466, "s": 21306, "text": "<var> ::= m | i<list-var> ::= li<number> ::= <num><num><num> | <num><num> | <num><num> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9<op> ::= + | - | * | / | // | %" }, { "code": null, "e": 21848, "s": 21466, "text": "This should be pretty straightforward. Our variables are m which we initialised at the beginning, and i which is initialised if a for-loop is run. Numbers can go from 0 to 999, and we have all the python operators (except exponential, which can cause integer overflow and a whole bunch of very slow to execute algorithms. Like the nested for loops, only include it if you need it)." }, { "code": null, "e": 21980, "s": 21848, "text": "And believe it or not, that’s our grammar done! Let’s see how we can go from a <code> tag to our final function. A chromosome like:" }, { "code": null, "e": 22026, "s": 21980, "text": "[0, 1, 0, 1, 0, 1, 1, 2, 1, 0, 0, 0, 0, 1, 1]" }, { "code": null, "e": 22053, "s": 22026, "text": "Mapped out, this gives us:" }, { "code": null, "e": 22143, "s": 22053, "text": "def fun(li): for i in li: if i > m: m = ireturn_val = fun(test_list)" }, { "code": null, "e": 22239, "s": 22143, "text": "Sweet! Now that we have our fitness function and our grammar, how can we run this with PonyGE2?" }, { "code": null, "e": 22446, "s": 22239, "text": "Well, if the fitness function is in PonyGE2/src/fitness (and has the same filename as the class it holds, max_in_list in this case), and the grammar is in PonyGE2/grammars, we can run from the command line:" }, { "code": null, "e": 22527, "s": 22446, "text": "python ponyge.py --fitness_function max_in_list --grammar_file max_in_list.pybnf" }, { "code": null, "e": 22789, "s": 22527, "text": "This will run your evolution with your grammar and fitness function, with default parameters for other options. There are a lot, and it’s worth reading the reference documentation, but the two really important ones are Population size and Number of generations." }, { "code": null, "e": 22979, "s": 22789, "text": "The population size is the number of chromosomes generated at the beginning, and evolved at each generation. The larger this number, the wider the search, but the slower the evolution time." }, { "code": null, "e": 23130, "s": 22979, "text": "The number of generations is the number of evolutions that the chromosomes go through. Again, it widens the search but at the cost of evolution speed." }, { "code": null, "e": 23165, "s": 23130, "text": "You can set these parameters with:" }, { "code": null, "e": 23281, "s": 23165, "text": "python ponyge.py --fitness_function max_in_list --grammar_file MIL_e2.pybnf --population_size 500 --generations 100" }, { "code": null, "e": 23809, "s": 23281, "text": "Now for simple grammars, values for these parameters in the range of 100–500 is sufficient, but as the grammars get more complex, they require more population and generations to ensure a sufficient algorithm is evolved. A good test is to add complexity to your grammar, and run it with the same fitness function as above. If you get a function which finds the maximum in a list, you can be confident that your parameters are appropriate, and then turn it onto your other fitness function for the problem you’re trying to solve." }, { "code": null, "e": 24074, "s": 23809, "text": "Unfortunately, run times get large quite quickly. For me, a population of 2000 and 750 generations took around 6 and a half hours, and that wasn’t enough to evolve an appropriate algorithm with the grammar above (but also including list and dictionary operations)." }, { "code": null, "e": 24409, "s": 24074, "text": "And herein lies the issue with GE. The promise is that if you can write a fitness function, and a robust grammar that encompasses a wide range of Python operations, then GE will be able to evolve a more efficient way of doing things. Unfortunately, the processing power and time this takes at present is infeasible on public machines." }, { "code": null, "e": 24573, "s": 24409, "text": "Regardless, this is a field to watch, as if we’re going to teach machines to code, there’s a good bet that Grammatical Evolution will have something to do with it." }, { "code": null, "e": 24781, "s": 24573, "text": "The team at UCD Natural Computing Research and Applications Group are the cutting edge of this research, and have published many great papers showing the power of GE (albeit on supercomputers). Some include:" }, { "code": null, "e": 24839, "s": 24781, "text": "A Search for Improved Performance in Regular Expressions;" }, { "code": null, "e": 24907, "s": 24839, "text": "Optimising complex pylon structures with grammatical evolution; and" }, { "code": null, "e": 25005, "s": 24907, "text": "Combining structural analysis and multi-objective criteria for evolutionary architectural design." } ]
Python 3 - Nested loops
Python programming language allows the usage of one loop inside another loop. The following section shows a few examples to illustrate the concept. for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s) The syntax for a nested while loop statement in Python programming language is as follows − while expression: while expression: statement(s) statement(s) A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a for loop can be inside a while loop or vice versa. The following program uses a nested-for loop to display multiplication tables from 1-10. #!/usr/bin/python3 import sys for i in range(1,11): for j in range(1,11): k = i*j print (k, end=' ') print() The print() function inner loop has end=' ' which appends a space instead of default newline. Hence, the numbers will appear in one row. Last print() will be executed at the end of inner for loop. When the above code is executed, it produces the following result − 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2340, "text": "Python programming language allows the usage of one loop inside another loop. The following section shows a few examples to illustrate the concept." }, { "code": null, "e": 2591, "s": 2488, "text": "for iterating_var in sequence:\n for iterating_var in sequence:\n statements(s)\n statements(s)\n" }, { "code": null, "e": 2683, "s": 2591, "text": "The syntax for a nested while loop statement in Python programming language is as follows −" }, { "code": null, "e": 2758, "s": 2683, "text": "while expression:\n while expression:\n statement(s)\n statement(s)\n" }, { "code": null, "e": 2920, "s": 2758, "text": "A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a for loop can be inside a while loop or vice versa." }, { "code": null, "e": 3009, "s": 2920, "text": "The following program uses a nested-for loop to display multiplication tables from 1-10." }, { "code": null, "e": 3137, "s": 3009, "text": "#!/usr/bin/python3\n\nimport sys\nfor i in range(1,11):\n for j in range(1,11):\n k = i*j\n print (k, end=' ')\n print()" }, { "code": null, "e": 3274, "s": 3137, "text": "The print() function inner loop has end=' ' which appends a space instead of default newline. Hence, the numbers will appear in one row." }, { "code": null, "e": 3334, "s": 3274, "text": "Last print() will be executed at the end of inner for loop." }, { "code": null, "e": 3402, "s": 3334, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3691, "s": 3402, "text": "1 2 3 4 5 6 7 8 9 10 \n2 4 6 8 10 12 14 16 18 20 \n3 6 9 12 15 18 21 24 27 30 \n4 8 12 16 20 24 28 32 36 40 \n5 10 15 20 25 30 35 40 45 50 \n6 12 18 24 30 36 42 48 54 60 \n7 14 21 28 35 42 49 56 63 70 \n8 16 24 32 40 48 56 64 72 80 \n9 18 27 36 45 54 63 72 81 90 \n10 20 30 40 50 60 70 80 90 100 \n" }, { "code": null, "e": 3728, "s": 3691, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3744, "s": 3728, "text": " Malhar Lathkar" }, { "code": null, "e": 3777, "s": 3744, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3796, "s": 3777, "text": " Arnab Chakraborty" }, { "code": null, "e": 3831, "s": 3796, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3853, "s": 3831, "text": " In28Minutes Official" }, { "code": null, "e": 3887, "s": 3853, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3915, "s": 3887, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3950, "s": 3915, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3964, "s": 3950, "text": " Lets Kode It" }, { "code": null, "e": 3997, "s": 3964, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4014, "s": 3997, "text": " Abhilash Nelson" }, { "code": null, "e": 4021, "s": 4014, "text": " Print" }, { "code": null, "e": 4032, "s": 4021, "text": " Add Notes" } ]
Sass - Functions
SASS supports the use of functions by providing some keyword arguments, which are specified using normal CSS function syntax. p { color: hsl($hue: 0, $saturation: 50%, $lightness: 50%); } HSL stands for hue, saturation, and lightness, which are more intuitive for creating a set of matching colors by using saturation and lightness. hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc. hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc. saturation − It is a percentage value that increases the saturation of color. saturation − It is a percentage value that increases the saturation of color. lightness − It is a percentage value which decreases the lightness of color. lightness − It is a percentage value which decreases the lightness of color. The following example demonstrates the use of functions in the SCSS file − <html> <head> <title>Functions Example</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Example using Functions</h2> <p>SASS stands for Syntactically Awesome Stylesheet..</p> </div> </body> </html> Next, create file style.scss. Use the following SCSS code which defines the HSL function on the SASS code. p { color: hsl(290,60%,70%); } You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command − sass --watch C:\ruby\lib\sass\style.scss:style.css Next, execute the above command; it will create the style.css file automatically with the following code − p { color: #d185e0; } Let us carry out the following steps to see how the above given code works − Save the above given html code in functions.html file. Save the above given html code in functions.html file. Open this HTML file in a browser, an output is displayed as shown below. Open this HTML file in a browser, an output is displayed as shown below. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 1978, "s": 1852, "text": "SASS supports the use of functions by providing some keyword arguments, which are specified using normal CSS function syntax." }, { "code": null, "e": 2044, "s": 1978, "text": "p {\n color: hsl($hue: 0, $saturation: 50%, $lightness: 50%);\n}\n" }, { "code": null, "e": 2189, "s": 2044, "text": "HSL stands for hue, saturation, and lightness, which are more intuitive for creating a set of matching colors by using saturation and lightness." }, { "code": null, "e": 2292, "s": 2189, "text": "hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc." }, { "code": null, "e": 2395, "s": 2292, "text": "hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc." }, { "code": null, "e": 2473, "s": 2395, "text": "saturation − It is a percentage value that increases the saturation of color." }, { "code": null, "e": 2551, "s": 2473, "text": "saturation − It is a percentage value that increases the saturation of color." }, { "code": null, "e": 2628, "s": 2551, "text": "lightness − It is a percentage value which decreases the lightness of color." }, { "code": null, "e": 2705, "s": 2628, "text": "lightness − It is a percentage value which decreases the lightness of color." }, { "code": null, "e": 2780, "s": 2705, "text": "The following example demonstrates the use of functions in the SCSS file −" }, { "code": null, "e": 3410, "s": 2780, "text": "<html>\n <head>\n <title>Functions Example</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\" />\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n </head>\n\n <body>\n <div class = \"container\">\n <h2>Example using Functions</h2>\n <p>SASS stands for Syntactically Awesome Stylesheet..</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3440, "s": 3410, "text": "Next, create file style.scss." }, { "code": null, "e": 3517, "s": 3440, "text": "Use the following SCSS code which defines the HSL function on the SASS code." }, { "code": null, "e": 3551, "s": 3517, "text": "p {\n color: hsl(290,60%,70%);\n}" }, { "code": null, "e": 3667, "s": 3551, "text": "You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −" }, { "code": null, "e": 3719, "s": 3667, "text": "sass --watch C:\\ruby\\lib\\sass\\style.scss:style.css\n" }, { "code": null, "e": 3826, "s": 3719, "text": "Next, execute the above command; it will create the style.css file automatically with the following code −" }, { "code": null, "e": 3851, "s": 3826, "text": "p {\n color: #d185e0;\n}" }, { "code": null, "e": 3928, "s": 3851, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 3983, "s": 3928, "text": "Save the above given html code in functions.html file." }, { "code": null, "e": 4038, "s": 3983, "text": "Save the above given html code in functions.html file." }, { "code": null, "e": 4111, "s": 4038, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4184, "s": 4111, "text": "Open this HTML file in a browser, an output is displayed as shown below." }, { "code": null, "e": 4219, "s": 4184, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4236, "s": 4219, "text": " Code And Create" }, { "code": null, "e": 4271, "s": 4236, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 4284, "s": 4271, "text": " Juan Galvan" }, { "code": null, "e": 4321, "s": 4284, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 4341, "s": 4321, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4378, "s": 4341, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 4394, "s": 4378, "text": " Muslim Helalee" }, { "code": null, "e": 4401, "s": 4394, "text": " Print" }, { "code": null, "e": 4412, "s": 4401, "text": " Add Notes" } ]
Recursive fibonacci method in Java
The fibonacci series is a series in which each number is the sum of the previous two numbers. The number at a particular position in the fibonacci series can be obtained using a recursive method. A program that demonstrates this is given as follows: Live Demo public class Demo { public static long fib(long n) { if ((n == 0) || (n == 1)) return n; else return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { System.out.println("The 0th fibonacci number is: " + fib(0)); System.out.println("The 7th fibonacci number is: " + fib(7)); System.out.println("The 12th fibonacci number is: " + fib(12)); } } The 0th fibonacci number is: 0 The 7th fibonacci number is: 13 The 12th fibonacci number is: 144 Now let us understand the above program. The method fib() calculates the fibonacci number at position n. If n is equal to 0 or 1, it returns n. Otherwise it recursively calls itself and returns fib(n - 1) + fib(n - 2). A code snippet which demonstrates this is as follows: public static long fib(long n) { if ((n == 0) || (n == 1)) return n; else return fib(n - 1) + fib(n - 2); } In main(), the method fib() is called with different values. A code snippet which demonstrates this is as follows: public static void main(String[] args) { System.out.println("The 0th fibonacci number is: " + fib(0)); System.out.println("The 7th fibonacci number is: " + fib(7)); System.out.println("The 12th fibonacci number is: " + fib(12)); }
[ { "code": null, "e": 1258, "s": 1062, "text": "The fibonacci series is a series in which each number is the sum of the previous two numbers. The number at a particular position in the fibonacci series can be obtained using a recursive method." }, { "code": null, "e": 1312, "s": 1258, "text": "A program that demonstrates this is given as follows:" }, { "code": null, "e": 1323, "s": 1312, "text": " Live Demo" }, { "code": null, "e": 1744, "s": 1323, "text": "public class Demo {\n public static long fib(long n) {\n if ((n == 0) || (n == 1))\n return n;\n else\n return fib(n - 1) + fib(n - 2);\n }\n public static void main(String[] args) {\n System.out.println(\"The 0th fibonacci number is: \" + fib(0));\n System.out.println(\"The 7th fibonacci number is: \" + fib(7));\n System.out.println(\"The 12th fibonacci number is: \" + fib(12));\n }\n}" }, { "code": null, "e": 1841, "s": 1744, "text": "The 0th fibonacci number is: 0\nThe 7th fibonacci number is: 13\nThe 12th fibonacci number is: 144" }, { "code": null, "e": 1882, "s": 1841, "text": "Now let us understand the above program." }, { "code": null, "e": 2114, "s": 1882, "text": "The method fib() calculates the fibonacci number at position n. If n is equal to 0 or 1, it returns n. Otherwise it recursively calls itself and returns fib(n - 1) + fib(n - 2). A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2240, "s": 2114, "text": "public static long fib(long n) {\n if ((n == 0) || (n == 1))\n return n;\n else\n return fib(n - 1) + fib(n - 2);\n}" }, { "code": null, "e": 2355, "s": 2240, "text": "In main(), the method fib() is called with different values. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2595, "s": 2355, "text": "public static void main(String[] args) {\n System.out.println(\"The 0th fibonacci number is: \" + fib(0));\n System.out.println(\"The 7th fibonacci number is: \" + fib(7));\n System.out.println(\"The 12th fibonacci number is: \" + fib(12));\n}" } ]
What are intent-filters in Android?
An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions. Before launching intent, android going to do action test, category test and data test. This example demonstrate about how to use intent filters in android. Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/buton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="intent filter button" /> </LinearLayout> In the above, we have given a button when you click on button it will show intent with action. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RadioButton; public class MainActivity extends AppCompatActivity { RadioButton radioButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button = findViewById(R.id.buton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact@tutorialspoint.com"}); intent.putExtra(Intent.EXTRA_SUBJECT, "Welcome to tutorialspoint.com"); startActivity(Intent.createChooser(intent, "Choose default Mail App")); } }); } } In the above when user click on button it will call intent using ACTION_SEND and will set type as message/rfc882. Now we passed out email id and subject message. Step 4 − Add the following code to manifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.andy.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <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" /> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="message/rfc822" /> </intent-filter> </activity> </application> </manifest> In the above we have declared action, category and data. 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 on above button it will call intent chooser to choose application to send data from intent as shown below - We have selected gmail application as shown below - In the above result, it going to take the data from intent and append to gmail application.
[ { "code": null, "e": 1393, "s": 1062, "text": "An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions." }, { "code": null, "e": 1549, "s": 1393, "text": "Before launching intent, android going to do action test, category test and data test. This example demonstrate about how to use intent filters in android." }, { "code": null, "e": 1677, "s": 1549, "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": 1742, "s": 1677, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2321, "s": 1742, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/buton\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"intent filter button\" />\n</LinearLayout>" }, { "code": null, "e": 2416, "s": 2321, "text": "In the above, we have given a button when you click on button it will show intent with action." }, { "code": null, "e": 2473, "s": 2416, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3514, "s": 2473, "text": "package com.example.andy.myapplication;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RadioButton;\npublic class MainActivity extends AppCompatActivity {\n RadioButton radioButton;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final Button button = findViewById(R.id.buton);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"message/rfc822\");\n intent.putExtra(Intent.EXTRA_EMAIL, new String[]{\"contact@tutorialspoint.com\"});\n intent.putExtra(Intent.EXTRA_SUBJECT, \"Welcome to tutorialspoint.com\");\n startActivity(Intent.createChooser(intent, \"Choose default Mail App\"));\n }\n });\n}\n}" }, { "code": null, "e": 3676, "s": 3514, "text": "In the above when user click on button it will call intent using ACTION_SEND and will set type as message/rfc882. Now we passed out email id and subject message." }, { "code": null, "e": 3724, "s": 3676, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 4668, "s": 3724, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.andy.myapplication\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\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 <action android:name=\"android.intent.action.SEND\" />\n <category android:name=\"android.intent.category.DEFAULT\" />\n <data android:mimeType=\"message/rfc822\" />\n </intent-filter>\n </activity>\n</application>\n</manifest>" }, { "code": null, "e": 5073, "s": 4668, "text": "In the above we have declared action, category and data. 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": 5187, "s": 5073, "text": "Click on above button it will call intent chooser to choose application to send data from intent as shown below -" }, { "code": null, "e": 5239, "s": 5187, "text": "We have selected gmail application as shown below -" }, { "code": null, "e": 5331, "s": 5239, "text": "In the above result, it going to take the data from intent and append to gmail application." } ]
JavaScript | Reverse a string in place. - GeeksforGeeks
16 May, 2019 In order to reverse the string in its place, We’re going to use a number of methods and the most preferred ones.We’re going to use these methods(click to know more). split() reverse() join() substr() Example-1: This example reverses the string by first splitting it with (“”) separator and then reversing it and finally joining it by (“”) separator. <!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Inplace Reverse </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = 'This is GeeksForGeeks'; el_up.innerHTML = "String = " + "'" + str + "'"; function gfg_Run() { el_down.innerHTML = str.split("").reverse().join(""); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2: This example uses the concept of merge sort algorithm. <!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Inplace Reverse </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = 'This is GeeksForGeeks'; el_up.innerHTML = "String = " + "'" + str + "'"; function reverse(s) { if (s.length < 2) return s; var hIndex = Math.ceil(s.length / 2); return reverse(s.substr(hIndex)) + reverse(s.substr(0, hIndex)); } function gfg_Run() { el_down.innerHTML = reverse(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-3:This example takes a variable and appending the result from the end of the string. <!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Inplace Reverse </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = 'A Computer Science Portal' el_up.innerHTML = "String = " + "'" + str + "'"; function reverse(s { for(var i = s.length - 1, o = ''; i >= 0; o += s[i--]) {} return o; } function gfg_Run() { el_down.innerHTML = reverse(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-string 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 Convert a string to an integer in JavaScript Form validation using HTML and JavaScript JavaScript | console.log() with Examples Installation of Node.js on Linux Express.js express.Router() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24123, "s": 24095, "text": "\n16 May, 2019" }, { "code": null, "e": 24289, "s": 24123, "text": "In order to reverse the string in its place, We’re going to use a number of methods and the most preferred ones.We’re going to use these methods(click to know more)." }, { "code": null, "e": 24297, "s": 24289, "text": "split()" }, { "code": null, "e": 24307, "s": 24297, "text": "reverse()" }, { "code": null, "e": 24314, "s": 24307, "text": "join()" }, { "code": null, "e": 24323, "s": 24314, "text": "substr()" }, { "code": null, "e": 24473, "s": 24323, "text": "Example-1: This example reverses the string by first splitting it with (“”) separator and then reversing it and finally joining it by (“”) separator." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Inplace Reverse </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = 'This is GeeksForGeeks'; el_up.innerHTML = \"String = \" + \"'\" + str + \"'\"; function gfg_Run() { el_down.innerHTML = str.split(\"\").reverse().join(\"\"); } </script></body> </html>", "e": 25323, "s": 24473, "text": null }, { "code": null, "e": 25331, "s": 25323, "text": "Output:" }, { "code": null, "e": 25362, "s": 25331, "text": "Before clicking on the button:" }, { "code": null, "e": 25392, "s": 25362, "text": "After clicking on the button:" }, { "code": null, "e": 25458, "s": 25392, "text": "Example-2: This example uses the concept of merge sort algorithm." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Inplace Reverse </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = 'This is GeeksForGeeks'; el_up.innerHTML = \"String = \" + \"'\" + str + \"'\"; function reverse(s) { if (s.length < 2) return s; var hIndex = Math.ceil(s.length / 2); return reverse(s.substr(hIndex)) + reverse(s.substr(0, hIndex)); } function gfg_Run() { el_down.innerHTML = reverse(str); } </script></body> </html>", "e": 26514, "s": 25458, "text": null }, { "code": null, "e": 26522, "s": 26514, "text": "Output:" }, { "code": null, "e": 26553, "s": 26522, "text": "Before clicking on the button:" }, { "code": null, "e": 26583, "s": 26553, "text": "After clicking on the button:" }, { "code": null, "e": 26676, "s": 26583, "text": "Example-3:This example takes a variable and appending the result from the end of the string." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Reverse a string in place. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Inplace Reverse </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var str = 'A Computer Science Portal' el_up.innerHTML = \"String = \" + \"'\" + str + \"'\"; function reverse(s { for(var i = s.length - 1, o = ''; i >= 0; o += s[i--]) {} return o; } function gfg_Run() { el_down.innerHTML = reverse(str); } </script></body> </html>", "e": 27684, "s": 26676, "text": null }, { "code": null, "e": 27692, "s": 27684, "text": "Output:" }, { "code": null, "e": 27723, "s": 27692, "text": "Before clicking on the button:" }, { "code": null, "e": 27753, "s": 27723, "text": "After clicking on the button:" }, { "code": null, "e": 27771, "s": 27753, "text": "javascript-string" }, { "code": null, "e": 27782, "s": 27771, "text": "JavaScript" }, { "code": null, "e": 27799, "s": 27782, "text": "Web Technologies" }, { "code": null, "e": 27897, "s": 27799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27906, "s": 27897, "text": "Comments" }, { "code": null, "e": 27919, "s": 27906, "text": "Old Comments" }, { "code": null, "e": 27980, "s": 27919, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28052, "s": 27980, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28097, "s": 28052, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28139, "s": 28097, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28180, "s": 28139, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 28213, "s": 28180, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28250, "s": 28213, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28312, "s": 28250, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28355, "s": 28312, "text": "How to fetch data from an API in ReactJS ?" } ]
The Holy Trinity of Topological Machine Learning: Gudhi, Scikit-Learn and Tensorflow | by Mathieu Carrière | Towards Data Science
Hi everyone! Today, I would like to highlight the power of Topological Data Analysis in machine learning and demonstrate how to use it practically using a combination of three Python libraries: Gudhi, Scikit-Learn and Tensorflow. First things first, let’s talk about Topological Data Analysis (TDA). It’s a relatively small field of data science (especially when compared to machine learning and deep learning), which is nevertheless actively growing and gathering attention from data scientists. Many start-ups and companies are actually integrating these techniques inside their toolboxes (we’re talking about IBM, Fujitsu, Ayasdi...), due to the recent successes it’s had in various applications, such as biology, time series, finance, scientific visualization, computer graphics... I might write a post about the general usefulness and best practices of TDA in the future, so stay tuned ;-) The goal of TDA is to compute and encode the topology of your data, which means recording the various connected components, loops, cavities, and higher-dimensional structures within your datasets. This can be extremely useful, mostly because this type of information cannot be computed by other descriptors, so TDA really stores a unique set of data features that you cannot find everywhere else. Turns out that these features have very often proved useful for enhancing machine learning predictions, so if you haven’t seen or heard about these features before, I’ll get you up to speed ;-) I’ve already written a couple of articles on this topic, and you can find many other posts about TDA on Medium, so I won’t spend time on the mathematical definitions, but rather illustrate how you can apply TDA on your datasets by breaking down a classic example of the TDA literature. This dataset was introduced in a seminal TDA article. It consists of a set of point clouds obtained by generating orbits of the following dynamical system: This means that we’ll randomly pick an initial point in the unit square, and generate a sequence of points with the equations above. This will give a single point cloud. Now we can repeat the operation as much as we like and end up with a bunch of point clouds. An interesting property of these clouds is that depending on the value of the r parameter that you use to generate the sequence of points, the point clouds end up having very different and interesting structures. For instance, if r = 3.5, the resulting point cloud seems to cover the whole unit square, whereas if r = 4.1, some areas in the unit square are empty: in other words, you have holes in your point clouds. That’s good news for us: TDA can directly compute the presence of these structures. The way TDA tracks these holes is actually quite simple. Imagine balls of a given radius R centered on each point of your point cloud. If R = 0, the union of these balls is the point cloud itself. If R = infinity, the union of balls is the full unit square. But if R is carefully chosen, the union of balls might contain a lot of topological structures, like holes. Hence, in order to avoid having to choose manually this “good” value for R, TDA will compute this union of balls for all possible values of R between 0 and infinity, and record the radii for which each hole appeared and disappeared, and use these values as 2D coordinates for some points. The output of TDA is then another point cloud, in which each point represents a hole: it is called a Rips persistence diagram. Assuming the point cloud is stored in a numpy array X of shape (n x 2), the diagram can be computed in two lines with Gudhi with the following piece of code: import gudhirips = gudhi.RipsComplex(points=X).create_simplex_tree()dgm = rips.persistence() The task we’ll solve is then to predict the value of r, given the point cloud. Persistence diagrams are neat, right? The issue with them though is that persistence diagrams computed from different point clouds might have a different number of points (since the point clouds might have a different number of holes). So if you want to predict r from the persistence diagrams with Scikit-Learn, there’s, unfortunately, no direct way since these libraries expect structured vectors as input. That’s why there’s been a large amount of work about turning persistence diagrams into Euclidean vectors of fixed length, or even developing kernels for persistence diagrams. That’s great, but which one should you use then? Worry no more! Gudhi is here for you again. With its representations module, not only can you compute all of these vectorizations and kernels, but you can even fully use Scikit-Learn in order to cross-validate and/or select the best ones. It’s as simple as this: import gudhi.representations as tdafrom sklearn.pipeline import Pipelinefrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifier as RFfrom sklearn.neighbors import KNeighborsClassifier as kNNfrom sklearn.model_selection import GridSearchCVpipe = Pipeline([("TDA", tda.PersistenceImage()), ("Estimator", SVC())])param = [{"TDA": [tda.SlicedWassersteinKernel()], "TDA__bandwidth": [0.1, 1.0], "TDA__num_directions": [20], "Estimator": [SVC(kernel="precomputed")]}, {"TDA": [tda.PersistenceWeightedGaussianKernel()], "TDA__bandwidth": [0.1, 0.01], "TDA__weight": [lambda x: np.arctan(x[1]-x[0])], "Estimator": [SVC(kernel="precomputed")]}, {"TDA": [tda.PersistenceImage()], "TDA__resolution": [ [5,5], [6,6] ], "TDA__bandwidth": [0.01, 0.1, 1.0, 10.0], "Estimator": [SVC()]}, {"TDA": [tda.Landscape()], "TDA__resolution": [100], "Estimator": [RF()]}, {"TDA": [tda.BottleneckDistance()], "TDA__epsilon": [0.1], "Estimator: [kNN(metric="precomputed")]} ]model = GridSearchCV(pipe, param, cv=3)model = model.fit(diagrams, labels) In the previous code, I am basically trying kernel SVM with the Sliced Wasserstein kernel and the Persistence Weighted Gaussian kernel, C-SVM with the Persistence Images, Random Forests with the Persistence Landscapes, and a simple k-NN with the so-called bottleneck distance between persistence diagrams. Many other possibilities are available in Gudhi, so you should definitely check it out! You can also take a look at this Gudhi tutorial if you want a little more details. I’m pretty sure you’ve become a TDA addict by now. If you are still a non-believer, I have something else for you, which was inspired by this paper. Imagine you want to solve an even harder problem now: I want you to give me a point cloud whose persistence diagram has as many points as possible. In other words, you have to generate a point cloud with a lot of holes. I can see the sweat on your forehead. But I am a merciful kind of person, and let you know that Gudhi can do this in the blink of an eye. Think about it: when you generate a persistence diagram, the coordinates of the different points in this diagram do not depend on the full original point cloud, right? For a given point p in this diagram, the coordinates of p only depend on the positions of the points that form the hole (that corresponds to p) in the original point cloud in a simple way: these coordinates are simply the radii for which the union of balls makes this hole appear or disappear — or, equivalently, the maximal pairwise distance within these points. Turns out that Gudhi can spit out these dependencies with its persistence_pairs() function. The gradient is then simply defined as the derivatives of the Euclidean distance function (see this paper for a formal definition). Let’s thus write a couple of functions, one that computes the Rips persistence diagram from a point cloud, and the one that computes the derivatives of the persistence diagram points. I simplified the code a little bit for readability, the actual code can be found here. def Rips(DX, mel, dim): rc = gd.RipsComplex(distance_matrix=DX, max_edge_length=mel) st = rc.create_simplex_tree(max_dimension=dim+1) dgm = st.persistence() indices = st.persistence_pairs() return indicesclass RipsModel(tf.keras.Model): def __init__(self, X, mel=12, dim=1, card=50): super(RipsModel, self).__init__() self.X = X self.mel = mel self.dim = dim self.card = card def call(self): m, d, c = self.mel, self.dim, self.card # Compute distance matrix DX = tfa.losses.metric_learning.pairwise_distance(self.X) DXX = tf.reshape(DX, [1, DX.shape[0], DX.shape[1]]) # Turn numpy function into tensorflow function RipsTF = lambda DX: tf.numpy_function(Rips, [DX, m, d, c], [tf.int32 for _ in range(4*c)]) # Compute vertices associated to positive and negative simplices # Don't compute gradient for this operation ids = tf.nest.map_structure(tf.stop_gradient, tf.map_fn(RipsTF,DXX,dtype=[tf.int32 for _ in range(4*c)])) # Get persistence diagram by simply picking the corresponding entries in the distance matrix dgm = tf.reshape(tf.gather_nd(DX, tf.reshape(ids, [2*c,2])), [c,2]) return dgm Now, let’s define a loss which is the opposite of the distances of the persistence diagram points to the diagonal. This will force the diagram to have many points, with ordinates much bigger than abscissae, and equivalently a point cloud with a lot of holes of large sizes. model = RipsModel()optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)for epoch in range(100): with tf.GradientTape() as tape: dgm = model.call() loss = -tf.math.reduce_sum(tf.square(.5*(dgm[:,1]-dgm[:,0]))) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) Now let’s optimize! Here are the results at epochs 0, 20 and 90: So many holes, so beautiful... We’re living the dream. If you want to go ahead and play with other losses, check this Gudhi tutorial, which also contains another example on image optimization. This post was only a glimpse of the many possibilities offered by combining Gudhi, Scikit-Learn and Tensorflow. I hope I convinced you that integrating TDA in your pipelines has now become as simple as it could possibly be. Even though many applications of TDA have already been presented in the literature, there is definitely much more that still needs to be discovered!
[ { "code": null, "e": 402, "s": 172, "text": "Hi everyone! Today, I would like to highlight the power of Topological Data Analysis in machine learning and demonstrate how to use it practically using a combination of three Python libraries: Gudhi, Scikit-Learn and Tensorflow." }, { "code": null, "e": 1067, "s": 402, "text": "First things first, let’s talk about Topological Data Analysis (TDA). It’s a relatively small field of data science (especially when compared to machine learning and deep learning), which is nevertheless actively growing and gathering attention from data scientists. Many start-ups and companies are actually integrating these techniques inside their toolboxes (we’re talking about IBM, Fujitsu, Ayasdi...), due to the recent successes it’s had in various applications, such as biology, time series, finance, scientific visualization, computer graphics... I might write a post about the general usefulness and best practices of TDA in the future, so stay tuned ;-)" }, { "code": null, "e": 1658, "s": 1067, "text": "The goal of TDA is to compute and encode the topology of your data, which means recording the various connected components, loops, cavities, and higher-dimensional structures within your datasets. This can be extremely useful, mostly because this type of information cannot be computed by other descriptors, so TDA really stores a unique set of data features that you cannot find everywhere else. Turns out that these features have very often proved useful for enhancing machine learning predictions, so if you haven’t seen or heard about these features before, I’ll get you up to speed ;-)" }, { "code": null, "e": 1944, "s": 1658, "text": "I’ve already written a couple of articles on this topic, and you can find many other posts about TDA on Medium, so I won’t spend time on the mathematical definitions, but rather illustrate how you can apply TDA on your datasets by breaking down a classic example of the TDA literature." }, { "code": null, "e": 2100, "s": 1944, "text": "This dataset was introduced in a seminal TDA article. It consists of a set of point clouds obtained by generating orbits of the following dynamical system:" }, { "code": null, "e": 2863, "s": 2100, "text": "This means that we’ll randomly pick an initial point in the unit square, and generate a sequence of points with the equations above. This will give a single point cloud. Now we can repeat the operation as much as we like and end up with a bunch of point clouds. An interesting property of these clouds is that depending on the value of the r parameter that you use to generate the sequence of points, the point clouds end up having very different and interesting structures. For instance, if r = 3.5, the resulting point cloud seems to cover the whole unit square, whereas if r = 4.1, some areas in the unit square are empty: in other words, you have holes in your point clouds. That’s good news for us: TDA can directly compute the presence of these structures." }, { "code": null, "e": 3229, "s": 2863, "text": "The way TDA tracks these holes is actually quite simple. Imagine balls of a given radius R centered on each point of your point cloud. If R = 0, the union of these balls is the point cloud itself. If R = infinity, the union of balls is the full unit square. But if R is carefully chosen, the union of balls might contain a lot of topological structures, like holes." }, { "code": null, "e": 3803, "s": 3229, "text": "Hence, in order to avoid having to choose manually this “good” value for R, TDA will compute this union of balls for all possible values of R between 0 and infinity, and record the radii for which each hole appeared and disappeared, and use these values as 2D coordinates for some points. The output of TDA is then another point cloud, in which each point represents a hole: it is called a Rips persistence diagram. Assuming the point cloud is stored in a numpy array X of shape (n x 2), the diagram can be computed in two lines with Gudhi with the following piece of code:" }, { "code": null, "e": 3896, "s": 3803, "text": "import gudhirips = gudhi.RipsComplex(points=X).create_simplex_tree()dgm = rips.persistence()" }, { "code": null, "e": 3975, "s": 3896, "text": "The task we’ll solve is then to predict the value of r, given the point cloud." }, { "code": null, "e": 4608, "s": 3975, "text": "Persistence diagrams are neat, right? The issue with them though is that persistence diagrams computed from different point clouds might have a different number of points (since the point clouds might have a different number of holes). So if you want to predict r from the persistence diagrams with Scikit-Learn, there’s, unfortunately, no direct way since these libraries expect structured vectors as input. That’s why there’s been a large amount of work about turning persistence diagrams into Euclidean vectors of fixed length, or even developing kernels for persistence diagrams. That’s great, but which one should you use then?" }, { "code": null, "e": 4871, "s": 4608, "text": "Worry no more! Gudhi is here for you again. With its representations module, not only can you compute all of these vectorizations and kernels, but you can even fully use Scikit-Learn in order to cross-validate and/or select the best ones. It’s as simple as this:" }, { "code": null, "e": 6206, "s": 4871, "text": "import gudhi.representations as tdafrom sklearn.pipeline import Pipelinefrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifier as RFfrom sklearn.neighbors import KNeighborsClassifier as kNNfrom sklearn.model_selection import GridSearchCVpipe = Pipeline([(\"TDA\", tda.PersistenceImage()), (\"Estimator\", SVC())])param = [{\"TDA\": [tda.SlicedWassersteinKernel()], \"TDA__bandwidth\": [0.1, 1.0], \"TDA__num_directions\": [20], \"Estimator\": [SVC(kernel=\"precomputed\")]}, {\"TDA\": [tda.PersistenceWeightedGaussianKernel()], \"TDA__bandwidth\": [0.1, 0.01], \"TDA__weight\": [lambda x: np.arctan(x[1]-x[0])], \"Estimator\": [SVC(kernel=\"precomputed\")]}, {\"TDA\": [tda.PersistenceImage()], \"TDA__resolution\": [ [5,5], [6,6] ], \"TDA__bandwidth\": [0.01, 0.1, 1.0, 10.0], \"Estimator\": [SVC()]}, {\"TDA\": [tda.Landscape()], \"TDA__resolution\": [100], \"Estimator\": [RF()]}, {\"TDA\": [tda.BottleneckDistance()], \"TDA__epsilon\": [0.1], \"Estimator: [kNN(metric=\"precomputed\")]} ]model = GridSearchCV(pipe, param, cv=3)model = model.fit(diagrams, labels)" }, { "code": null, "e": 6683, "s": 6206, "text": "In the previous code, I am basically trying kernel SVM with the Sliced Wasserstein kernel and the Persistence Weighted Gaussian kernel, C-SVM with the Persistence Images, Random Forests with the Persistence Landscapes, and a simple k-NN with the so-called bottleneck distance between persistence diagrams. Many other possibilities are available in Gudhi, so you should definitely check it out! You can also take a look at this Gudhi tutorial if you want a little more details." }, { "code": null, "e": 7052, "s": 6683, "text": "I’m pretty sure you’ve become a TDA addict by now. If you are still a non-believer, I have something else for you, which was inspired by this paper. Imagine you want to solve an even harder problem now: I want you to give me a point cloud whose persistence diagram has as many points as possible. In other words, you have to generate a point cloud with a lot of holes." }, { "code": null, "e": 7946, "s": 7052, "text": "I can see the sweat on your forehead. But I am a merciful kind of person, and let you know that Gudhi can do this in the blink of an eye. Think about it: when you generate a persistence diagram, the coordinates of the different points in this diagram do not depend on the full original point cloud, right? For a given point p in this diagram, the coordinates of p only depend on the positions of the points that form the hole (that corresponds to p) in the original point cloud in a simple way: these coordinates are simply the radii for which the union of balls makes this hole appear or disappear — or, equivalently, the maximal pairwise distance within these points. Turns out that Gudhi can spit out these dependencies with its persistence_pairs() function. The gradient is then simply defined as the derivatives of the Euclidean distance function (see this paper for a formal definition)." }, { "code": null, "e": 8217, "s": 7946, "text": "Let’s thus write a couple of functions, one that computes the Rips persistence diagram from a point cloud, and the one that computes the derivatives of the persistence diagram points. I simplified the code a little bit for readability, the actual code can be found here." }, { "code": null, "e": 9491, "s": 8217, "text": "def Rips(DX, mel, dim): rc = gd.RipsComplex(distance_matrix=DX, max_edge_length=mel) st = rc.create_simplex_tree(max_dimension=dim+1) dgm = st.persistence() indices = st.persistence_pairs() return indicesclass RipsModel(tf.keras.Model): def __init__(self, X, mel=12, dim=1, card=50): super(RipsModel, self).__init__() self.X = X self.mel = mel self.dim = dim self.card = card def call(self): m, d, c = self.mel, self.dim, self.card # Compute distance matrix DX = tfa.losses.metric_learning.pairwise_distance(self.X) DXX = tf.reshape(DX, [1, DX.shape[0], DX.shape[1]]) # Turn numpy function into tensorflow function RipsTF = lambda DX: tf.numpy_function(Rips, [DX, m, d, c], [tf.int32 for _ in range(4*c)]) # Compute vertices associated to positive and negative simplices # Don't compute gradient for this operation ids = tf.nest.map_structure(tf.stop_gradient, tf.map_fn(RipsTF,DXX,dtype=[tf.int32 for _ in range(4*c)])) # Get persistence diagram by simply picking the corresponding entries in the distance matrix dgm = tf.reshape(tf.gather_nd(DX, tf.reshape(ids, [2*c,2])), [c,2]) return dgm" }, { "code": null, "e": 9765, "s": 9491, "text": "Now, let’s define a loss which is the opposite of the distances of the persistence diagram points to the diagonal. This will force the diagram to have many points, with ordinates much bigger than abscissae, and equivalently a point cloud with a lot of holes of large sizes." }, { "code": null, "e": 10157, "s": 9765, "text": "model = RipsModel()optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)for epoch in range(100): with tf.GradientTape() as tape: dgm = model.call() loss = -tf.math.reduce_sum(tf.square(.5*(dgm[:,1]-dgm[:,0]))) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables))" }, { "code": null, "e": 10222, "s": 10157, "text": "Now let’s optimize! Here are the results at epochs 0, 20 and 90:" }, { "code": null, "e": 10415, "s": 10222, "text": "So many holes, so beautiful... We’re living the dream. If you want to go ahead and play with other losses, check this Gudhi tutorial, which also contains another example on image optimization." } ]
Receiver Operating Characteristic Curves Demystified (in Python) | by Syed Sadat Nazrul | Towards Data Science
In Data Science, evaluating model performance is very important and the most commonly used performance metric is the classification score. However, when dealing with fraud datasets with heavy class imbalance, a classification score does not make much sense. Instead, Receiver Operating Characteristic or ROC curves offer a better alternative. ROC is a plot of signal (True Positive Rate) against noise (False Positive Rate). The model performance is determined by looking at the area under the ROC curve (or AUC). The best possible AUC is 1 while the worst is 0.5 (the 45 degrees random line). Any value less than 0.5 means we can simply do the exact opposite of what the model recommends to get the value back above 0.5. While ROC curves are common, there aren’t that many pedagogical resources out there explaining how it is calculated or derived. In this blog, I will reveal, step by step, how to plot an ROC curve using Python. After that, I will explain the characteristics of a basic ROC curve. First off, let us assume that our hypothetical model produced some probabilities for predicting the class of each record. As with most binary fraud models, let’s assume our classes are ‘good’ and ‘bad’ and the model produced probabilities of P(X=‘bad’). To create this, probability distribution, we plot a Gaussian distribution with different mean values for each class. For more information on Gaussian distribution, read this blog. import numpy as npimport matplotlib.pyplot as pltdef pdf(x, std, mean): cons = 1.0 / np.sqrt(2*np.pi*(std**2)) pdf_normal_dist = const*np.exp(-((x-mean)**2)/(2.0*(std**2))) return pdf_normal_distx = np.linspace(0, 1, num=100)good_pdf = pdf(x,0.1,0.4)bad_pdf = pdf(x,0.1,0.6) Now that we have the distribution, let’s create a function to plot the distributions. def plot_pdf(good_pdf, bad_pdf, ax): ax.fill(x, good_pdf, "g", alpha=0.5) ax.fill(x, bad_pdf,"r", alpha=0.5) ax.set_xlim([0,1]) ax.set_ylim([0,5]) ax.set_title("Probability Distribution", fontsize=14) ax.set_ylabel('Counts', fontsize=12) ax.set_xlabel('P(X="bad")', fontsize=12) ax.legend(["good","bad"]) Now let’s use this plot_pdf function to generate the plot: fig, ax = plt.subplots(1,1, figsize=(10,5))plot_pdf(good_pdf, bad_pdf, ax) Now that we have the probability distribution of the binary classes, we can use this distribution to derive the ROC curve. To derive the ROC curve from the probability distribution, we need to calculate the True Positive Rate (TPR) and False Positive Rate (FPR). For a simple example, let’s assume the threshold is at P(X=‘bad’)=0.6 . True positive is the area designated as “bad” on the right side of the threshold. False positive denotes the area designated as “good” on the right of the threshold. Total positive is the total area under the “bad” curve while total negative is the total area under the “good” curve. We divide the value as shown in the diagram to derive TPR and FPR. We derive the TPR and FPR at different threshold values to get the ROC curve. Using this knowledge, we create the ROC plot function: def plot_roc(good_pdf, bad_pdf, ax): #Total total_bad = np.sum(bad_pdf) total_good = np.sum(good_pdf) #Cumulative sum cum_TP = 0 cum_FP = 0 #TPR and FPR list initialization TPR_list=[] FPR_list=[] #Iteratre through all values of x for i in range(len(x)): #We are only interested in non-zero values of bad if bad_pdf[i]>0: cum_TP+=bad_pdf[len(x)-1-i] cum_FP+=good_pdf[len(x)-1-i] FPR=cum_FP/total_good TPR=cum_TP/total_bad TPR_list.append(TPR) FPR_list.append(FPR) #Calculating AUC, taking the 100 timesteps into account auc=np.sum(TPR_list)/100 #Plotting final ROC curve ax.plot(FPR_list, TPR_list) ax.plot(x,x, "--") ax.set_xlim([0,1]) ax.set_ylim([0,1]) ax.set_title("ROC Curve", fontsize=14) ax.set_ylabel('TPR', fontsize=12) ax.set_xlabel('FPR', fontsize=12) ax.grid() ax.legend(["AUC=%.3f"%auc]) Now let’s use this plot_roc function to generate the plot: fig, ax = plt.subplots(1,1, figsize=(10,5))plot_roc(good_pdf, bad_pdf, ax) Now plotting the probability distribution and the ROC next to eachother for visual comparison: fig, ax = plt.subplots(1,2, figsize=(10,5))plot_pdf(good_pdf, bad_pdf, ax[0])plot_roc(good_pdf, bad_pdf, ax[1])plt.tight_layout() Now that we can derive both plots, let’s see how the ROC curve changes as the class separation (i.e. the model performance) improves. We do this by altering the mean value of the Gaussian in the probability distributions. x = np.linspace(0, 1, num=100)fig, ax = plt.subplots(3,2, figsize=(10,12))means_tuples = [(0.5,0.5),(0.4,0.6),(0.3,0.7)]i=0for good_mean, bad_mean in means_tuples: good_pdf = pdf(x, 0.1, good_mean) bad_pdf = pdf(x, 0.1, bad_mean) plot_pdf(good_pdf, bad_pdf, ax[i,0]) plot_roc(good_pdf, bad_pdf, ax[i,1]) i+=1plt.tight_layout() As you can see, the AUC increases as we increase the separation between the classes. Beyond AUC, the ROC curve can also help debug a model. By looking at the shape of the ROC curve, we can evaluate what the model is misclassifying. For example, if the bottom left corner of the curve is closer to the random line, it implies that the model is misclassifying at X=0. Whereas, if it is random on the top right, it implies the errors are occurring at X=1. Also, if there are spikes on the curve (as opposed to being smooth), it implies the model is not stable.
[ { "code": null, "e": 894, "s": 172, "text": "In Data Science, evaluating model performance is very important and the most commonly used performance metric is the classification score. However, when dealing with fraud datasets with heavy class imbalance, a classification score does not make much sense. Instead, Receiver Operating Characteristic or ROC curves offer a better alternative. ROC is a plot of signal (True Positive Rate) against noise (False Positive Rate). The model performance is determined by looking at the area under the ROC curve (or AUC). The best possible AUC is 1 while the worst is 0.5 (the 45 degrees random line). Any value less than 0.5 means we can simply do the exact opposite of what the model recommends to get the value back above 0.5." }, { "code": null, "e": 1173, "s": 894, "text": "While ROC curves are common, there aren’t that many pedagogical resources out there explaining how it is calculated or derived. In this blog, I will reveal, step by step, how to plot an ROC curve using Python. After that, I will explain the characteristics of a basic ROC curve." }, { "code": null, "e": 1607, "s": 1173, "text": "First off, let us assume that our hypothetical model produced some probabilities for predicting the class of each record. As with most binary fraud models, let’s assume our classes are ‘good’ and ‘bad’ and the model produced probabilities of P(X=‘bad’). To create this, probability distribution, we plot a Gaussian distribution with different mean values for each class. For more information on Gaussian distribution, read this blog." }, { "code": null, "e": 1891, "s": 1607, "text": "import numpy as npimport matplotlib.pyplot as pltdef pdf(x, std, mean): cons = 1.0 / np.sqrt(2*np.pi*(std**2)) pdf_normal_dist = const*np.exp(-((x-mean)**2)/(2.0*(std**2))) return pdf_normal_distx = np.linspace(0, 1, num=100)good_pdf = pdf(x,0.1,0.4)bad_pdf = pdf(x,0.1,0.6)" }, { "code": null, "e": 1977, "s": 1891, "text": "Now that we have the distribution, let’s create a function to plot the distributions." }, { "code": null, "e": 2306, "s": 1977, "text": "def plot_pdf(good_pdf, bad_pdf, ax): ax.fill(x, good_pdf, \"g\", alpha=0.5) ax.fill(x, bad_pdf,\"r\", alpha=0.5) ax.set_xlim([0,1]) ax.set_ylim([0,5]) ax.set_title(\"Probability Distribution\", fontsize=14) ax.set_ylabel('Counts', fontsize=12) ax.set_xlabel('P(X=\"bad\")', fontsize=12) ax.legend([\"good\",\"bad\"])" }, { "code": null, "e": 2365, "s": 2306, "text": "Now let’s use this plot_pdf function to generate the plot:" }, { "code": null, "e": 2440, "s": 2365, "text": "fig, ax = plt.subplots(1,1, figsize=(10,5))plot_pdf(good_pdf, bad_pdf, ax)" }, { "code": null, "e": 2563, "s": 2440, "text": "Now that we have the probability distribution of the binary classes, we can use this distribution to derive the ROC curve." }, { "code": null, "e": 2775, "s": 2563, "text": "To derive the ROC curve from the probability distribution, we need to calculate the True Positive Rate (TPR) and False Positive Rate (FPR). For a simple example, let’s assume the threshold is at P(X=‘bad’)=0.6 ." }, { "code": null, "e": 3259, "s": 2775, "text": "True positive is the area designated as “bad” on the right side of the threshold. False positive denotes the area designated as “good” on the right of the threshold. Total positive is the total area under the “bad” curve while total negative is the total area under the “good” curve. We divide the value as shown in the diagram to derive TPR and FPR. We derive the TPR and FPR at different threshold values to get the ROC curve. Using this knowledge, we create the ROC plot function:" }, { "code": null, "e": 4193, "s": 3259, "text": "def plot_roc(good_pdf, bad_pdf, ax): #Total total_bad = np.sum(bad_pdf) total_good = np.sum(good_pdf) #Cumulative sum cum_TP = 0 cum_FP = 0 #TPR and FPR list initialization TPR_list=[] FPR_list=[] #Iteratre through all values of x for i in range(len(x)): #We are only interested in non-zero values of bad if bad_pdf[i]>0: cum_TP+=bad_pdf[len(x)-1-i] cum_FP+=good_pdf[len(x)-1-i] FPR=cum_FP/total_good TPR=cum_TP/total_bad TPR_list.append(TPR) FPR_list.append(FPR) #Calculating AUC, taking the 100 timesteps into account auc=np.sum(TPR_list)/100 #Plotting final ROC curve ax.plot(FPR_list, TPR_list) ax.plot(x,x, \"--\") ax.set_xlim([0,1]) ax.set_ylim([0,1]) ax.set_title(\"ROC Curve\", fontsize=14) ax.set_ylabel('TPR', fontsize=12) ax.set_xlabel('FPR', fontsize=12) ax.grid() ax.legend([\"AUC=%.3f\"%auc])" }, { "code": null, "e": 4252, "s": 4193, "text": "Now let’s use this plot_roc function to generate the plot:" }, { "code": null, "e": 4327, "s": 4252, "text": "fig, ax = plt.subplots(1,1, figsize=(10,5))plot_roc(good_pdf, bad_pdf, ax)" }, { "code": null, "e": 4422, "s": 4327, "text": "Now plotting the probability distribution and the ROC next to eachother for visual comparison:" }, { "code": null, "e": 4552, "s": 4422, "text": "fig, ax = plt.subplots(1,2, figsize=(10,5))plot_pdf(good_pdf, bad_pdf, ax[0])plot_roc(good_pdf, bad_pdf, ax[1])plt.tight_layout()" }, { "code": null, "e": 4774, "s": 4552, "text": "Now that we can derive both plots, let’s see how the ROC curve changes as the class separation (i.e. the model performance) improves. We do this by altering the mean value of the Gaussian in the probability distributions." }, { "code": null, "e": 5117, "s": 4774, "text": "x = np.linspace(0, 1, num=100)fig, ax = plt.subplots(3,2, figsize=(10,12))means_tuples = [(0.5,0.5),(0.4,0.6),(0.3,0.7)]i=0for good_mean, bad_mean in means_tuples: good_pdf = pdf(x, 0.1, good_mean) bad_pdf = pdf(x, 0.1, bad_mean) plot_pdf(good_pdf, bad_pdf, ax[i,0]) plot_roc(good_pdf, bad_pdf, ax[i,1]) i+=1plt.tight_layout()" }, { "code": null, "e": 5202, "s": 5117, "text": "As you can see, the AUC increases as we increase the separation between the classes." } ]
How to convert from string to date data type in MongoDB?
To convert from String to date data type, you need to write some script. Let us first create a collection with documents >db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Carol","ShippingDate":"2019- 01-21"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2071d66324ffac2a7dc60") } >db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Bob","ShippingDate":"2019- 02-24"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2073566324ffac2a7dc61") } >db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Chris","ShippingDate":"2019- 04-01"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2074266324ffac2a7dc62") } Following is the query to display all documents from a collection with the help of find() method > db.stringToDateDataTypeDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5ca2071d66324ffac2a7dc60"), "CustomerName" : "Carol", "ShippingDate" : "2019-01-21" } { "_id" : ObjectId("5ca2073566324ffac2a7dc61"), "CustomerName" : "Bob", "ShippingDate" : "2019-02-24" } { "_id" : ObjectId("5ca2074266324ffac2a7dc62"), "CustomerName" : "Chris", "ShippingDate" : "2019-04-01" } Following is the query to convert String to date data type > db.stringToDateDataTypeDemo.find().forEach(function(data){ ... data.ShippingDate= ISODate(data.ShippingDate); ... db.stringToDateDataTypeDemo.save(data); ... }); Let us display all documents once again to check the string is converted to date data type or not. Following is the query > db.stringToDateDataTypeDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5ca2071d66324ffac2a7dc60"), "CustomerName" : "Carol", "ShippingDate" : ISODate("2019-01-21T00:00:00Z") } { "_id" : ObjectId("5ca2073566324ffac2a7dc61"), "CustomerName" : "Bob", "ShippingDate" : ISODate("2019-02-24T00:00:00Z") } { "_id" : ObjectId("5ca2074266324ffac2a7dc62"), "CustomerName" : "Chris", "ShippingDate" : ISODate("2019-04-01T00:00:00Z") }
[ { "code": null, "e": 1183, "s": 1062, "text": "To convert from String to date data type, you need to write some script. Let us first create a\ncollection with documents" }, { "code": null, "e": 1721, "s": 1183, "text": ">db.stringToDateDataTypeDemo.insertOne({\"CustomerName\":\"Carol\",\"ShippingDate\":\"2019-\n01-21\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2071d66324ffac2a7dc60\")\n}\n>db.stringToDateDataTypeDemo.insertOne({\"CustomerName\":\"Bob\",\"ShippingDate\":\"2019-\n02-24\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2073566324ffac2a7dc61\")\n}\n>db.stringToDateDataTypeDemo.insertOne({\"CustomerName\":\"Chris\",\"ShippingDate\":\"2019-\n04-01\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ca2074266324ffac2a7dc62\")\n}" }, { "code": null, "e": 1818, "s": 1721, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1865, "s": 1818, "text": "> db.stringToDateDataTypeDemo.find().pretty();" }, { "code": null, "e": 1904, "s": 1865, "text": "This will produce the following output" }, { "code": null, "e": 2247, "s": 1904, "text": "{\n \"_id\" : ObjectId(\"5ca2071d66324ffac2a7dc60\"),\n \"CustomerName\" : \"Carol\",\n \"ShippingDate\" : \"2019-01-21\"\n}\n{\n \"_id\" : ObjectId(\"5ca2073566324ffac2a7dc61\"),\n \"CustomerName\" : \"Bob\",\n \"ShippingDate\" : \"2019-02-24\"\n}\n{\n \"_id\" : ObjectId(\"5ca2074266324ffac2a7dc62\"),\n \"CustomerName\" : \"Chris\",\n \"ShippingDate\" : \"2019-04-01\"\n}" }, { "code": null, "e": 2306, "s": 2247, "text": "Following is the query to convert String to date data type" }, { "code": null, "e": 2476, "s": 2306, "text": "> db.stringToDateDataTypeDemo.find().forEach(function(data){\n... data.ShippingDate= ISODate(data.ShippingDate);\n... db.stringToDateDataTypeDemo.save(data);\n... });" }, { "code": null, "e": 2598, "s": 2476, "text": "Let us display all documents once again to check the string is converted to date data type or\nnot. Following is the query" }, { "code": null, "e": 2645, "s": 2598, "text": "> db.stringToDateDataTypeDemo.find().pretty();" }, { "code": null, "e": 2684, "s": 2645, "text": "This will produce the following output" }, { "code": null, "e": 3084, "s": 2684, "text": "{\n \"_id\" : ObjectId(\"5ca2071d66324ffac2a7dc60\"),\n \"CustomerName\" : \"Carol\",\n \"ShippingDate\" : ISODate(\"2019-01-21T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5ca2073566324ffac2a7dc61\"),\n \"CustomerName\" : \"Bob\",\n \"ShippingDate\" : ISODate(\"2019-02-24T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5ca2074266324ffac2a7dc62\"),\n \"CustomerName\" : \"Chris\",\n \"ShippingDate\" : ISODate(\"2019-04-01T00:00:00Z\")\n}" } ]
Heap Sort | Practice | GeeksforGeeks
Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort. Example 1: Input: N = 5 arr[] = {4,1,3,9,7} Output: 1 3 4 7 9 Explanation: After sorting elements using heap sort, elements will be in order as 1,3,4,7,9. Example 2: Input: N = 10 arr[] = {10,9,8,7,6,5,4,3,2,1} Output: 1 2 3 4 5 6 7 8 9 10 Explanation: After sorting elements using heap sort, elements will be in order as 1, 2,3,4,5,6,7,8,9,10. Your Task : You don't have to read input or print anything. Your task is to complete the functions heapify(), buildheap() and heapSort() where heapSort() and buildheap() takes the array and it's size as input and heapify() takes the array, it's size and an index i as input. Complete and use these functions to sort the array using heap sort algorithm. Note: You don't have to return the sorted list. You need to sort the array "arr" in place. Expected Time Complexity: O(N * Log(N)). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 106 1 ≤ arr[i] ≤ 106 0 rajeshbathula292 days ago can any one send a C program that uses both stack and heap memories plsss 0 hharshit81182 weeks ago class Solution{ public: void heapify(int arr[], int n, int i) { int left = 2*i+1, right = 2*i+2; int largest = i; if(left < n && arr[left] > arr[i]) largest = left; if(right < n && arr[largest] < arr[right]) largest = right; if(largest != i){ swap(arr[i], arr[largest]); heapify(arr, n, largest); } } public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { for(int i = (n-2)/2; i >= 0; i--){ heapify(arr, n, i); } } public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { buildHeap(arr, n); for(int i = n-1; i >= 0; i--){ swap(arr[0], arr[i]); heapify(arr, i, 0); } } }; -2 adarshgupta4011 month ago Easy Java Soln- class Solution { //Function to build a Heap from array. void buildHeap(int arr[], int n) { //code for(int i = n/2 -1; i>=0; i--) heapify(arr, n, i); } //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { //code int largest = i; int l = 2*i +1; int r = 2*i+ 2; if( l < n && arr[l] > arr[largest] ){ largest = l; } if( r < n && arr[r] > arr[largest] ){ largest = r; } if( largest != i){ int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; heapify(arr, n, largest ); } } //Function to sort an array using Heap Sort. public void heapSort(int arr[], int n) { //code here buildHeap(arr, n); for( int i = n-1; i>0; i--){ int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } } } +1 gunjangoyal2821 month ago class Solution: #Heapify function to maintain heap property. def heapify(self,arr, n, i): # code here largest = i l = 2*i + 1 r = 2*i + 2 if l < n and arr[l] > arr[largest]: largest = l if r < n and arr[r] > arr[largest]: largest = r if largest != i: arr[i],arr[largest] = arr[largest],arr[i] self.heapify(arr,n,largest) #Function to build a Heap from array. def buildHeap(self,arr,n): # code here idx = n//2 - 1 for i in range(idx,-1,-1): self.heapify(arr,n,i) #Function to sort an array using Heap Sort. def HeapSort(self, arr, n): #code here self.buildHeap(arr,n) for i in range(n-1,0,-1): arr[i],arr[0] = arr[0],arr[i] self.heapify(arr,i,0) +1 sanketbhagat2 months ago SIMPLE JAVA SOLUTION class Solution{ private void swap(int arr[], int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } //Function to build a Heap from array. void buildHeap(int arr[], int n){ // Your code here int child = n; int par = (child-1)/2; while(child>0 && arr[par]<arr[child]){ swap(arr,par,child); child = par; par = (child-1)/2; } } //Heapify function to maintain heap property. void heapify(int arr[], int n, int i){ // Your code here swap(arr,0,n); int par = 0; int child1 = 1; int child2 = 2; while(child1<n){ if(child2>=n){ if(arr[par]<arr[child1]) swap(arr,par,child1); return; } if(arr[par]>arr[child1] && arr[par]>arr[child2]) return; if(arr[child1]>arr[child2]){ swap(arr,par,child1); par = child1; }else{ swap(arr,par,child2); par = child2; } child1 = 2*par+1; child2 = 2*par+2; } } //Function to sort an array using Heap Sort. public void heapSort(int arr[], int n){ //code here for(int i=0;i<n;i++) buildHeap(arr,i); for(int i=0;i<n;i++) heapify(arr,n-i-1,i); } } 0 shilpfizzy2 months ago class Solution{ public: //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { for(int i = n/2 - 1; i >= 0; i--){ heapify(arr,n,i); } } public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { buildHeap(arr,n); for(int i = n-1; i > 0; i--){ swap(arr[0],arr[i]); heapify(arr,i,0); } }}; +1 johnniehdk122 months ago c++ solution class Solution{ public: //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { // Your Code Here int pospar = i; int left, right; while (pospar<n){ left = 2*pospar + 1; right = 2*pospar + 2; if (left<n && right<n){ if (arr[left]<=arr[right] && arr[left]<arr[pospar]) { swap(arr[left], arr[pospar]); pospar = left; } else if (arr[right]<=arr[left] && arr[right]<arr[pospar]){ swap(arr[right], arr[pospar]); pospar = right; } else break; } else if (left<n){ if (arr[left]<arr[pospar]){ swap(arr[left], arr[pospar]); pospar = left; } else break; } else break; } } public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { // Your Code Here for (int i=n/2-1;i>=0;i--){ heapify(arr, n, i); } } public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { //code here buildHeap(arr, n); int arr2[n], size=0, length=n; for (int i=0;i<n;i++) arr2[i] = 0; arr2[size] = arr[0]; size++; length--; if (length != 0){ arr[0] = arr[length]; int pospar=0; while (length>0){ heapify(arr, length, pospar); arr2[size] = arr[0]; size++; length--; if (length == 0) continue; arr[0] = arr[length]; } for (int i=0;i<n;i++) arr[i] = arr2[i]; } }}; 0 biniyamdemissew1122 months ago ggjh 0 amitanand22 months ago class Solution { public: //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { // Your Code Here int largest = i; int left = 2*largest+1; int right = left + 1; if(left < n && arr[left] > arr[largest]){ largest = left; } if(right < n && arr[right] > arr[largest]){ largest = right; } if(largest != i){ swap(arr[largest] , arr[i]); heapify(arr , n , largest); } } public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { // Your Code Here for(int i = (n-1)/2 ; i>= 0 ; i--){ heapify(arr , n , i); } } public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { //code here buildHeap(arr , n); for(int i = n-1 ; i> 0 ; i--){ swap(arr[0] , arr[i]); heapify(arr , i , 0); } } }; 0 vishalpandey100220002 months ago void buildHeap(int arr[], int n) { // Your code here for (int i=(n-2)/2;i>=0;i--){ heapify(arr,n,i); } } //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { // Your code here int largest=i; int lt=2*i+1; int rt=2*i+2; if (lt<n &&arr[lt]>arr[largest]){ largest=lt; } if (rt<n && arr[rt]>arr[largest]){ largest=rt; } if (largest!=i){ int temp=arr[largest]; arr[largest]=arr[i]; arr[i]=temp; heapify(arr,n,largest); } } //Function to sort an array using Heap Sort. public void heapSort(int arr[], int n) { //code here buildHeap(arr,n); for (int i=n-1;i>=1;i--){ int temp=arr[0]; arr[0]=arr[i]; arr[i]=temp; heapify(arr,i,0); } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 392, "s": 238, "text": "Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort." }, { "code": null, "e": 404, "s": 392, "text": "\nExample 1:" }, { "code": null, "e": 549, "s": 404, "text": "Input:\nN = 5\narr[] = {4,1,3,9,7}\nOutput:\n1 3 4 7 9\nExplanation:\nAfter sorting elements\nusing heap sort, elements will be\nin order as 1,3,4,7,9.\n" }, { "code": null, "e": 560, "s": 549, "text": "Example 2:" }, { "code": null, "e": 739, "s": 560, "text": "Input:\nN = 10\narr[] = {10,9,8,7,6,5,4,3,2,1}\nOutput:\n1 2 3 4 5 6 7 8 9 10\nExplanation:\nAfter sorting elements\nusing heap sort, elements will be\nin order as 1, 2,3,4,5,6,7,8,9,10." }, { "code": null, "e": 1184, "s": 739, "text": "\nYour Task :\nYou don't have to read input or print anything. Your task is to complete the functions heapify(), buildheap() and heapSort() where heapSort() and buildheap() takes the array and it's size as input and heapify() takes the array, it's size and an index i as input. Complete and use these functions to sort the array using heap sort algorithm.\nNote: You don't have to return the sorted list. You need to sort the array \"arr\" in place." }, { "code": null, "e": 1258, "s": 1184, "text": "\nExpected Time Complexity: O(N * Log(N)).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1301, "s": 1258, "text": "\nConstraints:\n1 ≤ N ≤ 106\n1 ≤ arr[i] ≤ 106" }, { "code": null, "e": 1303, "s": 1301, "text": "0" }, { "code": null, "e": 1329, "s": 1303, "text": "rajeshbathula292 days ago" }, { "code": null, "e": 1403, "s": 1329, "text": "can any one send a C program that uses both stack and heap memories plsss" }, { "code": null, "e": 1405, "s": 1403, "text": "0" }, { "code": null, "e": 1429, "s": 1405, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 1445, "s": 1429, "text": "class Solution{" }, { "code": null, "e": 1454, "s": 1445, "text": "public: " }, { "code": null, "e": 1814, "s": 1454, "text": " void heapify(int arr[], int n, int i) { int left = 2*i+1, right = 2*i+2; int largest = i; if(left < n && arr[left] > arr[i]) largest = left; if(right < n && arr[largest] < arr[right]) largest = right; if(largest != i){ swap(arr[i], arr[largest]); heapify(arr, n, largest); } }" }, { "code": null, "e": 1991, "s": 1814, "text": " public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { for(int i = (n-2)/2; i >= 0; i--){ heapify(arr, n, i); } }" }, { "code": null, "e": 2226, "s": 1991, "text": " public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { buildHeap(arr, n); for(int i = n-1; i >= 0; i--){ swap(arr[0], arr[i]); heapify(arr, i, 0); } }" }, { "code": null, "e": 2229, "s": 2226, "text": "};" }, { "code": null, "e": 2232, "s": 2229, "text": "-2" }, { "code": null, "e": 2258, "s": 2232, "text": "adarshgupta4011 month ago" }, { "code": null, "e": 2274, "s": 2258, "text": "Easy Java Soln-" }, { "code": null, "e": 3354, "s": 2274, "text": "class Solution\n{\n //Function to build a Heap from array.\n void buildHeap(int arr[], int n)\n {\n //code\n for(int i = n/2 -1; i>=0; i--)\n heapify(arr, n, i);\n }\n \n //Heapify function to maintain heap property.\n void heapify(int arr[], int n, int i)\n {\n //code\n int largest = i;\n int l = 2*i +1; int r = 2*i+ 2;\n \n if( l < n && arr[l] > arr[largest] ){\n largest = l;\n }\n if( r < n && arr[r] > arr[largest] ){\n largest = r;\n }\n if( largest != i){\n int temp = arr[i];\n arr[i] = arr[largest];\n arr[largest] = temp;\n \n heapify(arr, n, largest );\n }\n }\n \n //Function to sort an array using Heap Sort.\n public void heapSort(int arr[], int n)\n {\n //code here\n buildHeap(arr, n);\n for( int i = n-1; i>0; i--){\n int temp = arr[0];\n arr[0] = arr[i];\n arr[i] = temp;\n \n heapify(arr, i, 0);\n }\n }\n }\n " }, { "code": null, "e": 3357, "s": 3354, "text": "+1" }, { "code": null, "e": 3383, "s": 3357, "text": "gunjangoyal2821 month ago" }, { "code": null, "e": 4254, "s": 3383, "text": "class Solution:\n #Heapify function to maintain heap property.\n def heapify(self,arr, n, i):\n # code here\n largest = i\n l = 2*i + 1\n r = 2*i + 2\n if l < n and arr[l] > arr[largest]:\n largest = l\n if r < n and arr[r] > arr[largest]:\n largest = r\n if largest != i:\n arr[i],arr[largest] = arr[largest],arr[i]\n self.heapify(arr,n,largest)\n \n #Function to build a Heap from array.\n def buildHeap(self,arr,n):\n # code here\n idx = n//2 - 1\n for i in range(idx,-1,-1):\n self.heapify(arr,n,i)\n \n #Function to sort an array using Heap Sort. \n def HeapSort(self, arr, n):\n #code here\n self.buildHeap(arr,n)\n for i in range(n-1,0,-1):\n arr[i],arr[0] = arr[0],arr[i]\n self.heapify(arr,i,0)" }, { "code": null, "e": 4257, "s": 4254, "text": "+1" }, { "code": null, "e": 4282, "s": 4257, "text": "sanketbhagat2 months ago" }, { "code": null, "e": 4303, "s": 4282, "text": "SIMPLE JAVA SOLUTION" }, { "code": null, "e": 5712, "s": 4303, "text": "class Solution{\n \n private void swap(int arr[], int i, int j){\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n //Function to build a Heap from array.\n void buildHeap(int arr[], int n){\n // Your code here\n int child = n;\n int par = (child-1)/2;\n while(child>0 && arr[par]<arr[child]){\n swap(arr,par,child);\n child = par;\n par = (child-1)/2;\n }\n }\n \n //Heapify function to maintain heap property.\n void heapify(int arr[], int n, int i){\n // Your code here\n swap(arr,0,n);\n int par = 0;\n int child1 = 1;\n int child2 = 2;\n while(child1<n){\n if(child2>=n){\n if(arr[par]<arr[child1]) swap(arr,par,child1);\n return;\n }\n if(arr[par]>arr[child1] && arr[par]>arr[child2]) return;\n if(arr[child1]>arr[child2]){\n swap(arr,par,child1);\n par = child1;\n }else{\n swap(arr,par,child2);\n par = child2;\n }\n child1 = 2*par+1;\n child2 = 2*par+2;\n }\n }\n \n //Function to sort an array using Heap Sort.\n public void heapSort(int arr[], int n){\n //code here\n for(int i=0;i<n;i++) buildHeap(arr,i);\n for(int i=0;i<n;i++) heapify(arr,n-i-1,i);\n }\n }" }, { "code": null, "e": 5714, "s": 5712, "text": "0" }, { "code": null, "e": 5737, "s": 5714, "text": "shilpfizzy2 months ago" }, { "code": null, "e": 5923, "s": 5739, "text": "class Solution{ public: //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2;" }, { "code": null, "e": 5984, "s": 5923, "text": " if (l < n && arr[l] > arr[largest]) largest = l;" }, { "code": null, "e": 6045, "s": 5984, "text": " if (r < n && arr[r] > arr[largest]) largest = r;" }, { "code": null, "e": 6105, "s": 6045, "text": " if (largest != i) { swap(arr[i], arr[largest]);" }, { "code": null, "e": 6158, "s": 6105, "text": " heapify(arr, n, largest); } }" }, { "code": null, "e": 6327, "s": 6158, "text": " public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { for(int i = n/2 - 1; i >= 0; i--){ heapify(arr,n,i); } }" }, { "code": null, "e": 6559, "s": 6327, "text": " public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { buildHeap(arr,n); for(int i = n-1; i > 0; i--){ swap(arr[0],arr[i]); heapify(arr,i,0); } }};" }, { "code": null, "e": 6562, "s": 6559, "text": "+1" }, { "code": null, "e": 6587, "s": 6562, "text": "johnniehdk122 months ago" }, { "code": null, "e": 6600, "s": 6587, "text": "c++ solution" }, { "code": null, "e": 7526, "s": 6602, "text": "class Solution{ public: //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { // Your Code Here int pospar = i; int left, right; while (pospar<n){ left = 2*pospar + 1; right = 2*pospar + 2; if (left<n && right<n){ if (arr[left]<=arr[right] && arr[left]<arr[pospar]) { swap(arr[left], arr[pospar]); pospar = left; } else if (arr[right]<=arr[left] && arr[right]<arr[pospar]){ swap(arr[right], arr[pospar]); pospar = right; } else break; } else if (left<n){ if (arr[left]<arr[pospar]){ swap(arr[left], arr[pospar]); pospar = left; } else break; } else break; } }" }, { "code": null, "e": 7716, "s": 7526, "text": " public: //Function to build a Heap from array. void buildHeap(int arr[], int n) { // Your Code Here for (int i=n/2-1;i>=0;i--){ heapify(arr, n, i); } }" }, { "code": null, "e": 8432, "s": 7716, "text": " public: //Function to sort an array using Heap Sort. void heapSort(int arr[], int n) { //code here buildHeap(arr, n); int arr2[n], size=0, length=n; for (int i=0;i<n;i++) arr2[i] = 0; arr2[size] = arr[0]; size++; length--; if (length != 0){ arr[0] = arr[length]; int pospar=0; while (length>0){ heapify(arr, length, pospar); arr2[size] = arr[0]; size++; length--; if (length == 0) continue; arr[0] = arr[length]; } for (int i=0;i<n;i++) arr[i] = arr2[i]; } }};" }, { "code": null, "e": 8434, "s": 8432, "text": "0" }, { "code": null, "e": 8465, "s": 8434, "text": "biniyamdemissew1122 months ago" }, { "code": null, "e": 8470, "s": 8465, "text": "ggjh" }, { "code": null, "e": 8472, "s": 8470, "text": "0" }, { "code": null, "e": 8495, "s": 8472, "text": "amitanand22 months ago" }, { "code": null, "e": 9526, "s": 8495, "text": "class Solution\n{\n public:\n //Heapify function to maintain heap property.\n void heapify(int arr[], int n, int i) \n {\n // Your Code Here\n int largest = i;\n int left = 2*largest+1;\n int right = left + 1;\n \n if(left < n && arr[left] > arr[largest]){\n largest = left;\n }\n if(right < n && arr[right] > arr[largest]){\n largest = right;\n }\n if(largest != i){\n swap(arr[largest] , arr[i]);\n heapify(arr , n , largest);\n }\n \n }\n\n public:\n //Function to build a Heap from array.\n void buildHeap(int arr[], int n) \n { \n // Your Code Here\n for(int i = (n-1)/2 ; i>= 0 ; i--){\n heapify(arr , n , i);\n }\n }\n\n \n public:\n //Function to sort an array using Heap Sort.\n void heapSort(int arr[], int n)\n {\n //code here\n buildHeap(arr , n);\n \n for(int i = n-1 ; i> 0 ; i--){\n swap(arr[0] , arr[i]);\n heapify(arr , i , 0);\n }\n }\n};" }, { "code": null, "e": 9528, "s": 9526, "text": "0" }, { "code": null, "e": 9561, "s": 9528, "text": "vishalpandey100220002 months ago" }, { "code": null, "e": 10457, "s": 9561, "text": "void buildHeap(int arr[], int n) { // Your code here for (int i=(n-2)/2;i>=0;i--){ heapify(arr,n,i); } } //Heapify function to maintain heap property. void heapify(int arr[], int n, int i) { // Your code here int largest=i; int lt=2*i+1; int rt=2*i+2; if (lt<n &&arr[lt]>arr[largest]){ largest=lt; } if (rt<n && arr[rt]>arr[largest]){ largest=rt; } if (largest!=i){ int temp=arr[largest]; arr[largest]=arr[i]; arr[i]=temp; heapify(arr,n,largest); } } //Function to sort an array using Heap Sort. public void heapSort(int arr[], int n) { //code here buildHeap(arr,n); for (int i=n-1;i>=1;i--){ int temp=arr[0]; arr[0]=arr[i]; arr[i]=temp; heapify(arr,i,0); } }" }, { "code": null, "e": 10603, "s": 10457, "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": 10639, "s": 10603, "text": " Login to access your submissions. " }, { "code": null, "e": 10649, "s": 10639, "text": "\nProblem\n" }, { "code": null, "e": 10659, "s": 10649, "text": "\nContest\n" }, { "code": null, "e": 10722, "s": 10659, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10870, "s": 10722, "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": 11078, "s": 10870, "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": 11184, "s": 11078, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# How To Add Two Numbers
Learn how to add two numbers in C#: int x = 5; int y = 6; int sum = x + y; Console.WriteLine(sum); // Print the sum of x + y Try it Yourself » We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 36, "s": 0, "text": "Learn how to add two numbers in C#:" }, { "code": null, "e": 126, "s": 36, "text": "int x = 5;\nint y = 6;\nint sum = x + y;\nConsole.WriteLine(sum); // Print the sum of x + y\n" }, { "code": null, "e": 146, "s": 126, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 179, "s": 146, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 221, "s": 179, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 328, "s": 221, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 347, "s": 328, "text": "help@w3schools.com" } ]
How to get the full URL in ExpressJS ? - GeeksforGeeks
12 Aug, 2021 URL stands for Uniform Resource Locator. It is used to locate some resources on the internet it can be thought of as a web address. The string you type on your browser search bar to get something from the internet is a URL, so in this process, the browser somehow finds the address of the server associated with that web address and says hey, this is the content(an URL) I have got from the user and now tell me how I should respond. Now it is the server’s responsibility to respond according to that request. And after receiving a response, it’s the browser’s responsibility to provide that received data to a user in the way it is expected. Problem statement: So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response. Approach: There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user. Step 1: Creating nodejs project and installing packages. 1. Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application. npm init 2. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization. Install express framework npm install express 3. Create a new file app.js, inside this file, we will write the whole express code. Project Structure: It will look like the following. Step 2: Creating an express application. So inside app.js do the following: Import express with require keyword and,Then call the express() function provided by the express framework.That function call will return our created app, store it in a const variable.Set a PORT for your application 3000 is default but you can choose any other according to availability.After then, call the listen() function, and with this our express server starts listening to the connection on the specified path.The listen function takes port and callback function as an argument. Import express with require keyword and, Then call the express() function provided by the express framework. That function call will return our created app, store it in a const variable. Set a PORT for your application 3000 is default but you can choose any other according to availability. After then, call the listen() function, and with this our express server starts listening to the connection on the specified path. The listen function takes port and callback function as an argument. The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure. app.js const express = require('express'); // Importconst app = express(); // Createconst PORT = 3000; // Configure // Do your task here, in this space. app.listen(PORT, (error) => { // Listen if(!error) console.log("Server is Successfully Running, and App is listening on port "+ PORT) else console.log("Error occured, server can't start", error); }); Step 3: Now run the server with the provided command to check whether everything is working fine or not. node app.js If yes, then you’ll receive something like this in your terminal, otherwise, In case your server is not starting, analyze the error and check syntax, etc and then restart the server. Step 4: So now we will continue to create routes and finding the full URL of the request, But let’s first understand the parts of a URL. Below is the description and image which shows the structure of an URL. scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol.host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname.port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening.path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path).query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects. scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol. host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname. port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening. path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path). query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects. Note: We don’t have to access the baseUrl, path, and query separately express provides us a property called req.originalUrl which contains everything after the hostname. The above example URL we are showing will be in your browser’s search bar when you click the algorithm section from the homepage of geeksforgeeks.org Example: In this example, we are creating a route to receive user requests. We will use the following approach: In the route provided below, we have specified a function on the ‘*’ path for GET method.That’s because now we can send any URL from the browser to execute the given functionality.After then we are simply accessing some properties of the request object, objectName.propertyName this is one of the ways to extract data.We have extracted 3 variables as protocol, hostname, and original URL.In the next line, we are storing the port number which we have set earlier.Later, We have created a URL string with template literals of ES6, the backticks “ are the way to create string templates and we can inject any javascript expression inside ${}.In the end, the function send() is simply returning the string as a response. In the route provided below, we have specified a function on the ‘*’ path for GET method. That’s because now we can send any URL from the browser to execute the given functionality. After then we are simply accessing some properties of the request object, objectName.propertyName this is one of the ways to extract data. We have extracted 3 variables as protocol, hostname, and original URL. In the next line, we are storing the port number which we have set earlier. Later, We have created a URL string with template literals of ES6, the backticks “ are the way to create string templates and we can inject any javascript expression inside ${}. In the end, the function send() is simply returning the string as a response. app.js app.get('*', function (req, res) { const protocol = req.protocol; const host = req.hostname; const url = req.originalUrl; const port = process.env.PORT || PORT; const fullUrl = `${protocol}://${host}:${port}${url}` const responseString = `Full URL is: ${fullUrl}`; res.send(responseString); }) Step to run the application: Open the terminal and type the following command. node app.js Output: Explanation: When we enter any Url in the browser search bar, the browser sends a request object to the server in our case the server is a localhost. And Express catches all user requests at the provided route and inside the functionality of that route. The scheme http extracted from req.protocol, and hostname localhost is extracted from req.hostname and 3000 is being accessed from the PORT which we have set before running the server in step 3, and the remaining URL is being extracted from req.originalUrl. Express.js NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n12 Aug, 2021" }, { "code": null, "e": 25174, "s": 24531, "text": "URL stands for Uniform Resource Locator. It is used to locate some resources on the internet it can be thought of as a web address. The string you type on your browser search bar to get something from the internet is a URL, so in this process, the browser somehow finds the address of the server associated with that web address and says hey, this is the content(an URL) I have got from the user and now tell me how I should respond. Now it is the server’s responsibility to respond according to that request. And after receiving a response, it’s the browser’s responsibility to provide that received data to a user in the way it is expected." }, { "code": null, "e": 25494, "s": 25174, "text": "Problem statement: So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response. " }, { "code": null, "e": 25883, "s": 25494, "text": "Approach: There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user." }, { "code": null, "e": 25940, "s": 25883, "text": "Step 1: Creating nodejs project and installing packages." }, { "code": null, "e": 26106, "s": 25940, "text": "1. Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application." }, { "code": null, "e": 26115, "s": 26106, "text": "npm init" }, { "code": null, "e": 26320, "s": 26115, "text": "2. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization." }, { "code": null, "e": 26346, "s": 26320, "text": "Install express framework" }, { "code": null, "e": 26366, "s": 26346, "text": "npm install express" }, { "code": null, "e": 26452, "s": 26366, "text": "3. Create a new file app.js, inside this file, we will write the whole express code. " }, { "code": null, "e": 26504, "s": 26452, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26580, "s": 26504, "text": "Step 2: Creating an express application. So inside app.js do the following:" }, { "code": null, "e": 27066, "s": 26580, "text": "Import express with require keyword and,Then call the express() function provided by the express framework.That function call will return our created app, store it in a const variable.Set a PORT for your application 3000 is default but you can choose any other according to availability.After then, call the listen() function, and with this our express server starts listening to the connection on the specified path.The listen function takes port and callback function as an argument." }, { "code": null, "e": 27107, "s": 27066, "text": "Import express with require keyword and," }, { "code": null, "e": 27175, "s": 27107, "text": "Then call the express() function provided by the express framework." }, { "code": null, "e": 27253, "s": 27175, "text": "That function call will return our created app, store it in a const variable." }, { "code": null, "e": 27357, "s": 27253, "text": "Set a PORT for your application 3000 is default but you can choose any other according to availability." }, { "code": null, "e": 27488, "s": 27357, "text": "After then, call the listen() function, and with this our express server starts listening to the connection on the specified path." }, { "code": null, "e": 27557, "s": 27488, "text": "The listen function takes port and callback function as an argument." }, { "code": null, "e": 27702, "s": 27557, "text": "The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure." }, { "code": null, "e": 27711, "s": 27704, "text": "app.js" }, { "code": "const express = require('express'); // Importconst app = express(); // Createconst PORT = 3000; // Configure // Do your task here, in this space. app.listen(PORT, (error) => { // Listen if(!error) console.log(\"Server is Successfully Running, and App is listening on port \"+ PORT) else console.log(\"Error occured, server can't start\", error); });", "e": 28129, "s": 27711, "text": null }, { "code": null, "e": 28234, "s": 28129, "text": "Step 3: Now run the server with the provided command to check whether everything is working fine or not." }, { "code": null, "e": 28246, "s": 28234, "text": "node app.js" }, { "code": null, "e": 28429, "s": 28246, "text": "If yes, then you’ll receive something like this in your terminal, otherwise, In case your server is not starting, analyze the error and check syntax, etc and then restart the server." }, { "code": null, "e": 28639, "s": 28429, "text": "Step 4: So now we will continue to create routes and finding the full URL of the request, But let’s first understand the parts of a URL. Below is the description and image which shows the structure of an URL. " }, { "code": null, "e": 29604, "s": 28639, "text": "scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol.host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname.port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening.path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path).query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects." }, { "code": null, "e": 29821, "s": 29604, "text": "scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol." }, { "code": null, "e": 30025, "s": 29821, "text": "host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname." }, { "code": null, "e": 30184, "s": 30025, "text": "port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening." }, { "code": null, "e": 30390, "s": 30184, "text": "path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path)." }, { "code": null, "e": 30573, "s": 30390, "text": "query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects." }, { "code": null, "e": 30746, "s": 30573, "text": "Note: We don’t have to access the baseUrl, path, and query separately express provides us a property called req.originalUrl which contains everything after the hostname. " }, { "code": null, "e": 30896, "s": 30746, "text": "The above example URL we are showing will be in your browser’s search bar when you click the algorithm section from the homepage of geeksforgeeks.org" }, { "code": null, "e": 31008, "s": 30896, "text": "Example: In this example, we are creating a route to receive user requests. We will use the following approach:" }, { "code": null, "e": 31728, "s": 31008, "text": "In the route provided below, we have specified a function on the ‘*’ path for GET method.That’s because now we can send any URL from the browser to execute the given functionality.After then we are simply accessing some properties of the request object, objectName.propertyName this is one of the ways to extract data.We have extracted 3 variables as protocol, hostname, and original URL.In the next line, we are storing the port number which we have set earlier.Later, We have created a URL string with template literals of ES6, the backticks “ are the way to create string templates and we can inject any javascript expression inside ${}.In the end, the function send() is simply returning the string as a response." }, { "code": null, "e": 31818, "s": 31728, "text": "In the route provided below, we have specified a function on the ‘*’ path for GET method." }, { "code": null, "e": 31910, "s": 31818, "text": "That’s because now we can send any URL from the browser to execute the given functionality." }, { "code": null, "e": 32050, "s": 31910, "text": "After then we are simply accessing some properties of the request object, objectName.propertyName this is one of the ways to extract data." }, { "code": null, "e": 32121, "s": 32050, "text": "We have extracted 3 variables as protocol, hostname, and original URL." }, { "code": null, "e": 32197, "s": 32121, "text": "In the next line, we are storing the port number which we have set earlier." }, { "code": null, "e": 32375, "s": 32197, "text": "Later, We have created a URL string with template literals of ES6, the backticks “ are the way to create string templates and we can inject any javascript expression inside ${}." }, { "code": null, "e": 32454, "s": 32375, "text": "In the end, the function send() is simply returning the string as a response." }, { "code": null, "e": 32461, "s": 32454, "text": "app.js" }, { "code": "app.get('*', function (req, res) { const protocol = req.protocol; const host = req.hostname; const url = req.originalUrl; const port = process.env.PORT || PORT; const fullUrl = `${protocol}://${host}:${port}${url}` const responseString = `Full URL is: ${fullUrl}`; res.send(responseString); })", "e": 32812, "s": 32461, "text": null }, { "code": null, "e": 32891, "s": 32812, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 32903, "s": 32891, "text": "node app.js" }, { "code": null, "e": 32911, "s": 32903, "text": "Output:" }, { "code": null, "e": 33424, "s": 32911, "text": "Explanation: When we enter any Url in the browser search bar, the browser sends a request object to the server in our case the server is a localhost. And Express catches all user requests at the provided route and inside the functionality of that route. The scheme http extracted from req.protocol, and hostname localhost is extracted from req.hostname and 3000 is being accessed from the PORT which we have set before running the server in step 3, and the remaining URL is being extracted from req.originalUrl." }, { "code": null, "e": 33435, "s": 33424, "text": "Express.js" }, { "code": null, "e": 33452, "s": 33435, "text": "NodeJS-Questions" }, { "code": null, "e": 33459, "s": 33452, "text": "Picked" }, { "code": null, "e": 33467, "s": 33459, "text": "Node.js" }, { "code": null, "e": 33484, "s": 33467, "text": "Web Technologies" }, { "code": null, "e": 33582, "s": 33484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33591, "s": 33582, "text": "Comments" }, { "code": null, "e": 33604, "s": 33591, "text": "Old Comments" }, { "code": null, "e": 33661, "s": 33604, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 33700, "s": 33661, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 33727, "s": 33700, "text": "Mongoose Populate() Method" }, { "code": null, "e": 33758, "s": 33727, "text": "Express.js req.params Property" }, { "code": null, "e": 33783, "s": 33758, "text": "Mongoose find() Function" }, { "code": null, "e": 33839, "s": 33783, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33901, "s": 33839, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33944, "s": 33901, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33994, "s": 33944, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
3 Data structures | Practice | GeeksforGeeks
Given N operations. Each of type 1 or type 2 or type 3 Type 1: "1 x", insert number x in the priority queue (Greatest element on the top) Type 2: "2 x", insert number x in the queue (First In First Out) Type 3: "3 x", insert number x in the stack (First In Last Out) The task is to print the elements in all three data structures from top to bottom. First print elements of the priority queue, then elements of the queue and then elements of the stack. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. 3. The next N lines contains any operation as mentioned above. Output: For each test case, print the elements as mentioned above Constraints: 1. 1 <= T <= 100 2. 1 <= N <= 104 3. 1 <= X <= 109 Example: Input: 2 5 1 10 2 5 1 5 2 4 3 1 1 3 100 Output: 10 5 5 4 1 100 0 msbritogabriella2 months ago Easy C++ Solution #include <bits/stdc++.h> #define fim "\n"; #define ll long long; using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; priority_queue<int> pq; queue<int> q; stack<int> s; cin >> n; while(n--){ int op, val; cin >> op >> val; if (op == 1) pq.push(val); if (op == 2) q.push(val); if (op == 3) s.push(val); } while(!pq.empty()){ cout << pq.top() << " "; pq.pop(); } while(!q.empty()){ cout << q.front() << " "; q.pop(); } while(!s.empty()){ cout << s.top() << " "; s.pop(); } cout << fim; } return 0; } +2 badgujarsachin835 months ago #include<stack> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n; cin>>n; priority_queue<int > pq; stack<int> st; queue<int> q; while(n--){ int type,value; cin>>type; cin>>value; if(type==1){ pq.push(value); } else if(type==2){ q.push(value); } else if(type==3){ st.push(value); } } while(!pq.empty()){ cout<<pq.top()<<" "; pq.pop(); } while(!q.empty()){ cout<<q.front()<<" "; q.pop(); } while(!st.empty()){ cout<<st.top()<<" "; st.pop(); } cout<<endl; } return 0; } -1 Laxman Kumar vashist9 months ago Laxman Kumar vashist https://uploads.disquscdn.c... -1 Aman Kumar9 months ago Aman Kumar #include<iostream>#include<stack>#include<queue>using namespace std;int main() { int t; cin>>t; while(t--){ int n; cin>>n; priority_queue<int> pq; queue<int> q; stack<int> st; while(n--){ int type,x; cin>>type>>x; if(type==1){ pq.push(x); } else if(type==2){ q.push(x); } else if(type==3){ st.push(x); } } while(!pq.empty()){ cout<<pq.top()<<" ";="" pq.pop();="" }="" while(!q.empty()){="" cout<<q.front()<<"="" ";="" q.pop();="" }="" while(!st.empty()){="" cout<<st.top()<<"="" ";="" st.pop();="" }="" cout<<"\n";="" }="" return="" 0;="" }=""> -1 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.10 #include <bits stdc++.h="">using namespace std;int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--) { int N; cin >> N; priority_queue<int> pq; queue<int> q; stack<int> st; while(N--) { int type, x; cin >> type >> x; if(type == 1) { pq.push(x); } else if(type == 2) { q.push(x); } else if(type == 3) { st.push(x); } } while(!pq.empty()) { cout << pq.top() << " "; pq.pop(); } while(!q.empty()) { cout << q.front() << " "; q.pop(); } while(!st.empty()) { cout << st.top() << " "; st.pop(); } cout << "\n"; } return 0;} -1 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:2.79 import java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); PriorityQueue<integer> pq = new PriorityQueue<>(Collections.reverseOrder()); ArrayDeque<integer> q = new ArrayDeque<>(); ArrayDeque<integer> st = new ArrayDeque<>(); while(N-- > 0) { int type = sc.nextInt(); int x = sc.nextInt();; if(type == 1) { pq.offer(x); } else if(type == 2) { q.offer(x); } else if(type == 3) { st.push(x); } } while(!pq.isEmpty()) { System.out.print(pq.poll() + " "); } while(!q.isEmpty()) { System.out.print(q.poll() + " "); } while(!st.isEmpty()) { System.out.print(st.poll() + " "); } System.out.println(); } }} -1 Aaditya Burujwale1 year ago Aaditya Burujwale Java Solution 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": 281, "s": 226, "text": "Given N operations. Each of type 1 or type 2 or type 3" }, { "code": null, "e": 680, "s": 281, "text": "Type 1: \"1 x\", insert number x in the priority queue (Greatest element on the top)\nType 2: \"2 x\", insert number x in the queue (First In First Out)\nType 3: \"3 x\", insert number x in the stack (First In Last Out)\n\nThe task is to print the elements in all three data structures from top to bottom. First print elements of the priority queue, then elements of the queue and then elements of the stack." }, { "code": null, "e": 953, "s": 680, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N.\n3. The next N lines contains any operation as mentioned above. " }, { "code": null, "e": 1135, "s": 953, "text": "\nOutput: For each test case, print the elements as mentioned above\n\nConstraints:\n1. 1 <= T <= 100\n2. 1 <= N <= 104\n3. 1 <= X <= 109\n\nExample:\nInput:\n2\n5\n1 10\n2 5\n1 5\n2 4\n3 1\n1\n3 100" }, { "code": null, "e": 1158, "s": 1135, "text": "Output:\n10 5 5 4 1\n100" }, { "code": null, "e": 1160, "s": 1158, "text": "0" }, { "code": null, "e": 1189, "s": 1160, "text": "msbritogabriella2 months ago" }, { "code": null, "e": 2076, "s": 1189, "text": "Easy C++ Solution\n\n#include <bits/stdc++.h>\n#define fim \"\\n\";\n#define ll long long;\nusing namespace std;\n\nint main(){\n ios_base::sync_with_stdio(false); cin.tie(NULL);\n int t;\n cin >> t;\n while(t--){\n int n;\n priority_queue<int> pq;\n queue<int> q;\n stack<int> s;\n cin >> n;\n while(n--){\n int op, val;\n cin >> op >> val;\n if (op == 1) pq.push(val);\n if (op == 2) q.push(val);\n if (op == 3) s.push(val);\n }\n while(!pq.empty()){\n cout << pq.top() << \" \";\n pq.pop();\n }\n while(!q.empty()){\n cout << q.front() << \" \";\n q.pop();\n }\n while(!s.empty()){\n cout << s.top() << \" \";\n s.pop();\n }\n cout << fim;\n }\n return 0;\n}" }, { "code": null, "e": 2079, "s": 2076, "text": "+2" }, { "code": null, "e": 2108, "s": 2079, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 2853, "s": 2108, "text": "#include<stack>\nusing namespace std;\nint main()\n {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t int n;\n\t cin>>n;\n\t priority_queue<int > pq;\n\t stack<int> st;\n\t queue<int> q;\n\t while(n--){\n\t int type,value;\n\t cin>>type;\n\t cin>>value;\n\t if(type==1){\n\t pq.push(value);\n\t }\n\t else if(type==2){\n\t q.push(value);\n\t }\n\t else if(type==3){\n\t st.push(value);\n\t }\n\t }\n\t while(!pq.empty()){\n\t cout<<pq.top()<<\" \";\n\t pq.pop();\n\t }\n\t while(!q.empty()){\n\t cout<<q.front()<<\" \";\n\t q.pop();\n\t }\n\t while(!st.empty()){\n\t cout<<st.top()<<\" \";\n\t st.pop();\n\t }\n\t cout<<endl;\n\t}\n\t\n\treturn 0;\n}" }, { "code": null, "e": 2856, "s": 2853, "text": "-1" }, { "code": null, "e": 2889, "s": 2856, "text": "Laxman Kumar vashist9 months ago" }, { "code": null, "e": 2910, "s": 2889, "text": "Laxman Kumar vashist" }, { "code": null, "e": 2941, "s": 2910, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2944, "s": 2941, "text": "-1" }, { "code": null, "e": 2967, "s": 2944, "text": "Aman Kumar9 months ago" }, { "code": null, "e": 2978, "s": 2967, "text": "Aman Kumar" }, { "code": null, "e": 3663, "s": 2978, "text": "#include<iostream>#include<stack>#include<queue>using namespace std;int main() { int t; cin>>t; while(t--){ int n; cin>>n; priority_queue<int> pq; queue<int> q; stack<int> st; while(n--){ int type,x; cin>>type>>x; if(type==1){ pq.push(x); } else if(type==2){ q.push(x); } else if(type==3){ st.push(x); } } while(!pq.empty()){ cout<<pq.top()<<\" \";=\"\" pq.pop();=\"\" }=\"\" while(!q.empty()){=\"\" cout<<q.front()<<\"=\"\" \";=\"\" q.pop();=\"\" }=\"\" while(!st.empty()){=\"\" cout<<st.top()<<\"=\"\" \";=\"\" st.pop();=\"\" }=\"\" cout<<\"\\n\";=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 3666, "s": 3663, "text": "-1" }, { "code": null, "e": 3692, "s": 3666, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 3708, "s": 3692, "text": "Debojyoti Sinha" }, { "code": null, "e": 3757, "s": 3708, "text": "Correct Answer.Correct AnswerExecution Time:0.10" }, { "code": null, "e": 4801, "s": 3757, "text": "#include <bits stdc++.h=\"\">using namespace std;int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--) { int N; cin >> N; priority_queue<int> pq; queue<int> q; stack<int> st; while(N--) { int type, x; cin >> type >> x; if(type == 1) { pq.push(x); } else if(type == 2) { q.push(x); } else if(type == 3) { st.push(x); } } while(!pq.empty()) { cout << pq.top() << \" \"; pq.pop(); } while(!q.empty()) { cout << q.front() << \" \"; q.pop(); } while(!st.empty()) { cout << st.top() << \" \"; st.pop(); } cout << \"\\n\"; } return 0;}" }, { "code": null, "e": 4804, "s": 4801, "text": "-1" }, { "code": null, "e": 4830, "s": 4804, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 4846, "s": 4830, "text": "Debojyoti Sinha" }, { "code": null, "e": 4895, "s": 4846, "text": "Correct Answer.Correct AnswerExecution Time:2.79" }, { "code": null, "e": 6243, "s": 4895, "text": "import java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); PriorityQueue<integer> pq = new PriorityQueue<>(Collections.reverseOrder()); ArrayDeque<integer> q = new ArrayDeque<>(); ArrayDeque<integer> st = new ArrayDeque<>(); while(N-- > 0) { int type = sc.nextInt(); int x = sc.nextInt();; if(type == 1) { pq.offer(x); } else if(type == 2) { q.offer(x); } else if(type == 3) { st.push(x); } } while(!pq.isEmpty()) { System.out.print(pq.poll() + \" \"); } while(!q.isEmpty()) { System.out.print(q.poll() + \" \"); } while(!st.isEmpty()) { System.out.print(st.poll() + \" \"); } System.out.println(); } }}" }, { "code": null, "e": 6246, "s": 6243, "text": "-1" }, { "code": null, "e": 6274, "s": 6246, "text": "Aaditya Burujwale1 year ago" }, { "code": null, "e": 6292, "s": 6274, "text": "Aaditya Burujwale" }, { "code": null, "e": 6306, "s": 6292, "text": "Java Solution" }, { "code": null, "e": 6452, "s": 6306, "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": 6488, "s": 6452, "text": " Login to access your submissions. " }, { "code": null, "e": 6498, "s": 6488, "text": "\nProblem\n" }, { "code": null, "e": 6508, "s": 6498, "text": "\nContest\n" }, { "code": null, "e": 6571, "s": 6508, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6719, "s": 6571, "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": 6927, "s": 6719, "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": 7033, "s": 6927, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is Git and Why is It So Important? | by Soner Yıldırım | Towards Data Science
Linus Torvalds created the Linux operating system and he made it publicly available after a while. His initial purpose was to get comments and feedback about Linux from other people. People started contributing to and getting involved with Linux. The contributions were not only in the form of code but also ideas and comments. The community working together on Linux made it an open source project. Linux is in millions of computers and powering billions of devices. You may be wondering why I’m writing about Linux although the title is about Git. Git was also created by Linus Torvalds in the process of developing Linux. Many people were involved in the development of Linux by making small or large contributions. After some time, it became really hard to manage and maintain all the changes and updates. That is the reason why Git was created. Git is a version control system. It maintains a history of all changes made to the code. The changes are stored in a special database called “repository”, also known as “repo”. Two main advantages of using Git at software development: Tracking the changes and updates. We are able to see who made which changes. Git also provides when and why a change was made. Allowing to work collaboratively. Software development projects usually require many people to work together. Git provides the developers with a systematic way of doing that. Thus, the developers focus on the project instead of extensive communication sessions between the other developers. There are other version control systems such as Subversion, Mercurial and so on. However, Git is the most popular one. Some of the reasons that make Git the preferred one are: Speed Scalability Being free and open source Assume I have project files in my project directory. I make some changes on a file and want to add the updated file in the git repository. The first step is to add the updated file to the staging area. After review, it is committed to the git repository. The word “commit” means a lot and it is a fundamental operation in Git. Let’s delve into what happens when we commit a file to the repository. Git takes a snapshot of the project and stores it in the repository along with some other identifying information. Each time we commit, Git records the information above. Thus, we have a highly useful history of the project. When we commit a file, we provide a message that describes the change. This message should be as informative as possible in order to build a decent history. Note: The advantage of saving all these information for every change is that we can easily revert back to an earlier version in case of a mistake. You may be wondering why Git is taking a snapshot of the entire projects instead of just recording the changes. When there are lots of changes, it is easier to record a snapshot instead of the changes. Besides, when going back to a previous version, it becomes very complicated to track down all the modifications. One issue with recording the snapshot of entire project might be the space. We don’t have to worry about it because Git is quite efficient in storing the snapshots. Git does not store the duplicate content and also compresses the content. We have covered the workflow theoretically. Let’s also do a few basic practical examples. The easiest way to use Git is through the terminal. You can also use some text editors and IDEs but terminal provides the most functionality. I will first create new project directory. $ mkdir newproject$ cd newproject I’m now in the newproject directory. Let’s first initialize an empty git repository. $ git initInitialized empty Git repository in /home/soner/Desktop/projects/newproject/.git/ The git repository is hidden so you need to run the “ls -a” comment to check it has been created. $ls -a. .. file1.py .git Note: The git repository is hidden because we are not supposed to touch it. It contains some implementation details. We do not care what is in the git repository. We just want to know it is there. I have a python file in the project directory but it is not saved in the git repository yet. We will add it to the staging area and then commit to the repository. $ git add file1.py$ git commit -m "Initial commit."[master (root-commit) d95fba1] Initial commit. 1 file changed, 11 insertions(+) create mode 100644 file1.py The git add command adds the file in the staging area. The git commit command saves the file in the repository permanently. You can use “git show” comment to view the files in the git repository. When we first add a file, it is in the staging area. We can check it with “git status” command. $ git add file11.txt$ git status The new file (file11.txt) is waiting to be committed to the repository. Let’s commit it and check the status again. $ git commit -m "New file added."$ git status Git is a very important tool used in software development because of the advantages it provides. Even if you are or plan to be a data scientist, I suggest to learn Git to a certain level. What we have covered in the practical part of this article are just the very basic operations in Git. My goal is to get you familiar with the concept so you have an idea what Git is all about. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 355, "s": 172, "text": "Linus Torvalds created the Linux operating system and he made it publicly available after a while. His initial purpose was to get comments and feedback about Linux from other people." }, { "code": null, "e": 572, "s": 355, "text": "People started contributing to and getting involved with Linux. The contributions were not only in the form of code but also ideas and comments. The community working together on Linux made it an open source project." }, { "code": null, "e": 722, "s": 572, "text": "Linux is in millions of computers and powering billions of devices. You may be wondering why I’m writing about Linux although the title is about Git." }, { "code": null, "e": 891, "s": 722, "text": "Git was also created by Linus Torvalds in the process of developing Linux. Many people were involved in the development of Linux by making small or large contributions." }, { "code": null, "e": 1022, "s": 891, "text": "After some time, it became really hard to manage and maintain all the changes and updates. That is the reason why Git was created." }, { "code": null, "e": 1199, "s": 1022, "text": "Git is a version control system. It maintains a history of all changes made to the code. The changes are stored in a special database called “repository”, also known as “repo”." }, { "code": null, "e": 1257, "s": 1199, "text": "Two main advantages of using Git at software development:" }, { "code": null, "e": 1384, "s": 1257, "text": "Tracking the changes and updates. We are able to see who made which changes. Git also provides when and why a change was made." }, { "code": null, "e": 1675, "s": 1384, "text": "Allowing to work collaboratively. Software development projects usually require many people to work together. Git provides the developers with a systematic way of doing that. Thus, the developers focus on the project instead of extensive communication sessions between the other developers." }, { "code": null, "e": 1851, "s": 1675, "text": "There are other version control systems such as Subversion, Mercurial and so on. However, Git is the most popular one. Some of the reasons that make Git the preferred one are:" }, { "code": null, "e": 1857, "s": 1851, "text": "Speed" }, { "code": null, "e": 1869, "s": 1857, "text": "Scalability" }, { "code": null, "e": 1896, "s": 1869, "text": "Being free and open source" }, { "code": null, "e": 2035, "s": 1896, "text": "Assume I have project files in my project directory. I make some changes on a file and want to add the updated file in the git repository." }, { "code": null, "e": 2151, "s": 2035, "text": "The first step is to add the updated file to the staging area. After review, it is committed to the git repository." }, { "code": null, "e": 2294, "s": 2151, "text": "The word “commit” means a lot and it is a fundamental operation in Git. Let’s delve into what happens when we commit a file to the repository." }, { "code": null, "e": 2409, "s": 2294, "text": "Git takes a snapshot of the project and stores it in the repository along with some other identifying information." }, { "code": null, "e": 2519, "s": 2409, "text": "Each time we commit, Git records the information above. Thus, we have a highly useful history of the project." }, { "code": null, "e": 2676, "s": 2519, "text": "When we commit a file, we provide a message that describes the change. This message should be as informative as possible in order to build a decent history." }, { "code": null, "e": 2823, "s": 2676, "text": "Note: The advantage of saving all these information for every change is that we can easily revert back to an earlier version in case of a mistake." }, { "code": null, "e": 3138, "s": 2823, "text": "You may be wondering why Git is taking a snapshot of the entire projects instead of just recording the changes. When there are lots of changes, it is easier to record a snapshot instead of the changes. Besides, when going back to a previous version, it becomes very complicated to track down all the modifications." }, { "code": null, "e": 3377, "s": 3138, "text": "One issue with recording the snapshot of entire project might be the space. We don’t have to worry about it because Git is quite efficient in storing the snapshots. Git does not store the duplicate content and also compresses the content." }, { "code": null, "e": 3467, "s": 3377, "text": "We have covered the workflow theoretically. Let’s also do a few basic practical examples." }, { "code": null, "e": 3609, "s": 3467, "text": "The easiest way to use Git is through the terminal. You can also use some text editors and IDEs but terminal provides the most functionality." }, { "code": null, "e": 3652, "s": 3609, "text": "I will first create new project directory." }, { "code": null, "e": 3686, "s": 3652, "text": "$ mkdir newproject$ cd newproject" }, { "code": null, "e": 3771, "s": 3686, "text": "I’m now in the newproject directory. Let’s first initialize an empty git repository." }, { "code": null, "e": 3863, "s": 3771, "text": "$ git initInitialized empty Git repository in /home/soner/Desktop/projects/newproject/.git/" }, { "code": null, "e": 3961, "s": 3863, "text": "The git repository is hidden so you need to run the “ls -a” comment to check it has been created." }, { "code": null, "e": 3986, "s": 3961, "text": "$ls -a. .. file1.py .git" }, { "code": null, "e": 4183, "s": 3986, "text": "Note: The git repository is hidden because we are not supposed to touch it. It contains some implementation details. We do not care what is in the git repository. We just want to know it is there." }, { "code": null, "e": 4346, "s": 4183, "text": "I have a python file in the project directory but it is not saved in the git repository yet. We will add it to the staging area and then commit to the repository." }, { "code": null, "e": 4505, "s": 4346, "text": "$ git add file1.py$ git commit -m \"Initial commit.\"[master (root-commit) d95fba1] Initial commit. 1 file changed, 11 insertions(+) create mode 100644 file1.py" }, { "code": null, "e": 4701, "s": 4505, "text": "The git add command adds the file in the staging area. The git commit command saves the file in the repository permanently. You can use “git show” comment to view the files in the git repository." }, { "code": null, "e": 4797, "s": 4701, "text": "When we first add a file, it is in the staging area. We can check it with “git status” command." }, { "code": null, "e": 4830, "s": 4797, "text": "$ git add file11.txt$ git status" }, { "code": null, "e": 4946, "s": 4830, "text": "The new file (file11.txt) is waiting to be committed to the repository. Let’s commit it and check the status again." }, { "code": null, "e": 4992, "s": 4946, "text": "$ git commit -m \"New file added.\"$ git status" }, { "code": null, "e": 5180, "s": 4992, "text": "Git is a very important tool used in software development because of the advantages it provides. Even if you are or plan to be a data scientist, I suggest to learn Git to a certain level." }, { "code": null, "e": 5373, "s": 5180, "text": "What we have covered in the practical part of this article are just the very basic operations in Git. My goal is to get you familiar with the concept so you have an idea what Git is all about." } ]
Concept of indexing in Apache Cassandra - GeeksforGeeks
11 Oct, 2019 Prerequisite – Introduction to Apache CassandraIndex:As we can access data using attributes which having the partition key. For Example, if Emp_id is a column name for Employee table and if it is partition key of that table then we can filter or search data with the help of partition key. In this case we can used WHERE clause to define condition over attribute and to search data.But suppose if there exists a column which is not a partition key of that table and we want to filter or to search or to access data using WHERE clause then the query will not be executed and will give an error. So, to access data in that case using attributes other than the partition key for fast and efficient lookup of data matching a given condition then we need to define index. It can be used for various purpose like for collections, static columns, collection columns, and any other columns except counter columns. When to use an Index: Built-in indexes are the best option on a table which having many rows and that rows contain the indexed value.In a particular column which column having more unique values in that case we can used indexing.Table which more overhead due to several reason like column having more entries then in that case we can used indexing.To query and maintain the index we can used the indexing which is always a good option in that case. Built-in indexes are the best option on a table which having many rows and that rows contain the indexed value. In a particular column which column having more unique values in that case we can used indexing. Table which more overhead due to several reason like column having more entries then in that case we can used indexing. To query and maintain the index we can used the indexing which is always a good option in that case. Example:Suppose you had a cricket match entry table with a million entries for player’s in hundreds of matches and wanted to look up player’s rank by the number of match played. Many player’s ranks will share the same column value for match year. The match_year column is a good option for an index. Syntax to create an Index: CREATE INDEX [ IF NOT EXISTS ] index_name ON [keyspace_name.]table_name ([ ( KEYS | FULL ) ] column_name) (ENTRIES column_name); Example:To create table used keyspace1 as a keyspace and Task as a table name. Lets have a look. CREATE TABLE keyspace1.Task ( Task_id text, Task_name text, Task_time timestamp, T_location text, PRIMARY KEY (Task_id, Task_name) ); As Cassandra is a distributed and decentralized database with the data organized by partition key, In general case, WHERE clause queries need to include a partition key. Example: SELECT * FROM Task WHERE Task_id = ‘T210’; This query would work fine. SELECT * FROM Task WHERE Task_id = ‘T210’ AND Task_name; ‘set alarm’; This query would work fine. Note:In above table Task_id and Task_name columns are the part of primary key. SELECT * FROM Task WHERE Task_time= ‘2019-09-30 15:02:56’; This query would not work, because as we can see that here Task_time is not a part of partition key. Error: Bad Request : no indexed columns present in by columns clause with Equal operator. To resolve such type of errors by Creating an index on a clustering column. Define a table having a composite partition key, and then create an index on a clustering column. CREATE TABLE keyspace1.Task ( Task_id text, Task_name text, Task_time timestamp, T_location text, PRIMARY KEY ((Task_id, Task_name), Task_time) ); CREATE INDEX ON keyspace1.Task(Task_time); SELECT * FROM Task WHERE Task_time= ‘2019-09-30 15:02:56’; Now this query would work: Note:By creating an index such that creating secondary indexes does not mean that it will increase the speed of queries in Cassandra. One of the important advantage of Secondary indexes helps in accessing data which can simply make it so that WHERE clauses that references values in column beyond the primary and clustering columns can run. We have better option to increase the speed of queries in Cassandra that by creating a table specifically for the query.Lets have a look on another example. In this example Student_record is a table name and keyspace1 is a keyspace name. CREATE TABLE Student_record ( Stu_state text, Stu_zip text, Stu_address text, PRIMARY KEY(Stu_state, Stu_zip) ); Here in this table Stu_state and Stu_zip may be same so, to define a unique record in a table we can add Stu_id as primary key which uniquely defined the record. Now we can do modification in existing table by using ALTER command in CQL. ALTER TABLE Student_record ADD Stu_id int PRIMARY KEY; Output: To check the description of a table in Cassandra used the following CQL query given below.Describe table Student_record; SELECT * FROM Student_record WHERE Stu_id = '107'; Output: To create Composite Partition key in Cassandra:A composite partition key is defined as the key where a partition key is having more than one column then it is called composite partition key. Example: CREATE TABLE Registration ( Name text, Date timestamp, Email text, Query text, PRIMARY KEY((Name, Date), Email) WITH CLUSTERING ORDER BY(Date DESC); SELECT * FROM Registration LIMIT 2; Note:There is an row key for each Row in Cassandra when we create an index. It is common to have denormalized data in Cassandra. It is false that secondary indexes make queries run faster in Cassandra. Parenthesis is used to specify a composite partition key. Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database Introduction of B-Tree Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of ER Model CTE in SQL SQL | Views Difference between DELETE, DROP and TRUNCATE Third Normal Form (3NF) Difference between Primary Key and Foreign Key
[ { "code": null, "e": 23683, "s": 23655, "text": "\n11 Oct, 2019" }, { "code": null, "e": 24277, "s": 23683, "text": "Prerequisite – Introduction to Apache CassandraIndex:As we can access data using attributes which having the partition key. For Example, if Emp_id is a column name for Employee table and if it is partition key of that table then we can filter or search data with the help of partition key. In this case we can used WHERE clause to define condition over attribute and to search data.But suppose if there exists a column which is not a partition key of that table and we want to filter or to search or to access data using WHERE clause then the query will not be executed and will give an error." }, { "code": null, "e": 24589, "s": 24277, "text": "So, to access data in that case using attributes other than the partition key for fast and efficient lookup of data matching a given condition then we need to define index. It can be used for various purpose like for collections, static columns, collection columns, and any other columns except counter columns." }, { "code": null, "e": 24611, "s": 24589, "text": "When to use an Index:" }, { "code": null, "e": 25038, "s": 24611, "text": "Built-in indexes are the best option on a table which having many rows and that rows contain the indexed value.In a particular column which column having more unique values in that case we can used indexing.Table which more overhead due to several reason like column having more entries then in that case we can used indexing.To query and maintain the index we can used the indexing which is always a good option in that case." }, { "code": null, "e": 25150, "s": 25038, "text": "Built-in indexes are the best option on a table which having many rows and that rows contain the indexed value." }, { "code": null, "e": 25247, "s": 25150, "text": "In a particular column which column having more unique values in that case we can used indexing." }, { "code": null, "e": 25367, "s": 25247, "text": "Table which more overhead due to several reason like column having more entries then in that case we can used indexing." }, { "code": null, "e": 25468, "s": 25367, "text": "To query and maintain the index we can used the indexing which is always a good option in that case." }, { "code": null, "e": 25768, "s": 25468, "text": "Example:Suppose you had a cricket match entry table with a million entries for player’s in hundreds of matches and wanted to look up player’s rank by the number of match played. Many player’s ranks will share the same column value for match year. The match_year column is a good option for an index." }, { "code": null, "e": 25795, "s": 25768, "text": "Syntax to create an Index:" }, { "code": null, "e": 25932, "s": 25795, "text": "CREATE INDEX [ IF NOT EXISTS ] index_name\n ON [keyspace_name.]table_name\n ([ ( KEYS | FULL ) ] column_name) \n (ENTRIES column_name); " }, { "code": null, "e": 26029, "s": 25932, "text": "Example:To create table used keyspace1 as a keyspace and Task as a table name. Lets have a look." }, { "code": null, "e": 26180, "s": 26029, "text": "CREATE TABLE keyspace1.Task \n(\n Task_id text,\n Task_name text,\n Task_time timestamp,\n T_location text,\n PRIMARY KEY (Task_id, Task_name)\n); " }, { "code": null, "e": 26350, "s": 26180, "text": "As Cassandra is a distributed and decentralized database with the data organized by partition key, In general case, WHERE clause queries need to include a partition key." }, { "code": null, "e": 26359, "s": 26350, "text": "Example:" }, { "code": null, "e": 26405, "s": 26359, "text": "SELECT * \nFROM Task \nWHERE Task_id = ‘T210’; " }, { "code": null, "e": 26433, "s": 26405, "text": "This query would work fine." }, { "code": null, "e": 26506, "s": 26433, "text": "SELECT * \nFROM Task \nWHERE Task_id = ‘T210’ AND Task_name; ‘set alarm’; " }, { "code": null, "e": 26534, "s": 26506, "text": "This query would work fine." }, { "code": null, "e": 26613, "s": 26534, "text": "Note:In above table Task_id and Task_name columns are the part of primary key." }, { "code": null, "e": 26673, "s": 26613, "text": "SELECT * FROM Task WHERE Task_time= ‘2019-09-30 15:02:56’; " }, { "code": null, "e": 26774, "s": 26673, "text": "This query would not work, because as we can see that here Task_time is not a part of partition key." }, { "code": null, "e": 26864, "s": 26774, "text": "Error: Bad Request : no indexed columns present in by columns clause with Equal operator." }, { "code": null, "e": 27038, "s": 26864, "text": "To resolve such type of errors by Creating an index on a clustering column. Define a table having a composite partition key, and then create an index on a clustering column." }, { "code": null, "e": 27251, "s": 27038, "text": "CREATE TABLE keyspace1.Task (\n Task_id text,\n Task_name text,\n Task_time timestamp,\n T_location text,\n PRIMARY KEY ((Task_id, Task_name), Task_time) \n);\n \nCREATE INDEX ON keyspace1.Task(Task_time); " }, { "code": null, "e": 27313, "s": 27251, "text": "SELECT * \nFROM Task \nWHERE Task_time= ‘2019-09-30 15:02:56’; " }, { "code": null, "e": 27340, "s": 27313, "text": "Now this query would work:" }, { "code": null, "e": 27474, "s": 27340, "text": "Note:By creating an index such that creating secondary indexes does not mean that it will increase the speed of queries in Cassandra." }, { "code": null, "e": 27681, "s": 27474, "text": "One of the important advantage of Secondary indexes helps in accessing data which can simply make it so that WHERE clauses that references values in column beyond the primary and clustering columns can run." }, { "code": null, "e": 27919, "s": 27681, "text": "We have better option to increase the speed of queries in Cassandra that by creating a table specifically for the query.Lets have a look on another example. In this example Student_record is a table name and keyspace1 is a keyspace name." }, { "code": null, "e": 28043, "s": 27919, "text": "CREATE TABLE Student_record \n(\n Stu_state text,\n Stu_zip text,\n Stu_address text,\n PRIMARY KEY(Stu_state, Stu_zip)\n ); " }, { "code": null, "e": 28205, "s": 28043, "text": "Here in this table Stu_state and Stu_zip may be same so, to define a unique record in a table we can add Stu_id as primary key which uniquely defined the record." }, { "code": null, "e": 28281, "s": 28205, "text": "Now we can do modification in existing table by using ALTER command in CQL." }, { "code": null, "e": 28337, "s": 28281, "text": "ALTER TABLE Student_record ADD Stu_id int PRIMARY KEY; " }, { "code": null, "e": 28345, "s": 28337, "text": "Output:" }, { "code": null, "e": 28466, "s": 28345, "text": "To check the description of a table in Cassandra used the following CQL query given below.Describe table Student_record;" }, { "code": null, "e": 28520, "s": 28466, "text": "SELECT * \nFROM Student_record \nWHERE Stu_id = '107'; " }, { "code": null, "e": 28528, "s": 28520, "text": "Output:" }, { "code": null, "e": 28719, "s": 28528, "text": "To create Composite Partition key in Cassandra:A composite partition key is defined as the key where a partition key is having more than one column then it is called composite partition key." }, { "code": null, "e": 28728, "s": 28719, "text": "Example:" }, { "code": null, "e": 28889, "s": 28728, "text": "CREATE TABLE Registration (\n Name text,\n Date timestamp,\n Email text, \n Query text,\n PRIMARY KEY((Name, Date), Email) WITH CLUSTERING ORDER BY(Date DESC); " }, { "code": null, "e": 28927, "s": 28889, "text": "SELECT * \nFROM Registration LIMIT 2; " }, { "code": null, "e": 29187, "s": 28927, "text": "Note:There is an row key for each Row in Cassandra when we create an index. It is common to have denormalized data in Cassandra. It is false that secondary indexes make queries run faster in Cassandra. Parenthesis is used to specify a composite partition key." }, { "code": null, "e": 29194, "s": 29187, "text": "Apache" }, { "code": null, "e": 29199, "s": 29194, "text": "DBMS" }, { "code": null, "e": 29204, "s": 29199, "text": "DBMS" }, { "code": null, "e": 29302, "s": 29204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29311, "s": 29302, "text": "Comments" }, { "code": null, "e": 29324, "s": 29311, "text": "Old Comments" }, { "code": null, "e": 29355, "s": 29324, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 29378, "s": 29355, "text": "Introduction of B-Tree" }, { "code": null, "e": 29431, "s": 29378, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 29489, "s": 29431, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 29514, "s": 29489, "text": "Introduction of ER Model" }, { "code": null, "e": 29525, "s": 29514, "text": "CTE in SQL" }, { "code": null, "e": 29537, "s": 29525, "text": "SQL | Views" }, { "code": null, "e": 29582, "s": 29537, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 29606, "s": 29582, "text": "Third Normal Form (3NF)" } ]
Eroding an image using the OpenCV function erode()
In this program, we will erode an image using the OpenCV function erode(). Erosion of image means to shrink the image. If any of the pixels in a kernel is 0, then all the pixels in the kernel are set to 0. One condition before applying an erosion function on image is that the image should be a grayscale image. Step 1: Import cv2 Step 2: Import numpy. Step 3: Read the image using imread(). Step 4: Define the kernel size using numpy ones. Step 5: Pass the image and kernel to the erode function. Step 6: Display the output. import cv2 import numpy as np image = cv2.imread('testimage.jpg') kernel = np.ones((7,7), np.uint8) image = cv2.erode(image, kernel) cv2.imshow('Eroded Image', image)
[ { "code": null, "e": 1374, "s": 1062, "text": "In this program, we will erode an image using the OpenCV function erode(). Erosion of image means to shrink the image. If any of the pixels in a kernel is 0, then all the pixels in the kernel are set to 0. One condition before applying an erosion function on image is that the image should be a grayscale image." }, { "code": null, "e": 1588, "s": 1374, "text": "Step 1: Import cv2\nStep 2: Import numpy.\nStep 3: Read the image using imread().\nStep 4: Define the kernel size using numpy ones.\nStep 5: Pass the image and kernel to the erode function.\nStep 6: Display the output." }, { "code": null, "e": 1755, "s": 1588, "text": "import cv2\nimport numpy as np\nimage = cv2.imread('testimage.jpg')\nkernel = np.ones((7,7), np.uint8)\nimage = cv2.erode(image, kernel)\ncv2.imshow('Eroded Image', image)" } ]
How to Collect Data From The New York Times Over Any Period of Time | by Brienna Herold | Towards Data Science
Suppose we want to find out how discourse in The New York Times has evolved over a period of time. These days it would be neat to analyze this, since whenever we visit the front page we get firehosed with news about the coronavirus. How has the pandemic shaped the headlines of one of the most popular newspapers in the United States? To answer a question like this, we would need to collect article metadata from The New York Times. Here I describe how to do this in Python. Table of Contents: Where to find The New York Times article metadataHow to request article metadata from The New York Times Where to find The New York Times article metadata How to request article metadata from The New York Times The New York Times offers a developer network consisting of several APIs to let non-employees request articles and metadata from them, which is super convenient for this analysis. Not many newspapers do this, actually. Maintaining an API takes a lot of work. For newspapers that do not offer an API, we would need a different approach to get their headlines. It’s still possible, just not as easy. To begin using The New York Times APIs: Create a free developer’s account here. Sign in after you open the link in the verification email. Make your way to the developer’s home page. Register a new app in your developer’s account. Click on your e-mail address in the upper-right corner.Select Apps in the drop-down menu that appears.Select +NEW APP on your Apps page.Enter any name and description.Activate the Archive API.Select Create. Click on your e-mail address in the upper-right corner. Select Apps in the drop-down menu that appears. Select +NEW APP on your Apps page. Enter any name and description. Activate the Archive API. Select Create. Take note of your just registered app’s API key. This is the only piece of information we need to get data from The New York Times, and we will need it soon. We will use the Archive API to get all article metadata from the past year. This code can be modified for any period of time between 1851 and today. Load dependencies. import osimport jsonimport timeimport requestsimport datetimeimport dateutilimport pandas as pdfrom dateutil.relativedelta import relativedelta Specify the date range. end = datetime.date.today()start = end - relativedelta(years=1) Make a list of the months that fall within this range, even if partially. We need this information for making calls to the Archive API, since it works with only one month at a time. months_in_range = [x.split(' ') for x in pd.date_range(start, end, freq='MS').strftime("%Y %-m").tolist()] I wrote some code to request and process article metadata from the Archive API. This code works with only one month at a time for optimal memory management. We send a request to the API for a given month, receive and parse the response, and populate a data frame with some details about each article, including its publication date, main headline, section, subject keywords, document type, and material type. Finally, we save the data frame as a CSV file and move on to the next month, until we have reached the end of the desired time range. Note that there are two rate limits per API: 4,000 requests per day and 10 requests per minute. We sleep for 6 seconds between calls to avoid hitting the per minute rate limit. Don’t forget to switch out YOUR_API_KEY on line 4 with your API key. Run the code to get and process articles from months_in_range. We have collected metadata for 80,460 articles from the past year! Each month has been saved to a CSV file in the headlines directory. Let’s see what the response looks like for the last month that we processed, which is still in memory. response There’s a lot more. The documentation tells us what is all there. See what the CSV file for this month looks like. df As seen in the data frame, there is the occasional consistency quirk to watch out for. Sometimes the 1st of a month is considered part of the previous month. Sometimes there is missing data, like with September and October 1978 due to a multi-union strike. There is a lot that we can do with all of the article metadata we now have in our headlines directory. One of the things we could do is explore how The New York Times has evolved in its reporting over the past year, with an emphasis on the coronavirus pandemic. This would be interesting as we consider not just what happened, but how the media discussed it. The complete notebook is here. If you’d like to read more of my articles or explore millions of other articles, you can sign up for a Medium membership: brienna.medium.com You can also subscribe to my email list to get notified whenever I publish a new article: brienna.medium.com Some other stories from me that might interest you:
[ { "code": null, "e": 506, "s": 171, "text": "Suppose we want to find out how discourse in The New York Times has evolved over a period of time. These days it would be neat to analyze this, since whenever we visit the front page we get firehosed with news about the coronavirus. How has the pandemic shaped the headlines of one of the most popular newspapers in the United States?" }, { "code": null, "e": 647, "s": 506, "text": "To answer a question like this, we would need to collect article metadata from The New York Times. Here I describe how to do this in Python." }, { "code": null, "e": 666, "s": 647, "text": "Table of Contents:" }, { "code": null, "e": 771, "s": 666, "text": "Where to find The New York Times article metadataHow to request article metadata from The New York Times" }, { "code": null, "e": 821, "s": 771, "text": "Where to find The New York Times article metadata" }, { "code": null, "e": 877, "s": 821, "text": "How to request article metadata from The New York Times" }, { "code": null, "e": 1057, "s": 877, "text": "The New York Times offers a developer network consisting of several APIs to let non-employees request articles and metadata from them, which is super convenient for this analysis." }, { "code": null, "e": 1275, "s": 1057, "text": "Not many newspapers do this, actually. Maintaining an API takes a lot of work. For newspapers that do not offer an API, we would need a different approach to get their headlines. It’s still possible, just not as easy." }, { "code": null, "e": 1315, "s": 1275, "text": "To begin using The New York Times APIs:" }, { "code": null, "e": 1458, "s": 1315, "text": "Create a free developer’s account here. Sign in after you open the link in the verification email. Make your way to the developer’s home page." }, { "code": null, "e": 1506, "s": 1458, "text": "Register a new app in your developer’s account." }, { "code": null, "e": 1713, "s": 1506, "text": "Click on your e-mail address in the upper-right corner.Select Apps in the drop-down menu that appears.Select +NEW APP on your Apps page.Enter any name and description.Activate the Archive API.Select Create." }, { "code": null, "e": 1769, "s": 1713, "text": "Click on your e-mail address in the upper-right corner." }, { "code": null, "e": 1817, "s": 1769, "text": "Select Apps in the drop-down menu that appears." }, { "code": null, "e": 1852, "s": 1817, "text": "Select +NEW APP on your Apps page." }, { "code": null, "e": 1884, "s": 1852, "text": "Enter any name and description." }, { "code": null, "e": 1910, "s": 1884, "text": "Activate the Archive API." }, { "code": null, "e": 1925, "s": 1910, "text": "Select Create." }, { "code": null, "e": 2083, "s": 1925, "text": "Take note of your just registered app’s API key. This is the only piece of information we need to get data from The New York Times, and we will need it soon." }, { "code": null, "e": 2232, "s": 2083, "text": "We will use the Archive API to get all article metadata from the past year. This code can be modified for any period of time between 1851 and today." }, { "code": null, "e": 2251, "s": 2232, "text": "Load dependencies." }, { "code": null, "e": 2395, "s": 2251, "text": "import osimport jsonimport timeimport requestsimport datetimeimport dateutilimport pandas as pdfrom dateutil.relativedelta import relativedelta" }, { "code": null, "e": 2419, "s": 2395, "text": "Specify the date range." }, { "code": null, "e": 2483, "s": 2419, "text": "end = datetime.date.today()start = end - relativedelta(years=1)" }, { "code": null, "e": 2665, "s": 2483, "text": "Make a list of the months that fall within this range, even if partially. We need this information for making calls to the Archive API, since it works with only one month at a time." }, { "code": null, "e": 2772, "s": 2665, "text": "months_in_range = [x.split(' ') for x in pd.date_range(start, end, freq='MS').strftime(\"%Y %-m\").tolist()]" }, { "code": null, "e": 3315, "s": 2772, "text": "I wrote some code to request and process article metadata from the Archive API. This code works with only one month at a time for optimal memory management. We send a request to the API for a given month, receive and parse the response, and populate a data frame with some details about each article, including its publication date, main headline, section, subject keywords, document type, and material type. Finally, we save the data frame as a CSV file and move on to the next month, until we have reached the end of the desired time range." }, { "code": null, "e": 3492, "s": 3315, "text": "Note that there are two rate limits per API: 4,000 requests per day and 10 requests per minute. We sleep for 6 seconds between calls to avoid hitting the per minute rate limit." }, { "code": null, "e": 3561, "s": 3492, "text": "Don’t forget to switch out YOUR_API_KEY on line 4 with your API key." }, { "code": null, "e": 3624, "s": 3561, "text": "Run the code to get and process articles from months_in_range." }, { "code": null, "e": 3759, "s": 3624, "text": "We have collected metadata for 80,460 articles from the past year! Each month has been saved to a CSV file in the headlines directory." }, { "code": null, "e": 3862, "s": 3759, "text": "Let’s see what the response looks like for the last month that we processed, which is still in memory." }, { "code": null, "e": 3871, "s": 3862, "text": "response" }, { "code": null, "e": 3937, "s": 3871, "text": "There’s a lot more. The documentation tells us what is all there." }, { "code": null, "e": 3986, "s": 3937, "text": "See what the CSV file for this month looks like." }, { "code": null, "e": 3989, "s": 3986, "text": "df" }, { "code": null, "e": 4246, "s": 3989, "text": "As seen in the data frame, there is the occasional consistency quirk to watch out for. Sometimes the 1st of a month is considered part of the previous month. Sometimes there is missing data, like with September and October 1978 due to a multi-union strike." }, { "code": null, "e": 4605, "s": 4246, "text": "There is a lot that we can do with all of the article metadata we now have in our headlines directory. One of the things we could do is explore how The New York Times has evolved in its reporting over the past year, with an emphasis on the coronavirus pandemic. This would be interesting as we consider not just what happened, but how the media discussed it." }, { "code": null, "e": 4636, "s": 4605, "text": "The complete notebook is here." }, { "code": null, "e": 4758, "s": 4636, "text": "If you’d like to read more of my articles or explore millions of other articles, you can sign up for a Medium membership:" }, { "code": null, "e": 4777, "s": 4758, "text": "brienna.medium.com" }, { "code": null, "e": 4867, "s": 4777, "text": "You can also subscribe to my email list to get notified whenever I publish a new article:" }, { "code": null, "e": 4886, "s": 4867, "text": "brienna.medium.com" } ]
Minimum number of groups of nodes such that no ancestor is present in the same group - GeeksforGeeks
07 Jun, 2021 Given a tree of N nodes. The task is to form the minimum number of groups of nodes such that every node belong to exactly one group, and none of its ancestors are in the same group. The parent of each node is given (-1 if a node does not have a parent).Examples: Input: par[] = {-1, 1, 2, 1, 4} Output: 3 The three groups can be: Group 1: {1} Group 2: {2, 4} Group 3: {3, 5}Input: par[] = {-1, 1, 1, 2, 2, 5, 6} Output: 5 Approach: The groups can be made by grouping nodes on the same level together (A node and any of it’s ancestors cannot be on the same level). So the minimum number of groups will be the maximum depth of the tree.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the depth of the treeint findDepth(int x, vector<int> child[]){ int mx = 0; // Find the maximum depth of all its children for (auto ch : child[x]) mx = max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1;} // Function to return// the minimum number of groups requiredint minimumGroups(int n, int par[]){ vector<int> child[n + 1]; // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].push_back(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = max(res, findDepth(i, child)); return res;} // Driver codemain(){ int par[] = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = sizeof(par) / sizeof(par[0]) - 1; cout << minimumGroups(n, par);} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the depth of the tree static int findDepth(int x, Vector<Integer> child[]) { int mx = 0; // Find the maximum depth of all its children for (Integer ch : child[x]) mx = Math.max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1; } // Function to return // the minimum number of groups required static int minimumGroups(int n, int par[]) { Vector<Integer>[] child = new Vector[n + 1]; for (int i = 0; i <= n; i++) { child[i] = new Vector<Integer>(); } // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].add(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.max(res, findDepth(i, child)); return res; } // Driver code public static void main(String[] args) { int par[] = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = par.length - 1; System.out.print(minimumGroups(n, par)); }} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to return the depth of the treedef findDepth(x, child): mx = 0 # Find the maximum depth # of all its children for ch in child[x]: mx = max(mx, findDepth(ch, child)) # Add 1 for the depth # of the current node return mx + 1 # Function to return the minimum # number of groups requireddef minimumGroups(n, par): child = [[] for i in range(n + 1)] # For every node create a list # of its children for i in range(0, n): if (par[i] != -1): child[par[i]].append(i) res = 0 for i in range(0, n): # If the node is root # perform dfs starting with this node if(par[i] == -1): res = max(res, findDepth(i, child)) return res # Driver Codearray = [0, -1, 1, 1, 2, 2, 5, 6]print(minimumGroups(len(array), array)) # This code is contributed# by SidharthPanicker // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the depth of the tree static int findDepth(int x, List<int> []child) { int mx = 0; // Find the maximum depth of all its children foreach (int ch in child[x]) mx = Math.Max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1; } // Function to return // the minimum number of groups required static int minimumGroups(int n, int []par) { List<int>[] child = new List<int>[n + 1]; for (int i = 0; i <= n; i++) { child[i] = new List<int>(); } // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].Add(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.Max(res, findDepth(i, child)); return res; } // Driver code public static void Main(String[] args) { int []par = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = par.Length - 1; Console.Write(minimumGroups(n, par)); }} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to return the depth of the treefunction findDepth(x, child){ var mx = 0; // Find the maximum depth of all its children child[x].forEach(ch => { mx = Math.max(mx, findDepth(ch, child)); }); // Add 1 for the depth of the current node return mx + 1;} // Function to return// the minimum number of groups requiredfunction minimumGroups(n, par){ var child = Array.from(Array(n+1), ()=>Array()); // For every node create a list of its children for (var i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].push(i); var res = 0; for (var i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.max(res, findDepth(i, child)); return res;} // Driver codevar par = [0, -1, 1, 1, 2, 2, 5, 6 ];var n = par.length - 1;document.write( minimumGroups(n, par)); // This code is contributed by famously.</script> 5 SidharthPanicker princiraj1992 Rajput-Ji famously DFS Tree DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Tree Data Structure DFS traversal of a tree using recursion Threaded Binary Tree Find maximum (or minimum) in Binary Tree Iterative Postorder Traversal | Set 2 (Using One Stack) Find the node with minimum value in a Binary Search Tree Top 50 Tree Coding Problems for Interviews Maximum Path Sum in a Binary Tree Construct Complete Binary Tree from its Linked List Representation Iterative Preorder Traversal
[ { "code": null, "e": 24938, "s": 24910, "text": "\n07 Jun, 2021" }, { "code": null, "e": 25203, "s": 24938, "text": "Given a tree of N nodes. The task is to form the minimum number of groups of nodes such that every node belong to exactly one group, and none of its ancestors are in the same group. The parent of each node is given (-1 if a node does not have a parent).Examples: " }, { "code": null, "e": 25364, "s": 25203, "text": "Input: par[] = {-1, 1, 2, 1, 4} Output: 3 The three groups can be: Group 1: {1} Group 2: {2, 4} Group 3: {3, 5}Input: par[] = {-1, 1, 1, 2, 2, 5, 6} Output: 5 " }, { "code": null, "e": 25631, "s": 25366, "text": "Approach: The groups can be made by grouping nodes on the same level together (A node and any of it’s ancestors cannot be on the same level). So the minimum number of groups will be the maximum depth of the tree.Below is the implementation of the above approach: " }, { "code": null, "e": 25635, "s": 25631, "text": "C++" }, { "code": null, "e": 25640, "s": 25635, "text": "Java" }, { "code": null, "e": 25648, "s": 25640, "text": "Python3" }, { "code": null, "e": 25651, "s": 25648, "text": "C#" }, { "code": null, "e": 25662, "s": 25651, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the depth of the treeint findDepth(int x, vector<int> child[]){ int mx = 0; // Find the maximum depth of all its children for (auto ch : child[x]) mx = max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1;} // Function to return// the minimum number of groups requiredint minimumGroups(int n, int par[]){ vector<int> child[n + 1]; // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].push_back(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = max(res, findDepth(i, child)); return res;} // Driver codemain(){ int par[] = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = sizeof(par) / sizeof(par[0]) - 1; cout << minimumGroups(n, par);}", "e": 26669, "s": 25662, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the depth of the tree static int findDepth(int x, Vector<Integer> child[]) { int mx = 0; // Find the maximum depth of all its children for (Integer ch : child[x]) mx = Math.max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1; } // Function to return // the minimum number of groups required static int minimumGroups(int n, int par[]) { Vector<Integer>[] child = new Vector[n + 1]; for (int i = 0; i <= n; i++) { child[i] = new Vector<Integer>(); } // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].add(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.max(res, findDepth(i, child)); return res; } // Driver code public static void main(String[] args) { int par[] = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = par.length - 1; System.out.print(minimumGroups(n, par)); }} // This code is contributed by PrinciRaj1992", "e": 28020, "s": 26669, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the depth of the treedef findDepth(x, child): mx = 0 # Find the maximum depth # of all its children for ch in child[x]: mx = max(mx, findDepth(ch, child)) # Add 1 for the depth # of the current node return mx + 1 # Function to return the minimum # number of groups requireddef minimumGroups(n, par): child = [[] for i in range(n + 1)] # For every node create a list # of its children for i in range(0, n): if (par[i] != -1): child[par[i]].append(i) res = 0 for i in range(0, n): # If the node is root # perform dfs starting with this node if(par[i] == -1): res = max(res, findDepth(i, child)) return res # Driver Codearray = [0, -1, 1, 1, 2, 2, 5, 6]print(minimumGroups(len(array), array)) # This code is contributed# by SidharthPanicker", "e": 28947, "s": 28020, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the depth of the tree static int findDepth(int x, List<int> []child) { int mx = 0; // Find the maximum depth of all its children foreach (int ch in child[x]) mx = Math.Max(mx, findDepth(ch, child)); // Add 1 for the depth of the current node return mx + 1; } // Function to return // the minimum number of groups required static int minimumGroups(int n, int []par) { List<int>[] child = new List<int>[n + 1]; for (int i = 0; i <= n; i++) { child[i] = new List<int>(); } // For every node create a list of its children for (int i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].Add(i); int res = 0; for (int i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.Max(res, findDepth(i, child)); return res; } // Driver code public static void Main(String[] args) { int []par = { 0, -1, 1, 1, 2, 2, 5, 6 }; int n = par.Length - 1; Console.Write(minimumGroups(n, par)); }} // This code is contributed by Rajput-Ji", "e": 30302, "s": 28947, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the depth of the treefunction findDepth(x, child){ var mx = 0; // Find the maximum depth of all its children child[x].forEach(ch => { mx = Math.max(mx, findDepth(ch, child)); }); // Add 1 for the depth of the current node return mx + 1;} // Function to return// the minimum number of groups requiredfunction minimumGroups(n, par){ var child = Array.from(Array(n+1), ()=>Array()); // For every node create a list of its children for (var i = 1; i <= n; i++) if (par[i] != -1) child[par[i]].push(i); var res = 0; for (var i = 1; i <= n; i++) // If the node is root // perform dfs starting with this node if (par[i] == -1) res = Math.max(res, findDepth(i, child)); return res;} // Driver codevar par = [0, -1, 1, 1, 2, 2, 5, 6 ];var n = par.length - 1;document.write( minimumGroups(n, par)); // This code is contributed by famously.</script>", "e": 31325, "s": 30302, "text": null }, { "code": null, "e": 31327, "s": 31325, "text": "5" }, { "code": null, "e": 31346, "s": 31329, "text": "SidharthPanicker" }, { "code": null, "e": 31360, "s": 31346, "text": "princiraj1992" }, { "code": null, "e": 31370, "s": 31360, "text": "Rajput-Ji" }, { "code": null, "e": 31379, "s": 31370, "text": "famously" }, { "code": null, "e": 31383, "s": 31379, "text": "DFS" }, { "code": null, "e": 31388, "s": 31383, "text": "Tree" }, { "code": null, "e": 31392, "s": 31388, "text": "DFS" }, { "code": null, "e": 31397, "s": 31392, "text": "Tree" }, { "code": null, "e": 31495, "s": 31397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31504, "s": 31495, "text": "Comments" }, { "code": null, "e": 31517, "s": 31504, "text": "Old Comments" }, { "code": null, "e": 31553, "s": 31517, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 31593, "s": 31553, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 31614, "s": 31593, "text": "Threaded Binary Tree" }, { "code": null, "e": 31655, "s": 31614, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 31711, "s": 31655, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 31768, "s": 31711, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 31811, "s": 31768, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 31845, "s": 31811, "text": "Maximum Path Sum in a Binary Tree" }, { "code": null, "e": 31912, "s": 31845, "text": "Construct Complete Binary Tree from its Linked List Representation" } ]
How to select first and last data row from a MySQL result?
You can select the first and last data row using MIN() and MAX(). The syntax is as follows − SELECT * FROM yourTableName WHERE yourColumnName = (SELECT MIN(yourColumnName) FROM yourTableName) UNION SELECT * FROM yourTableName WHERE yourColumnName = (SELECT MAX(yourColumnName) FROM yourTableName) ; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table FirstAndLastDataDemo -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20), -> EmployeeAge int -> ); Query OK, 0 rows affected (0.59 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23); Query OK, 1 row affected (0.15 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13); Query OK, 1 row affected (0.11 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24); Query OK, 1 row affected (0.14 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14); Query OK, 1 row affected (0.18 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31); Query OK, 1 row affected (0.10 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18); Query OK, 1 row affected (0.16 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Maxwell',28); Query OK, 1 row affected (0.17 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27); Query OK, 1 row affected (0.12 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement − mysql> select *from FirstAndLastDataDemo; +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 2 | Bob | 13 | | 3 | Larry | 24 | | 4 | Sam | 14 | | 5 | Mike | 31 | | 6 | James | 18 | | 7 | Maxwell | 28 | | 8 | David | 27 | | 9 | Chris | 22 | +------------+--------------+-------------+ 9 rows in set (0.00 sec) Here is the query to get first row data and last row data − mysql> SELECT * -> FROM FirstAndLastDataDemo -> WHERE EmployeeId = (SELECT MIN(EmployeeId) FROM FirstAndLastDataDemo) -> UNION -> SELECT * -> FROM FirstAndLastDataDemo -> WHERE EmployeeId = (SELECT MAX(EmployeeId) FROM FirstAndLastDataDemo); +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 9 | Chris | 22 | +------------+--------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "You can select the first and last data row using MIN() and MAX(). The syntax is as follows −" }, { "code": null, "e": 1361, "s": 1155, "text": "SELECT *\nFROM yourTableName\nWHERE yourColumnName = (SELECT MIN(yourColumnName) FROM yourTableName)\nUNION\nSELECT *\nFROM yourTableName\nWHERE yourColumnName = (SELECT MAX(yourColumnName) FROM yourTableName) ;" }, { "code": null, "e": 1460, "s": 1361, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1667, "s": 1460, "text": "mysql> create table FirstAndLastDataDemo\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> EmployeeName varchar(20),\n -> EmployeeAge int\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1748, "s": 1667, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2842, "s": 1748, "text": "mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)\nvalues('Maxwell',28);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2902, "s": 2842, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2944, "s": 2902, "text": "mysql> select *from FirstAndLastDataDemo;" }, { "code": null, "e": 3541, "s": 2944, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | John | 23 |\n| 2 | Bob | 13 |\n| 3 | Larry | 24 |\n| 4 | Sam | 14 |\n| 5 | Mike | 31 |\n| 6 | James | 18 |\n| 7 | Maxwell | 28 |\n| 8 | David | 27 |\n| 9 | Chris | 22 |\n+------------+--------------+-------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 3601, "s": 3541, "text": "Here is the query to get first row data and last row data −" }, { "code": null, "e": 3843, "s": 3601, "text": "mysql> SELECT *\n-> FROM FirstAndLastDataDemo\n-> WHERE EmployeeId = (SELECT MIN(EmployeeId) FROM FirstAndLastDataDemo)\n-> UNION\n-> SELECT *\n-> FROM FirstAndLastDataDemo\n-> WHERE EmployeeId = (SELECT MAX(EmployeeId) FROM FirstAndLastDataDemo);" }, { "code": null, "e": 4132, "s": 3843, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | John | 23 |\n| 9 | Chris | 22 |\n+------------+--------------+-------------+\n2 rows in set (0.00 sec)" } ]
Next higher palindromic number using the same set of digits - GeeksforGeeks
18 May, 2021 Given a palindromic number num having n number of digits. The problem is to find the smallest palindromic number greater than num using the same set of digits as in num. If no such number can be formed then print “Not Possible”. The number could be very large and may or may not even fit into long long int. Examples: Input : 4697557964 Output : 4756996574 Input : 543212345 Output : Not Possible Approach: Following are the steps: If number of digits n <= 3, then print “Not Possible” and return.Calculate mid = n/2 – 1.Start traversing from the digit at index mid up to the 1st digit and while traversing find the index i of the rightmost digit which is smaller than the digit on its right side.Now search for the smallest digit greater than the digit num[i] in the index range i+1 to mid. Let the index of this digit be smallest.If no such smallest digit found, then print “Not Possible”.Else the swap the digits at index i and smallest and also swap the digits at index n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property in num.Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic property in num.Print the final modified number num. If number of digits n <= 3, then print “Not Possible” and return. Calculate mid = n/2 – 1. Start traversing from the digit at index mid up to the 1st digit and while traversing find the index i of the rightmost digit which is smaller than the digit on its right side. Now search for the smallest digit greater than the digit num[i] in the index range i+1 to mid. Let the index of this digit be smallest. If no such smallest digit found, then print “Not Possible”. Else the swap the digits at index i and smallest and also swap the digits at index n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property in num. Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic property in num. Print the final modified number num. C++ Java Python C# PHP Javascript // C++ implementation to find next higher// palindromic number using the same set// of digits#include <bits/stdc++.h>using namespace std; // function to reverse the digits in the// range i to j in 'num'void reverse(char num[], int i, int j){ while (i < j) { swap(num[i], num[j]); i++; j--; }} // function to find next higher palindromic// number using the same set of digitsvoid nextPalin(char num[], int n){ // if length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { cout << "Not Possible"; return; } // find the index of last digit // in the 1st half of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { cout << "Not Possible"; return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // swap num[i] with num[smallest] swap(num[i], num[smallest]); // as the number is a palindrome, the same // swap of digits should be performed in // the 2nd half of 'num' swap(num[n - i - 1], num[n - smallest - 1]); // reverse digits in the range (i+1) to mid reverse(num, i + 1, mid); // if n is even, then reverse digits in the // range mid+1 to n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then reverse digits // in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher palindromic number cout << "Next Palindrome: " << num;} // Driver program to test aboveint main(){ char num[] = "4697557964"; int n = strlen(num); nextPalin(num, n); return 0;} // Java implementation to find next higher// palindromic number using the same set// of digitsimport java.util.*; class NextHigherPalindrome{ // function to reverse the digits in the // range i to j in 'num' public static void reverse(char num[], int i, int j) { while (i < j) { char temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; } } // function to find next higher palindromic // number using the same set of digits public static void nextPalin(char num[], int n) { // if length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { System.out.println("Not Possible"); return; } char temp; // find the index of last digit // in the 1st half of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { System.out.println("Not Possible"); return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // swap num[i] with num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // reverse digits in the range (i+1) // to mid reverse(num, i + 1, mid); // if n is even, then reverse // digits in the range mid+1 to // n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then reverse // digits in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher palindromic // number String result=String.valueOf(num); System.out.println("Next Palindrome: "+ result); } // Driver Code public static void main(String args[]) { String str="4697557964"; char num[]=str.toCharArray(); int n=str.length(); nextPalin(num,n); }} // This code is contributed by Danish Kaleem # Python implementation to find next higher# palindromic number using the same set# of digits # function to reverse the digits in the# range i to j in 'num'def reverse(num, i, j) : while (i < j) : temp = num[i] num[i] = num[j] num[j] = temp i = i + 1 j = j - 1 # function to find next higher palindromic# number using the same set of digitsdef nextPalin(num, n) : # if length of number is less than '3' # then no higher palindromic number # can be formed if (n <= 3) : print "Not Possible" return # find the index of last digit # in the 1st half of 'num' mid = n / 2 - 1 # Start from the (mid-1)th digit and # find the first digit that is # smaller than the digit next to it. i = mid - 1 while i >= 0 : if (num[i] < num[i + 1]) : break i = i - 1 # If no such digit is found, then all # digits are in descending order which # means there cannot be a greater # palindromic number with same set of # digits if (i < 0) : print "Not Possible" return # Find the smallest digit on right # side of ith digit which is greater # than num[i] up to index 'mid' smallest = i + 1 j = i + 2 while j <= mid : if (num[j] > num[i] and num[j] < num[smallest]) : smallest = j j = j + 1 # swap num[i] with num[smallest] temp = num[i] num[i] = num[smallest] num[smallest] = temp # as the number is a palindrome, # the same swap of digits should # be performed in the 2nd half of # 'num' temp = num[n - i - 1] num[n - i - 1] = num[n - smallest - 1] num[n - smallest - 1] = temp # reverse digits in the range (i+1) # to mid reverse(num, i + 1, mid) # if n is even, then reverse # digits in the range mid+1 to # n-i-2 if (n % 2 == 0) : reverse(num, mid + 1, n - i - 2) # else if n is odd, then reverse # digits in the range mid+2 to n-i-2 else : reverse(num, mid + 2, n - i - 2) # required next higher palindromic # number result = ''.join(num) print "Next Palindrome: ",result # Driver Codest = "4697557964"num = list(st)n = len(st)nextPalin(num, n) # This code is contributed by Nikita Tiwari // C# implementation to find// next higher palindromic// number using the same set// of digitsusing System; class GFG{ // function to reverse // the digits in the // range i to j in 'num' public static void reverse(char[] num, int i, int j) { while (i < j) { char temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; } } // function to find next // higher palindromic number // using the same set of digits public static void nextPalin(char[] num, int n) { // if length of number is // less than '3' then no // higher palindromic number // can be formed if (n <= 3) { Console.WriteLine("Not Possible"); return; } char temp; // find the index of last // digit in the 1st half // of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th // digit and find the // first digit that is // smaller than the digit // next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, // then all digits are in // descending order which // means there cannot be a // greater palindromic number // with same set of digits if (i < 0) { Console.WriteLine("Not Possible"); return; } // Find the smallest digit on // right side of ith digit // which is greater than num[i] // up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] < num[smallest]) smallest = j; // swap num[i] with // num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // reverse digits in the // range (i+1) to mid reverse(num, i + 1, mid); // if n is even, then // reverse digits in the // range mid+1 to n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then // reverse digits in the // range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher // palindromic number String result = new String(num); Console.WriteLine("Next Palindrome: "+ result); } // Driver Code public static void Main() { String str = "4697557964"; char[] num = str.ToCharArray(); int n = str.Length; nextPalin(num, n); }} // This code is contributed by mits <?php// PHP implementation to find// next higher palindromic number// using the same set of digits // function to reverse the digits// in the range i to j in 'num'function reverse(&$num, $i, $j){ while ($i < $j) { $t = $num[$i]; $num[$i] = $num[$j]; $num[$j] = $t; $i++; $j--; }} // function to find next higher// palindromic number using the// same set of digitsfunction nextPalin($num, $n){ // if length of number is less // than '3' then no higher // palindromic number can be formed if ($n <= 3) { echo "Not Possible"; return; } // find the index of last digit // in the 1st half of 'num' $mid = ($n / 2) - 1; $i = $mid - 1; $j; // Start from the (mid-1)th digit // and find the first digit // that is smaller than the digit // next to it. for (; $i >= 0; $i--) if ($num[$i] < $num[$i + 1]) break; // If no such digit is found, // then all digits are in // descending order which means // there cannot be a greater // palindromic number with same // set of digits if ($i < 0) { echo "Not Possible"; return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' $smallest = $i + 1; $j = 0; for ($j = $i + 2; $j <= $mid; $j++) if ($num[$j] > $num[$i] && $num[$j] < $num[$smallest]) $smallest = $j; // swap num[i] with num[smallest] $t = $num[$i]; $num[$i] = $num[$smallest]; $num[$smallest] = $t; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of 'num' $t = $num[$n - $i - 1]; $num[$n - $i - 1] = $num[$n - $smallest - 1]; $num[$n - $smallest - 1] = $t; // reverse digits in the // range (i+1) to mid reverse($num, $i + 1, $mid); // if n is even, then // reverse digits in the // range mid+1 to n-i-2 if ($n % 2 == 0) reverse($num, $mid + 1, $n - $i - 2); // else if n is odd, then reverse // digits in the range mid+2 // to n-i-2 else reverse($num, $mid + 2, $n - $i - 2); // required next higher // palindromic number echo "Next Palindrome: " . $num;} // Driver Code$num = "4697557964";$n = strlen($num);nextPalin($num, $n); // This code is contributed by mits?> <script> // Javascript implementation to find next higher// palindromic number using the same set// of digitsclass NextHigherPalindrome // Function to reverse the digits in the// range i to j in 'num'function reverse(num , i, j){ while (i < j) { var temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; }} // Function to find next higher palindromic// number using the same set of digitsfunction nextPalin(num, n){ // If length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { document.write("Not Possible"); return; } var temp; // Find the index of last digit // in the 1st half of 'num' var mid = n / 2 - 1; var i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for(i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { document.write("Not Possible"); return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' var smallest = i + 1; for(j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // Swap num[i] with num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // As the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // Reverse digits in the range (i+1) // to mid reverse(num, i + 1, mid); // If n is even, then reverse // digits in the range mid+1 to // n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // Else if n is odd, then reverse // digits in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // Required next higher palindromic // number var result = num.join(''); document.write("Next Palindrome: "+ result);} // Driver Codevar str = "4697557964";var num = str.split('');var n = str.length; nextPalin(num,n); // This code is contributed by 29AjayKumar </script> Output: Next Palindrome: 4756996574 Time Complexity: O(n) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar Akanksha_Rai shivam2608 29AjayKumar number-digits Numbers palindrome Mathematical Strings Strings Mathematical Numbers palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Python program to check if a string is palindrome or not Different methods to reverse a string in C/C++
[ { "code": null, "e": 25116, "s": 25088, "text": "\n18 May, 2021" }, { "code": null, "e": 25424, "s": 25116, "text": "Given a palindromic number num having n number of digits. The problem is to find the smallest palindromic number greater than num using the same set of digits as in num. If no such number can be formed then print “Not Possible”. The number could be very large and may or may not even fit into long long int." }, { "code": null, "e": 25435, "s": 25424, "text": "Examples: " }, { "code": null, "e": 25516, "s": 25435, "text": "Input : 4697557964\nOutput : 4756996574\n\nInput : 543212345\nOutput : Not Possible" }, { "code": null, "e": 25551, "s": 25516, "text": "Approach: Following are the steps:" }, { "code": null, "e": 26496, "s": 25551, "text": "If number of digits n <= 3, then print “Not Possible” and return.Calculate mid = n/2 – 1.Start traversing from the digit at index mid up to the 1st digit and while traversing find the index i of the rightmost digit which is smaller than the digit on its right side.Now search for the smallest digit greater than the digit num[i] in the index range i+1 to mid. Let the index of this digit be smallest.If no such smallest digit found, then print “Not Possible”.Else the swap the digits at index i and smallest and also swap the digits at index n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property in num.Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic property in num.Print the final modified number num." }, { "code": null, "e": 26562, "s": 26496, "text": "If number of digits n <= 3, then print “Not Possible” and return." }, { "code": null, "e": 26587, "s": 26562, "text": "Calculate mid = n/2 – 1." }, { "code": null, "e": 26764, "s": 26587, "text": "Start traversing from the digit at index mid up to the 1st digit and while traversing find the index i of the rightmost digit which is smaller than the digit on its right side." }, { "code": null, "e": 26900, "s": 26764, "text": "Now search for the smallest digit greater than the digit num[i] in the index range i+1 to mid. Let the index of this digit be smallest." }, { "code": null, "e": 26960, "s": 26900, "text": "If no such smallest digit found, then print “Not Possible”." }, { "code": null, "e": 27136, "s": 26960, "text": "Else the swap the digits at index i and smallest and also swap the digits at index n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property in num." }, { "code": null, "e": 27411, "s": 27136, "text": "Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic property in num." }, { "code": null, "e": 27448, "s": 27411, "text": "Print the final modified number num." }, { "code": null, "e": 27452, "s": 27448, "text": "C++" }, { "code": null, "e": 27457, "s": 27452, "text": "Java" }, { "code": null, "e": 27464, "s": 27457, "text": "Python" }, { "code": null, "e": 27467, "s": 27464, "text": "C#" }, { "code": null, "e": 27471, "s": 27467, "text": "PHP" }, { "code": null, "e": 27482, "s": 27471, "text": "Javascript" }, { "code": "// C++ implementation to find next higher// palindromic number using the same set// of digits#include <bits/stdc++.h>using namespace std; // function to reverse the digits in the// range i to j in 'num'void reverse(char num[], int i, int j){ while (i < j) { swap(num[i], num[j]); i++; j--; }} // function to find next higher palindromic// number using the same set of digitsvoid nextPalin(char num[], int n){ // if length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { cout << \"Not Possible\"; return; } // find the index of last digit // in the 1st half of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { cout << \"Not Possible\"; return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // swap num[i] with num[smallest] swap(num[i], num[smallest]); // as the number is a palindrome, the same // swap of digits should be performed in // the 2nd half of 'num' swap(num[n - i - 1], num[n - smallest - 1]); // reverse digits in the range (i+1) to mid reverse(num, i + 1, mid); // if n is even, then reverse digits in the // range mid+1 to n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then reverse digits // in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher palindromic number cout << \"Next Palindrome: \" << num;} // Driver program to test aboveint main(){ char num[] = \"4697557964\"; int n = strlen(num); nextPalin(num, n); return 0;}", "e": 29713, "s": 27482, "text": null }, { "code": "// Java implementation to find next higher// palindromic number using the same set// of digitsimport java.util.*; class NextHigherPalindrome{ // function to reverse the digits in the // range i to j in 'num' public static void reverse(char num[], int i, int j) { while (i < j) { char temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; } } // function to find next higher palindromic // number using the same set of digits public static void nextPalin(char num[], int n) { // if length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { System.out.println(\"Not Possible\"); return; } char temp; // find the index of last digit // in the 1st half of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { System.out.println(\"Not Possible\"); return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // swap num[i] with num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // reverse digits in the range (i+1) // to mid reverse(num, i + 1, mid); // if n is even, then reverse // digits in the range mid+1 to // n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then reverse // digits in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher palindromic // number String result=String.valueOf(num); System.out.println(\"Next Palindrome: \"+ result); } // Driver Code public static void main(String args[]) { String str=\"4697557964\"; char num[]=str.toCharArray(); int n=str.length(); nextPalin(num,n); }} // This code is contributed by Danish Kaleem", "e": 32772, "s": 29713, "text": null }, { "code": "# Python implementation to find next higher# palindromic number using the same set# of digits # function to reverse the digits in the# range i to j in 'num'def reverse(num, i, j) : while (i < j) : temp = num[i] num[i] = num[j] num[j] = temp i = i + 1 j = j - 1 # function to find next higher palindromic# number using the same set of digitsdef nextPalin(num, n) : # if length of number is less than '3' # then no higher palindromic number # can be formed if (n <= 3) : print \"Not Possible\" return # find the index of last digit # in the 1st half of 'num' mid = n / 2 - 1 # Start from the (mid-1)th digit and # find the first digit that is # smaller than the digit next to it. i = mid - 1 while i >= 0 : if (num[i] < num[i + 1]) : break i = i - 1 # If no such digit is found, then all # digits are in descending order which # means there cannot be a greater # palindromic number with same set of # digits if (i < 0) : print \"Not Possible\" return # Find the smallest digit on right # side of ith digit which is greater # than num[i] up to index 'mid' smallest = i + 1 j = i + 2 while j <= mid : if (num[j] > num[i] and num[j] < num[smallest]) : smallest = j j = j + 1 # swap num[i] with num[smallest] temp = num[i] num[i] = num[smallest] num[smallest] = temp # as the number is a palindrome, # the same swap of digits should # be performed in the 2nd half of # 'num' temp = num[n - i - 1] num[n - i - 1] = num[n - smallest - 1] num[n - smallest - 1] = temp # reverse digits in the range (i+1) # to mid reverse(num, i + 1, mid) # if n is even, then reverse # digits in the range mid+1 to # n-i-2 if (n % 2 == 0) : reverse(num, mid + 1, n - i - 2) # else if n is odd, then reverse # digits in the range mid+2 to n-i-2 else : reverse(num, mid + 2, n - i - 2) # required next higher palindromic # number result = ''.join(num) print \"Next Palindrome: \",result # Driver Codest = \"4697557964\"num = list(st)n = len(st)nextPalin(num, n) # This code is contributed by Nikita Tiwari", "e": 35141, "s": 32772, "text": null }, { "code": "// C# implementation to find// next higher palindromic// number using the same set// of digitsusing System; class GFG{ // function to reverse // the digits in the // range i to j in 'num' public static void reverse(char[] num, int i, int j) { while (i < j) { char temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; } } // function to find next // higher palindromic number // using the same set of digits public static void nextPalin(char[] num, int n) { // if length of number is // less than '3' then no // higher palindromic number // can be formed if (n <= 3) { Console.WriteLine(\"Not Possible\"); return; } char temp; // find the index of last // digit in the 1st half // of 'num' int mid = n / 2 - 1; int i, j; // Start from the (mid-1)th // digit and find the // first digit that is // smaller than the digit // next to it. for (i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, // then all digits are in // descending order which // means there cannot be a // greater palindromic number // with same set of digits if (i < 0) { Console.WriteLine(\"Not Possible\"); return; } // Find the smallest digit on // right side of ith digit // which is greater than num[i] // up to index 'mid' int smallest = i + 1; for (j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] < num[smallest]) smallest = j; // swap num[i] with // num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // reverse digits in the // range (i+1) to mid reverse(num, i + 1, mid); // if n is even, then // reverse digits in the // range mid+1 to n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // else if n is odd, then // reverse digits in the // range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // required next higher // palindromic number String result = new String(num); Console.WriteLine(\"Next Palindrome: \"+ result); } // Driver Code public static void Main() { String str = \"4697557964\"; char[] num = str.ToCharArray(); int n = str.Length; nextPalin(num, n); }} // This code is contributed by mits", "e": 38331, "s": 35141, "text": null }, { "code": "<?php// PHP implementation to find// next higher palindromic number// using the same set of digits // function to reverse the digits// in the range i to j in 'num'function reverse(&$num, $i, $j){ while ($i < $j) { $t = $num[$i]; $num[$i] = $num[$j]; $num[$j] = $t; $i++; $j--; }} // function to find next higher// palindromic number using the// same set of digitsfunction nextPalin($num, $n){ // if length of number is less // than '3' then no higher // palindromic number can be formed if ($n <= 3) { echo \"Not Possible\"; return; } // find the index of last digit // in the 1st half of 'num' $mid = ($n / 2) - 1; $i = $mid - 1; $j; // Start from the (mid-1)th digit // and find the first digit // that is smaller than the digit // next to it. for (; $i >= 0; $i--) if ($num[$i] < $num[$i + 1]) break; // If no such digit is found, // then all digits are in // descending order which means // there cannot be a greater // palindromic number with same // set of digits if ($i < 0) { echo \"Not Possible\"; return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' $smallest = $i + 1; $j = 0; for ($j = $i + 2; $j <= $mid; $j++) if ($num[$j] > $num[$i] && $num[$j] < $num[$smallest]) $smallest = $j; // swap num[i] with num[smallest] $t = $num[$i]; $num[$i] = $num[$smallest]; $num[$smallest] = $t; // as the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of 'num' $t = $num[$n - $i - 1]; $num[$n - $i - 1] = $num[$n - $smallest - 1]; $num[$n - $smallest - 1] = $t; // reverse digits in the // range (i+1) to mid reverse($num, $i + 1, $mid); // if n is even, then // reverse digits in the // range mid+1 to n-i-2 if ($n % 2 == 0) reverse($num, $mid + 1, $n - $i - 2); // else if n is odd, then reverse // digits in the range mid+2 // to n-i-2 else reverse($num, $mid + 2, $n - $i - 2); // required next higher // palindromic number echo \"Next Palindrome: \" . $num;} // Driver Code$num = \"4697557964\";$n = strlen($num);nextPalin($num, $n); // This code is contributed by mits?>", "e": 40718, "s": 38331, "text": null }, { "code": "<script> // Javascript implementation to find next higher// palindromic number using the same set// of digitsclass NextHigherPalindrome // Function to reverse the digits in the// range i to j in 'num'function reverse(num , i, j){ while (i < j) { var temp = num[i]; num[i] = num[j]; num[j] = temp; i++; j--; }} // Function to find next higher palindromic// number using the same set of digitsfunction nextPalin(num, n){ // If length of number is less than '3' // then no higher palindromic number // can be formed if (n <= 3) { document.write(\"Not Possible\"); return; } var temp; // Find the index of last digit // in the 1st half of 'num' var mid = n / 2 - 1; var i, j; // Start from the (mid-1)th digit and // find the first digit that is // smaller than the digit next to it. for(i = mid - 1; i >= 0; i--) if (num[i] < num[i + 1]) break; // If no such digit is found, then all // digits are in descending order which // means there cannot be a greater // palindromic number with same set of // digits if (i < 0) { document.write(\"Not Possible\"); return; } // Find the smallest digit on right // side of ith digit which is greater // than num[i] up to index 'mid' var smallest = i + 1; for(j = i + 2; j <= mid; j++) if (num[j] > num[i] && num[j] <= num[smallest]) smallest = j; // Swap num[i] with num[smallest] temp = num[i]; num[i] = num[smallest]; num[smallest] = temp; // As the number is a palindrome, // the same swap of digits should // be performed in the 2nd half of // 'num' temp = num[n - i - 1]; num[n - i - 1] = num[n - smallest - 1]; num[n - smallest - 1] = temp; // Reverse digits in the range (i+1) // to mid reverse(num, i + 1, mid); // If n is even, then reverse // digits in the range mid+1 to // n-i-2 if (n % 2 == 0) reverse(num, mid + 1, n - i - 2); // Else if n is odd, then reverse // digits in the range mid+2 to n-i-2 else reverse(num, mid + 2, n - i - 2); // Required next higher palindromic // number var result = num.join(''); document.write(\"Next Palindrome: \"+ result);} // Driver Codevar str = \"4697557964\";var num = str.split('');var n = str.length; nextPalin(num,n); // This code is contributed by 29AjayKumar </script>", "e": 43210, "s": 40718, "text": null }, { "code": null, "e": 43219, "s": 43210, "text": "Output: " }, { "code": null, "e": 43247, "s": 43219, "text": "Next Palindrome: 4756996574" }, { "code": null, "e": 43269, "s": 43247, "text": "Time Complexity: O(n)" }, { "code": null, "e": 43691, "s": 43269, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 43704, "s": 43691, "text": "Mithun Kumar" }, { "code": null, "e": 43717, "s": 43704, "text": "Akanksha_Rai" }, { "code": null, "e": 43728, "s": 43717, "text": "shivam2608" }, { "code": null, "e": 43740, "s": 43728, "text": "29AjayKumar" }, { "code": null, "e": 43754, "s": 43740, "text": "number-digits" }, { "code": null, "e": 43762, "s": 43754, "text": "Numbers" }, { "code": null, "e": 43773, "s": 43762, "text": "palindrome" }, { "code": null, "e": 43786, "s": 43773, "text": "Mathematical" }, { "code": null, "e": 43794, "s": 43786, "text": "Strings" }, { "code": null, "e": 43802, "s": 43794, "text": "Strings" }, { "code": null, "e": 43815, "s": 43802, "text": "Mathematical" }, { "code": null, "e": 43823, "s": 43815, "text": "Numbers" }, { "code": null, "e": 43834, "s": 43823, "text": "palindrome" }, { "code": null, "e": 43932, "s": 43834, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43941, "s": 43932, "text": "Comments" }, { "code": null, "e": 43954, "s": 43941, "text": "Old Comments" }, { "code": null, "e": 43996, "s": 43954, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 44020, "s": 43996, "text": "Merge two sorted arrays" }, { "code": null, "e": 44063, "s": 44020, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 44077, "s": 44063, "text": "Prime Numbers" }, { "code": null, "e": 44126, "s": 44077, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 44151, "s": 44126, "text": "Reverse a string in Java" }, { "code": null, "e": 44197, "s": 44151, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 44231, "s": 44197, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 44288, "s": 44231, "text": "Python program to check if a string is palindrome or not" } ]
Removing display of row names from dataframe in R - GeeksforGeeks
16 May, 2021 The dataframe rows and columns are referenced using unique row and column names for the elements. The dataframe method has an attribute row.names that don’t make any modification to the existing structure of the dataframe, it just ignores the names assigned to rows. As a result, the first column consisting of row names is not displayed. By default, the logical value assigned to this attribute is TRUE. In this article, we are going to see how to not display DataFrame row names in R Programming Language. Method 1: Using row.names = FALSE. In case, the row names are not assigned explicitly, row numbers beginning with 1 are assigned as row names of the dataframe. The following R program illustrates the method where while displaying the row.names attribute is set to FALSE and hence, row names are not visible in the following output. R # declaring a dataframe in Rdata_frame = data.frame("Col_1" = c(1, 2, NA, 0), "Col_2" = c( NA, NA, 3, 8), "Col_3" = c("A", "V", "j", "y")) print("Original dataframe")print(data_frame) # printing modified dataframeprint("Modified dataframe") # without displaying rownamesprint(data_frame,row.names=FALSE) Output: [1] "Original dataframe" Col_1 Col_2 Col_3 1 1 NA A 2 2 NA V 3 NA 3 j 4 0 8 y [1] "Modified dataframe" Col_1 Col_2 Col_3 1 NA A 2 NA V NA 3 j 0 8 y Using row.names(df) we can assign a string variable object as each row name of the dataframe. The length of the character vector should be equivalent to the length of the dataframe. In this case, the default row numbers are overwritten by the row names assigned. R # declaring a dataframe in Rdata_frame = data.frame("Col_1" = c(1, 2, NA, 0), "Col_2" = c( NA, NA, 3, 8), "Col_3" = c("A", "V", "j", "y")) # assigning row names to dataframerow.names(data_frame) <- c("ROW1", "ROW2", "ROW3", "ROW4")print("Original dataframe")print(data_frame) # printing modified dataframeprint("Modified dataframe") # without displaying rownamesprint(data_frame, row.names = FALSE) Output: [1] "Original dataframe" Col_1 Col_2 Col_3 ROW1 1 NA A ROW2 2 NA V ROW3 NA 3 j ROW4 0 8 y [1] "Modified dataframe" Col_1 Col_2 Col_3 1 NA A 2 NA V NA 3 j 0 8 y Method 2: Assigning row names to NULL In case, we wish to delete the row names of the dataframe, then we can assign them to NULL using the rownames() method over the dataframe. However, this will lead to the modification in the entire dataframe. In case, the row names are explicitly assigned to the rows, then using rownames(df) to NULL, deletes the row names and uses row numbers to access the rows. In this case, initially the row names are used to reference to rows, but as soon as the rownames(df) is assigned to null, any references to the row names is removed. R # declaring a dataframe in Rdata_frame = data.frame("Col_1" = c(1, 2, NA, 0), "Col_2" = c( NA, NA, 3, 8), "Col_3" = c("A", "V", "j", "y")) # assigning row names to dataframerow.names(data_frame) <- c("ROW1","ROW2","ROW3","ROW4")print("Original dataframe")print(data_frame) # assigning the rownames to nullrownames(data_frame) <- NULL # printing modified dataframeprint("Modified dataframe") # without displaying rownamesprint(data_frame) Output: [1] "Original dataframe" Col_1 Col_2 Col_3 ROW1 1 NA A ROW2 2 NA V ROW3 NA 3 j ROW4 0 8 y [1] "Modified dataframe" Col_1 Col_2 Col_3 1 1 NA A 2 2 NA V 3 NA 3 j 4 0 8 y Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n16 May, 2021" }, { "code": null, "e": 25750, "s": 25242, "text": "The dataframe rows and columns are referenced using unique row and column names for the elements. The dataframe method has an attribute row.names that don’t make any modification to the existing structure of the dataframe, it just ignores the names assigned to rows. As a result, the first column consisting of row names is not displayed. By default, the logical value assigned to this attribute is TRUE. In this article, we are going to see how to not display DataFrame row names in R Programming Language." }, { "code": null, "e": 25785, "s": 25750, "text": "Method 1: Using row.names = FALSE." }, { "code": null, "e": 26083, "s": 25785, "text": "In case, the row names are not assigned explicitly, row numbers beginning with 1 are assigned as row names of the dataframe. The following R program illustrates the method where while displaying the row.names attribute is set to FALSE and hence, row names are not visible in the following output. " }, { "code": null, "e": 26085, "s": 26083, "text": "R" }, { "code": "# declaring a dataframe in Rdata_frame = data.frame(\"Col_1\" = c(1, 2, NA, 0), \"Col_2\" = c( NA, NA, 3, 8), \"Col_3\" = c(\"A\", \"V\", \"j\", \"y\")) print(\"Original dataframe\")print(data_frame) # printing modified dataframeprint(\"Modified dataframe\") # without displaying rownamesprint(data_frame,row.names=FALSE)", "e": 26438, "s": 26085, "text": null }, { "code": null, "e": 26446, "s": 26438, "text": "Output:" }, { "code": null, "e": 26686, "s": 26446, "text": "[1] \"Original dataframe\"\n Col_1 Col_2 Col_3\n1 1 NA A\n2 2 NA V\n3 NA 3 j\n4 0 8 y\n[1] \"Modified dataframe\"\nCol_1 Col_2 Col_3\n 1 NA A\n 2 NA V\n NA 3 j\n 0 8 y" }, { "code": null, "e": 26950, "s": 26686, "text": "Using row.names(df) we can assign a string variable object as each row name of the dataframe. The length of the character vector should be equivalent to the length of the dataframe. In this case, the default row numbers are overwritten by the row names assigned. " }, { "code": null, "e": 26952, "s": 26950, "text": "R" }, { "code": "# declaring a dataframe in Rdata_frame = data.frame(\"Col_1\" = c(1, 2, NA, 0), \"Col_2\" = c( NA, NA, 3, 8), \"Col_3\" = c(\"A\", \"V\", \"j\", \"y\")) # assigning row names to dataframerow.names(data_frame) <- c(\"ROW1\", \"ROW2\", \"ROW3\", \"ROW4\")print(\"Original dataframe\")print(data_frame) # printing modified dataframeprint(\"Modified dataframe\") # without displaying rownamesprint(data_frame, row.names = FALSE)", "e": 27401, "s": 26952, "text": null }, { "code": null, "e": 27409, "s": 27401, "text": "Output:" }, { "code": null, "e": 27663, "s": 27409, "text": "[1] \"Original dataframe\"\n Col_1 Col_2 Col_3\nROW1 1 NA A\nROW2 2 NA V\nROW3 NA 3 j\nROW4 0 8 y\n[1] \"Modified dataframe\"\nCol_1 Col_2 Col_3\n 1 NA A\n 2 NA V\n NA 3 j\n 0 8 y" }, { "code": null, "e": 27701, "s": 27663, "text": "Method 2: Assigning row names to NULL" }, { "code": null, "e": 28232, "s": 27701, "text": "In case, we wish to delete the row names of the dataframe, then we can assign them to NULL using the rownames() method over the dataframe. However, this will lead to the modification in the entire dataframe. In case, the row names are explicitly assigned to the rows, then using rownames(df) to NULL, deletes the row names and uses row numbers to access the rows. In this case, initially the row names are used to reference to rows, but as soon as the rownames(df) is assigned to null, any references to the row names is removed. " }, { "code": null, "e": 28234, "s": 28232, "text": "R" }, { "code": "# declaring a dataframe in Rdata_frame = data.frame(\"Col_1\" = c(1, 2, NA, 0), \"Col_2\" = c( NA, NA, 3, 8), \"Col_3\" = c(\"A\", \"V\", \"j\", \"y\")) # assigning row names to dataframerow.names(data_frame) <- c(\"ROW1\",\"ROW2\",\"ROW3\",\"ROW4\")print(\"Original dataframe\")print(data_frame) # assigning the rownames to nullrownames(data_frame) <- NULL # printing modified dataframeprint(\"Modified dataframe\") # without displaying rownamesprint(data_frame)", "e": 28723, "s": 28234, "text": null }, { "code": null, "e": 28731, "s": 28723, "text": "Output:" }, { "code": null, "e": 28998, "s": 28731, "text": "[1] \"Original dataframe\"\n Col_1 Col_2 Col_3\nROW1 1 NA A\nROW2 2 NA V\nROW3 NA 3 j\nROW4 0 8 y\n[1] \"Modified dataframe\"\n Col_1 Col_2 Col_3\n1 1 NA A\n2 2 NA V\n3 NA 3 j\n4 0 8 y" }, { "code": null, "e": 29005, "s": 28998, "text": "Picked" }, { "code": null, "e": 29026, "s": 29005, "text": "R DataFrame-Programs" }, { "code": null, "e": 29038, "s": 29026, "text": "R-DataFrame" }, { "code": null, "e": 29049, "s": 29038, "text": "R Language" }, { "code": null, "e": 29060, "s": 29049, "text": "R Programs" }, { "code": null, "e": 29158, "s": 29060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29167, "s": 29158, "text": "Comments" }, { "code": null, "e": 29180, "s": 29167, "text": "Old Comments" }, { "code": null, "e": 29232, "s": 29180, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29270, "s": 29232, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29305, "s": 29270, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29363, "s": 29305, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29412, "s": 29363, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29470, "s": 29412, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29519, "s": 29470, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29569, "s": 29519, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29612, "s": 29569, "text": "Replace Specific Characters in String in R" } ]
The Complete Guide of SQL For Data Scientists | by Jun Wu | Towards Data Science
SQL used to rule in the land of Enterprise Data. Before the NoSQL movement, SQL was the main query language used to retrieve data from relational databases. According to a survey done by High Scalability asking IT leaders at DeveloperWeek about the trend for database usage in 2019, SQL is still used more than 60% of the time. Multiple database strategy (SQL+NoSQL) is used more than 75% of the time. This is no surprise. Different types of databases are used for different purposes. (If you are interested, you can read more about that here.) Out of all the relational databases, MySQL remains the most popular database for organizations. To aspiring Data Scientists who have aced machine learning algorithms, participated in Kaggle competitions, and manipulated data heavily using Pandas, walking into an interview with questions about SQL may come as a shock. But, it happens. You want to be prepared. In the real world, relational databases are used heavily to house all types of Enterprise data. Data is stored for easy retrieval from all types of data sources. Knowing SQL can lead to easy data retrieval and manipulation. Before the whole Data Science “hype”, Data Science was done by Statisticians in large organizations. Data Mining was the intersection of statistics and computer science that these Statisticians operated in. Data mining is simply the process that uses Machine Learning and Statistics to discover patterns in large sets of data. Data Mining eliminates the need to transfer data or merge data before analysis. Analysis can be done across many data stores on the fly. For Data Mining, in Enterprise Technology, large datasets are often processed using SAS. SAS enables Data Scientists to easily perform statistical analysis on a large amount of data without having to write too much code. Built-in functions in SAS are powerful for all types of data analysis. SQL can easily be wrapped up to run in SAS. The syntax of SAS commands are also similar to SQL. DataMiner from Oracle is also another popular Database Mining software that’s used in Enterprise Technology for Data Science. It contains a host of data analysis algorithms such as classification, prediction, regression, association, feature extraction, etc.. that can be performed on large sets of data housed in relational databases. Before we dive into SQL, there are a few relational database (RDBMS) concepts that will set the background for you. The database schema refers to the organization of data. It is a blueprint of how the database is constructed. In RDBMS, the database model is implemented by the schema. It is the Entity-relationship model. Here’s a good blog post describing this relationship. One of the main units of the schema is the table. In RDBMS, tables are laid out and associated with each other in different types of relationships (one to one, one to many, many to many) relationships. The vertical partitions of tables are called columns. In RDBMS, a column is often also called an attribute. The horizontal partitions of tables are called rows. In RDBMS, a row is often also called a tuple. In RDBMS, the index is a data structure that improves the operation of the table by quickly locating the data. Depending on the type of index, by creating an index, you can create copies of the data ordered in a certain way located on the server for easier retrieval. Sometimes, instead of copies of the data, the data can be ordered in a particular way by the index when it’s created for optimized retrieval. There are two main types of indexes: Non-clustered and clustered. Non-clustered index is when data is stored in an arbitrary order but the logical order is specified by the index. Clustered index is when the data block where data is stored is altered to match a distinct order by the index. Here’s a blog post describing the difference between a Non-clustered index and a Clustered index. SQL is the Structured Query Language for RDBMS databases. When you retrieve data, you typically use SQL statements to retrieve the data. You can join tables together to select out just the right types of data from different purposes using SQL statements. Rather than executing your SQL statements on the fly, you may want to create a set of programs called “stored procedures”. You can pass arguments to them just like you would for a function. A query plan is an ordered set of steps to access the data. The query plan is determined by the query optimizer located inside the database. Your SQL statements and stored procedure merely state your intentions of how you want to retrieve the data. The query plan specified by the query optimizer shows the exact steps sequentially of how your SQL statements are executed by the database. Analyzing the query plan is one way to optimize and tune your stored procedures and SQL statements. Constraints enforce data integrity inside an RDBMS database. You can configure constraints to enforce limits on the data and type of data. Constraints can be set either at the column level or at the table level. A few different types of constraints could be: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, INDEX. Primary Key — It is the constraint that uniquely identifies each record in the table. It is usually the unique record id. Foreign Key — It is the constraint that allows a parent-child relationship to be established in a table. Usually, the table with the foreign key is the child table while the table without the foreign is the parent table. Here’s a good blog post describing the relationship of Foreign keys and Primary keys in the MySQL database. Normalization is the process of efficiently organizing the data in your RDBMS database. The idea is to eliminate redundant data. For instance, if you have a table of ClientInfo, your client has three different addresses, to normalize the data, you want to store the client information in a table called ClientInfo indexed by a ClientId. Then, you want to store the three different addresses in a ClientAddress table with the ClientId. After that, you can relate the two tables together by the ClientId. By ensuring “unique” data in each table, you can saving storage space and optimize for performance. (That is the idea, anyway.) Setting up the MySQL database is very easy. You simply download the executable to your Mac or PC and run it to install the executable. Then, you connect to the server using the MySQL client. Here are the instructions that you can follow. The following query creates the table with a primary key. CREATE TABLE ClientInfo ( ClientId INT NOT NULL ClientName VARCHAR(255) PRIMARY KEY (ClientId)); The following query retrieves data from one table. SELECT * FROM ClientInfo The following query retrieves data from two tables by inner join: The output will be all the records that represent the overlap of both ClientInfo and ClientAddress table. SELECT * from ClientInfoINNER JOIN ClientAddressONClientInfo.ClientId = ClientAddress.ClientId The following query retrieves data from two tables by implicit “inner” join notation: The output will be the same as the output from before. SELECT * from ClientInfo, ClientAddressWHEREClientInfo.ClientId = ClientAddress.ClientId The following query retrieves data from two tables by outer join: The output will be all the records of ClientInfo + the overlap of ClientInfo and ClientAddress table. SELECT * from ClientInfoLEFT OUTER JOIN ClientAddressONClientInfo.ClientId = ClientAddress.ClientId The following query creates a unique index on a table: CREATE UNIQUE INDEX ClientId ON ClientInfo(ClientId) Now that you have an idea of how to interact with the MySQL tables and retrieve information from the tables, here are the next steps. Create a simple project working with the data in your database. The easiest way is to load a set of “dirty data” into the database. Then, go through data cleaning steps using SQL instead of using pandas.After that you can delve a little deeper into the following references: Create a simple project working with the data in your database. The easiest way is to load a set of “dirty data” into the database. Then, go through data cleaning steps using SQL instead of using pandas. After that you can delve a little deeper into the following references: Different types of SQL joins Commonly used SQL functions Different types of SQL indexes Different types of SQL datatypes SQL Query Performance and Tuning Now that you have studied the basic concepts, worked through your first project and checked out some references, it’s time to test your knowledge with these interview questions. www.interviewbit.com www.softwaretestinghelp.com About the Author Jun Wu is a Content Writer for Technology, AI, Data Science, Psychology, and Parenting. She has a background in programming and statistics. On her spare time, she writes poetry and blogs on her website. Subscribe to my weekly newsletter to stay connected
[ { "code": null, "e": 717, "s": 172, "text": "SQL used to rule in the land of Enterprise Data. Before the NoSQL movement, SQL was the main query language used to retrieve data from relational databases. According to a survey done by High Scalability asking IT leaders at DeveloperWeek about the trend for database usage in 2019, SQL is still used more than 60% of the time. Multiple database strategy (SQL+NoSQL) is used more than 75% of the time. This is no surprise. Different types of databases are used for different purposes. (If you are interested, you can read more about that here.)" }, { "code": null, "e": 813, "s": 717, "text": "Out of all the relational databases, MySQL remains the most popular database for organizations." }, { "code": null, "e": 1078, "s": 813, "text": "To aspiring Data Scientists who have aced machine learning algorithms, participated in Kaggle competitions, and manipulated data heavily using Pandas, walking into an interview with questions about SQL may come as a shock. But, it happens. You want to be prepared." }, { "code": null, "e": 1629, "s": 1078, "text": "In the real world, relational databases are used heavily to house all types of Enterprise data. Data is stored for easy retrieval from all types of data sources. Knowing SQL can lead to easy data retrieval and manipulation. Before the whole Data Science “hype”, Data Science was done by Statisticians in large organizations. Data Mining was the intersection of statistics and computer science that these Statisticians operated in. Data mining is simply the process that uses Machine Learning and Statistics to discover patterns in large sets of data." }, { "code": null, "e": 1766, "s": 1629, "text": "Data Mining eliminates the need to transfer data or merge data before analysis. Analysis can be done across many data stores on the fly." }, { "code": null, "e": 2154, "s": 1766, "text": "For Data Mining, in Enterprise Technology, large datasets are often processed using SAS. SAS enables Data Scientists to easily perform statistical analysis on a large amount of data without having to write too much code. Built-in functions in SAS are powerful for all types of data analysis. SQL can easily be wrapped up to run in SAS. The syntax of SAS commands are also similar to SQL." }, { "code": null, "e": 2490, "s": 2154, "text": "DataMiner from Oracle is also another popular Database Mining software that’s used in Enterprise Technology for Data Science. It contains a host of data analysis algorithms such as classification, prediction, regression, association, feature extraction, etc.. that can be performed on large sets of data housed in relational databases." }, { "code": null, "e": 2606, "s": 2490, "text": "Before we dive into SQL, there are a few relational database (RDBMS) concepts that will set the background for you." }, { "code": null, "e": 2812, "s": 2606, "text": "The database schema refers to the organization of data. It is a blueprint of how the database is constructed. In RDBMS, the database model is implemented by the schema. It is the Entity-relationship model." }, { "code": null, "e": 2866, "s": 2812, "text": "Here’s a good blog post describing this relationship." }, { "code": null, "e": 3068, "s": 2866, "text": "One of the main units of the schema is the table. In RDBMS, tables are laid out and associated with each other in different types of relationships (one to one, one to many, many to many) relationships." }, { "code": null, "e": 3176, "s": 3068, "text": "The vertical partitions of tables are called columns. In RDBMS, a column is often also called an attribute." }, { "code": null, "e": 3275, "s": 3176, "text": "The horizontal partitions of tables are called rows. In RDBMS, a row is often also called a tuple." }, { "code": null, "e": 3685, "s": 3275, "text": "In RDBMS, the index is a data structure that improves the operation of the table by quickly locating the data. Depending on the type of index, by creating an index, you can create copies of the data ordered in a certain way located on the server for easier retrieval. Sometimes, instead of copies of the data, the data can be ordered in a particular way by the index when it’s created for optimized retrieval." }, { "code": null, "e": 3751, "s": 3685, "text": "There are two main types of indexes: Non-clustered and clustered." }, { "code": null, "e": 3865, "s": 3751, "text": "Non-clustered index is when data is stored in an arbitrary order but the logical order is specified by the index." }, { "code": null, "e": 3976, "s": 3865, "text": "Clustered index is when the data block where data is stored is altered to match a distinct order by the index." }, { "code": null, "e": 4074, "s": 3976, "text": "Here’s a blog post describing the difference between a Non-clustered index and a Clustered index." }, { "code": null, "e": 4329, "s": 4074, "text": "SQL is the Structured Query Language for RDBMS databases. When you retrieve data, you typically use SQL statements to retrieve the data. You can join tables together to select out just the right types of data from different purposes using SQL statements." }, { "code": null, "e": 4519, "s": 4329, "text": "Rather than executing your SQL statements on the fly, you may want to create a set of programs called “stored procedures”. You can pass arguments to them just like you would for a function." }, { "code": null, "e": 5008, "s": 4519, "text": "A query plan is an ordered set of steps to access the data. The query plan is determined by the query optimizer located inside the database. Your SQL statements and stored procedure merely state your intentions of how you want to retrieve the data. The query plan specified by the query optimizer shows the exact steps sequentially of how your SQL statements are executed by the database. Analyzing the query plan is one way to optimize and tune your stored procedures and SQL statements." }, { "code": null, "e": 5325, "s": 5008, "text": "Constraints enforce data integrity inside an RDBMS database. You can configure constraints to enforce limits on the data and type of data. Constraints can be set either at the column level or at the table level. A few different types of constraints could be: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, INDEX." }, { "code": null, "e": 5447, "s": 5325, "text": "Primary Key — It is the constraint that uniquely identifies each record in the table. It is usually the unique record id." }, { "code": null, "e": 5668, "s": 5447, "text": "Foreign Key — It is the constraint that allows a parent-child relationship to be established in a table. Usually, the table with the foreign key is the child table while the table without the foreign is the parent table." }, { "code": null, "e": 5776, "s": 5668, "text": "Here’s a good blog post describing the relationship of Foreign keys and Primary keys in the MySQL database." }, { "code": null, "e": 6407, "s": 5776, "text": "Normalization is the process of efficiently organizing the data in your RDBMS database. The idea is to eliminate redundant data. For instance, if you have a table of ClientInfo, your client has three different addresses, to normalize the data, you want to store the client information in a table called ClientInfo indexed by a ClientId. Then, you want to store the three different addresses in a ClientAddress table with the ClientId. After that, you can relate the two tables together by the ClientId. By ensuring “unique” data in each table, you can saving storage space and optimize for performance. (That is the idea, anyway.)" }, { "code": null, "e": 6542, "s": 6407, "text": "Setting up the MySQL database is very easy. You simply download the executable to your Mac or PC and run it to install the executable." }, { "code": null, "e": 6598, "s": 6542, "text": "Then, you connect to the server using the MySQL client." }, { "code": null, "e": 6645, "s": 6598, "text": "Here are the instructions that you can follow." }, { "code": null, "e": 6703, "s": 6645, "text": "The following query creates the table with a primary key." }, { "code": null, "e": 6803, "s": 6703, "text": "CREATE TABLE ClientInfo ( ClientId INT NOT NULL ClientName VARCHAR(255) PRIMARY KEY (ClientId));" }, { "code": null, "e": 6854, "s": 6803, "text": "The following query retrieves data from one table." }, { "code": null, "e": 6879, "s": 6854, "text": "SELECT * FROM ClientInfo" }, { "code": null, "e": 6945, "s": 6879, "text": "The following query retrieves data from two tables by inner join:" }, { "code": null, "e": 7051, "s": 6945, "text": "The output will be all the records that represent the overlap of both ClientInfo and ClientAddress table." }, { "code": null, "e": 7146, "s": 7051, "text": "SELECT * from ClientInfoINNER JOIN ClientAddressONClientInfo.ClientId = ClientAddress.ClientId" }, { "code": null, "e": 7232, "s": 7146, "text": "The following query retrieves data from two tables by implicit “inner” join notation:" }, { "code": null, "e": 7287, "s": 7232, "text": "The output will be the same as the output from before." }, { "code": null, "e": 7376, "s": 7287, "text": "SELECT * from ClientInfo, ClientAddressWHEREClientInfo.ClientId = ClientAddress.ClientId" }, { "code": null, "e": 7442, "s": 7376, "text": "The following query retrieves data from two tables by outer join:" }, { "code": null, "e": 7544, "s": 7442, "text": "The output will be all the records of ClientInfo + the overlap of ClientInfo and ClientAddress table." }, { "code": null, "e": 7644, "s": 7544, "text": "SELECT * from ClientInfoLEFT OUTER JOIN ClientAddressONClientInfo.ClientId = ClientAddress.ClientId" }, { "code": null, "e": 7699, "s": 7644, "text": "The following query creates a unique index on a table:" }, { "code": null, "e": 7752, "s": 7699, "text": "CREATE UNIQUE INDEX ClientId ON ClientInfo(ClientId)" }, { "code": null, "e": 7886, "s": 7752, "text": "Now that you have an idea of how to interact with the MySQL tables and retrieve information from the tables, here are the next steps." }, { "code": null, "e": 8161, "s": 7886, "text": "Create a simple project working with the data in your database. The easiest way is to load a set of “dirty data” into the database. Then, go through data cleaning steps using SQL instead of using pandas.After that you can delve a little deeper into the following references:" }, { "code": null, "e": 8365, "s": 8161, "text": "Create a simple project working with the data in your database. The easiest way is to load a set of “dirty data” into the database. Then, go through data cleaning steps using SQL instead of using pandas." }, { "code": null, "e": 8437, "s": 8365, "text": "After that you can delve a little deeper into the following references:" }, { "code": null, "e": 8466, "s": 8437, "text": "Different types of SQL joins" }, { "code": null, "e": 8494, "s": 8466, "text": "Commonly used SQL functions" }, { "code": null, "e": 8525, "s": 8494, "text": "Different types of SQL indexes" }, { "code": null, "e": 8558, "s": 8525, "text": "Different types of SQL datatypes" }, { "code": null, "e": 8591, "s": 8558, "text": "SQL Query Performance and Tuning" }, { "code": null, "e": 8769, "s": 8591, "text": "Now that you have studied the basic concepts, worked through your first project and checked out some references, it’s time to test your knowledge with these interview questions." }, { "code": null, "e": 8790, "s": 8769, "text": "www.interviewbit.com" }, { "code": null, "e": 8818, "s": 8790, "text": "www.softwaretestinghelp.com" }, { "code": null, "e": 8835, "s": 8818, "text": "About the Author" }, { "code": null, "e": 9038, "s": 8835, "text": "Jun Wu is a Content Writer for Technology, AI, Data Science, Psychology, and Parenting. She has a background in programming and statistics. On her spare time, she writes poetry and blogs on her website." } ]
How to find the first 10 characters of a string in C#?
To get the first 10 characters, use the substring() method. Let’s say the following is our string − string str = "Cricket is a religion in India!"; Now to get the first 10 characters, set the value 10 in the substring() method as shown below − string res = str.Substring(0, 10); Let us see the complete code. Live Demo using System; public class Demo { public static void Main() { string str = "Cricket is a religion in India!"; string res = str.Substring(0, 10); Console.WriteLine(res); } } Cricket is
[ { "code": null, "e": 1122, "s": 1062, "text": "To get the first 10 characters, use the substring() method." }, { "code": null, "e": 1162, "s": 1122, "text": "Let’s say the following is our string −" }, { "code": null, "e": 1210, "s": 1162, "text": "string str = \"Cricket is a religion in India!\";" }, { "code": null, "e": 1306, "s": 1210, "text": "Now to get the first 10 characters, set the value 10 in the substring() method as shown below −" }, { "code": null, "e": 1341, "s": 1306, "text": "string res = str.Substring(0, 10);" }, { "code": null, "e": 1371, "s": 1341, "text": "Let us see the complete code." }, { "code": null, "e": 1382, "s": 1371, "text": " Live Demo" }, { "code": null, "e": 1579, "s": 1382, "text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"Cricket is a religion in India!\";\n string res = str.Substring(0, 10);\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1590, "s": 1579, "text": "Cricket is" } ]
How to customize spines of Matplotlib figures?
When we plot a figure in Matplotlib, it creates four spines around the figure, top, left, bottom and right. Spines are nothing but a box surrounded with the pictorial representation of the grid which displays some ticks and tickable axes on left(y) and bottom(x). Let us see how to customize the spines in a given figure. We will create six figures to see and customize the spines for it. First import the required libraries for the workbook. import numpy as np import matplotlib.pyplot as plt Let us draw graph for sines, theta = np.linspace(0, 2*np.pi, 128) y = np.sin(theta) fig = plt.figure(figsize=(8,6)) Define the axes with default spines, ax1 = fig.add_subplot(2, 3, 1) ax1.plot(theta, np.sin(theta), 'b-*') ax1.set_title('default spines') Define the function to plot the graph, def plot_graph(axs, title, lposition, bposition): ax = fig.add_subplot(axs) ax.plot(theta, y, 'b-*') ax.set_title(title) ax.spines['left'].set_position(lposition) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_position(bposition) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') Let us plot 3 graphs. plot_graph(232, 'centered spines', 'center', 'center') plot_graph(233, 'zeroed spines', 'zero', 'zero') plot_graph(234, 'spines at axes [0.25, 0.75]', ('axes', 0.25),('axes', 0.75)) plot_graph(235, 'spines at data [1.0, -1.0]', ('data', 1.0),('data', -1.0)) plot_graph(236, 'adjusted spines', ('outward', 10), ('outward', 10)) Let us fit the plot in the grid and show. plt.tight_layout() plt.show()
[ { "code": null, "e": 1326, "s": 1062, "text": "When we plot a figure in Matplotlib, it creates four spines around the figure, top, left, bottom and right. Spines are nothing but a box surrounded with the pictorial representation of the grid which displays some ticks and tickable axes on left(y) and bottom(x)." }, { "code": null, "e": 1451, "s": 1326, "text": "Let us see how to customize the spines in a given figure. We will create six figures to see and customize the spines for it." }, { "code": null, "e": 1505, "s": 1451, "text": "First import the required libraries for the workbook." }, { "code": null, "e": 1556, "s": 1505, "text": "import numpy as np\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 1585, "s": 1556, "text": "Let us draw graph for sines," }, { "code": null, "e": 1672, "s": 1585, "text": "theta = np.linspace(0, 2*np.pi, 128)\ny = np.sin(theta)\nfig = plt.figure(figsize=(8,6))" }, { "code": null, "e": 1709, "s": 1672, "text": "Define the axes with default spines," }, { "code": null, "e": 1810, "s": 1709, "text": "ax1 = fig.add_subplot(2, 3, 1)\nax1.plot(theta, np.sin(theta), 'b-*')\nax1.set_title('default spines')" }, { "code": null, "e": 1849, "s": 1810, "text": "Define the function to plot the graph," }, { "code": null, "e": 2231, "s": 1849, "text": "def plot_graph(axs, title, lposition, bposition):\n ax = fig.add_subplot(axs)\n ax.plot(theta, y, 'b-*')\n ax.set_title(title)\n ax.spines['left'].set_position(lposition)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_position(bposition)\n ax.spines['top'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')" }, { "code": null, "e": 2253, "s": 2231, "text": "Let us plot 3 graphs." }, { "code": null, "e": 2580, "s": 2253, "text": "plot_graph(232, 'centered spines', 'center', 'center')\nplot_graph(233, 'zeroed spines', 'zero', 'zero')\nplot_graph(234, 'spines at axes [0.25, 0.75]', ('axes', 0.25),('axes', 0.75))\nplot_graph(235, 'spines at data [1.0, -1.0]', ('data', 1.0),('data', -1.0))\nplot_graph(236, 'adjusted spines', ('outward', 10), ('outward', 10))" }, { "code": null, "e": 2622, "s": 2580, "text": "Let us fit the plot in the grid and show." }, { "code": null, "e": 2652, "s": 2622, "text": "plt.tight_layout()\nplt.show()" } ]
Understanding A* Path Algorithms and Implementation with Python | by Adem Akdogan | Towards Data Science
The A* algorithm is one of the most effective path finding algorithms used to find the shortest path between two points. It was first published in 1968 by Peter Hart, Nils Nilsson and Bertram Raphael [1]. Although it initially can be seen as an extension of Dijkstra’s algorithm, it has become one of the most frequently used pathfinding algorithms today. The A* algorithm basically reaches the optimum result by calculating the positions of all the other nodes between the starting node and the ending node. In addition, it is faster than Dijkstra’s algorithm due to the heuristic function[2]. f(n) = g(n) + h(n) f(n) : Calculated total cost of path g(n): The cost of path between the first node and the current node h(n): Heuristic function If we want to find the shortest path on Figure 2 using the above function; Let’s say we are trying to get from point X to point Y. Since the point X is not moved to a different node, the g(n) cost does not occur and its value is 0. The heuristic value of this point is the value 5 written on the node in red. In such problems, the heuristic value in general is the air distance between the current node and the desired node. There are two points to go from point X. In case of going to point A, g(n) = 5 (path cost) because it moves to a new node. The heuristic is set to h(n) = 1. The f(n) value of point A is found as 5+1 = 6. If we want to find the f(n) values ​​of all points using this method, X— A => g(A) + f(A) = 5 + 1 = 6, A — Y=> g(Y) + f(Y) = 6+ 0= 6, X— B => g(B) + f(B) = 1+ 4= 5, B — C => g(C) + f(C) = 3+ 2= 5, C — Y=> g(Y) + f(Y) = 5 + 0= 5, As seen in the simple example above, the shortest path is the X-B-C-Y route. The cost of this road is 5 units, while the cost of the alternative X-A-Y route is 6 units. The example in Figure 3 can be examined in more detail once we have fully understood how to use the above equation. Let’s say we want to reach node A from node J. There are 2 points (B and F), that can be reached from point A. Calculating the overhead costs, we get f(B) = 8 + 6 = 14 and f(F) = 3+6 =9.Since the least cost is at point F, the A* algorithm continues from here. There are 2 paths at point F. f(G) = 4 +5 = 9 and f(H) = 10 + 3 = 13. Since the least cost is at point G, we can do it from that point. Then, following the I and J nodes, we get f(I) = 7 + 1 = 8 , f(J) = 10. Since all the values ​​obtained after going to the F node are less than the f(B) node, it was not returned to the B node. But in a different scenario, let’s assume that f(I) is greater than f(B) after nodes F and G (f(I) > 14). In this case, according to the A* algorithm, the process is interrupted here and the path is continued with the B node. Here, as soon as f(C) > f(I), the path determination process continues again from the I node. All of the codes below are available at https://github.com/ademakdogan/Implementation-of-A-Algorithm-Visualization-via-Pyp5js- First, the grid structure is created. Some nodes here are marked as obstacles. Then the start and end nodes are determined and the shortest path between these two points is found with the A* algorithm [3]. The working logic of the algorithm is basically based on two lists named open_set and closed_set. While there are nodes that can be processed in open_set, there are node paths that are processed in closed_set and therefore should not be repeated (In some approaches, obstacles are also thrown directly into the closed_set list, while in some approaches, it can be added as one of the qualifying properties of each node produced as an object.). As a result of various processes, these lists are filled and emptied, and the final result is reached. Pseudocodes of all stages can be viewed on wikipedia. Figure 4 shows the python implementation of the A* algorithm. Pyp5js library was used to visualize in this work. In addition, the A* algorithm can work according to the obstacle list to be given specifically, the coordinates of the start and end nodes and the size of the grid structure. Thus, this project can also be used against specific problems. python AStar.py -c 25 -r 25 -s 1 -q 3 -e 23 -t 21 -l True As a result, The way found!!!23 2023 1923 1823 1723 1623 1523 1423 1323 1223 1123 1023 923 823 723 623 523 423 322 321 320 319 318 317 316 315 314 313 312 311 310 39 38 37 36 35 34 33 32 31 3 Pyp5js is a framework for visualizing python codes on the browser. It enables the use of p5.js javascript library via Transcrypt with Python. After the necessary installations are made, it is simply run with the following command. $ SKETCHBOOK_DIR='~/my-custom-sketchbook' pyp5js serve Afterwards, the necessary config settings are made by accessing the interface section via http://localhost:5000/ . In the specified folder (SKETCHBOOK_DIR), operations are performed according to the codes in the python file that is the same name as the project name. If you want to examine this project in detail, https://berinhard.github.io/pyp5js/ can be visited. As a result, the A* algorithm is one of the most frequently used path finding algorithms. In this article, the working principles of this algorithm and its coding with python are discussed. All codes can be found at github. The pyp5js library was used to visualize the algorithm. In the next articles, comparisons of different path determination algorithms with the A* algorithm will be discussed. Github : https://github.com/ademakdogan Linkedin : https://www.linkedin.com/in/adem-akdo%C4%9Fan-948334177/ [1] Hart, P. E.; Nilsson, N. J.; Raphael, B. (1968). “A Formal Basis for the Heuristic Determination of Minimum Cost Paths”. IEEE Transactions on Systems Science and Cybernetics. 4 (2): 100–107. [2] Zeng, W.; Church, R. L. (2009). “Finding shortest paths on real road networks: the case for A*”. International Journal of Geographical Information Science. 23 (4): 531–543. [3] Hetland, Magnus Lie (2010), Python Algorithms: Mastering Basic Algorithms in the Python Language, Apress, p. 214, ISBN 9781430232377.
[ { "code": null, "e": 528, "s": 172, "text": "The A* algorithm is one of the most effective path finding algorithms used to find the shortest path between two points. It was first published in 1968 by Peter Hart, Nils Nilsson and Bertram Raphael [1]. Although it initially can be seen as an extension of Dijkstra’s algorithm, it has become one of the most frequently used pathfinding algorithms today." }, { "code": null, "e": 767, "s": 528, "text": "The A* algorithm basically reaches the optimum result by calculating the positions of all the other nodes between the starting node and the ending node. In addition, it is faster than Dijkstra’s algorithm due to the heuristic function[2]." }, { "code": null, "e": 786, "s": 767, "text": "f(n) = g(n) + h(n)" }, { "code": null, "e": 823, "s": 786, "text": "f(n) : Calculated total cost of path" }, { "code": null, "e": 890, "s": 823, "text": "g(n): The cost of path between the first node and the current node" }, { "code": null, "e": 915, "s": 890, "text": "h(n): Heuristic function" }, { "code": null, "e": 990, "s": 915, "text": "If we want to find the shortest path on Figure 2 using the above function;" }, { "code": null, "e": 1614, "s": 990, "text": "Let’s say we are trying to get from point X to point Y. Since the point X is not moved to a different node, the g(n) cost does not occur and its value is 0. The heuristic value of this point is the value 5 written on the node in red. In such problems, the heuristic value in general is the air distance between the current node and the desired node. There are two points to go from point X. In case of going to point A, g(n) = 5 (path cost) because it moves to a new node. The heuristic is set to h(n) = 1. The f(n) value of point A is found as 5+1 = 6. If we want to find the f(n) values ​​of all points using this method," }, { "code": null, "e": 1647, "s": 1614, "text": "X— A => g(A) + f(A) = 5 + 1 = 6," }, { "code": null, "e": 1678, "s": 1647, "text": "A — Y=> g(Y) + f(Y) = 6+ 0= 6," }, { "code": null, "e": 1709, "s": 1678, "text": "X— B => g(B) + f(B) = 1+ 4= 5," }, { "code": null, "e": 1741, "s": 1709, "text": "B — C => g(C) + f(C) = 3+ 2= 5," }, { "code": null, "e": 1773, "s": 1741, "text": "C — Y=> g(Y) + f(Y) = 5 + 0= 5," }, { "code": null, "e": 2058, "s": 1773, "text": "As seen in the simple example above, the shortest path is the X-B-C-Y route. The cost of this road is 5 units, while the cost of the alternative X-A-Y route is 6 units. The example in Figure 3 can be examined in more detail once we have fully understood how to use the above equation." }, { "code": null, "e": 2968, "s": 2058, "text": "Let’s say we want to reach node A from node J. There are 2 points (B and F), that can be reached from point A. Calculating the overhead costs, we get f(B) = 8 + 6 = 14 and f(F) = 3+6 =9.Since the least cost is at point F, the A* algorithm continues from here. There are 2 paths at point F. f(G) = 4 +5 = 9 and f(H) = 10 + 3 = 13. Since the least cost is at point G, we can do it from that point. Then, following the I and J nodes, we get f(I) = 7 + 1 = 8 , f(J) = 10. Since all the values ​​obtained after going to the F node are less than the f(B) node, it was not returned to the B node. But in a different scenario, let’s assume that f(I) is greater than f(B) after nodes F and G (f(I) > 14). In this case, according to the A* algorithm, the process is interrupted here and the path is continued with the B node. Here, as soon as f(C) > f(I), the path determination process continues again from the I node." }, { "code": null, "e": 3095, "s": 2968, "text": "All of the codes below are available at https://github.com/ademakdogan/Implementation-of-A-Algorithm-Visualization-via-Pyp5js-" }, { "code": null, "e": 3848, "s": 3095, "text": "First, the grid structure is created. Some nodes here are marked as obstacles. Then the start and end nodes are determined and the shortest path between these two points is found with the A* algorithm [3]. The working logic of the algorithm is basically based on two lists named open_set and closed_set. While there are nodes that can be processed in open_set, there are node paths that are processed in closed_set and therefore should not be repeated (In some approaches, obstacles are also thrown directly into the closed_set list, while in some approaches, it can be added as one of the qualifying properties of each node produced as an object.). As a result of various processes, these lists are filled and emptied, and the final result is reached." }, { "code": null, "e": 3902, "s": 3848, "text": "Pseudocodes of all stages can be viewed on wikipedia." }, { "code": null, "e": 4253, "s": 3902, "text": "Figure 4 shows the python implementation of the A* algorithm. Pyp5js library was used to visualize in this work. In addition, the A* algorithm can work according to the obstacle list to be given specifically, the coordinates of the start and end nodes and the size of the grid structure. Thus, this project can also be used against specific problems." }, { "code": null, "e": 4311, "s": 4253, "text": "python AStar.py -c 25 -r 25 -s 1 -q 3 -e 23 -t 21 -l True" }, { "code": null, "e": 4324, "s": 4311, "text": "As a result," }, { "code": null, "e": 4503, "s": 4324, "text": "The way found!!!23 2023 1923 1823 1723 1623 1523 1423 1323 1223 1123 1023 923 823 723 623 523 423 322 321 320 319 318 317 316 315 314 313 312 311 310 39 38 37 36 35 34 33 32 31 3" }, { "code": null, "e": 4734, "s": 4503, "text": "Pyp5js is a framework for visualizing python codes on the browser. It enables the use of p5.js javascript library via Transcrypt with Python. After the necessary installations are made, it is simply run with the following command." }, { "code": null, "e": 4789, "s": 4734, "text": "$ SKETCHBOOK_DIR='~/my-custom-sketchbook' pyp5js serve" }, { "code": null, "e": 5155, "s": 4789, "text": "Afterwards, the necessary config settings are made by accessing the interface section via http://localhost:5000/ . In the specified folder (SKETCHBOOK_DIR), operations are performed according to the codes in the python file that is the same name as the project name. If you want to examine this project in detail, https://berinhard.github.io/pyp5js/ can be visited." }, { "code": null, "e": 5553, "s": 5155, "text": "As a result, the A* algorithm is one of the most frequently used path finding algorithms. In this article, the working principles of this algorithm and its coding with python are discussed. All codes can be found at github. The pyp5js library was used to visualize the algorithm. In the next articles, comparisons of different path determination algorithms with the A* algorithm will be discussed." }, { "code": null, "e": 5593, "s": 5553, "text": "Github : https://github.com/ademakdogan" }, { "code": null, "e": 5661, "s": 5593, "text": "Linkedin : https://www.linkedin.com/in/adem-akdo%C4%9Fan-948334177/" }, { "code": null, "e": 5856, "s": 5661, "text": "[1] Hart, P. E.; Nilsson, N. J.; Raphael, B. (1968). “A Formal Basis for the Heuristic Determination of Minimum Cost Paths”. IEEE Transactions on Systems Science and Cybernetics. 4 (2): 100–107." }, { "code": null, "e": 6033, "s": 5856, "text": "[2] Zeng, W.; Church, R. L. (2009). “Finding shortest paths on real road networks: the case for A*”. International Journal of Geographical Information Science. 23 (4): 531–543." } ]
How to update the _id of a MongoDB Document?
You cannot update it but you can save a new id and remove the old id. Follow some steps in order to update the _id of a MongoDB. The steps are as follows: Step1: In the first step, you need to store ObjectId into a variable. anyVariableName=db.yourCollectionName.findOne({_id:yourObjectIdValue)}); Step 2: In the second step, you need to set a new id. yourDeclaredVariableName._id=yourNewObjectIdValue; Step 3: In the third step, you need to insert new id on a document. db.yourCollectionName.insert(yourDeclaredVariableName); Step 4: In the fourth step, you need to remove the old id. db.yourCollectionName.remove({_id:yourOldObjectIdValue)}); To understand the above steps, let us create a collection with document. The query to create a collection with document is as follows: > db.updateIdDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ebfec6fd07954a4890683") } > db.updateIdDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ebff66fd07954a4890684") } > db.updateIdDemo.insertOne({"StudentName":"Maxwell"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ebfff6fd07954a4890685") } Display all documents from a collection with the help of find() method. The query is as follows: > db.updateIdDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" } { "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" } { "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" } The following is the query to update the _id of a MongoDB document: Step1: > myId=db.updateIdDemo.findOne({_id:ObjectId("5c6ebfec6fd07954a4890683")}); { "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" } Step 2: > myId._id=ObjectId("5c6ebfec6fd07954a4890689"); ObjectId("5c6ebfec6fd07954a4890689") Step 3: > db.updateIdDemo.insert(myId); WriteResult({ "nInserted" : 1 }) Step 4: > db.updateIdDemo.remove({_id:ObjectId("5c6ebfec6fd07954a4890683")}); WriteResult({ "nRemoved" : 1 }) Let us check the _id has been updated or not. Display all documents from a collection with the help of find() method: > db.updateIdDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" } { "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" } { "_id" : ObjectId("5c6ebfec6fd07954a4890689"), "StudentName" : "Robert" } Look at the sample output, the _id of “StudentName”:”Robert” has been changed.
[ { "code": null, "e": 1217, "s": 1062, "text": "You cannot update it but you can save a new id and remove the old id. Follow some steps in order to update the _id of a MongoDB. The steps are as follows:" }, { "code": null, "e": 1287, "s": 1217, "text": "Step1: In the first step, you need to store ObjectId into a variable." }, { "code": null, "e": 1360, "s": 1287, "text": "anyVariableName=db.yourCollectionName.findOne({_id:yourObjectIdValue)});" }, { "code": null, "e": 1414, "s": 1360, "text": "Step 2: In the second step, you need to set a new id." }, { "code": null, "e": 1465, "s": 1414, "text": "yourDeclaredVariableName._id=yourNewObjectIdValue;" }, { "code": null, "e": 1533, "s": 1465, "text": "Step 3: In the third step, you need to insert new id on a document." }, { "code": null, "e": 1589, "s": 1533, "text": "db.yourCollectionName.insert(yourDeclaredVariableName);" }, { "code": null, "e": 1648, "s": 1589, "text": "Step 4: In the fourth step, you need to remove the old id." }, { "code": null, "e": 1707, "s": 1648, "text": "db.yourCollectionName.remove({_id:yourOldObjectIdValue)});" }, { "code": null, "e": 1842, "s": 1707, "text": "To understand the above steps, let us create a collection with document. The query to create a collection with document is as follows:" }, { "code": null, "e": 2262, "s": 1842, "text": "> db.updateIdDemo.insertOne({\"StudentName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ebfec6fd07954a4890683\")\n}\n> db.updateIdDemo.insertOne({\"StudentName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ebff66fd07954a4890684\")\n}\n> db.updateIdDemo.insertOne({\"StudentName\":\"Maxwell\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ebfff6fd07954a4890685\")\n}" }, { "code": null, "e": 2359, "s": 2262, "text": "Display all documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 2394, "s": 2359, "text": "> db.updateIdDemo.find().pretty();" }, { "code": null, "e": 2423, "s": 2394, "text": "The following is the output:" }, { "code": null, "e": 2648, "s": 2423, "text": "{ \"_id\" : ObjectId(\"5c6ebfec6fd07954a4890683\"), \"StudentName\" : \"Robert\" }\n{ \"_id\" : ObjectId(\"5c6ebff66fd07954a4890684\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c6ebfff6fd07954a4890685\"), \"StudentName\" : \"Maxwell\" }" }, { "code": null, "e": 2716, "s": 2648, "text": "The following is the query to update the _id of a MongoDB document:" }, { "code": null, "e": 3154, "s": 2716, "text": "Step1:\n> myId=db.updateIdDemo.findOne({_id:ObjectId(\"5c6ebfec6fd07954a4890683\")});\n{ \"_id\" : ObjectId(\"5c6ebfec6fd07954a4890683\"), \"StudentName\" : \"Robert\" }\n\nStep 2:\n> myId._id=ObjectId(\"5c6ebfec6fd07954a4890689\");\nObjectId(\"5c6ebfec6fd07954a4890689\")\n\nStep 3:\n> db.updateIdDemo.insert(myId);\nWriteResult({ \"nInserted\" : 1 })\n\nStep 4:\n> db.updateIdDemo.remove({_id:ObjectId(\"5c6ebfec6fd07954a4890683\")});\nWriteResult({ \"nRemoved\" : 1 })" }, { "code": null, "e": 3272, "s": 3154, "text": "Let us check the _id has been updated or not. Display all documents from a collection with the help of find() method:" }, { "code": null, "e": 3307, "s": 3272, "text": "> db.updateIdDemo.find().pretty();" }, { "code": null, "e": 3336, "s": 3307, "text": "The following is the output:" }, { "code": null, "e": 3561, "s": 3336, "text": "{ \"_id\" : ObjectId(\"5c6ebff66fd07954a4890684\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c6ebfff6fd07954a4890685\"), \"StudentName\" : \"Maxwell\" }\n{ \"_id\" : ObjectId(\"5c6ebfec6fd07954a4890689\"), \"StudentName\" : \"Robert\" }" }, { "code": null, "e": 3640, "s": 3561, "text": "Look at the sample output, the _id of “StudentName”:”Robert” has been changed." } ]
Check whether a given number is an ugly number or not - GeeksforGeeks
03 Mar, 2021 Given an integer N, the task is to find out whether the given number is an Ugly number or not . Ugly numbers are numbers whose only prime factors are 2, 3 or 5. Examples: Input: N = 14 Output: No Explanation: 14 is not ugly since it includes another prime factor 7. Input: N = 6 Output: Yes Explanation: 6 is a ugly since it includes 2 and 3. Approach: The idea is to use recursion to solve this problem and check if a number is divisible by 2, 3 or 5. If yes then divide the number by that and recursively check that a number is an ugly number or not. If at any time, there is no such divisor, then return false, else true. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to check// if a number is an ugly// number or not #include <stdio.h>#include <stdlib.h> // Function to check if a number// is an ugly number or notint isUgly(int n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if the // number is divided by 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } // Otherwise return false return 0;}// Driver Codeint main(){ int no = isUgly(14); if (no == 1) printf("Yes"); else printf("No"); return 0;} // Java implementation to// check if a number is ugly numberclass GFG { // Function to check the ugly // number static int isUgly(int n) { // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if // a number is divide by // 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } return 0; } // Driver Code public static void main(String args[]) { int no = isUgly(14); if (no == 1) System.out.println("Yes"); else System.out.println("No"); }} # Python3 implementation to check# if a number is an ugly number# or not # Function to check if a number# is an ugly number or notdef isUgly(n): # Base Cases if (n == 1): return 1 if (n <= 0): return 0 # Condition to check if the # number is divided by 2, 3, or 5 if (n % 2 == 0): return (isUgly(n // 2)) if (n % 3 == 0): return (isUgly(n // 3)) if (n % 5 == 0): return (isUgly(n // 5)) # Otherwise return false return 0 # Driver Codeif __name__ == "__main__": no = isUgly(14) if (no == 1): print("Yes") else: print("No") # This code is contributed by chitranayal // C# implementation to check// if a number is ugly numberusing System; class GFG{ // Function to check the ugly// numberstatic int isUgly(int n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if // a number is divide by // 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } return 0;} // Driver Codepublic static void Main(String []args){ int no = isUgly(14); if (no == 1) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by amal kumar choubey <script> // Javascript implementation to check// if a number is an ugly// number or not // Function to check if a number// is an ugly number or notfunction isUgly(n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if the // number is divided by 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } // Otherwise return false return 0;}// Driver Code let no = isUgly(14); if (no == 1) document.write("Yes"); else document.write("No"); // This code is contributed by Mayank Tyagi </script> No ukasp Amal Kumar Choubey mayanktyagi1709 prime-factor Mathematical Recursion School Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Program to multiply two matrices Fizz Buzz Implementation Complexity Analysis of Binary Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number Backtracking | Introduction
[ { "code": null, "e": 24717, "s": 24689, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24814, "s": 24717, "text": "Given an integer N, the task is to find out whether the given number is an Ugly number or not . " }, { "code": null, "e": 24879, "s": 24814, "text": "Ugly numbers are numbers whose only prime factors are 2, 3 or 5." }, { "code": null, "e": 24890, "s": 24879, "text": "Examples: " }, { "code": null, "e": 24985, "s": 24890, "text": "Input: N = 14 Output: No Explanation: 14 is not ugly since it includes another prime factor 7." }, { "code": null, "e": 25064, "s": 24985, "text": "Input: N = 6 Output: Yes Explanation: 6 is a ugly since it includes 2 and 3. " }, { "code": null, "e": 25347, "s": 25064, "text": "Approach: The idea is to use recursion to solve this problem and check if a number is divisible by 2, 3 or 5. If yes then divide the number by that and recursively check that a number is an ugly number or not. If at any time, there is no such divisor, then return false, else true." }, { "code": null, "e": 25399, "s": 25347, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25403, "s": 25399, "text": "C++" }, { "code": null, "e": 25408, "s": 25403, "text": "Java" }, { "code": null, "e": 25416, "s": 25408, "text": "Python3" }, { "code": null, "e": 25419, "s": 25416, "text": "C#" }, { "code": null, "e": 25430, "s": 25419, "text": "Javascript" }, { "code": "// C++ implementation to check// if a number is an ugly// number or not #include <stdio.h>#include <stdlib.h> // Function to check if a number// is an ugly number or notint isUgly(int n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if the // number is divided by 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } // Otherwise return false return 0;}// Driver Codeint main(){ int no = isUgly(14); if (no == 1) printf(\"Yes\"); else printf(\"No\"); return 0;}", "e": 26115, "s": 25430, "text": null }, { "code": "// Java implementation to// check if a number is ugly numberclass GFG { // Function to check the ugly // number static int isUgly(int n) { // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if // a number is divide by // 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } return 0; } // Driver Code public static void main(String args[]) { int no = isUgly(14); if (no == 1) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 26890, "s": 26115, "text": null }, { "code": "# Python3 implementation to check# if a number is an ugly number# or not # Function to check if a number# is an ugly number or notdef isUgly(n): # Base Cases if (n == 1): return 1 if (n <= 0): return 0 # Condition to check if the # number is divided by 2, 3, or 5 if (n % 2 == 0): return (isUgly(n // 2)) if (n % 3 == 0): return (isUgly(n // 3)) if (n % 5 == 0): return (isUgly(n // 5)) # Otherwise return false return 0 # Driver Codeif __name__ == \"__main__\": no = isUgly(14) if (no == 1): print(\"Yes\") else: print(\"No\") # This code is contributed by chitranayal", "e": 27565, "s": 26890, "text": null }, { "code": "// C# implementation to check// if a number is ugly numberusing System; class GFG{ // Function to check the ugly// numberstatic int isUgly(int n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if // a number is divide by // 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } return 0;} // Driver Codepublic static void Main(String []args){ int no = isUgly(14); if (no == 1) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by amal kumar choubey", "e": 28290, "s": 27565, "text": null }, { "code": "<script> // Javascript implementation to check// if a number is an ugly// number or not // Function to check if a number// is an ugly number or notfunction isUgly(n){ // Base Cases if (n == 1) return 1; if (n <= 0) return 0; // Condition to check if the // number is divided by 2, 3, or 5 if (n % 2 == 0) { return (isUgly(n / 2)); } if (n % 3 == 0) { return (isUgly(n / 3)); } if (n % 5 == 0) { return (isUgly(n / 5)); } // Otherwise return false return 0;}// Driver Code let no = isUgly(14); if (no == 1) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Mayank Tyagi </script>", "e": 29006, "s": 28290, "text": null }, { "code": null, "e": 29009, "s": 29006, "text": "No" }, { "code": null, "e": 29017, "s": 29011, "text": "ukasp" }, { "code": null, "e": 29036, "s": 29017, "text": "Amal Kumar Choubey" }, { "code": null, "e": 29052, "s": 29036, "text": "mayanktyagi1709" }, { "code": null, "e": 29065, "s": 29052, "text": "prime-factor" }, { "code": null, "e": 29078, "s": 29065, "text": "Mathematical" }, { "code": null, "e": 29088, "s": 29078, "text": "Recursion" }, { "code": null, "e": 29107, "s": 29088, "text": "School Programming" }, { "code": null, "e": 29120, "s": 29107, "text": "Mathematical" }, { "code": null, "e": 29130, "s": 29120, "text": "Recursion" }, { "code": null, "e": 29228, "s": 29130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29260, "s": 29228, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 29304, "s": 29260, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29337, "s": 29304, "text": "Program to multiply two matrices" }, { "code": null, "e": 29362, "s": 29337, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29399, "s": 29362, "text": "Complexity Analysis of Binary Search" }, { "code": null, "e": 29484, "s": 29399, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 29494, "s": 29484, "text": "Recursion" }, { "code": null, "e": 29521, "s": 29494, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 29569, "s": 29521, "text": "Program for Sum of the digits of a given number" } ]
Matplotlib.axes.Axes.set_title() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_title() function in axes module of matplotlib library is used to set a title for the axes. Syntax: Axes.set_title(self, label, fontdict=None, loc=’center’, pad=None, **kwargs) Parameters: This method accepts the following parameters. label : This parameter is the Text to use for the title. fontdict : This parameter is the dictionary controlling the appearance of the title text. loc : This parameter is used to set the location of the title {‘center’, ‘left’, ‘right’}. pad : This parameter is the offset of the title from the top of the axes, in points. Returns:This method returns the matplotlib text instance representing the title. Below examples illustrate the matplotlib.axes.Axes.set_title() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport osfrom matplotlib import font_manager as fm, rcParamsimport matplotlib.pyplot as plt fig, ax = plt.subplots() fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf") prop = fm.FontProperties(fname = fpath)fname = os.path.split(fpath)[1]ax.set_title('Title with special font: {}'.format(fname), fontproperties = prop, fontsize = 14) plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(0.1, 5, 0.1)y = np.exp(-x) yerr = 0.1 + 0.1 * np.sqrt(x) fig, axs = plt.subplots(nrows = 1, ncols = 2, sharex = True)ax = axs[0]ax.errorbar(x, y, yerr = yerr, color ="green")ax.set_title('Title of Axes 1', fontweight ="bold") ax = axs[1]ax.errorbar(x, y, yerr = yerr, errorevery = 5, color ="green") ax.set_title('Title of Axes 2', fontweight ="bold") fig.suptitle('matplotlib.axes.Axes.set_title() \function Example\n') plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python
[ { "code": null, "e": 24900, "s": 24872, "text": "\n19 Apr, 2020" }, { "code": null, "e": 25200, "s": 24900, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 25304, "s": 25200, "text": "The Axes.set_title() function in axes module of matplotlib library is used to set a title for the axes." }, { "code": null, "e": 25389, "s": 25304, "text": "Syntax: Axes.set_title(self, label, fontdict=None, loc=’center’, pad=None, **kwargs)" }, { "code": null, "e": 25447, "s": 25389, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 25504, "s": 25447, "text": "label : This parameter is the Text to use for the title." }, { "code": null, "e": 25594, "s": 25504, "text": "fontdict : This parameter is the dictionary controlling the appearance of the title text." }, { "code": null, "e": 25685, "s": 25594, "text": "loc : This parameter is used to set the location of the title {‘center’, ‘left’, ‘right’}." }, { "code": null, "e": 25770, "s": 25685, "text": "pad : This parameter is the offset of the title from the top of the axes, in points." }, { "code": null, "e": 25851, "s": 25770, "text": "Returns:This method returns the matplotlib text instance representing the title." }, { "code": null, "e": 25943, "s": 25851, "text": "Below examples illustrate the matplotlib.axes.Axes.set_title() function in matplotlib.axes:" }, { "code": null, "e": 25954, "s": 25943, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport osfrom matplotlib import font_manager as fm, rcParamsimport matplotlib.pyplot as plt fig, ax = plt.subplots() fpath = os.path.join(rcParams[\"datapath\"], \"fonts/ttf/cmr10.ttf\") prop = fm.FontProperties(fname = fpath)fname = os.path.split(fpath)[1]ax.set_title('Title with special font: {}'.format(fname), fontproperties = prop, fontsize = 14) plt.show()", "e": 26403, "s": 25954, "text": null }, { "code": null, "e": 26411, "s": 26403, "text": "Output:" }, { "code": null, "e": 26422, "s": 26411, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.arange(0.1, 5, 0.1)y = np.exp(-x) yerr = 0.1 + 0.1 * np.sqrt(x) fig, axs = plt.subplots(nrows = 1, ncols = 2, sharex = True)ax = axs[0]ax.errorbar(x, y, yerr = yerr, color =\"green\")ax.set_title('Title of Axes 1', fontweight =\"bold\") ax = axs[1]ax.errorbar(x, y, yerr = yerr, errorevery = 5, color =\"green\") ax.set_title('Title of Axes 2', fontweight =\"bold\") fig.suptitle('matplotlib.axes.Axes.set_title() \\function Example\\n') plt.show()", "e": 27075, "s": 26422, "text": null }, { "code": null, "e": 27083, "s": 27075, "text": "Output:" }, { "code": null, "e": 27101, "s": 27083, "text": "Python-matplotlib" }, { "code": null, "e": 27108, "s": 27101, "text": "Python" }, { "code": null, "e": 27206, "s": 27108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27224, "s": 27206, "text": "Python Dictionary" }, { "code": null, "e": 27259, "s": 27224, "text": "Read a file line by line in Python" }, { "code": null, "e": 27291, "s": 27259, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27313, "s": 27291, "text": "Enumerate() in Python" }, { "code": null, "e": 27355, "s": 27313, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27385, "s": 27355, "text": "Iterate over a list in Python" }, { "code": null, "e": 27411, "s": 27385, "text": "Python String | replace()" }, { "code": null, "e": 27455, "s": 27411, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27492, "s": 27455, "text": "Create a Pandas DataFrame from Lists" } ]
MomentJS - Week of year
This method will get/set the week of the year. The output will depend on the locale being used, as first day of week differs from country to country. moment().week(Number); moment().week(); moment().weeks(Number); moment().weeks(); var m = moment().week(); var d = moment().week(50); var a = moment().week(90); Print Add Notes Bookmark this page
[ { "code": null, "e": 2110, "s": 1960, "text": "This method will get/set the week of the year. The output will depend on the locale being used, as first day of week differs from country to country." }, { "code": null, "e": 2193, "s": 2110, "text": "moment().week(Number);\nmoment().week();\nmoment().weeks(Number);\nmoment().weeks();\n" }, { "code": null, "e": 2272, "s": 2193, "text": "var m = moment().week();\nvar d = moment().week(50);\nvar a = moment().week(90);" }, { "code": null, "e": 2279, "s": 2272, "text": " Print" }, { "code": null, "e": 2290, "s": 2279, "text": " Add Notes" } ]
Collision Detection in PyGame - GeeksforGeeks
18 Aug, 2021 Prerequisite: Introduction to pygame Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision. In this article, we will be detecting a collision between two objects where one object would be coming in a downward direction and the other one would be moved from the left and right with key control. It’s the same as to escape from the block falling on the player and if block collides the player, then the collision is detected. Let’s see the part wise implementation: Part 1: Python3 # import required librariesimport pygameimport random # initialize pygame objectspygame.init() # define the colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # set the Dimensionswidth = 650height = 700 # size of a blockpixel = 64 # set Screenscreen = pygame.display.set_mode((width, height)) # set captionpygame.display.set_caption("CORONA SCARPER") # load the imagegameIcon = pygame.image.load("rectangleBlock.png") # set iconpygame.display.set_icon(gameIcon) # load the imagebackgroundImg = pygame.image.load("wallBackground.jpg") This is the basic simple code for creating a window screen and setting up the caption, icon, and some pre-defined variables which are not so important to get into in deep. The pixel variable is the size of the block image i.e 64 pixels. Part 2: Python3 # load the imageplayerImage = pygame.image.load("player.png") # set the positionplayerXPosition = (width/2) - (pixel/2) # So that the player will be# at height of 20 above the baseplayerYPosition = height - pixel - 10 # set initially 0playerXPositionChange = 0 # define a function for setting# the image at particular# coordinatesdef player(x, y): # paste image on screen object screen.blit(playerImage, (x, y)) # load the imageblockImage = pygame.image.load("rectangleBlock.png") # set the random positionblockXPosition = random.randint(0, (width - pixel)) blockYPosition = 0 - pixel # set the speed of# the blockblockXPositionChange = 0blockYPositionChange = 2 # define a function for setting# the image at particular# coordinatesdef block(x, y): # paste image on screen object screen.blit(blockImage, (x, y)) Here we are displaying the player and the block at their respective X and Y positions. The block’s X position is random in each round. Note: Wherever the pixel word is used, it is used to subtract 64 pixels from the given position so that the full image is shown E.g: The block if shown is at width position, then it will be drawn starting from that point and hence it will be shown out of the screen. Hence we are subtracting 64 pixels to be viewing the image full Now, Horizontal Collision First, we check if the block passes through the player’s horizontal line. We will set the range such that the block’s base horizontal line should match the player’s horizontal line. In the above image, block 2 and 3 having their baseline out of range of player P’s top and bottom surface line. Hence, they are not in the collision range. Block 1’s baseline is in the range of the player P’s top and bottom. Hence we further see that the block comes in the range of the player’s vertical range or not. Vertical Collision Here, we check the range of player’s left and right side surface dimensions with the blocks left and right surfaces. Here, the blocks 2 and 3 when coming down, will collide the player, and hence the range of 2 and 3 block’s range are between player’s X and player’s Y position. Hence, this concept is to used to detect the collision. Part 3: Python3 # define a function for# collision detectiondef crash(): # take a global variable global blockYPosition # check conditions if playerYPosition < (blockYPosition + pixel): if ((playerXPosition > blockXPosition and playerXPosition < (blockXPosition + pixel)) or ((playerXPosition + pixel) > blockXPosition and (playerXPosition + pixel) < (blockXPosition + pixel))): blockYPosition = height + 1000 the crash function defines the collision condition. In the first IF condition, we check the horizontal collision. Here, if the player’s Y position is less than blocks Y position, i.e the block is passed away from the player’s horizontal range, then the next condition is to be checked is horizontal. Pixel is added to blockYPosition because its Y position is at top of the block and the bottom or base of the block is a block’s top position + its pixel size(image size). The second IF condition checks the vertical collision. If the block is passing from the horizontal range then only check for vertical, so that the block’s collision is detected in all its four sides. Now, if the players X position is greater then block’s X position, i.e block is at left w.r.t player. Here, if the block’s starting position is less than player starting position and block’s end position(block Y position + pixel) is greater than player starting position, this means that the block will overlap the player’s starting position and hence collide. This is shown in the above vertical collision image for block 2. Similarly, the second range is given that if the blocks start position is less than the player’s end position and blocks end position is greater than the player’s end position. This is shown for the same image for block 3. The image clearly explains the view of the collision. Hence, if a collision happens, we will move the block to below the screen i.e at 1000+ distance below so that it would be invisible and the new block will not appear. Part 4: Python3 running = True while running: # set the image on screen object screen.blit(backgroundImg, (0, 0)) # loop through all events for event in pygame.event.get(): # check the quit condition if event.type == pygame.QUIT: # quit the game pygame.quit() # movement key control of player if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: playerXPositionChange = 3 if event.key == pygame.K_LEFT: playerXPositionChange = -3 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or pygame.K_LEFT: playerXPositionChange = 0 This is the gaming loop where the movement of the player is controlled. and the game is started. Part 5: Python3 # Boundaries to the Player # if it comes at right end,# stay at right end and# does not exceedif playerXPosition >= (width - pixel): playerXPosition = (width - pixel) # if it comes at left end,# stay at left end and# does not exceedif playerXPosition <= 0: playerXPosition = 0 These are the boundaries to the player so that when the player moves to its rightmost or leftmost position on the screen, it should not go further and bounce back. Part 6: Python3 # Multiple Blocks Movement after each other# and condition used because of game over functionif (blockYPosition >= height - 0 and blockYPosition <= (height + 200)): blockYPosition = 0 - pixel # randomly assign value in range blockXPosition = random.randint(0, (width - pixel)) When the block without colliding goes away from the player, then we need to let him come again from the top. Hence we provide a condition that if the block’s Y position is below the height of the screen and below height+200(as above 1000+, the block appears when the block has collided), then move it again at the top. Part 7: Python3 # movement of PlayerplayerXPosition += playerXPositionChange # movement of BlockblockYPosition += blockYPositionChange # player Function Callplayer(playerXPosition, playerYPosition) # block Function Callblock(blockXPosition, blockYPosition) # crash function callcrash() # update screenpygame.display.update() At the last, the movement of the player and the block is given and the screen is refreshed Output: sweetyty Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() 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": 24423, "s": 24395, "text": "\n18 Aug, 2021" }, { "code": null, "e": 24460, "s": 24423, "text": "Prerequisite: Introduction to pygame" }, { "code": null, "e": 24717, "s": 24460, "text": "Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision." }, { "code": null, "e": 25049, "s": 24717, "text": "In this article, we will be detecting a collision between two objects where one object would be coming in a downward direction and the other one would be moved from the left and right with key control. It’s the same as to escape from the block falling on the player and if block collides the player, then the collision is detected." }, { "code": null, "e": 25089, "s": 25049, "text": "Let’s see the part wise implementation:" }, { "code": null, "e": 25097, "s": 25089, "text": "Part 1:" }, { "code": null, "e": 25105, "s": 25097, "text": "Python3" }, { "code": "# import required librariesimport pygameimport random # initialize pygame objectspygame.init() # define the colourswhite = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)black = (0, 0, 0) # set the Dimensionswidth = 650height = 700 # size of a blockpixel = 64 # set Screenscreen = pygame.display.set_mode((width, height)) # set captionpygame.display.set_caption(\"CORONA SCARPER\") # load the imagegameIcon = pygame.image.load(\"rectangleBlock.png\") # set iconpygame.display.set_icon(gameIcon) # load the imagebackgroundImg = pygame.image.load(\"wallBackground.jpg\")", "e": 25723, "s": 25105, "text": null }, { "code": null, "e": 25963, "s": 25726, "text": "This is the basic simple code for creating a window screen and setting up the caption, icon, and some pre-defined variables which are not so important to get into in deep. The pixel variable is the size of the block image i.e 64 pixels." }, { "code": null, "e": 25974, "s": 25965, "text": " Part 2:" }, { "code": null, "e": 25984, "s": 25976, "text": "Python3" }, { "code": "# load the imageplayerImage = pygame.image.load(\"player.png\") # set the positionplayerXPosition = (width/2) - (pixel/2) # So that the player will be# at height of 20 above the baseplayerYPosition = height - pixel - 10 # set initially 0playerXPositionChange = 0 # define a function for setting# the image at particular# coordinatesdef player(x, y): # paste image on screen object screen.blit(playerImage, (x, y)) # load the imageblockImage = pygame.image.load(\"rectangleBlock.png\") # set the random positionblockXPosition = random.randint(0, (width - pixel)) blockYPosition = 0 - pixel # set the speed of# the blockblockXPositionChange = 0blockYPositionChange = 2 # define a function for setting# the image at particular# coordinatesdef block(x, y): # paste image on screen object screen.blit(blockImage, (x, y))", "e": 26851, "s": 25984, "text": null }, { "code": null, "e": 26989, "s": 26854, "text": "Here we are displaying the player and the block at their respective X and Y positions. The block’s X position is random in each round." }, { "code": null, "e": 27119, "s": 26991, "text": "Note: Wherever the pixel word is used, it is used to subtract 64 pixels from the given position so that the full image is shown" }, { "code": null, "e": 27329, "s": 27121, "text": " E.g: The block if shown is at width position, then it will be drawn starting from that point and hence it will be shown out of the screen. Hence we are subtracting 64 pixels to be viewing the image full" }, { "code": null, "e": 27336, "s": 27331, "text": "Now," }, { "code": null, "e": 27359, "s": 27338, "text": "Horizontal Collision" }, { "code": null, "e": 27862, "s": 27361, "text": "First, we check if the block passes through the player’s horizontal line. We will set the range such that the block’s base horizontal line should match the player’s horizontal line. In the above image, block 2 and 3 having their baseline out of range of player P’s top and bottom surface line. Hence, they are not in the collision range. Block 1’s baseline is in the range of the player P’s top and bottom. Hence we further see that the block comes in the range of the player’s vertical range or not." }, { "code": null, "e": 27883, "s": 27864, "text": "Vertical Collision" }, { "code": null, "e": 28164, "s": 27885, "text": "Here, we check the range of player’s left and right side surface dimensions with the blocks left and right surfaces. Here, the blocks 2 and 3 when coming down, will collide the player, and hence the range of 2 and 3 block’s range are between player’s X and player’s Y position. " }, { "code": null, "e": 28222, "s": 28166, "text": "Hence, this concept is to used to detect the collision." }, { "code": null, "e": 28233, "s": 28224, "text": " Part 3:" }, { "code": null, "e": 28243, "s": 28235, "text": "Python3" }, { "code": "# define a function for# collision detectiondef crash(): # take a global variable global blockYPosition # check conditions if playerYPosition < (blockYPosition + pixel): if ((playerXPosition > blockXPosition and playerXPosition < (blockXPosition + pixel)) or ((playerXPosition + pixel) > blockXPosition and (playerXPosition + pixel) < (blockXPosition + pixel))): blockYPosition = height + 1000", "e": 28687, "s": 28243, "text": null }, { "code": null, "e": 28739, "s": 28687, "text": "the crash function defines the collision condition." }, { "code": null, "e": 29158, "s": 28739, "text": "In the first IF condition, we check the horizontal collision. Here, if the player’s Y position is less than blocks Y position, i.e the block is passed away from the player’s horizontal range, then the next condition is to be checked is horizontal. Pixel is added to blockYPosition because its Y position is at top of the block and the bottom or base of the block is a block’s top position + its pixel size(image size)." }, { "code": null, "e": 29784, "s": 29158, "text": "The second IF condition checks the vertical collision. If the block is passing from the horizontal range then only check for vertical, so that the block’s collision is detected in all its four sides. Now, if the players X position is greater then block’s X position, i.e block is at left w.r.t player. Here, if the block’s starting position is less than player starting position and block’s end position(block Y position + pixel) is greater than player starting position, this means that the block will overlap the player’s starting position and hence collide. This is shown in the above vertical collision image for block 2." }, { "code": null, "e": 30007, "s": 29784, "text": "Similarly, the second range is given that if the blocks start position is less than the player’s end position and blocks end position is greater than the player’s end position. This is shown for the same image for block 3." }, { "code": null, "e": 30061, "s": 30007, "text": "The image clearly explains the view of the collision." }, { "code": null, "e": 30228, "s": 30061, "text": "Hence, if a collision happens, we will move the block to below the screen i.e at 1000+ distance below so that it would be invisible and the new block will not appear." }, { "code": null, "e": 30236, "s": 30228, "text": "Part 4:" }, { "code": null, "e": 30244, "s": 30236, "text": "Python3" }, { "code": "running = True while running: # set the image on screen object screen.blit(backgroundImg, (0, 0)) # loop through all events for event in pygame.event.get(): # check the quit condition if event.type == pygame.QUIT: # quit the game pygame.quit() # movement key control of player if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: playerXPositionChange = 3 if event.key == pygame.K_LEFT: playerXPositionChange = -3 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT or pygame.K_LEFT: playerXPositionChange = 0", "e": 30912, "s": 30244, "text": null }, { "code": null, "e": 31013, "s": 30915, "text": "This is the gaming loop where the movement of the player is controlled. and the game is started. " }, { "code": null, "e": 31023, "s": 31015, "text": "Part 5:" }, { "code": null, "e": 31033, "s": 31025, "text": "Python3" }, { "code": "# Boundaries to the Player # if it comes at right end,# stay at right end and# does not exceedif playerXPosition >= (width - pixel): playerXPosition = (width - pixel) # if it comes at left end,# stay at left end and# does not exceedif playerXPosition <= 0: playerXPosition = 0", "e": 31314, "s": 31033, "text": null }, { "code": null, "e": 31478, "s": 31314, "text": "These are the boundaries to the player so that when the player moves to its rightmost or leftmost position on the screen, it should not go further and bounce back." }, { "code": null, "e": 31486, "s": 31478, "text": "Part 6:" }, { "code": null, "e": 31494, "s": 31486, "text": "Python3" }, { "code": "# Multiple Blocks Movement after each other# and condition used because of game over functionif (blockYPosition >= height - 0 and blockYPosition <= (height + 200)): blockYPosition = 0 - pixel # randomly assign value in range blockXPosition = random.randint(0, (width - pixel))", "e": 31783, "s": 31494, "text": null }, { "code": null, "e": 32105, "s": 31786, "text": "When the block without colliding goes away from the player, then we need to let him come again from the top. Hence we provide a condition that if the block’s Y position is below the height of the screen and below height+200(as above 1000+, the block appears when the block has collided), then move it again at the top." }, { "code": null, "e": 32115, "s": 32107, "text": "Part 7:" }, { "code": null, "e": 32125, "s": 32117, "text": "Python3" }, { "code": "# movement of PlayerplayerXPosition += playerXPositionChange # movement of BlockblockYPosition += blockYPositionChange # player Function Callplayer(playerXPosition, playerYPosition) # block Function Callblock(blockXPosition, blockYPosition) # crash function callcrash() # update screenpygame.display.update()", "e": 32434, "s": 32125, "text": null }, { "code": null, "e": 32528, "s": 32437, "text": "At the last, the movement of the player and the block is given and the screen is refreshed" }, { "code": null, "e": 32538, "s": 32530, "text": "Output:" }, { "code": null, "e": 32551, "s": 32542, "text": "sweetyty" }, { "code": null, "e": 32565, "s": 32551, "text": "Python-PyGame" }, { "code": null, "e": 32572, "s": 32565, "text": "Python" }, { "code": null, "e": 32670, "s": 32572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32688, "s": 32670, "text": "Python Dictionary" }, { "code": null, "e": 32723, "s": 32688, "text": "Read a file line by line in Python" }, { "code": null, "e": 32745, "s": 32723, "text": "Enumerate() in Python" }, { "code": null, "e": 32777, "s": 32745, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32807, "s": 32777, "text": "Iterate over a list in Python" }, { "code": null, "e": 32849, "s": 32807, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32875, "s": 32849, "text": "Python String | replace()" }, { "code": null, "e": 32918, "s": 32875, "text": "Python program to convert a list to string" }, { "code": null, "e": 32955, "s": 32918, "text": "Create a Pandas DataFrame from Lists" } ]
Tokenize Text Columns Into Sentences in Pandas | by Baris Sari | Towards Data Science
In this tutorial, I’m going to show you a few different options you may use for sentence tokenization. I’m going to use one of my favourite TV show’s data: Seinfeld Chronicles (Don’t worry, I won’t give you any spoilers :) We will be using the very first dialogues from S1E1). It’s publicly available on Kaggle platform. scripts.csv has dialogue column that has many sentences in most of the rows and we’re going to split it into sentences. The steps we will follow are: Read CSV using Pandas and acquire the first value for step 2.Sentence Tokenization Read CSV using Pandas and acquire the first value for step 2. Sentence Tokenization Tokenize an example text using Python’s split(). (Never use it for production!) Tokenize an example text using regex. Tokenize an example text using spaCy. Tokenize an example text using nltk. 3. Tokenize whole data in dialogue column using spaCy. 4. Split list of sentences to a sentence in each row by replicating rows. Check the modified DataFrame and save to your disk. Note: Many of the gists don’t show all the outcomes if you look only in the article. Please don’t forget to check them on GitHub. Note-2: Many of the gists won’t work if you don’t follow the steps in the article in order. You might check the last gist in the conclusion section or you might go step-by-step. I’ll keep this very short. Put scripts.csv to the same directory with your Python script or Jupyter notebook and then run the following commands: You can directly give scripts.csv to Pandas’s read_csv() but it is always more robust to use os or glob to give file path. It’s also a good practice for production. You might forget to change all of magic filenames if you use strings. Let’s create a DataFrame from our CSV file and assign the first row’s Dialogue column to first_dialogue variable. import pandas as pd # Read the file df = pd.read_csv(FILE_PATH) # Assign first_dialogue to the first row's "Dialogue" column first_dialogue = df.loc[0, "Dialogue"] print(first_dialogue) Do you know what this is all about? Do you know, why were here? To be out, this is out...and out is one of the single most enjoyable experiences of life. People...did you ever hear people talking about We should go out? This is what theyre talking about...this whole thing, were all out now, no one is home. Not one person here is home, were all out! There are people tryin to find us, they dont know where we are. (on an imaginary phone) Did you ring?, I cant find him. Where did he go? He didnt tell me where he was going. He must have gone out. You wanna go out you get ready, you pick out the clothes, right? You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...Then youre standing around, whatta you do? You go We gotta be getting back. Once youre out, you wanna get back! You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? Where ever you are in life, its my feeling, youve gotta go. df.head() So, we are ready to try different sentence tokenizers. This might be a great example because it has many punctuations such as three dots, exclamation mark, question mark; long sentences; sentences without punctuation between them; etc. This will be a naive method, which you should never use for sentence tokenization! I prefer using built-in functions as much as possible in my projects. But if it doesn’t fit, then don’t use it, check for the alternatives (you will probably find a better library because Python has a vast community and lots of great open-source libraries!). So, you might use the following gist, which will only work if you are very lucky and all of your sentences end with “.”: first_dialogue.split(".") ['Do you know what this is all about? Do you know, why were here? To be out, this is out', '', '', 'and out is one of the single most enjoyable experiences of life', ' People', '', '', 'did you ever hear people talking about We should go out? This is what theyre talking about', '', '', 'this whole thing, were all out now, no one is home', ' Not one person here is home, were all out! There are people tryin to find us, they dont know where we are', ' (on an imaginary phone) Did you ring?, I cant find him', ' Where did he go? He didnt tell me where he was going', ' He must have gone out', ' You wanna go out you get ready, you pick out the clothes, right? You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation', '', '', 'Then youre standing around, whatta you do? You go We gotta be getting back', ' Once youre out, you wanna get back! You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? Where ever you are in life, its my feeling, youve gotta go', ''] Not so good, right? I see that split() is used in many articles for word tokenization. Which might be acceptable because it splits texts by taking care of extra spaces, etc. For sentence tokenization, it just doesn’t work. You might use replace() and then split() to replace all end-of-line characters with one character and split the text into sentences using that character. It would give a better result, but the performance of your code would decrease. Another problem is we’re losing the character we used for splitting. If we aggregated the transformed data, we wouldn’t have the original punctuations any more. Regular expression is always useful if you’re working on texts. It’s a quite old and robust approach. Many programming languages offer it natively. So, you can use your regex across different languages with small or no changes. Let’s give it a try to one of the accepted answers on Stackoverflow (with a small change, by adding |! to the third group): import re re.split(r"(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s", first_dialogue) ['Do you know what this is all about?', 'Do you know, why were here?', 'To be out, this is out...and out is one of the single most enjoyable experiences of life.', 'People...did you ever hear people talking about We should go out?', 'This is what theyre talking about...this whole thing, were all out now, no one is home.', 'Not one person here is home, were all out!', 'There are people tryin to find us, they dont know where we are.', '(on an imaginary phone) Did you ring?, I cant find him.', 'Where did he go?', 'He didnt tell me where he was going.', 'He must have gone out.', 'You wanna go out you get ready, you pick out the clothes, right?', 'You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...Then youre standing around, whatta you do?', 'You go We gotta be getting back.', 'Once youre out, you wanna get back!', 'You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right?', 'Where ever you are in life, its my feeling, youve gotta go.'] Let me explain the regex pattern: (?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s step by step: (?<!X)Y is called negative lookbehind. It tries to capture Y (any whitespace character \s in our case) where preceded characters of Y do not match with X. For example, let’s say you have this regex: (?<!TEST)MATCH . If your text is “TESTMATCH”, it will not match, if it’s “RANDOM_MATCH” (preceded characters are not “TEST”), it will match. (?<=X)Y is called positive lookbehind. It tries to capture Y (any whitespace character \s in our case) where preceded characters of Y match with X. Let’s use the same example as above and check the outcomes: In our regex, we have three capturing groups: the first two are looking for negative lookbehind and the last one is looking for a positive lookbehind. Now, let’s look at the inside of these capturing groups to understand what kind of strings we’re looking for: Inside of the first capturing group is as follows: \w\.\w. . \w matches any word character (letter, number, or underscore). \. matches literal dot character (backslash is the escape character in regex). . matches any character. An example match: i.e. MATCH Inside of the second capturing group is [A-Z][a-z]\. . It matches any lowercase or uppercase letter following with dot character. An example match:Mr. MATCH . Inside of the third capturing group is \.|\?|! . We already know that \ is used for literal characters. | means to match either the first part or the latter part. In other words, (A|B|C) means either match A, B or C. In our case, it will match either dot, question, or exclamation mark. We may finally know all we need to know about our regex. To sum up, we’re searching for whitespace characters by checking its preceded characters. If it passes from our three validations, we match it. So, we can split the text from these matches. The disadvantage of using regex is: It might be quite painful to explain what is going on! It’s not intuitive. You should spend some time to learn it, otherwise, it will look scary. You might create infinite loops or low-performance regular expressions if you’re not much familiar with it. It’s not easy to cover edge cases before you face with them. When you start to write a regex, you might easily miss some of these cases. Our regex relies on whitespace characters. If there is no whitespace between two sentences, then it doesn’t match anything. So, it might fail if your text is not properly formatted. For example, if you give this text to our regex, “This is an example sentence.This is another one without space after the dot.”, it will think it’s one sentence. The advantage of using regex is: You don’t need to rely on third-party libraries. It’s lightning fast because just as many of Python’s built-in functions, re module is converted and executed on C. It exists since the 1950s, and it’s a quite known thing for string search, replace, etc. You can write one regex in Python and use it in Javascript with minor changes. You only need to know the programming language specific behaviours, the rest will be easy. But, you can’t use a Python library in Javascript. If you can, you will need a workaround, or you will use a Python API etc. spaCy is capable of preprocessing texts in many languages. It offers tokenization, lemmatization, linguistic features, creating pipelines, training, running on GPU, etc. So, it’s a resourceful and powerful library. If you have unstructured text data such as scraped texts from the web, I’d suggest using it without any hesitation. If you think of only doing basic preprocessing, it might add extra complexity which you don’t actually need. Before you try spaCy’s tokenization, you should download the library and one of its models. We will use the small English model which will be sufficient for our task. This approach takes a long time. However, this is a bit misleading because spaCy might work much faster. It took a long time because we need to convert each value to an nlp object and we used the default sentence segmentation component. It is called DependencyParser. It’s possible to modify -to remove dependency parser and use custom segmentation- nlp() object and define it without using any model. Let’s use sentencizer pipeline component this time: As you can see, there is a trade-off between the speed and the result. sentencizer struggled just as nltk and regex because it uses a rule-based strategy. The advantage of using spaCy is: It is a well-documented library which is maintained actively by a large community. It offers tons of NLP functionalities that you might use. It supports many languages such as German, Dutch, French, and Chinese. The disadvantage of using spaCy is: It’s slower than re module in normal usage. It might be overkill to include it to your project and use it only for tokenization. nltk is another NLP library which you may use for text processing. It is natively supporting sentence tokenization as spaCy. To use its sent_tokenize function, you should download punkt (default sentence tokenizer). nltk tokenizer gave almost the same result with regex. It struggled and couldn’t split many sentences. When we check the results carefully, we see that spaCy with the dependency parse outperforms others in sentence tokenization. It is handling the case which two sentences do not have whitespace character between them. It also handles if there are two sentences and there is only a space between them. Thus, it gave the best result. I’m going to benchmark when I apply these tokenizations to all data. We will also see their speed. I’m going to skip split() for benchmarking. It is so obvious that we can’t consider to use it. We will create lambda functions and use Pandas DataFrame’s apply method. Before transforming the whole data, I’d like to test the performances using the first 5000 rows. The outcomes are as follows: As you can see, regex is blazingly fast. It’s 10x faster than nltk and spaCy with sentencizer! It’s ~1600x faster than spaCy with the dependency parse. Yet, you might try to increase spaCy’s speed more. You may use nlp.pipe which helps to send column values in a batch instead of one-by-one. You might also modify your code to run spaCy transformation using multiprocessing. However, I’m not going to show it here. You can check the link in the further reading section. I’m going to use the first approach we have used in spaCy to transform whole data: nlp = spacy.load("en_core_web_sm")df["Dialogue"] = df["Dialogue"].apply(lambda x: [sent.text for sent in nlp(x).sents]) We have transformed data, which have a list of sentences in each Dialogue column. And it may not useful for further analysis. Luckily, Pandas offers an elegant method which will help us to create new rows for each sentence in the lists. We will replicate the values in other columns, but our Dialogue column will have only one sentence in a row. And, its type will be string, not list. Okay, that’s it! In the first cell, we called explode() method with ignore_index parameter, it will create a new index for each row but it will keep the previous index values in another column named Unnamed 0 . In the second cell, the new index and the previous index values are renamed to Sentence ID and Dialogue ID respectively. It is important to keep the track of your original data and allow yourself to transform backwardly. Because you may make amazing analysis in the sentence level, after you’re done you may want to see the results in the dialogue level. It might sound silly for this task but it might be useful in other text corpora. In our case, we can use Dialogue ID if we would like to return to original data because we’re 100% sure that it has unique IDs for each dialogue. A simple group_by() with correct aggregation parameters (taking first values for existing columns, and taking sum/mean etc. for the new columns that we add for analysis) would give use the original version. We have come up to the last point. Let’s save our file, and complete our tutorial: df.to_csv("scripts_tokenized.csv") In this tutorial, I have tried to show you a few different approaches to sentence tokenization. These approaches are not the only approaches we have currently. NLP is quite a big subject and I’m sure you may find alternatives. I tried to select the prevalent libraries. If you think of further text preprocessing, I would certainly suggest using spaCy. Because it is easy-to-use, documentations are richly detailed, its community has almost 500 members, and new features are constantly coming. If you think of tokenizing your text only, I would reformat the text a bit, and then would use regex, so that importing Python’s re module to my script would be enough instead of adding new dependencies. Full working code in one gist: Thanks for reading up to the end! Multiprocessing on spaCy: https://prrao87.github.io/blog/spacy/nlp/performance/2020/05/02/spacy-multiprocess.html#Option-1:-Sequentially-process-DataFrame-column Multiprocessing on spaCy: https://prrao87.github.io/blog/spacy/nlp/performance/2020/05/02/spacy-multiprocess.html#Option-1:-Sequentially-process-DataFrame-column Sentence Segmentation — SpaCy: https://spacy.io/usage/linguistic-features#sbd-componentPunk sentence tokenizer: https://www.nltk.org/_modules/nltk/tokenize/punkt.htmlRegex sentence tokenizer: https://stackoverflow.com/a/25736082/9686506Regex cheatsheet: https://www.rexegg.com/regex-disambiguation.htmlPandas explode(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html Sentence Segmentation — SpaCy: https://spacy.io/usage/linguistic-features#sbd-component Punk sentence tokenizer: https://www.nltk.org/_modules/nltk/tokenize/punkt.html Regex sentence tokenizer: https://stackoverflow.com/a/25736082/9686506 Regex cheatsheet: https://www.rexegg.com/regex-disambiguation.html Pandas explode(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html
[ { "code": null, "e": 613, "s": 172, "text": "In this tutorial, I’m going to show you a few different options you may use for sentence tokenization. I’m going to use one of my favourite TV show’s data: Seinfeld Chronicles (Don’t worry, I won’t give you any spoilers :) We will be using the very first dialogues from S1E1). It’s publicly available on Kaggle platform. scripts.csv has dialogue column that has many sentences in most of the rows and we’re going to split it into sentences." }, { "code": null, "e": 643, "s": 613, "text": "The steps we will follow are:" }, { "code": null, "e": 726, "s": 643, "text": "Read CSV using Pandas and acquire the first value for step 2.Sentence Tokenization" }, { "code": null, "e": 788, "s": 726, "text": "Read CSV using Pandas and acquire the first value for step 2." }, { "code": null, "e": 810, "s": 788, "text": "Sentence Tokenization" }, { "code": null, "e": 890, "s": 810, "text": "Tokenize an example text using Python’s split(). (Never use it for production!)" }, { "code": null, "e": 928, "s": 890, "text": "Tokenize an example text using regex." }, { "code": null, "e": 966, "s": 928, "text": "Tokenize an example text using spaCy." }, { "code": null, "e": 1003, "s": 966, "text": "Tokenize an example text using nltk." }, { "code": null, "e": 1058, "s": 1003, "text": "3. Tokenize whole data in dialogue column using spaCy." }, { "code": null, "e": 1184, "s": 1058, "text": "4. Split list of sentences to a sentence in each row by replicating rows. Check the modified DataFrame and save to your disk." }, { "code": null, "e": 1314, "s": 1184, "text": "Note: Many of the gists don’t show all the outcomes if you look only in the article. Please don’t forget to check them on GitHub." }, { "code": null, "e": 1492, "s": 1314, "text": "Note-2: Many of the gists won’t work if you don’t follow the steps in the article in order. You might check the last gist in the conclusion section or you might go step-by-step." }, { "code": null, "e": 1638, "s": 1492, "text": "I’ll keep this very short. Put scripts.csv to the same directory with your Python script or Jupyter notebook and then run the following commands:" }, { "code": null, "e": 1873, "s": 1638, "text": "You can directly give scripts.csv to Pandas’s read_csv() but it is always more robust to use os or glob to give file path. It’s also a good practice for production. You might forget to change all of magic filenames if you use strings." }, { "code": null, "e": 1987, "s": 1873, "text": "Let’s create a DataFrame from our CSV file and assign the first row’s Dialogue column to first_dialogue variable." }, { "code": null, "e": 2175, "s": 1987, "text": "import pandas as pd\n\n# Read the file\ndf = pd.read_csv(FILE_PATH)\n# Assign first_dialogue to the first row's \"Dialogue\" column\nfirst_dialogue = df.loc[0, \"Dialogue\"]\nprint(first_dialogue)\n" }, { "code": null, "e": 3151, "s": 2175, "text": "Do you know what this is all about? Do you know, why were here? To be out, this is out...and out is one of the single most enjoyable experiences of life. People...did you ever hear people talking about We should go out? This is what theyre talking about...this whole thing, were all out now, no one is home. Not one person here is home, were all out! There are people tryin to find us, they dont know where we are. (on an imaginary phone) Did you ring?, I cant find him. Where did he go? He didnt tell me where he was going. He must have gone out. You wanna go out you get ready, you pick out the clothes, right? You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...Then youre standing around, whatta you do? You go We gotta be getting back. Once youre out, you wanna get back! You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? Where ever you are in life, its my feeling, youve gotta go.\n" }, { "code": null, "e": 3162, "s": 3151, "text": "df.head()\n" }, { "code": null, "e": 3398, "s": 3162, "text": "So, we are ready to try different sentence tokenizers. This might be a great example because it has many punctuations such as three dots, exclamation mark, question mark; long sentences; sentences without punctuation between them; etc." }, { "code": null, "e": 3861, "s": 3398, "text": "This will be a naive method, which you should never use for sentence tokenization! I prefer using built-in functions as much as possible in my projects. But if it doesn’t fit, then don’t use it, check for the alternatives (you will probably find a better library because Python has a vast community and lots of great open-source libraries!). So, you might use the following gist, which will only work if you are very lucky and all of your sentences end with “.”:" }, { "code": null, "e": 3888, "s": 3861, "text": "first_dialogue.split(\".\")\n" }, { "code": null, "e": 4947, "s": 3888, "text": "['Do you know what this is all about? Do you know, why were here? To be out, this is out',\n '',\n '',\n 'and out is one of the single most enjoyable experiences of life',\n ' People',\n '',\n '',\n 'did you ever hear people talking about We should go out? This is what theyre talking about',\n '',\n '',\n 'this whole thing, were all out now, no one is home',\n ' Not one person here is home, were all out! There are people tryin to find us, they dont know where we are',\n ' (on an imaginary phone) Did you ring?, I cant find him',\n ' Where did he go? He didnt tell me where he was going',\n ' He must have gone out',\n ' You wanna go out you get ready, you pick out the clothes, right? You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation',\n '',\n '',\n 'Then youre standing around, whatta you do? You go We gotta be getting back',\n ' Once youre out, you wanna get back! You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? Where ever you are in life, its my feeling, youve gotta go',\n '']" }, { "code": null, "e": 5404, "s": 4947, "text": "Not so good, right? I see that split() is used in many articles for word tokenization. Which might be acceptable because it splits texts by taking care of extra spaces, etc. For sentence tokenization, it just doesn’t work. You might use replace() and then split() to replace all end-of-line characters with one character and split the text into sentences using that character. It would give a better result, but the performance of your code would decrease." }, { "code": null, "e": 5565, "s": 5404, "text": "Another problem is we’re losing the character we used for splitting. If we aggregated the transformed data, we wouldn’t have the original punctuations any more." }, { "code": null, "e": 5793, "s": 5565, "text": "Regular expression is always useful if you’re working on texts. It’s a quite old and robust approach. Many programming languages offer it natively. So, you can use your regex across different languages with small or no changes." }, { "code": null, "e": 5917, "s": 5793, "text": "Let’s give it a try to one of the accepted answers on Stackoverflow (with a small change, by adding |! to the third group):" }, { "code": null, "e": 6003, "s": 5917, "text": "import re\n\n\nre.split(r\"(?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=\\.|\\?|!)\\s\", first_dialogue)\n" }, { "code": null, "e": 7046, "s": 6003, "text": "['Do you know what this is all about?',\n 'Do you know, why were here?',\n 'To be out, this is out...and out is one of the single most enjoyable experiences of life.',\n 'People...did you ever hear people talking about We should go out?',\n 'This is what theyre talking about...this whole thing, were all out now, no one is home.',\n 'Not one person here is home, were all out!',\n 'There are people tryin to find us, they dont know where we are.',\n '(on an imaginary phone) Did you ring?, I cant find him.',\n 'Where did he go?',\n 'He didnt tell me where he was going.',\n 'He must have gone out.',\n 'You wanna go out you get ready, you pick out the clothes, right?',\n 'You take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...Then youre standing around, whatta you do?',\n 'You go We gotta be getting back.',\n 'Once youre out, you wanna get back!',\n 'You wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right?',\n 'Where ever you are in life, its my feeling, youve gotta go.']" }, { "code": null, "e": 7138, "s": 7046, "text": "Let me explain the regex pattern: (?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=\\.|\\?|!)\\s step by step:" }, { "code": null, "e": 7478, "s": 7138, "text": "(?<!X)Y is called negative lookbehind. It tries to capture Y (any whitespace character \\s in our case) where preceded characters of Y do not match with X. For example, let’s say you have this regex: (?<!TEST)MATCH . If your text is “TESTMATCH”, it will not match, if it’s “RANDOM_MATCH” (preceded characters are not “TEST”), it will match." }, { "code": null, "e": 7686, "s": 7478, "text": "(?<=X)Y is called positive lookbehind. It tries to capture Y (any whitespace character \\s in our case) where preceded characters of Y match with X. Let’s use the same example as above and check the outcomes:" }, { "code": null, "e": 7947, "s": 7686, "text": "In our regex, we have three capturing groups: the first two are looking for negative lookbehind and the last one is looking for a positive lookbehind. Now, let’s look at the inside of these capturing groups to understand what kind of strings we’re looking for:" }, { "code": null, "e": 8204, "s": 7947, "text": "Inside of the first capturing group is as follows: \\w\\.\\w. . \\w matches any word character (letter, number, or underscore). \\. matches literal dot character (backslash is the escape character in regex). . matches any character. An example match: i.e. MATCH" }, { "code": null, "e": 8363, "s": 8204, "text": "Inside of the second capturing group is [A-Z][a-z]\\. . It matches any lowercase or uppercase letter following with dot character. An example match:Mr. MATCH ." }, { "code": null, "e": 8650, "s": 8363, "text": "Inside of the third capturing group is \\.|\\?|! . We already know that \\ is used for literal characters. | means to match either the first part or the latter part. In other words, (A|B|C) means either match A, B or C. In our case, it will match either dot, question, or exclamation mark." }, { "code": null, "e": 8897, "s": 8650, "text": "We may finally know all we need to know about our regex. To sum up, we’re searching for whitespace characters by checking its preceded characters. If it passes from our three validations, we match it. So, we can split the text from these matches." }, { "code": null, "e": 8933, "s": 8897, "text": "The disadvantage of using regex is:" }, { "code": null, "e": 9079, "s": 8933, "text": "It might be quite painful to explain what is going on! It’s not intuitive. You should spend some time to learn it, otherwise, it will look scary." }, { "code": null, "e": 9187, "s": 9079, "text": "You might create infinite loops or low-performance regular expressions if you’re not much familiar with it." }, { "code": null, "e": 9324, "s": 9187, "text": "It’s not easy to cover edge cases before you face with them. When you start to write a regex, you might easily miss some of these cases." }, { "code": null, "e": 9668, "s": 9324, "text": "Our regex relies on whitespace characters. If there is no whitespace between two sentences, then it doesn’t match anything. So, it might fail if your text is not properly formatted. For example, if you give this text to our regex, “This is an example sentence.This is another one without space after the dot.”, it will think it’s one sentence." }, { "code": null, "e": 9701, "s": 9668, "text": "The advantage of using regex is:" }, { "code": null, "e": 9750, "s": 9701, "text": "You don’t need to rely on third-party libraries." }, { "code": null, "e": 9865, "s": 9750, "text": "It’s lightning fast because just as many of Python’s built-in functions, re module is converted and executed on C." }, { "code": null, "e": 10249, "s": 9865, "text": "It exists since the 1950s, and it’s a quite known thing for string search, replace, etc. You can write one regex in Python and use it in Javascript with minor changes. You only need to know the programming language specific behaviours, the rest will be easy. But, you can’t use a Python library in Javascript. If you can, you will need a workaround, or you will use a Python API etc." }, { "code": null, "e": 10689, "s": 10249, "text": "spaCy is capable of preprocessing texts in many languages. It offers tokenization, lemmatization, linguistic features, creating pipelines, training, running on GPU, etc. So, it’s a resourceful and powerful library. If you have unstructured text data such as scraped texts from the web, I’d suggest using it without any hesitation. If you think of only doing basic preprocessing, it might add extra complexity which you don’t actually need." }, { "code": null, "e": 10856, "s": 10689, "text": "Before you try spaCy’s tokenization, you should download the library and one of its models. We will use the small English model which will be sufficient for our task." }, { "code": null, "e": 11310, "s": 10856, "text": "This approach takes a long time. However, this is a bit misleading because spaCy might work much faster. It took a long time because we need to convert each value to an nlp object and we used the default sentence segmentation component. It is called DependencyParser. It’s possible to modify -to remove dependency parser and use custom segmentation- nlp() object and define it without using any model. Let’s use sentencizer pipeline component this time:" }, { "code": null, "e": 11465, "s": 11310, "text": "As you can see, there is a trade-off between the speed and the result. sentencizer struggled just as nltk and regex because it uses a rule-based strategy." }, { "code": null, "e": 11498, "s": 11465, "text": "The advantage of using spaCy is:" }, { "code": null, "e": 11581, "s": 11498, "text": "It is a well-documented library which is maintained actively by a large community." }, { "code": null, "e": 11639, "s": 11581, "text": "It offers tons of NLP functionalities that you might use." }, { "code": null, "e": 11710, "s": 11639, "text": "It supports many languages such as German, Dutch, French, and Chinese." }, { "code": null, "e": 11746, "s": 11710, "text": "The disadvantage of using spaCy is:" }, { "code": null, "e": 11790, "s": 11746, "text": "It’s slower than re module in normal usage." }, { "code": null, "e": 11875, "s": 11790, "text": "It might be overkill to include it to your project and use it only for tokenization." }, { "code": null, "e": 12091, "s": 11875, "text": "nltk is another NLP library which you may use for text processing. It is natively supporting sentence tokenization as spaCy. To use its sent_tokenize function, you should download punkt (default sentence tokenizer)." }, { "code": null, "e": 12194, "s": 12091, "text": "nltk tokenizer gave almost the same result with regex. It struggled and couldn’t split many sentences." }, { "code": null, "e": 12525, "s": 12194, "text": "When we check the results carefully, we see that spaCy with the dependency parse outperforms others in sentence tokenization. It is handling the case which two sentences do not have whitespace character between them. It also handles if there are two sentences and there is only a space between them. Thus, it gave the best result." }, { "code": null, "e": 12719, "s": 12525, "text": "I’m going to benchmark when I apply these tokenizations to all data. We will also see their speed. I’m going to skip split() for benchmarking. It is so obvious that we can’t consider to use it." }, { "code": null, "e": 12918, "s": 12719, "text": "We will create lambda functions and use Pandas DataFrame’s apply method. Before transforming the whole data, I’d like to test the performances using the first 5000 rows. The outcomes are as follows:" }, { "code": null, "e": 13388, "s": 12918, "text": "As you can see, regex is blazingly fast. It’s 10x faster than nltk and spaCy with sentencizer! It’s ~1600x faster than spaCy with the dependency parse. Yet, you might try to increase spaCy’s speed more. You may use nlp.pipe which helps to send column values in a batch instead of one-by-one. You might also modify your code to run spaCy transformation using multiprocessing. However, I’m not going to show it here. You can check the link in the further reading section." }, { "code": null, "e": 13471, "s": 13388, "text": "I’m going to use the first approach we have used in spaCy to transform whole data:" }, { "code": null, "e": 13591, "s": 13471, "text": "nlp = spacy.load(\"en_core_web_sm\")df[\"Dialogue\"] = df[\"Dialogue\"].apply(lambda x: [sent.text for sent in nlp(x).sents])" }, { "code": null, "e": 13977, "s": 13591, "text": "We have transformed data, which have a list of sentences in each Dialogue column. And it may not useful for further analysis. Luckily, Pandas offers an elegant method which will help us to create new rows for each sentence in the lists. We will replicate the values in other columns, but our Dialogue column will have only one sentence in a row. And, its type will be string, not list." }, { "code": null, "e": 14977, "s": 13977, "text": "Okay, that’s it! In the first cell, we called explode() method with ignore_index parameter, it will create a new index for each row but it will keep the previous index values in another column named Unnamed 0 . In the second cell, the new index and the previous index values are renamed to Sentence ID and Dialogue ID respectively. It is important to keep the track of your original data and allow yourself to transform backwardly. Because you may make amazing analysis in the sentence level, after you’re done you may want to see the results in the dialogue level. It might sound silly for this task but it might be useful in other text corpora. In our case, we can use Dialogue ID if we would like to return to original data because we’re 100% sure that it has unique IDs for each dialogue. A simple group_by() with correct aggregation parameters (taking first values for existing columns, and taking sum/mean etc. for the new columns that we add for analysis) would give use the original version." }, { "code": null, "e": 15060, "s": 14977, "text": "We have come up to the last point. Let’s save our file, and complete our tutorial:" }, { "code": null, "e": 15095, "s": 15060, "text": "df.to_csv(\"scripts_tokenized.csv\")" }, { "code": null, "e": 15365, "s": 15095, "text": "In this tutorial, I have tried to show you a few different approaches to sentence tokenization. These approaches are not the only approaches we have currently. NLP is quite a big subject and I’m sure you may find alternatives. I tried to select the prevalent libraries." }, { "code": null, "e": 15589, "s": 15365, "text": "If you think of further text preprocessing, I would certainly suggest using spaCy. Because it is easy-to-use, documentations are richly detailed, its community has almost 500 members, and new features are constantly coming." }, { "code": null, "e": 15793, "s": 15589, "text": "If you think of tokenizing your text only, I would reformat the text a bit, and then would use regex, so that importing Python’s re module to my script would be enough instead of adding new dependencies." }, { "code": null, "e": 15824, "s": 15793, "text": "Full working code in one gist:" }, { "code": null, "e": 15858, "s": 15824, "text": "Thanks for reading up to the end!" }, { "code": null, "e": 16020, "s": 15858, "text": "Multiprocessing on spaCy: https://prrao87.github.io/blog/spacy/nlp/performance/2020/05/02/spacy-multiprocess.html#Option-1:-Sequentially-process-DataFrame-column" }, { "code": null, "e": 16182, "s": 16020, "text": "Multiprocessing on spaCy: https://prrao87.github.io/blog/spacy/nlp/performance/2020/05/02/spacy-multiprocess.html#Option-1:-Sequentially-process-DataFrame-column" }, { "code": null, "e": 16591, "s": 16182, "text": "Sentence Segmentation — SpaCy: https://spacy.io/usage/linguistic-features#sbd-componentPunk sentence tokenizer: https://www.nltk.org/_modules/nltk/tokenize/punkt.htmlRegex sentence tokenizer: https://stackoverflow.com/a/25736082/9686506Regex cheatsheet: https://www.rexegg.com/regex-disambiguation.htmlPandas explode(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" }, { "code": null, "e": 16679, "s": 16591, "text": "Sentence Segmentation — SpaCy: https://spacy.io/usage/linguistic-features#sbd-component" }, { "code": null, "e": 16759, "s": 16679, "text": "Punk sentence tokenizer: https://www.nltk.org/_modules/nltk/tokenize/punkt.html" }, { "code": null, "e": 16830, "s": 16759, "text": "Regex sentence tokenizer: https://stackoverflow.com/a/25736082/9686506" }, { "code": null, "e": 16897, "s": 16830, "text": "Regex cheatsheet: https://www.rexegg.com/regex-disambiguation.html" } ]
How to remove html tags from a string in JavaScript?
We can remove HTML/XML tags in a string using regular expressions in javascript. HTML elements such as span, div etc. are present between left and right arrows for instance <div>,<span> etc. So replacing the content within the arrows, along with the arrows, with nothing('') can make our task easy. str.replace( /(<([^>]+)>)/ig, ''); Live Demo <html> <body> <script> function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); return str.replace( /(<([^>]+)>)/ig, ''); } document.write(removeTags('<html> <body> Javascript<body> is not Java'));; </script> </body> </html> Javascript is not Java Live Demo <html> <body> <script> function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); return str.replace( /(<([^>]+)>)/ig, ''); } document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));; </script> </body> </html> Tutorix is the best e-learning platform
[ { "code": null, "e": 1361, "s": 1062, "text": "We can remove HTML/XML tags in a string using regular expressions in javascript. HTML elements such as span, div etc. are present between left and right arrows for instance <div>,<span> etc. So replacing the content within the arrows, along with the arrows, with nothing('') can make our task easy." }, { "code": null, "e": 1396, "s": 1361, "text": "str.replace( /(<([^>]+)>)/ig, '');" }, { "code": null, "e": 1406, "s": 1396, "text": "Live Demo" }, { "code": null, "e": 1713, "s": 1406, "text": "<html>\n<body>\n<script>\n function removeTags(str) {\n if ((str===null) || (str===''))\n return false;\n else\n str = str.toString();\n return str.replace( /(<([^>]+)>)/ig, '');\n }\n document.write(removeTags('<html> <body> Javascript<body> is not Java'));;\n</script>\n</body>\n</html>" }, { "code": null, "e": 1736, "s": 1713, "text": "Javascript is not Java" }, { "code": null, "e": 1746, "s": 1736, "text": "Live Demo" }, { "code": null, "e": 2073, "s": 1746, "text": "<html>\n<body>\n<script>\n function removeTags(str) {\n if ((str===null) || (str===''))\n return false;\n else\n str = str.toString();\n return str.replace( /(<([^>]+)>)/ig, '');\n }\n document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));;\n</script>\n</body>\n</html>" }, { "code": null, "e": 2113, "s": 2073, "text": "Tutorix is the best e-learning platform" } ]
Terraform 101 | by Shanika Perera | Towards Data Science
If you’re a DevOps engineer or someone that has to deal with DevOps-related work in your day-to-day work-life, I’m certain that you have heard about the Infrastructure as Code (IaC) concept. Simply, IaC is something that has fallen right out from Heaven to lend a helping hand to everyday struggling DevOps engineers. IaC is the method of using machine-readable definition files to manage and provision an entire IT infrastructure. Using programming scripts, aids in the automation of the whole IT infrastructure. IaC has many benefits around it. It allows faster execution when configuring infrastructure, helps reduce the cost as well as the risk associated with implementing infrastructure, has full traceability of the changes, etc. There are several IaC tools in the market right now. Today I’m going to explain about Terraform, which has caught the eye of many IT engineers. According to the official Terraform documentation, Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. It is an open-source IaC tool developed by HashiCorp. It looks a lot like CloudFormation, which is used to automate AWS infrastructure. You can use Terraform on other cloud services as well. Terraform creates an execution plan that explains how it will get to the desired state and then implements it to build the infrastructure specified. Terraform can decide what changed as the configuration changes and build gradual execution plans that can be implemented. Input Variables — Serve as parameters for a Terraform module, so users can customize behavior without editing the source Modules — Acts as a container for multiple resources that are used together. It is a way to package and reuse resource configurations. Resources — Documents the syntax for declaring resources Data sources — Allow data to be fetched or computed for use elsewhere in Terraform configuration Output values — Return values for a Terraform module Local values — A convenience feature for assigning a short name to an expression terraform init — Initializes the working directory which consists of all the configuration files terraform validate — Validates the configuration files in a directory terraform plan — Creates an execution plan to reach a desired state of the infrastructure terraform apply — Makes the changes in the infrastructure as defined in the plan terraform destroy — Deletes all the old infrastructure resources For this tutorial, I’m going to work with the AWS platform. To connect with our AWS account and the Terraform code, we need to set up the AWS user credentials. Ensure that the user credentials you’re using have access to the resources you’re going to provision. Get a hold of the AWS Access key and the Secret access key of the IAM user with the right permissions and save it in a secure place. We will be needing this later in the tutorial. As I’m using Linux, I’ll provide the necessary commands for installing Terraform in Linux distribution in this tutorial. For other OS, please visit this webpage to install Terraform accordingly. To add the HashiCorp GPG key — curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add - To Add the official HashiCorp Linux repository — sudo apt-add-repository “deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main” Update and install — sudo apt-get update && sudo apt-get install terraform Verify the installation — terraform -help Since we’re dealing with AWS, we need to provide the credentials that we retrieved earlier to connect with our respective AWS resources. To set the AWS credentials in your command-line workspace, export AWS_ACCESS_KEY_ID=(access key)export AWS_SECRET_ACCESS_KEY=(secret access key) Terraform can build infrastructure on several platforms, or providers, such as AWS, Azure, Google Cloud, DigitalOcean, and others. Usually, the first step in using Terraform is to set up the provider you want to use. Make a file named aws.tf and insert the code below into it. As the first step, we’ll learn how to deploy a simple EC2 instance in AWS. Terraform has well-explained documentation about their language, syntaxes, resources, etc. Below mentioned is the code that you need to deploy a t2.micro instance. Note that this is just a simple code snippet to create an ec2 instance. There are many attributes that you can specify such as the availability zone, security group, EBS information, private key value, etc. These attributes can be found on the official resource pages of respective hashicorp documentation. **(Please note that I’m using separate files for each resource because it’s easy to manage and understand. You can copy and paste both aws.tf file and ec2.tf file content in one file called main.tf and get the same output.)** In a terminal, go to the folder that you created ec2.tf and aws.tf and run terraform init command. The terraform init command creates a working directory in which Terraform configuration files can be found. After creating a new Terraform configuration or cloning an existing one from version control, you have to run this command first. It is appropriate to use this command more than once. You can run terraform validate to make sure that your code is valid. If there are any errors in the syntax or missing data, this will display that. Our code is initialized and validated. We can run terraform plan to see the execution plan. This is a fantastic way to double-check the changes before executing them. If you don’t specify any VPC, subnet IDs, this configuration will create the resources in the default VPC with respective default values. To actually create the resources, run terraform apply. As you can see, we have now successfully created our first ec2 instance with the help of Terraform. If you navigate to your AWS console, you’ll see something like this. Let’s say you need to change something in your instance. You can edit the ec2.tf file and run terraform plan again. It will show you what’s going to be created, modified, or deleted. If I want to add a new Env tag, this is how the execution plan will look like. Now that you have a slight idea about how Terraform works, in this section I’ll explain how you can write and use Terraform modules. Imagine you’re working in a company that handles multiple AWS resources. For example, you have 5 instances for the Dev environment, another 5 instances for the QA environment, etc. Instead of writing the same terraform resource block, we can create modules and reuse that code which will act as a template. In your current working directory, create a folder named “modules”. Inside that create two folders named “dev-instance”, “qa-instance”. I’ll leave the GitHub link for this project at the end of the tutorial. You can find the file structure and all these files in that repository. To separate the modules from each other, I have specified a tag named “Dev” in the dev-instance module and “QA” in the qa-instance module. So, when we’re using these modules, these tags will be added to the respective resource. I have also changed the root ebs volume size in both modules. This is how the ec2.tf file should change when we’re using modules. Unlike in the previous section, now we’re using module block to create resources. If you’re using a module block, it is a must to provide the source of that module. In our case, it is the modules that we defined earlier locally. You can provide different source types such as Github, Bitbucket, HTTP URLs, Terraform Registry, etc. As you can see, I have used variables in this script. Variables are defined in a separate file called variables.tf. You can use them anywhere in your script with the unique name you provide. Eg- var.ami_id, var.instance_type. You can provide a default AMI ID in the module definition, in the variables.tf file as a variable or manually apply an ID as I have done here. The outputs.tf file is shown below. Each output value exported by a module must be declared using the output block. If you go to the module outputs files, I have declared two outputs in each module which will return the instance ID and the public IP of the instance. Now that we’re using the modules, we can call the output values by the respective module names as shown below. Syntax - module.<module-name>.<output-name-mentioned-in-module> It’s time to create these resources. You have to run terraform init to initialize the newly created modules. Run terraform validate to check whether our script configurations are valid. If it’s valid run terraform plan to see the execution plan. module.dev_server has the environment tag as “Dev” while module.qa_server has its environment tag as “QA” as we specified separately in the modules. When you have an outputs.tf file, you will see the return values in the terraform plan like shown below. When you’re done with experimenting with Terraform, make sure to clean up the environment to prevent unnecessary costs. Simply run terraform destroy and it will also display the resources that you’re going to destroy. If you’re certain, type yes and the specified resources will be destroyed accordingly. Github Link — https://github.com/Shani1116/terraform-101 Congratulations 😻 At last, you now have a basic understanding of using Terraform. But we’ve just begun to scratch the surface. In the future, I’ll publish more Terraform-related blog posts. What am I missing here? Let me know in the comments and I’ll add it in. Keep in touch for more cool stuff!
[ { "code": null, "e": 784, "s": 47, "text": "If you’re a DevOps engineer or someone that has to deal with DevOps-related work in your day-to-day work-life, I’m certain that you have heard about the Infrastructure as Code (IaC) concept. Simply, IaC is something that has fallen right out from Heaven to lend a helping hand to everyday struggling DevOps engineers. IaC is the method of using machine-readable definition files to manage and provision an entire IT infrastructure. Using programming scripts, aids in the automation of the whole IT infrastructure. IaC has many benefits around it. It allows faster execution when configuring infrastructure, helps reduce the cost as well as the risk associated with implementing infrastructure, has full traceability of the changes, etc." }, { "code": null, "e": 928, "s": 784, "text": "There are several IaC tools in the market right now. Today I’m going to explain about Terraform, which has caught the eye of many IT engineers." }, { "code": null, "e": 979, "s": 928, "text": "According to the official Terraform documentation," }, { "code": null, "e": 1175, "s": 979, "text": "Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions." }, { "code": null, "e": 1637, "s": 1175, "text": "It is an open-source IaC tool developed by HashiCorp. It looks a lot like CloudFormation, which is used to automate AWS infrastructure. You can use Terraform on other cloud services as well. Terraform creates an execution plan that explains how it will get to the desired state and then implements it to build the infrastructure specified. Terraform can decide what changed as the configuration changes and build gradual execution plans that can be implemented." }, { "code": null, "e": 1758, "s": 1637, "text": "Input Variables — Serve as parameters for a Terraform module, so users can customize behavior without editing the source" }, { "code": null, "e": 1893, "s": 1758, "text": "Modules — Acts as a container for multiple resources that are used together. It is a way to package and reuse resource configurations." }, { "code": null, "e": 1950, "s": 1893, "text": "Resources — Documents the syntax for declaring resources" }, { "code": null, "e": 2047, "s": 1950, "text": "Data sources — Allow data to be fetched or computed for use elsewhere in Terraform configuration" }, { "code": null, "e": 2100, "s": 2047, "text": "Output values — Return values for a Terraform module" }, { "code": null, "e": 2181, "s": 2100, "text": "Local values — A convenience feature for assigning a short name to an expression" }, { "code": null, "e": 2278, "s": 2181, "text": "terraform init — Initializes the working directory which consists of all the configuration files" }, { "code": null, "e": 2348, "s": 2278, "text": "terraform validate — Validates the configuration files in a directory" }, { "code": null, "e": 2438, "s": 2348, "text": "terraform plan — Creates an execution plan to reach a desired state of the infrastructure" }, { "code": null, "e": 2519, "s": 2438, "text": "terraform apply — Makes the changes in the infrastructure as defined in the plan" }, { "code": null, "e": 2584, "s": 2519, "text": "terraform destroy — Deletes all the old infrastructure resources" }, { "code": null, "e": 3026, "s": 2584, "text": "For this tutorial, I’m going to work with the AWS platform. To connect with our AWS account and the Terraform code, we need to set up the AWS user credentials. Ensure that the user credentials you’re using have access to the resources you’re going to provision. Get a hold of the AWS Access key and the Secret access key of the IAM user with the right permissions and save it in a secure place. We will be needing this later in the tutorial." }, { "code": null, "e": 3221, "s": 3026, "text": "As I’m using Linux, I’ll provide the necessary commands for installing Terraform in Linux distribution in this tutorial. For other OS, please visit this webpage to install Terraform accordingly." }, { "code": null, "e": 3252, "s": 3221, "text": "To add the HashiCorp GPG key —" }, { "code": null, "e": 3323, "s": 3252, "text": "curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -" }, { "code": null, "e": 3372, "s": 3323, "text": "To Add the official HashiCorp Linux repository —" }, { "code": null, "e": 3474, "s": 3372, "text": "sudo apt-add-repository “deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main”" }, { "code": null, "e": 3495, "s": 3474, "text": "Update and install —" }, { "code": null, "e": 3549, "s": 3495, "text": "sudo apt-get update && sudo apt-get install terraform" }, { "code": null, "e": 3575, "s": 3549, "text": "Verify the installation —" }, { "code": null, "e": 3591, "s": 3575, "text": "terraform -help" }, { "code": null, "e": 3787, "s": 3591, "text": "Since we’re dealing with AWS, we need to provide the credentials that we retrieved earlier to connect with our respective AWS resources. To set the AWS credentials in your command-line workspace," }, { "code": null, "e": 3873, "s": 3787, "text": "export AWS_ACCESS_KEY_ID=(access key)export AWS_SECRET_ACCESS_KEY=(secret access key)" }, { "code": null, "e": 4150, "s": 3873, "text": "Terraform can build infrastructure on several platforms, or providers, such as AWS, Azure, Google Cloud, DigitalOcean, and others. Usually, the first step in using Terraform is to set up the provider you want to use. Make a file named aws.tf and insert the code below into it." }, { "code": null, "e": 4389, "s": 4150, "text": "As the first step, we’ll learn how to deploy a simple EC2 instance in AWS. Terraform has well-explained documentation about their language, syntaxes, resources, etc. Below mentioned is the code that you need to deploy a t2.micro instance." }, { "code": null, "e": 4696, "s": 4389, "text": "Note that this is just a simple code snippet to create an ec2 instance. There are many attributes that you can specify such as the availability zone, security group, EBS information, private key value, etc. These attributes can be found on the official resource pages of respective hashicorp documentation." }, { "code": null, "e": 4922, "s": 4696, "text": "**(Please note that I’m using separate files for each resource because it’s easy to manage and understand. You can copy and paste both aws.tf file and ec2.tf file content in one file called main.tf and get the same output.)**" }, { "code": null, "e": 5021, "s": 4922, "text": "In a terminal, go to the folder that you created ec2.tf and aws.tf and run terraform init command." }, { "code": null, "e": 5313, "s": 5021, "text": "The terraform init command creates a working directory in which Terraform configuration files can be found. After creating a new Terraform configuration or cloning an existing one from version control, you have to run this command first. It is appropriate to use this command more than once." }, { "code": null, "e": 5461, "s": 5313, "text": "You can run terraform validate to make sure that your code is valid. If there are any errors in the syntax or missing data, this will display that." }, { "code": null, "e": 5766, "s": 5461, "text": "Our code is initialized and validated. We can run terraform plan to see the execution plan. This is a fantastic way to double-check the changes before executing them. If you don’t specify any VPC, subnet IDs, this configuration will create the resources in the default VPC with respective default values." }, { "code": null, "e": 5821, "s": 5766, "text": "To actually create the resources, run terraform apply." }, { "code": null, "e": 5990, "s": 5821, "text": "As you can see, we have now successfully created our first ec2 instance with the help of Terraform. If you navigate to your AWS console, you’ll see something like this." }, { "code": null, "e": 6252, "s": 5990, "text": "Let’s say you need to change something in your instance. You can edit the ec2.tf file and run terraform plan again. It will show you what’s going to be created, modified, or deleted. If I want to add a new Env tag, this is how the execution plan will look like." }, { "code": null, "e": 6385, "s": 6252, "text": "Now that you have a slight idea about how Terraform works, in this section I’ll explain how you can write and use Terraform modules." }, { "code": null, "e": 6692, "s": 6385, "text": "Imagine you’re working in a company that handles multiple AWS resources. For example, you have 5 instances for the Dev environment, another 5 instances for the QA environment, etc. Instead of writing the same terraform resource block, we can create modules and reuse that code which will act as a template." }, { "code": null, "e": 6972, "s": 6692, "text": "In your current working directory, create a folder named “modules”. Inside that create two folders named “dev-instance”, “qa-instance”. I’ll leave the GitHub link for this project at the end of the tutorial. You can find the file structure and all these files in that repository." }, { "code": null, "e": 7262, "s": 6972, "text": "To separate the modules from each other, I have specified a tag named “Dev” in the dev-instance module and “QA” in the qa-instance module. So, when we’re using these modules, these tags will be added to the respective resource. I have also changed the root ebs volume size in both modules." }, { "code": null, "e": 7661, "s": 7262, "text": "This is how the ec2.tf file should change when we’re using modules. Unlike in the previous section, now we’re using module block to create resources. If you’re using a module block, it is a must to provide the source of that module. In our case, it is the modules that we defined earlier locally. You can provide different source types such as Github, Bitbucket, HTTP URLs, Terraform Registry, etc." }, { "code": null, "e": 8030, "s": 7661, "text": "As you can see, I have used variables in this script. Variables are defined in a separate file called variables.tf. You can use them anywhere in your script with the unique name you provide. Eg- var.ami_id, var.instance_type. You can provide a default AMI ID in the module definition, in the variables.tf file as a variable or manually apply an ID as I have done here." }, { "code": null, "e": 8408, "s": 8030, "text": "The outputs.tf file is shown below. Each output value exported by a module must be declared using the output block. If you go to the module outputs files, I have declared two outputs in each module which will return the instance ID and the public IP of the instance. Now that we’re using the modules, we can call the output values by the respective module names as shown below." }, { "code": null, "e": 8472, "s": 8408, "text": "Syntax - module.<module-name>.<output-name-mentioned-in-module>" }, { "code": null, "e": 8581, "s": 8472, "text": "It’s time to create these resources. You have to run terraform init to initialize the newly created modules." }, { "code": null, "e": 8718, "s": 8581, "text": "Run terraform validate to check whether our script configurations are valid. If it’s valid run terraform plan to see the execution plan." }, { "code": null, "e": 8867, "s": 8718, "text": "module.dev_server has the environment tag as “Dev” while module.qa_server has its environment tag as “QA” as we specified separately in the modules." }, { "code": null, "e": 8972, "s": 8867, "text": "When you have an outputs.tf file, you will see the return values in the terraform plan like shown below." }, { "code": null, "e": 9277, "s": 8972, "text": "When you’re done with experimenting with Terraform, make sure to clean up the environment to prevent unnecessary costs. Simply run terraform destroy and it will also display the resources that you’re going to destroy. If you’re certain, type yes and the specified resources will be destroyed accordingly." }, { "code": null, "e": 9334, "s": 9277, "text": "Github Link — https://github.com/Shani1116/terraform-101" } ]
Blocking Methods in Java - GeeksforGeeks
14 Sep, 2021 Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods. For example, the InputStream read() method blocks until all InputStream data has been completely read. Here are some of the most common Java blocking methods: InvokeAndWait(): Wait for the Event Dispatcher thread to execute code.InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream.ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made.CountDownLatch.await(): Cause the current thread to wait until the latch counts to zero unless the thread is interrupted. InvokeAndWait(): Wait for the Event Dispatcher thread to execute code. InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream. ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made. CountDownLatch.await(): Cause the current thread to wait until the latch counts to zero unless the thread is interrupted. There are several disadvantages of blocking methods: Blocking techniques pose a significant threat to system scalability. A classic blocking solution consists of ways to mitigate blocking, using multiple threads to serve multiple customers. Design is the most important aspect since even if a multi-threaded system cannot reach beyond a certain point, a poorly designed system can only support several hundred or thousands of threads because of the limited number of JVM threads. Implementation: Here in the below example, following the execution of the first print statement, the program will be blocked by a second print statement until some characters are entered in the console. Then click enter because read() blocks the method until some input is readable. Example 1: Java // Java Program to illsutare Blocking methods // Importing all input output classesimport java.io.*; // Classclass GFG { // main driver method public static void main(String args[]) throws FileNotFoundException, IOException { // Print statement System.out.println("GFG"); int result; result = System.in.read(); // Print statement System.out.println("Geeks for Geeks"); } } GFG Geeks for Geeks Example 2: Here in this example, CountDownLatch.await() is used when a thread needs to wait for other threads before starting its work. CountDown() method decreases count and wait() method blocks until count == 0. Java // Java Program to illsutare Blocking methods // Importing all input output classesimport java.io.*;// Importing concurrent CountDownLatch class// from java.util packageimport java.util.concurrent.CountDownLatch; // Classclass GFG { // Main driver method public static void main(String args[]) throws InterruptedException { // Let us create task that is going to wait // for five threads before it starts CountDownLatch latch = new CountDownLatch(4); // Creating threads of Person type // Custom parameter inputs Person p1 = new Person(1500, latch, "PERSON-1"); Person p2 = new Person(2500, latch, "PERSON-2"); Person p3 = new Person(3500, latch, "PERSON-3"); Person p4 = new Person(4500, latch, "PERSON-4"); Person p5 = new Person(5500, latch, "PERSON-5"); // Starting the thread // using the start() method p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); // Waiting for the four threads // using the latch.await() method latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + " has finished his work"); }} // Class 2// Helper class extending Thread class// To represent threads for which the main thread waitsclass Person extends Thread { // Member variables of this class private int delay; private CountDownLatch latch; // Method of this class public Person(int delay, CountDownLatch latch, String name) { // super refers to parent class super(name); // This keyword refers to current object itself this.delay = delay; this.latch = latch; } @Override public void run() { // Try block to check for exceptions try { Thread.sleep(delay); latch.countDown(); // Print the current thread by getting its name // using the getName() method // of whose work is completed System.out.println( Thread.currentThread().getName() + " has finished his work"); } // Catch block to handle the exception catch (InterruptedException e) { // Print the line number where exception occured // using the printStackTrace() method e.printStackTrace(); } }} PERSON-1 has finished his work PERSON-2 has finished his work PERSON-3 has finished his work PERSON-4 has finished his work main has finished his work PERSON-5 has finished his work sagartomar9927 simmytarika5 Java-Multithreading Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24007, "s": 23979, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24459, "s": 24007, "text": "Blocking methods in java are the particular set of methods that block the thread until its operation is complete. So, they will have to block the current thread until the condition that fulfills their task is satisfied. Since, in nature, these methods are blocking so-called blocking methods. For example, the InputStream read() method blocks until all InputStream data has been completely read. Here are some of the most common Java blocking methods:" }, { "code": null, "e": 24874, "s": 24459, "text": "InvokeAndWait(): Wait for the Event Dispatcher thread to execute code.InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream.ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made.CountDownLatch.await(): Cause the current thread to wait until the latch counts to zero unless the thread is interrupted." }, { "code": null, "e": 24945, "s": 24874, "text": "InvokeAndWait(): Wait for the Event Dispatcher thread to execute code." }, { "code": null, "e": 25061, "s": 24945, "text": "InputStream.read(): It blocks until input data is available, throws an exception, or detects the end of the stream." }, { "code": null, "e": 25170, "s": 25061, "text": "ServerSocket.accept(): Listen to inbound Java socket connection and blocks until a connection has been made." }, { "code": null, "e": 25292, "s": 25170, "text": "CountDownLatch.await(): Cause the current thread to wait until the latch counts to zero unless the thread is interrupted." }, { "code": null, "e": 25345, "s": 25292, "text": "There are several disadvantages of blocking methods:" }, { "code": null, "e": 25533, "s": 25345, "text": "Blocking techniques pose a significant threat to system scalability. A classic blocking solution consists of ways to mitigate blocking, using multiple threads to serve multiple customers." }, { "code": null, "e": 25772, "s": 25533, "text": "Design is the most important aspect since even if a multi-threaded system cannot reach beyond a certain point, a poorly designed system can only support several hundred or thousands of threads because of the limited number of JVM threads." }, { "code": null, "e": 25788, "s": 25772, "text": "Implementation:" }, { "code": null, "e": 26055, "s": 25788, "text": "Here in the below example, following the execution of the first print statement, the program will be blocked by a second print statement until some characters are entered in the console. Then click enter because read() blocks the method until some input is readable." }, { "code": null, "e": 26066, "s": 26055, "text": "Example 1:" }, { "code": null, "e": 26071, "s": 26066, "text": "Java" }, { "code": "// Java Program to illsutare Blocking methods // Importing all input output classesimport java.io.*; // Classclass GFG { // main driver method public static void main(String args[]) throws FileNotFoundException, IOException { // Print statement System.out.println(\"GFG\"); int result; result = System.in.read(); // Print statement System.out.println(\"Geeks for Geeks\"); } }", "e": 26488, "s": 26071, "text": null }, { "code": null, "e": 26508, "s": 26488, "text": "GFG\nGeeks for Geeks" }, { "code": null, "e": 26519, "s": 26508, "text": "Example 2:" }, { "code": null, "e": 26723, "s": 26519, "text": "Here in this example, CountDownLatch.await() is used when a thread needs to wait for other threads before starting its work. CountDown() method decreases count and wait() method blocks until count == 0." }, { "code": null, "e": 26728, "s": 26723, "text": "Java" }, { "code": "// Java Program to illsutare Blocking methods // Importing all input output classesimport java.io.*;// Importing concurrent CountDownLatch class// from java.util packageimport java.util.concurrent.CountDownLatch; // Classclass GFG { // Main driver method public static void main(String args[]) throws InterruptedException { // Let us create task that is going to wait // for five threads before it starts CountDownLatch latch = new CountDownLatch(4); // Creating threads of Person type // Custom parameter inputs Person p1 = new Person(1500, latch, \"PERSON-1\"); Person p2 = new Person(2500, latch, \"PERSON-2\"); Person p3 = new Person(3500, latch, \"PERSON-3\"); Person p4 = new Person(4500, latch, \"PERSON-4\"); Person p5 = new Person(5500, latch, \"PERSON-5\"); // Starting the thread // using the start() method p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); // Waiting for the four threads // using the latch.await() method latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + \" has finished his work\"); }} // Class 2// Helper class extending Thread class// To represent threads for which the main thread waitsclass Person extends Thread { // Member variables of this class private int delay; private CountDownLatch latch; // Method of this class public Person(int delay, CountDownLatch latch, String name) { // super refers to parent class super(name); // This keyword refers to current object itself this.delay = delay; this.latch = latch; } @Override public void run() { // Try block to check for exceptions try { Thread.sleep(delay); latch.countDown(); // Print the current thread by getting its name // using the getName() method // of whose work is completed System.out.println( Thread.currentThread().getName() + \" has finished his work\"); } // Catch block to handle the exception catch (InterruptedException e) { // Print the line number where exception occured // using the printStackTrace() method e.printStackTrace(); } }}", "e": 29178, "s": 26728, "text": null }, { "code": null, "e": 29360, "s": 29178, "text": "PERSON-1 has finished his work\nPERSON-2 has finished his work\nPERSON-3 has finished his work\nPERSON-4 has finished his work\nmain has finished his work\nPERSON-5 has finished his work" }, { "code": null, "e": 29377, "s": 29362, "text": "sagartomar9927" }, { "code": null, "e": 29390, "s": 29377, "text": "simmytarika5" }, { "code": null, "e": 29410, "s": 29390, "text": "Java-Multithreading" }, { "code": null, "e": 29417, "s": 29410, "text": "Picked" }, { "code": null, "e": 29422, "s": 29417, "text": "Java" }, { "code": null, "e": 29427, "s": 29422, "text": "Java" }, { "code": null, "e": 29525, "s": 29427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29534, "s": 29525, "text": "Comments" }, { "code": null, "e": 29547, "s": 29534, "text": "Old Comments" }, { "code": null, "e": 29598, "s": 29547, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29628, "s": 29598, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29659, "s": 29628, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29678, "s": 29659, "text": "Interfaces in Java" }, { "code": null, "e": 29710, "s": 29678, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29728, "s": 29710, "text": "ArrayList in Java" }, { "code": null, "e": 29748, "s": 29728, "text": "Stack Class in Java" }, { "code": null, "e": 29780, "s": 29748, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29804, "s": 29780, "text": "Singleton Class in Java" } ]
YOLOv4 on Google Colab: Train your Custom Dataset (Traffic signs) with ease | by Quang Nguyen | Towards Data Science
Colab Notebook for training YOLOv4 with custom dataset (traffic signs) Introduction Why YOLOv4? Data preparation Training with Colab Predict with YOLOv4 Conclusion A while ago, I wrote a tutorial on training YOLOv3 with a custom dataset (gun detection) using the free GPU provided by Google Colab. After publishing the tutorial, many people emailed me asking about problems they faced during their training process. What I noticed is that the majority of those issues come from modifying inappropriate layer architecture, running cells in incorrect directory paths or missing one/some of the required configuration steps. I also realized that the setting up process might take time and often can be quite confusing. For those reasons, I have came up with a new approach in which most of the setting up steps are automated with a python script (Colab allows you modifying and running python script directly on its environment). With this new procedure, the only thing you need to perform locally is to prepare your custom dataset following YOLO format, while all of the remains would be executed in Colab environment. YOLOv4 was developed by Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao. It was released in April 2020 and claimed as one of the state-of-the-art real-time object detectors at the time. According to its paper, YOLOv4 is 12% faster and 10% more accurate compare to YOLOv3. The new architecture of YOLOV4 is built with CSPDarknet54 as a backbone, which promotes the learning capability of CNN. Furthermore, the implement of universal features includes Weighted-Residual-Connections (WRC), Cross-Stage-Partial-connections (CSP), Cross mini-Batch Normalization (CmBN), Self-adversarial-training (SAT) and Mish-activation help YOLOv4 obtain a very impressive results. To get more details about YOLOv4, you can refer to the original paper here. [1] To be able to train our custom dataset with YOLOv4, it is mandatory that our dataset follows the YOLO format. Each image from the dataset would associate with a .txt file having the same name, which contains the object classes and their coordinate following this syntax: <object-class> <x_center> <y_center> <width> <height> There are many open-source GUI tools which can help you easily generate label file from image such as Yolo_label, OpenLabeling, Yolo_mark, BBox-Label-Tool, etc. Just simply drag and drop your mouse to create a bounding box around your objects, then the tool would generate the label file automatically. Next, you need to create 3 files: classes.names, train.txt and test.txt. The classes.names contains the names of your objects following format: object1_nameobject2_nameobject3_name...objectn_name Make sure that the index of your <object-class> from label file .txt is corresponded to the index of your classes name, e.g, <object-class> of object1_name, object2_name, object3_name are 0, 1, 2 respectively. train.txt and test.txt contains file paths of your training images and testing images. The idea is that you split your dataset into training set and test sets so that you will train your model on the training set and validate it on the test set. If the loss on your training set is high, it means your model is underfitting and you will need to train longer. If the loss is low on your training set and high on your test set, it means your model is overfitting and you will need to add more data. Depending on the number of images in your dataset that your validation set can be extracted from around 5% (small dataset) to 30% (large dataset) of the total dataset. These two files share the same format syntax as data/<image_path>. In this tutorial, I will use the Traffic Signs Dataset in YOLO format from Kaggle. You don’t have to download it now since we will directly download it from Colab environment later. Examples of some of its images and labels can be seen as below (notice that one image can have multiple objects): 00058.txt: 3 0.5919117647058824 0.518125 0.027941176470588237 0.05125 00011.txt: 0 0.5477941176470589 0.46 0.03676470588235294 0.075 1 0.5477941176470589 0.379375 0.051470588235294115 0.09625 00334.txt: 0 0.25441176470588234 0.59375 0.033823529411764704 0.0575 0 0.5724264705882353 0.566875 0.027205882352941177 0.04625 00136.txt: 1 0.6150735294117647 0.52375 0.030147058823529412 0.045 In summary, the traffic sign dataset which we would use in this tutorial would be: |- ts/| |- 00000.jpg| |- 00000.txt| |- ...|- classes.names|- train.txt|- test.txt For who is already familiar with Colab, you can jump right in my Colab notebook here and start playing around with it. However, make sure that you enable GPU in advance by select Runtime -> Change runtime type>Hardware accelerator>GPU, create directory YOLOv4_weight/backup in your Google Drive and mount Drive with Colab environment. As mentioned before, I have implemented some modifications which help the training process more straightforward: assert function: a function that checks whether you’re running the cell in the correct directory path. If you’re in the wrong directory, it will give you a hint to which directory you should be. In case you don’t know how to change the directory, please refer to this cd command in Linux terminal. darknet_for_colab: darknet folder which was modified specifically to adapt with Colab environment (no MAKEFILE change necessary). yolov4_config.py: Taking the advantage of the direct python editing feature on Colab, you can now define training parameters just by double click on yolov4_config.py and edit it (Figure 1). For example, I will set my classes=4 (our traffic sign dataset has 4 classes), max_batches=8000 (number of training iterations), batch=64 (number of samples in one batch), subdivisions=16 (number of mini_batches in one batch), etc. You can refer this page to find more details about the meaning of each parameter. yolov4_setup.py (cell [6]): a python script which automatically generates YOLOv4 architecture config files (yolov4_custom_train.cfg and yolov4_custom_test.cfg) based on user-input parameters in yolov4_config.py. The notebook below demonstrates the pipeline of YOLOv4 training procedure on Colab. I will recommend you to take a look at my Colab Notebook to see what kind of output of each cell you should expect. # check whether GPU is provided import os !nvcc --version # remove the existing folder if have #!rm -r darknet_for_colab # download and compile darknet_for_colab assert os.getcwd()=='/content', 'Directory should be "/content" instead of "{}"'.format(os.getcwd()) !git clone https://github.com/quangnhat185/darknet_for_colab.git %cd darknet_for_colab !make !chmod +x ./darknet assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) !wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.conv.137 %cd data assert os.getcwd()=='/content/darknet_for_colab/data', 'Directory should be "/content/darknet_for_colab/data" instead of "{}"'.format(os.getcwd()) # download custom data of common traffic signs !wget --no-check-certificate "https://onedrive.live.com/download?cid=A86CBC7F31A1C06B&resid=A86CBC7F31A1C06B%21109&authkey=ACmKGNgx4G2TT4A" -O ts.zip !unzip ts.zip !rm -f ts.zip !ls %cd .. assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import glob def read_label(image_path): file_name = image_path.replace('.jpg', '.txt') with open(file_name, 'rt') as file: print(os.path.basename(file_name) + ': \n' + file.read()) image_path = glob.glob("data/ts/*.jpg") fig = plt.figure(figsize=(12,8)) cols = 2 rows = 2 grid = gridspec.GridSpec(nrows=rows, ncols=cols, figure=fig) for i in range(cols*rows): fig.add_subplot(grid[i]) image=plt.imread(image_path[i]) plt.title(os.path.basename(image_path[i])) plt.axis(False) plt.imshow(image) read_label(image_path[i]) plt.savefig("dataset_examples.jpg", dpi=300) Double click on file yolov4_config.py to modify the hyperpameters directly from Colab environment E.g: I will train my dataset with these parameters: classes= 4, max_batches=8000 batch=64 subdivisions=16 width=416 height=416 ... assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # Run python script to create our customize yolov4_custom_train.cfg # and yolov4_custom_tes.cfg in folder /cfg !python yolov4_setup.py assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # create Symlinks so we can save trained weight in our Google Drive # create folder YOLOv4_weight/back in your Drive to store trained weights !rm /content/darknet_for_colab/backup -r !ln -s /content/drive/'My Drive'/YOLOv4_weight/backup /content/darknet_for_colab assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # Training with YOLOv4 !./darknet detector train data/yolov4.data cfg/yolov4_custom_train.cfg yolov4.conv.137 -dont_show -map # If you get CUDA out of memory adjust subdivisions above! # adjust max batches down for shorter training above assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # Plotting training result after 2000 epochs import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) train_result = plt.imread("chart.png") plt.axis(False) plt.imshow(train_result) assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # show labels of our custom traffic sign dataset !cat data/classes.names assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # download example images an video !wget --no-check-certificate "https://onedrive.live.com/download?cid=A86CBC7F31A1C06B&resid=A86CBC7F31A1C06B%21120&authkey=AM5VslNNW9a8aO8" -O examples.zip !unzip examples.zip !rm -r examples.zip assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # cfg/coco.data was harcode in darknet, thus we need # to duplicate one with the same content of data/yolov4.data %cp data/yolov4.data cfg/coco.data assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # coco.names is hardcoded somewhere in the detector # the processed image would be save as file 'prediction.jpg' img_path = "examples/test_image_4.jpg" !./darknet detect cfg/yolov4_custom_test.cfg backup/yolov4_custom_train_last.weights {img_path} -dont-show assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # plot predict image import matplotlib.pyplot as plt fig = plt.figure(figsize=(12,12)) plt.axis(False) processed_image = plt.imread("./predictions.jpg") plt.imshow(processed_image) assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be "/content/darknet_for_colab" instead of "{}"'.format(os.getcwd()) # video processed !python darknet_video.py -v examples/test_video.mp4 -c cfg/yolov4_custom_test.cfg -w backup/yolov4_custom_train_last.weights -o output.mp4 Although I did define my max_batches=8000, both accuracy and loss from training result didn’t improve much after 2000 iterations (Figure 2). The number of iterations might increase if you train with more classes or harder-to-learn dataset. Make sure that you monitor the loss and accuracy by double click on file chart.png or just simply look at the training statistic from the output cell. After obtain the training weights, there are several ways to deploy YOLOv4 with third-party frameworks including OpenCV, Keras, Pytorch, etc. However, those are beyond the scope of this tutorial. You can predict an image or video using the same Colab working space which you’ve used for training process (Figure 3 and Figure 4). Cell 13 and 15 gives you an explicit way to predict an image and video respectively. By default, the predicted image is saved at predictions.jpg while the predicted video would be saved at output.mp4. This tutorial has introduced a new approach which allows you training your custom dataset with YOLOv4 on Google Colab with ease. All modifications relating to neural network architecture and training parameters are automated and can be performed within Colab environment, while unit tests are integrated to debug common compiling errors. However, I would like to point out that using an automated tool has its own price. The fact that you have no idea what is happening behind might be disturbing, especially people who want to have a better intuition about YOLOv4 architecture. In that case, you can refer to the original GitHub repository of YOLOv4 or read my article on training YOLOv3 on Colab. Train YOLOv4 on Colab notebook Darknet for colab repository YOLOv4 weights for traffic sign detection (2000 iterations) Traffic signs dataset in YOLO format [1] Bochkovskiy, Alexey, Chien-Yao Wang, and Hong-Yuan Mark Liao. “YOLOv4: Optimal Speed and Accuracy of Object Detection.” arXiv preprint arXiv:2004.10934 (2020).
[ { "code": null, "e": 243, "s": 172, "text": "Colab Notebook for training YOLOv4 with custom dataset (traffic signs)" }, { "code": null, "e": 256, "s": 243, "text": "Introduction" }, { "code": null, "e": 268, "s": 256, "text": "Why YOLOv4?" }, { "code": null, "e": 285, "s": 268, "text": "Data preparation" }, { "code": null, "e": 305, "s": 285, "text": "Training with Colab" }, { "code": null, "e": 325, "s": 305, "text": "Predict with YOLOv4" }, { "code": null, "e": 336, "s": 325, "text": "Conclusion" }, { "code": null, "e": 888, "s": 336, "text": "A while ago, I wrote a tutorial on training YOLOv3 with a custom dataset (gun detection) using the free GPU provided by Google Colab. After publishing the tutorial, many people emailed me asking about problems they faced during their training process. What I noticed is that the majority of those issues come from modifying inappropriate layer architecture, running cells in incorrect directory paths or missing one/some of the required configuration steps. I also realized that the setting up process might take time and often can be quite confusing." }, { "code": null, "e": 1289, "s": 888, "text": "For those reasons, I have came up with a new approach in which most of the setting up steps are automated with a python script (Colab allows you modifying and running python script directly on its environment). With this new procedure, the only thing you need to perform locally is to prepare your custom dataset following YOLO format, while all of the remains would be executed in Colab environment." }, { "code": null, "e": 2044, "s": 1289, "text": "YOLOv4 was developed by Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao. It was released in April 2020 and claimed as one of the state-of-the-art real-time object detectors at the time. According to its paper, YOLOv4 is 12% faster and 10% more accurate compare to YOLOv3. The new architecture of YOLOV4 is built with CSPDarknet54 as a backbone, which promotes the learning capability of CNN. Furthermore, the implement of universal features includes Weighted-Residual-Connections (WRC), Cross-Stage-Partial-connections (CSP), Cross mini-Batch Normalization (CmBN), Self-adversarial-training (SAT) and Mish-activation help YOLOv4 obtain a very impressive results. To get more details about YOLOv4, you can refer to the original paper here. [1]" }, { "code": null, "e": 2369, "s": 2044, "text": "To be able to train our custom dataset with YOLOv4, it is mandatory that our dataset follows the YOLO format. Each image from the dataset would associate with a .txt file having the same name, which contains the object classes and their coordinate following this syntax: <object-class> <x_center> <y_center> <width> <height>" }, { "code": null, "e": 2672, "s": 2369, "text": "There are many open-source GUI tools which can help you easily generate label file from image such as Yolo_label, OpenLabeling, Yolo_mark, BBox-Label-Tool, etc. Just simply drag and drop your mouse to create a bounding box around your objects, then the tool would generate the label file automatically." }, { "code": null, "e": 2816, "s": 2672, "text": "Next, you need to create 3 files: classes.names, train.txt and test.txt. The classes.names contains the names of your objects following format:" }, { "code": null, "e": 2868, "s": 2816, "text": "object1_nameobject2_nameobject3_name...objectn_name" }, { "code": null, "e": 3078, "s": 2868, "text": "Make sure that the index of your <object-class> from label file .txt is corresponded to the index of your classes name, e.g, <object-class> of object1_name, object2_name, object3_name are 0, 1, 2 respectively." }, { "code": null, "e": 3810, "s": 3078, "text": "train.txt and test.txt contains file paths of your training images and testing images. The idea is that you split your dataset into training set and test sets so that you will train your model on the training set and validate it on the test set. If the loss on your training set is high, it means your model is underfitting and you will need to train longer. If the loss is low on your training set and high on your test set, it means your model is overfitting and you will need to add more data. Depending on the number of images in your dataset that your validation set can be extracted from around 5% (small dataset) to 30% (large dataset) of the total dataset. These two files share the same format syntax as data/<image_path>." }, { "code": null, "e": 4106, "s": 3810, "text": "In this tutorial, I will use the Traffic Signs Dataset in YOLO format from Kaggle. You don’t have to download it now since we will directly download it from Colab environment later. Examples of some of its images and labels can be seen as below (notice that one image can have multiple objects):" }, { "code": null, "e": 4493, "s": 4106, "text": "00058.txt: 3 0.5919117647058824 0.518125 0.027941176470588237 0.05125 00011.txt: 0 0.5477941176470589 0.46 0.03676470588235294 0.075 1 0.5477941176470589 0.379375 0.051470588235294115 0.09625 00334.txt: 0 0.25441176470588234 0.59375 0.033823529411764704 0.0575 0 0.5724264705882353 0.566875 0.027205882352941177 0.04625 00136.txt: 1 0.6150735294117647 0.52375 0.030147058823529412 0.045" }, { "code": null, "e": 4576, "s": 4493, "text": "In summary, the traffic sign dataset which we would use in this tutorial would be:" }, { "code": null, "e": 4664, "s": 4576, "text": "|- ts/| |- 00000.jpg| |- 00000.txt| |- ...|- classes.names|- train.txt|- test.txt" }, { "code": null, "e": 4999, "s": 4664, "text": "For who is already familiar with Colab, you can jump right in my Colab notebook here and start playing around with it. However, make sure that you enable GPU in advance by select Runtime -> Change runtime type>Hardware accelerator>GPU, create directory YOLOv4_weight/backup in your Google Drive and mount Drive with Colab environment." }, { "code": null, "e": 5112, "s": 4999, "text": "As mentioned before, I have implemented some modifications which help the training process more straightforward:" }, { "code": null, "e": 5410, "s": 5112, "text": "assert function: a function that checks whether you’re running the cell in the correct directory path. If you’re in the wrong directory, it will give you a hint to which directory you should be. In case you don’t know how to change the directory, please refer to this cd command in Linux terminal." }, { "code": null, "e": 5540, "s": 5410, "text": "darknet_for_colab: darknet folder which was modified specifically to adapt with Colab environment (no MAKEFILE change necessary)." }, { "code": null, "e": 6044, "s": 5540, "text": "yolov4_config.py: Taking the advantage of the direct python editing feature on Colab, you can now define training parameters just by double click on yolov4_config.py and edit it (Figure 1). For example, I will set my classes=4 (our traffic sign dataset has 4 classes), max_batches=8000 (number of training iterations), batch=64 (number of samples in one batch), subdivisions=16 (number of mini_batches in one batch), etc. You can refer this page to find more details about the meaning of each parameter." }, { "code": null, "e": 6256, "s": 6044, "text": "yolov4_setup.py (cell [6]): a python script which automatically generates YOLOv4 architecture config files (yolov4_custom_train.cfg and yolov4_custom_test.cfg) based on user-input parameters in yolov4_config.py." }, { "code": null, "e": 6456, "s": 6256, "text": "The notebook below demonstrates the pipeline of YOLOv4 training procedure on Colab. I will recommend you to take a look at my Colab Notebook to see what kind of output of each cell you should expect." }, { "code": null, "e": 6515, "s": 6456, "text": "# check whether GPU is provided\nimport os\n!nvcc --version\n" }, { "code": null, "e": 6835, "s": 6515, "text": "# remove the existing folder if have\n#!rm -r darknet_for_colab\n\n# download and compile darknet_for_colab\nassert os.getcwd()=='/content', 'Directory should be \"/content\" instead of \"{}\"'.format(os.getcwd())\n!git clone https://github.com/quangnhat185/darknet_for_colab.git\n%cd darknet_for_colab\n!make\n!chmod +x ./darknet\n" }, { "code": null, "e": 7073, "s": 6835, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n!wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.conv.137\n" }, { "code": null, "e": 7467, "s": 7073, "text": "%cd data\nassert os.getcwd()=='/content/darknet_for_colab/data', 'Directory should be \"/content/darknet_for_colab/data\" instead of \"{}\"'.format(os.getcwd())\n\n# download custom data of common traffic signs\n!wget --no-check-certificate \"https://onedrive.live.com/download?cid=A86CBC7F31A1C06B&resid=A86CBC7F31A1C06B%21109&authkey=ACmKGNgx4G2TT4A\" -O ts.zip\n!unzip ts.zip\n!rm -f ts.zip\n!ls\n%cd ..\n" }, { "code": null, "e": 8264, "s": 7467, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport glob\n\ndef read_label(image_path):\n file_name = image_path.replace('.jpg', '.txt')\n with open(file_name, 'rt') as file:\n print(os.path.basename(file_name) + ': \\n' + file.read())\n\nimage_path = glob.glob(\"data/ts/*.jpg\")\nfig = plt.figure(figsize=(12,8))\ncols = 2\nrows = 2\ngrid = gridspec.GridSpec(nrows=rows, ncols=cols, figure=fig)\nfor i in range(cols*rows):\n fig.add_subplot(grid[i])\n image=plt.imread(image_path[i])\n plt.title(os.path.basename(image_path[i]))\n plt.axis(False)\n plt.imshow(image)\n read_label(image_path[i])\n\nplt.savefig(\"dataset_examples.jpg\", dpi=300)\n" }, { "code": null, "e": 8362, "s": 8264, "text": "Double click on file yolov4_config.py to modify the hyperpameters directly from Colab environment" }, { "code": null, "e": 8414, "s": 8362, "text": "E.g: I will train my dataset with these parameters:" }, { "code": null, "e": 8427, "s": 8414, "text": "classes= 4, " }, { "code": null, "e": 8444, "s": 8427, "text": "max_batches=8000" }, { "code": null, "e": 8453, "s": 8444, "text": "batch=64" }, { "code": null, "e": 8469, "s": 8453, "text": "subdivisions=16" }, { "code": null, "e": 8479, "s": 8469, "text": "width=416" }, { "code": null, "e": 8490, "s": 8479, "text": "height=416" }, { "code": null, "e": 8494, "s": 8490, "text": "..." }, { "code": null, "e": 8769, "s": 8494, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# Run python script to create our customize yolov4_custom_train.cfg \n# and yolov4_custom_tes.cfg in folder /cfg\n!python yolov4_setup.py\n" }, { "code": null, "e": 9172, "s": 8769, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# create Symlinks so we can save trained weight in our Google Drive\n# create folder YOLOv4_weight/back in your Drive to store trained weights\n!rm /content/darknet_for_colab/backup -r\n!ln -s /content/drive/'My Drive'/YOLOv4_weight/backup /content/darknet_for_colab\n" }, { "code": null, "e": 9550, "s": 9172, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# Training with YOLOv4\n!./darknet detector train data/yolov4.data cfg/yolov4_custom_train.cfg yolov4.conv.137 -dont_show -map\n\n# If you get CUDA out of memory adjust subdivisions above!\n# adjust max batches down for shorter training above\n" }, { "code": null, "e": 9880, "s": 9550, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# Plotting training result after 2000 epochs\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(10,10))\ntrain_result = plt.imread(\"chart.png\")\nplt.axis(False)\nplt.imshow(train_result)\n" }, { "code": null, "e": 10092, "s": 9880, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# show labels of our custom traffic sign dataset\n!cat data/classes.names\n" }, { "code": null, "e": 10462, "s": 10092, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# download example images an video\n!wget --no-check-certificate \"https://onedrive.live.com/download?cid=A86CBC7F31A1C06B&resid=A86CBC7F31A1C06B%21120&authkey=AM5VslNNW9a8aO8\" -O examples.zip\n!unzip examples.zip\n!rm -r examples.zip\n" }, { "code": null, "e": 10751, "s": 10462, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# cfg/coco.data was harcode in darknet, thus we need \n# to duplicate one with the same content of data/yolov4.data\n%cp data/yolov4.data cfg/coco.data\n" }, { "code": null, "e": 11149, "s": 10751, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# coco.names is hardcoded somewhere in the detector\n# the processed image would be save as file 'prediction.jpg'\nimg_path = \"examples/test_image_4.jpg\"\n!./darknet detect cfg/yolov4_custom_test.cfg backup/yolov4_custom_train_last.weights {img_path} -dont-show\n" }, { "code": null, "e": 11470, "s": 11149, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# plot predict image\nimport matplotlib.pyplot as plt \nfig = plt.figure(figsize=(12,12))\nplt.axis(False)\nprocessed_image = plt.imread(\"./predictions.jpg\")\nplt.imshow(processed_image)\n" }, { "code": null, "e": 11766, "s": 11470, "text": "assert os.getcwd()=='/content/darknet_for_colab', 'Directory should be \"/content/darknet_for_colab\" instead of \"{}\"'.format(os.getcwd())\n\n# video processed\n!python darknet_video.py -v examples/test_video.mp4 -c cfg/yolov4_custom_test.cfg -w backup/yolov4_custom_train_last.weights -o output.mp4\n" }, { "code": null, "e": 12157, "s": 11766, "text": "Although I did define my max_batches=8000, both accuracy and loss from training result didn’t improve much after 2000 iterations (Figure 2). The number of iterations might increase if you train with more classes or harder-to-learn dataset. Make sure that you monitor the loss and accuracy by double click on file chart.png or just simply look at the training statistic from the output cell." }, { "code": null, "e": 12687, "s": 12157, "text": "After obtain the training weights, there are several ways to deploy YOLOv4 with third-party frameworks including OpenCV, Keras, Pytorch, etc. However, those are beyond the scope of this tutorial. You can predict an image or video using the same Colab working space which you’ve used for training process (Figure 3 and Figure 4). Cell 13 and 15 gives you an explicit way to predict an image and video respectively. By default, the predicted image is saved at predictions.jpg while the predicted video would be saved at output.mp4." }, { "code": null, "e": 13025, "s": 12687, "text": "This tutorial has introduced a new approach which allows you training your custom dataset with YOLOv4 on Google Colab with ease. All modifications relating to neural network architecture and training parameters are automated and can be performed within Colab environment, while unit tests are integrated to debug common compiling errors." }, { "code": null, "e": 13386, "s": 13025, "text": "However, I would like to point out that using an automated tool has its own price. The fact that you have no idea what is happening behind might be disturbing, especially people who want to have a better intuition about YOLOv4 architecture. In that case, you can refer to the original GitHub repository of YOLOv4 or read my article on training YOLOv3 on Colab." }, { "code": null, "e": 13417, "s": 13386, "text": "Train YOLOv4 on Colab notebook" }, { "code": null, "e": 13446, "s": 13417, "text": "Darknet for colab repository" }, { "code": null, "e": 13506, "s": 13446, "text": "YOLOv4 weights for traffic sign detection (2000 iterations)" }, { "code": null, "e": 13543, "s": 13506, "text": "Traffic signs dataset in YOLO format" } ]
How to match text at the start or end of a string in Python?
Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this. A simple way to check the beginning of a string is by using startswith() method. text = "Is USA colder than Australia?" print(f"output \n {text.startswith('Is')}") True filename = "Hello_world.txt" print(f"output \n {filename.startswith('Hello')}") True site_url = 'https://www.something.com' print(f"output \n {site_url.startswith('http:')}") False print(f"output \n {site_url.startswith('https:')}") True A simple way to check the ending of a string is by using endswith() method. text = "Is USA colder than Australia?" print(f"output \n {text.endswith('?')}") True filename = "Hello_world.txt" print(f"output \n {filename.endswith('.txt')}") True Now if we want to check for multiple choices with the above methods we need to provide tuples. One of the common usage is the check for file extensions let us say we need to validate for ".txt" and ".csv" files in a directory. import os filenames = os.listdir('.') # Let us first check if there are files print(f"output \n {any(name.endswith(('.csv',',txt')) for name in filenames)}") True [name for name in filenames if name.endswith(('.csv', '.txt')) ] ['file1.csv', 'HRDataset.csv', 'Input.csv', 'input.txt', 'input_copy.txt', 'movies_data.csv', 'my_html_data_to_csv.csv', 'temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv', 'test.csv', 'test1.txt', 'test2.txt', 'tmdb_5000_movies.csv'] Remember these methods accepts tuples, if you have a list of choices to search, then we need to convert them in tuples. import os # list with choices patters = ['.csv','.txt'] # get the file names filenames = os.listdir('.') # Let us first check if there are files any(name.endswith(patters) for name in filenames) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 8 9 # Let us first check if there are files ---> 10 any(name.endswith(patters) for name in filenames) in (.0) 8 9 # Let us first check if there are files ---> 10 any(name.endswith(patters) for name in filenames) TypeError: endswith first arg must be str or a tuple of str, not list The above command returned an error, so we need to convert the list into a tuple. # Let us first check if there are files any(name.endswith(tuple(patters)) for name in filenames) True Similarly, we need to convert list to tuple to get the file names. [name for name in filenames if name.endswith(tuple(patters)) ] ['file1.csv', 'HRDataset.csv', 'Input.csv', 'input.txt', 'input_copy.txt', 'movies_data.csv', 'my_html_data_to_csv.csv', 'temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv', 'test.csv', 'test1.txt', 'test2.txt', 'tmdb_5000_movies.csv'] Finally, the startswith() and endswith() methods look nice when combined with other operations, such as common data reductions. For example: if any(name.endswith(tuple(patters)) for name in filenames): <perform the logic here>
[ { "code": null, "e": 1273, "s": 1062, "text": "Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this." }, { "code": null, "e": 1354, "s": 1273, "text": "A simple way to check the beginning of a string is by using startswith() method." }, { "code": null, "e": 1437, "s": 1354, "text": "text = \"Is USA colder than Australia?\"\nprint(f\"output \\n {text.startswith('Is')}\")" }, { "code": null, "e": 1442, "s": 1437, "text": "True" }, { "code": null, "e": 1522, "s": 1442, "text": "filename = \"Hello_world.txt\"\nprint(f\"output \\n {filename.startswith('Hello')}\")" }, { "code": null, "e": 1527, "s": 1522, "text": "True" }, { "code": null, "e": 1617, "s": 1527, "text": "site_url = 'https://www.something.com'\nprint(f\"output \\n {site_url.startswith('http:')}\")" }, { "code": null, "e": 1623, "s": 1617, "text": "False" }, { "code": null, "e": 1675, "s": 1623, "text": "print(f\"output \\n {site_url.startswith('https:')}\")" }, { "code": null, "e": 1680, "s": 1675, "text": "True" }, { "code": null, "e": 1756, "s": 1680, "text": "A simple way to check the ending of a string is by using endswith() method." }, { "code": null, "e": 1836, "s": 1756, "text": "text = \"Is USA colder than Australia?\"\nprint(f\"output \\n {text.endswith('?')}\")" }, { "code": null, "e": 1841, "s": 1836, "text": "True" }, { "code": null, "e": 1918, "s": 1841, "text": "filename = \"Hello_world.txt\"\nprint(f\"output \\n {filename.endswith('.txt')}\")" }, { "code": null, "e": 1923, "s": 1918, "text": "True" }, { "code": null, "e": 2150, "s": 1923, "text": "Now if we want to check for multiple choices with the above methods we need to provide tuples. One of the common usage is the check for file extensions let us say we need to validate for \".txt\" and \".csv\" files in a directory." }, { "code": null, "e": 2188, "s": 2150, "text": "import os\nfilenames = os.listdir('.')" }, { "code": null, "e": 2308, "s": 2188, "text": "# Let us first check if there are files\nprint(f\"output \\n {any(name.endswith(('.csv',',txt')) for name in filenames)}\")" }, { "code": null, "e": 2313, "s": 2308, "text": "True" }, { "code": null, "e": 2378, "s": 2313, "text": "[name for name in filenames if name.endswith(('.csv', '.txt')) ]" }, { "code": null, "e": 2623, "s": 2378, "text": "['file1.csv',\n'HRDataset.csv',\n'Input.csv',\n'input.txt',\n'input_copy.txt',\n'movies_data.csv',\n'my_html_data_to_csv.csv',\n'temporary_file1_for_zip.csv',\n'temporary_file2_for_zip.csv',\n'test.csv',\n'test1.txt',\n'test2.txt',\n'tmdb_5000_movies.csv']" }, { "code": null, "e": 2743, "s": 2623, "text": "Remember these methods accepts tuples, if you have a list of choices to search, then we need to convert them in tuples." }, { "code": null, "e": 2941, "s": 2743, "text": "import os\n\n# list with choices\npatters = ['.csv','.txt']\n\n# get the file names\nfilenames = os.listdir('.')\n\n# Let us first check if there are files\nany(name.endswith(patters) for name in filenames)" }, { "code": null, "e": 3348, "s": 2941, "text": "---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\nin\n8\n9 # Let us first check if there are files\n---> 10 any(name.endswith(patters) for name in filenames)\n\nin (.0)\n8\n9 # Let us first check if there are files\n---> 10 any(name.endswith(patters) for name in filenames)\n\nTypeError: endswith first arg must be str or a tuple of str, not list" }, { "code": null, "e": 3430, "s": 3348, "text": "The above command returned an error, so we need to convert the list into a tuple." }, { "code": null, "e": 3527, "s": 3430, "text": "# Let us first check if there are files\nany(name.endswith(tuple(patters)) for name in filenames)" }, { "code": null, "e": 3532, "s": 3527, "text": "True" }, { "code": null, "e": 3599, "s": 3532, "text": "Similarly, we need to convert list to tuple to get the file names." }, { "code": null, "e": 3662, "s": 3599, "text": "[name for name in filenames if name.endswith(tuple(patters)) ]" }, { "code": null, "e": 3907, "s": 3662, "text": "['file1.csv',\n'HRDataset.csv',\n'Input.csv',\n'input.txt',\n'input_copy.txt',\n'movies_data.csv',\n'my_html_data_to_csv.csv',\n'temporary_file1_for_zip.csv',\n'temporary_file2_for_zip.csv',\n'test.csv',\n'test1.txt',\n'test2.txt',\n'tmdb_5000_movies.csv']" }, { "code": null, "e": 4048, "s": 3907, "text": "Finally, the startswith() and endswith() methods look nice when combined with other operations, such as common data reductions. For example:" }, { "code": null, "e": 4134, "s": 4048, "text": "if any(name.endswith(tuple(patters)) for name in filenames):\n<perform the logic here>" } ]
Convert List of Vectors to DataFrame in R - GeeksforGeeks
09 May, 2021 In this article, we will discuss how to convert the given list of vectors to Dataframe using the help of different functions in the R Programming Language. For all the methods discussed below, few functions are common because of their functionality. Let us discuss them first. as.data.frame() is one of the simplest methods to convert the given list of vectors to the DataFrame in R language with just calling the as.data.frame() function and passing the required parameters, and further this function will be returning the DataFrame converted from the list of vectors given before. Syntax: as.data.frame(x, row.names = NULL, optional = FALSE, ...) Further, with the as.data.frame() function user needs to also call the do.call() function which is used here to constructs and executes a function call from a name or a function and a list of arguments to be passed to it. Syntax: do.call(what, args, quote = FALSE, envir = parent.frame()) Parameters: what:-either a function or a non-empty character string naming the function to be called. args:a list of arguments to the function call. The names attribute of args gives the argument names. quote:-a logical value indicating whether to quote the arguments. envir:-an environment within which to evaluate the call. cbind() function stands for column-bind. This function can be used to combine several vectors, matrices, or DataFrames by columns. Syntax: cbind(x1, x2, ..., deparse.level = 1) In this approach, a single vector is considered as one column and then these columns are combined to form a dataframe. Example: R my_list <- list(A =c(1,2,3,4,5), B =c(6,7,8,9,10)) my_list as.data.frame(do.call(cbind, my_list)) Output: rbind() function stands for row-bind. This function can be used to combine several vectors, matrices, or DataFrames by rows. Syntax: rbind(x1, x2, ..., deparse.level = 1) Parameters:x1, x2: vector, matrix, DataFramesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1. In this approach, each vector is considered a row and then these rows are combined to form a dataframe. Example: R my_list <- list(A =c(1,2,3,4,5), B =c(6,7,8,9,10)) my_list as.data.frame(do.call(rbind, my_list)) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs 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 Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n09 May, 2021" }, { "code": null, "e": 25398, "s": 25242, "text": "In this article, we will discuss how to convert the given list of vectors to Dataframe using the help of different functions in the R Programming Language." }, { "code": null, "e": 25519, "s": 25398, "text": "For all the methods discussed below, few functions are common because of their functionality. Let us discuss them first." }, { "code": null, "e": 25826, "s": 25519, "text": "as.data.frame() is one of the simplest methods to convert the given list of vectors to the DataFrame in R language with just calling the as.data.frame() function and passing the required parameters, and further this function will be returning the DataFrame converted from the list of vectors given before. " }, { "code": null, "e": 25892, "s": 25826, "text": "Syntax: as.data.frame(x, row.names = NULL, optional = FALSE, ...)" }, { "code": null, "e": 26114, "s": 25892, "text": "Further, with the as.data.frame() function user needs to also call the do.call() function which is used here to constructs and executes a function call from a name or a function and a list of arguments to be passed to it." }, { "code": null, "e": 26181, "s": 26114, "text": "Syntax: do.call(what, args, quote = FALSE, envir = parent.frame())" }, { "code": null, "e": 26193, "s": 26181, "text": "Parameters:" }, { "code": null, "e": 26283, "s": 26193, "text": "what:-either a function or a non-empty character string naming the function to be called." }, { "code": null, "e": 26384, "s": 26283, "text": "args:a list of arguments to the function call. The names attribute of args gives the argument names." }, { "code": null, "e": 26450, "s": 26384, "text": "quote:-a logical value indicating whether to quote the arguments." }, { "code": null, "e": 26507, "s": 26450, "text": "envir:-an environment within which to evaluate the call." }, { "code": null, "e": 26638, "s": 26507, "text": "cbind() function stands for column-bind. This function can be used to combine several vectors, matrices, or DataFrames by columns." }, { "code": null, "e": 26684, "s": 26638, "text": "Syntax: cbind(x1, x2, ..., deparse.level = 1)" }, { "code": null, "e": 26803, "s": 26684, "text": "In this approach, a single vector is considered as one column and then these columns are combined to form a dataframe." }, { "code": null, "e": 26812, "s": 26803, "text": "Example:" }, { "code": null, "e": 26814, "s": 26812, "text": "R" }, { "code": "my_list <- list(A =c(1,2,3,4,5), B =c(6,7,8,9,10)) my_list as.data.frame(do.call(cbind, my_list)) ", "e": 26933, "s": 26814, "text": null }, { "code": null, "e": 26941, "s": 26933, "text": "Output:" }, { "code": null, "e": 27066, "s": 26941, "text": "rbind() function stands for row-bind. This function can be used to combine several vectors, matrices, or DataFrames by rows." }, { "code": null, "e": 27112, "s": 27066, "text": "Syntax: rbind(x1, x2, ..., deparse.level = 1)" }, { "code": null, "e": 27267, "s": 27112, "text": "Parameters:x1, x2: vector, matrix, DataFramesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1." }, { "code": null, "e": 27371, "s": 27267, "text": "In this approach, each vector is considered a row and then these rows are combined to form a dataframe." }, { "code": null, "e": 27380, "s": 27371, "text": "Example:" }, { "code": null, "e": 27382, "s": 27380, "text": "R" }, { "code": "my_list <- list(A =c(1,2,3,4,5), B =c(6,7,8,9,10)) my_list as.data.frame(do.call(rbind, my_list)) ", "e": 27501, "s": 27382, "text": null }, { "code": null, "e": 27509, "s": 27501, "text": "Output:" }, { "code": null, "e": 27516, "s": 27509, "text": "Picked" }, { "code": null, "e": 27537, "s": 27516, "text": "R DataFrame-Programs" }, { "code": null, "e": 27549, "s": 27537, "text": "R-DataFrame" }, { "code": null, "e": 27560, "s": 27549, "text": "R Language" }, { "code": null, "e": 27571, "s": 27560, "text": "R Programs" }, { "code": null, "e": 27669, "s": 27571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27721, "s": 27669, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27759, "s": 27721, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27794, "s": 27759, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27852, "s": 27794, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27901, "s": 27852, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27959, "s": 27901, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28008, "s": 27959, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28058, "s": 28008, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28101, "s": 28058, "text": "Replace Specific Characters in String in R" } ]
Using C codes in Python | Set 1 - GeeksforGeeks
18 Mar, 2019 Prerequisite: How to Call a C function in Python Let’s discuss the problem of accessing C code from Python. As it is very evident that many of Python’s built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C programming API that Python provides but there are many different to deal with C. Code #1 : [work.c] C-Code that we are dealing. #include <math.h> int gcd(int x, int y){ int g = y; while (x > 0) { g = x; x = y % x; y = g; } return g;} int divide(int a, int b, int * remainder){ int quot = a / b; *remainder = a % b; return quot;} double avg(double * a, int n){ int i; double total = 0.0; for (i = 0; i < n; i++) { total += a[i]; } return total / n;} typedef struct Point{ double x, y;} Point; double distance(Point * p1, Point * p2){ return hypot(p1->x - p2->x, p1->y - p2->y);} Above code has different C-programming features. gcd()divide() – returning multiple values, one through a pointer argumentavg() – performing a data reduction across a C arrayPoint and distance() – involve C structures. Let’s assume that the code above is found in a file named work.c and it has been compiled into a library libsample that can be linked to other C code. Now, we have a number of C functions that have been compiled into a shared library. So, we call the functions entirely from Python without having to write additional C code or using a third-party extension tool. Using ctypes :Python ctypes will come to play but make sure the C code, that is to be converted, has been compiled into a shared library that is compatible with the Python interpreter (e.g., same architecture, word size, compiler, etc.). Further the libsample.so file has been placed in the same directory as the work.py. Let’s understand work.py now. Code #2 : Python module that wraps around resulting library to access it # work.pyimport ctypesimport os # locating the 'libsample.so' file in the# same directory as this file_file = 'libsample.so'_path = os.path.join(*(os.path.split(__file__)[:-1] + (_file, )))_mod = ctypes.cdll.LoadLibrary(_path) Code #3 : Accessing code # int gcd(int, int)gcd = _mod.gcdgcd.argtypes = (ctypes.c_int, ctypes.c_int)gcd.restype = ctypes.c_int # int divide(int, int, int *)_divide = _mod.divide_divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)) _divide.restype = ctypes.c_int def divide(x, y): rem = ctypes.c_int() quot = _divide(x, y, rem) return quot, rem.value # void avg(double *, int n)# Define a special type for the 'double *' argumentclass DoubleArrayType: def from_param(self, param): typename = type(param).__name__ if hasattr(self, 'from_' + typename): return getattr(self, 'from_' + typename)(param) elif isinstance(param, ctypes.Array): return param else: raise TypeError("Can't convert % s" % typename) # Cast from array.array objects def from_array(self, param): if param.typecode != 'd': raise TypeError('must be an array of doubles') ptr, _ = param.buffer_info() return ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double)) # Cast from lists / tuples def from_list(self, param): val = ((ctypes.c_double)*len(param))(*param) return val from_tuple = from_list # Cast from a numpy array def from_ndarray(self, param): return param.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) DoubleArray = DoubleArrayType()_avg = _mod.avg_avg.argtypes = (DoubleArray, ctypes.c_int)_avg.restype = ctypes.c_double def avg(values): return _avg(values, len(values)) # struct Point { }class Point(ctypes.Structure): _fields_ = [('x', ctypes.c_double), ('y', ctypes.c_double)] # double distance(Point *, Point *)distance = _mod.distancedistance.argtypes = (ctypes.POINTER(Point), ctypes.POINTER(Point))distance.restype = ctypes.c_double Now, one can easily load the module and use the resulting C functions. See the next part – Using C codes in Python | Set 2. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python How to Install PIP on Windows ? Deque in Python Python String | replace()
[ { "code": null, "e": 23839, "s": 23811, "text": "\n18 Mar, 2019" }, { "code": null, "e": 23888, "s": 23839, "text": "Prerequisite: How to Call a C function in Python" }, { "code": null, "e": 24220, "s": 23888, "text": "Let’s discuss the problem of accessing C code from Python. As it is very evident that many of Python’s built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C programming API that Python provides but there are many different to deal with C." }, { "code": null, "e": 24267, "s": 24220, "text": "Code #1 : [work.c] C-Code that we are dealing." }, { "code": "#include <math.h> int gcd(int x, int y){ int g = y; while (x > 0) { g = x; x = y % x; y = g; } return g;} int divide(int a, int b, int * remainder){ int quot = a / b; *remainder = a % b; return quot;} double avg(double * a, int n){ int i; double total = 0.0; for (i = 0; i < n; i++) { total += a[i]; } return total / n;} typedef struct Point{ double x, y;} Point; double distance(Point * p1, Point * p2){ return hypot(p1->x - p2->x, p1->y - p2->y);}", "e": 24798, "s": 24267, "text": null }, { "code": null, "e": 24847, "s": 24798, "text": "Above code has different C-programming features." }, { "code": null, "e": 25017, "s": 24847, "text": "gcd()divide() – returning multiple values, one through a pointer argumentavg() – performing a data reduction across a C arrayPoint and distance() – involve C structures." }, { "code": null, "e": 25618, "s": 25017, "text": "Let’s assume that the code above is found in a file named work.c and it has been compiled into a library libsample that can be linked to other C code. Now, we have a number of C functions that have been compiled into a shared library. So, we call the functions entirely from Python without having to write additional C code or using a third-party extension tool. Using ctypes :Python ctypes will come to play but make sure the C code, that is to be converted, has been compiled into a shared library that is compatible with the Python interpreter (e.g., same architecture, word size, compiler, etc.)." }, { "code": null, "e": 25732, "s": 25618, "text": "Further the libsample.so file has been placed in the same directory as the work.py. Let’s understand work.py now." }, { "code": null, "e": 25805, "s": 25732, "text": "Code #2 : Python module that wraps around resulting library to access it" }, { "code": "# work.pyimport ctypesimport os # locating the 'libsample.so' file in the# same directory as this file_file = 'libsample.so'_path = os.path.join(*(os.path.split(__file__)[:-1] + (_file, )))_mod = ctypes.cdll.LoadLibrary(_path)", "e": 26033, "s": 25805, "text": null }, { "code": null, "e": 26058, "s": 26033, "text": "Code #3 : Accessing code" }, { "code": "# int gcd(int, int)gcd = _mod.gcdgcd.argtypes = (ctypes.c_int, ctypes.c_int)gcd.restype = ctypes.c_int # int divide(int, int, int *)_divide = _mod.divide_divide.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)) _divide.restype = ctypes.c_int def divide(x, y): rem = ctypes.c_int() quot = _divide(x, y, rem) return quot, rem.value # void avg(double *, int n)# Define a special type for the 'double *' argumentclass DoubleArrayType: def from_param(self, param): typename = type(param).__name__ if hasattr(self, 'from_' + typename): return getattr(self, 'from_' + typename)(param) elif isinstance(param, ctypes.Array): return param else: raise TypeError(\"Can't convert % s\" % typename) # Cast from array.array objects def from_array(self, param): if param.typecode != 'd': raise TypeError('must be an array of doubles') ptr, _ = param.buffer_info() return ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double)) # Cast from lists / tuples def from_list(self, param): val = ((ctypes.c_double)*len(param))(*param) return val from_tuple = from_list # Cast from a numpy array def from_ndarray(self, param): return param.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) DoubleArray = DoubleArrayType()_avg = _mod.avg_avg.argtypes = (DoubleArray, ctypes.c_int)_avg.restype = ctypes.c_double def avg(values): return _avg(values, len(values)) # struct Point { }class Point(ctypes.Structure): _fields_ = [('x', ctypes.c_double), ('y', ctypes.c_double)] # double distance(Point *, Point *)distance = _mod.distancedistance.argtypes = (ctypes.POINTER(Point), ctypes.POINTER(Point))distance.restype = ctypes.c_double", "e": 27930, "s": 26058, "text": null }, { "code": null, "e": 28054, "s": 27930, "text": "Now, one can easily load the module and use the resulting C functions. See the next part – Using C codes in Python | Set 2." }, { "code": null, "e": 28069, "s": 28054, "text": "python-utility" }, { "code": null, "e": 28076, "s": 28069, "text": "Python" }, { "code": null, "e": 28174, "s": 28076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28183, "s": 28174, "text": "Comments" }, { "code": null, "e": 28196, "s": 28183, "text": "Old Comments" }, { "code": null, "e": 28214, "s": 28196, "text": "Python Dictionary" }, { "code": null, "e": 28236, "s": 28214, "text": "Enumerate() in Python" }, { "code": null, "e": 28271, "s": 28236, "text": "Read a file line by line in Python" }, { "code": null, "e": 28293, "s": 28271, "text": "Defaultdict in Python" }, { "code": null, "e": 28335, "s": 28293, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28360, "s": 28335, "text": "sum() function in Python" }, { "code": null, "e": 28390, "s": 28360, "text": "Iterate over a list in Python" }, { "code": null, "e": 28422, "s": 28390, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28438, "s": 28422, "text": "Deque in Python" } ]
Deleting a binary tree using the delete keyword in C++ program
In this tutorial, we are going to learn how to delete a binary tree using the delete keyword. We are going to use a destructor member function to delete the binary. The destructor member function is invoked automatically when the object goes out of the scope or it is destroyed by calling delete. The destructor member function has the name as a class with tilde (~) before it. Let's see the steps to solve the problem. Write a class called Node. Write a class called Node. Write a constructor function that accepts data for the node. Write a constructor function that accepts data for the node. Write a destructor function.Delete the left node.Delete the right node.Print the current node data. Write a destructor function. Delete the left node. Delete the left node. Delete the right node. Delete the right node. Print the current node data. Print the current node data. Initialize the binary tree with dummy data. Initialize the binary tree with dummy data. Delete the binary tress using the delete root statement. Delete the binary tress using the delete root statement. Live Demo #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node* left; Node* right; // constructor Node(int data) { this->data = data; this->left = NULL; this->right = NULL; } // destructor ~Node() { // deleting the left and right pointers delete left; delete right; // printing node data cout << "Deleted node with data " << this->data << endl; } }; int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); // deleting the entire tree using destructure function delete root; return 0; } If you execute the above program, then you will get the following result. Deleted node with data 4 Deleted node with data 5 Deleted node with data 2 Deleted node with data 6 Deleted node with data 7 Deleted node with data 3 Deleted node with data 1 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1156, "s": 1062, "text": "In this tutorial, we are going to learn how to delete a binary tree using the delete keyword." }, { "code": null, "e": 1359, "s": 1156, "text": "We are going to use a destructor member function to delete the binary. The destructor member function is invoked automatically when the object goes out of the scope or it is destroyed by calling delete." }, { "code": null, "e": 1440, "s": 1359, "text": "The destructor member function has the name as a class with tilde (~) before it." }, { "code": null, "e": 1482, "s": 1440, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1509, "s": 1482, "text": "Write a class called Node." }, { "code": null, "e": 1536, "s": 1509, "text": "Write a class called Node." }, { "code": null, "e": 1597, "s": 1536, "text": "Write a constructor function that accepts data for the node." }, { "code": null, "e": 1658, "s": 1597, "text": "Write a constructor function that accepts data for the node." }, { "code": null, "e": 1758, "s": 1658, "text": "Write a destructor function.Delete the left node.Delete the right node.Print the current node data." }, { "code": null, "e": 1787, "s": 1758, "text": "Write a destructor function." }, { "code": null, "e": 1809, "s": 1787, "text": "Delete the left node." }, { "code": null, "e": 1831, "s": 1809, "text": "Delete the left node." }, { "code": null, "e": 1854, "s": 1831, "text": "Delete the right node." }, { "code": null, "e": 1877, "s": 1854, "text": "Delete the right node." }, { "code": null, "e": 1906, "s": 1877, "text": "Print the current node data." }, { "code": null, "e": 1935, "s": 1906, "text": "Print the current node data." }, { "code": null, "e": 1979, "s": 1935, "text": "Initialize the binary tree with dummy data." }, { "code": null, "e": 2023, "s": 1979, "text": "Initialize the binary tree with dummy data." }, { "code": null, "e": 2080, "s": 2023, "text": "Delete the binary tress using the delete root statement." }, { "code": null, "e": 2137, "s": 2080, "text": "Delete the binary tress using the delete root statement." }, { "code": null, "e": 2148, "s": 2137, "text": " Live Demo" }, { "code": null, "e": 2929, "s": 2148, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Node {\n public:\n int data;\n Node* left;\n Node* right;\n // constructor\n Node(int data) {\n this->data = data;\n this->left = NULL;\n this->right = NULL;\n }\n // destructor\n ~Node() {\n // deleting the left and right pointers\n delete left;\n delete right;\n // printing node data\n cout << \"Deleted node with data \" << this->data << endl;\n }\n};\nint main() {\n Node* root = new Node(1);\n root->left = new Node(2);\n root->right = new Node(3);\n root->left->left = new Node(4);\n root->left->right = new Node(5);\n root->right->left = new Node(6);\n root->right->right = new Node(7);\n // deleting the entire tree using destructure function\n delete root;\n return 0;\n}" }, { "code": null, "e": 3003, "s": 2929, "text": "If you execute the above program, then you will get the following result." }, { "code": null, "e": 3178, "s": 3003, "text": "Deleted node with data 4\nDeleted node with data 5\nDeleted node with data 2\nDeleted node with data 6\nDeleted node with data 7\nDeleted node with data 3\nDeleted node with data 1" }, { "code": null, "e": 3256, "s": 3178, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
How to handle the ArithmeticException (unchecked) in Java?
The java.lang.ArithmeticException is an unchecked exception in Java. Usually, one would come across java.lang.ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM. Live Demo public class ArithmeticExceptionTest { public static void main(String[] args) { int a = 0, b = 10; int c = b/a; System.out.println("Value of c is : "+ c); } } In the above example, ArithmeticExeption is occurred due to denominator value is zero. java.lang.ArithmeticException: Exception thrown by java during division. / by zero: is the detail message given to ArithmeticException class while creating the ArithmeticException object. Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5) Let us handle the ArithmeticException using try and catch blocks. Surround the statements that can throw ArithmeticException with try and catch blocks. We can Catch the ArithmeticException Take necessary action for our program, as the execution doesn’t abort. Live Demo public class ArithmeticExceptionTest { public static void main(String[] args) { int a = 0, b = 10 ; int c = 0; try { c = b/a; } catch (ArithmeticException e) { e.printStackTrace(); System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\""); } System.out.println("Value of c :"+ c); } } When an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks. We are just printing the stack trace. ArithmeticException is handled. But take care of the variable "c" Value of c is : 0 java.lang.ArithmeticException: / by zero at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)
[ { "code": null, "e": 1364, "s": 1062, "text": "The java.lang.ArithmeticException is an unchecked exception in Java. Usually, one would come across java.lang.ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM." }, { "code": null, "e": 1374, "s": 1364, "text": "Live Demo" }, { "code": null, "e": 1557, "s": 1374, "text": "public class ArithmeticExceptionTest {\n public static void main(String[] args) {\n int a = 0, b = 10;\n int c = b/a;\n System.out.println(\"Value of c is : \"+ c);\n }\n}" }, { "code": null, "e": 1645, "s": 1557, "text": "In the above example, ArithmeticExeption is occurred due to denominator value is zero." }, { "code": null, "e": 1718, "s": 1645, "text": "java.lang.ArithmeticException: Exception thrown by java during division." }, { "code": null, "e": 1833, "s": 1718, "text": "/ by zero: is the detail message given to ArithmeticException class while creating the ArithmeticException object." }, { "code": null, "e": 1971, "s": 1833, "text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero\n at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)" }, { "code": null, "e": 2037, "s": 1971, "text": "Let us handle the ArithmeticException using try and catch blocks." }, { "code": null, "e": 2123, "s": 2037, "text": "Surround the statements that can throw ArithmeticException with try and catch blocks." }, { "code": null, "e": 2160, "s": 2123, "text": "We can Catch the ArithmeticException" }, { "code": null, "e": 2231, "s": 2160, "text": "Take necessary action for our program, as the execution doesn’t abort." }, { "code": null, "e": 2241, "s": 2231, "text": "Live Demo" }, { "code": null, "e": 2670, "s": 2241, "text": "public class ArithmeticExceptionTest {\n public static void main(String[] args) {\n int a = 0, b = 10 ;\n int c = 0;\n try {\n c = b/a;\n } catch (ArithmeticException e) {\n e.printStackTrace();\n System.out.println(\"We are just printing the stack trace.\\n\"+ \"ArithmeticException is handled. But take care of the variable \\\"c\\\"\");\n }\n System.out.println(\"Value of c :\"+ c);\n }\n}" }, { "code": null, "e": 2899, "s": 2670, "text": "When an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks." }, { "code": null, "e": 3134, "s": 2899, "text": "We are just printing the stack trace.\nArithmeticException is handled. But take care of the variable \"c\"\nValue of c is : 0\njava.lang.ArithmeticException: / by zero\n at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)" } ]
Difference between Linker and Loader - GeeksforGeeks
14 Mar, 2022 In execution of the program, major role is played by two utility programs known as Linker and Loader. 1. Linker : A linker is special program that combines the object files, generated by compiler/assembler, and other pieces of codes to originate an executable file have. exe extension. In the object file, linker searches and append all libraries needed for execution of file. It regulates the memory space that will hold the code from each module. It also merges two or more separate object programs and establishes link among them. Generally, linkers are of two types : 1. Linkage Editor 2. Dynamic Linker 2. Loader : The loader is special program that takes input of executable files from linker, loads it to main memory, and prepares this code for execution by computer. Loader allocates memory space to program. Even it settles down symbolic reference between objects. It is in charge of loading programs and libraries in operating system. The embedded computer systems don’t have loaders. In them, code is executed through ROM. There are following various loading schemes: 1. Absolute Loaders 2. Relocating Loaders 3. Direct Linking Loaders 4. Bootstrap Loaders Difference Between Linker and Loader : sukhseeratkaur zubymantasha aftab1x0 vai43 Picked Compiler Design Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Construction of LL(1) Parsing Table Introduction of Lexical Analysis Flex (Fast Lexical Analyzer Generator ) C program to detect tokens in a C program Introduction of Compiler Design Difference between BFS and DFS Class method vs Static method in Python Difference between var, let and const keywords in JavaScript Differences between TCP and UDP Difference between Process and Thread
[ { "code": null, "e": 24131, "s": 24103, "text": "\n14 Mar, 2022" }, { "code": null, "e": 24234, "s": 24131, "text": "In execution of the program, major role is played by two utility programs known as Linker and Loader. " }, { "code": null, "e": 24705, "s": 24234, "text": "1. Linker : A linker is special program that combines the object files, generated by compiler/assembler, and other pieces of codes to originate an executable file have. exe extension. In the object file, linker searches and append all libraries needed for execution of file. It regulates the memory space that will hold the code from each module. It also merges two or more separate object programs and establishes link among them. Generally, linkers are of two types : " }, { "code": null, "e": 24742, "s": 24705, "text": "1. Linkage Editor\n2. Dynamic Linker " }, { "code": null, "e": 25214, "s": 24742, "text": "2. Loader : The loader is special program that takes input of executable files from linker, loads it to main memory, and prepares this code for execution by computer. Loader allocates memory space to program. Even it settles down symbolic reference between objects. It is in charge of loading programs and libraries in operating system. The embedded computer systems don’t have loaders. In them, code is executed through ROM. There are following various loading schemes: " }, { "code": null, "e": 25303, "s": 25214, "text": "1. Absolute Loaders\n2. Relocating Loaders\n3. Direct Linking Loaders\n4. Bootstrap Loaders" }, { "code": null, "e": 25344, "s": 25303, "text": "Difference Between Linker and Loader : " }, { "code": null, "e": 25359, "s": 25344, "text": "sukhseeratkaur" }, { "code": null, "e": 25372, "s": 25359, "text": "zubymantasha" }, { "code": null, "e": 25381, "s": 25372, "text": "aftab1x0" }, { "code": null, "e": 25387, "s": 25381, "text": "vai43" }, { "code": null, "e": 25394, "s": 25387, "text": "Picked" }, { "code": null, "e": 25410, "s": 25394, "text": "Compiler Design" }, { "code": null, "e": 25429, "s": 25410, "text": "Difference Between" }, { "code": null, "e": 25447, "s": 25429, "text": "Operating Systems" }, { "code": null, "e": 25465, "s": 25447, "text": "Operating Systems" }, { "code": null, "e": 25563, "s": 25465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25572, "s": 25563, "text": "Comments" }, { "code": null, "e": 25585, "s": 25572, "text": "Old Comments" }, { "code": null, "e": 25621, "s": 25585, "text": "Construction of LL(1) Parsing Table" }, { "code": null, "e": 25654, "s": 25621, "text": "Introduction of Lexical Analysis" }, { "code": null, "e": 25694, "s": 25654, "text": "Flex (Fast Lexical Analyzer Generator )" }, { "code": null, "e": 25736, "s": 25694, "text": "C program to detect tokens in a C program" }, { "code": null, "e": 25768, "s": 25736, "text": "Introduction of Compiler Design" }, { "code": null, "e": 25799, "s": 25768, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25839, "s": 25799, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25900, "s": 25839, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25932, "s": 25900, "text": "Differences between TCP and UDP" } ]
Creating array with repeated elements in Julia - repeat() Method - GeeksforGeeks
26 Mar, 2020 The repeat() is an inbuilt function in julia which is used to construct an array by repeating the specified array elements with the specified number of times. Syntax:repeat(A::AbstractArray, counts::Integer...)orrepeat(A::AbstractArray; inner, outer)orrepeat(s::AbstractString, r::Integer)orrepeat(c::AbstractChar, r::Integer) Parameters: A::AbstractArray: Specified array. counts::Integer: Specified number of times each element get repeated. inner: It says the repetition of individual element. outer: It says the repetition of whole slice. s::AbstractString: Specified string. r::Integer: Specified number of times each element get repeated. c::AbstractChar: Specified character. Returns: It returns a new constructed array. Example 1: # Julia program to illustrate # the use of Array repeat() method # Constructing an array by repeating# the specified 1D array with the # specified number of times.A = [1, 2, 3, 4];println(repeat(A, 1)) # Constructing an array by repeating# the specified 1D array with the # specified number of times.B = [1, 2, 3, 4];println(repeat(B, 1, 2)) # Constructing an array by repeating# the specified 2D array with the # specified number of times.C = [1 2; 3 4];println(repeat(C, 2)) # Constructing an array by repeating# the specified 2D array with the # specified number of times.D = [1 2; 3 4];println(repeat(D, 2, 2)) Output: Example 2: # Julia program to illustrate # the use of Array repeat() method # Constructing an array by repeating# the specified elements with the # specified inner valueprintln(repeat(1:3, inner = 2)) # Constructing an array by repeating# the specified elements with the # specified outer valueprintln(repeat(2:4, outer = 2)) # Constructing an array by repeating# the specified elements with the # specified inner and outer valueprintln(repeat([5 10; 15 20], inner =(2, 1), outer =(1, 3))) Output: Example 3: # Julia program to illustrate # the use of Array repeat() method # Getting new string after repetition of# specified string or characterprintln(repeat("GFG", 3))println(repeat("GeeksforGeeks", 2))println(repeat("a", 4))println(repeat("A", 5)) Output: GFGGFGGFG GeeksforGeeksGeeksforGeeks aaaa AAAAA Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Working with Date and Time in Julia Get array dimensions and size of a dimension in Julia - size() Method Functions in Julia Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Getting the maximum value from a list in Julia - max() Method Julia Language Introduction Regular Expressions in Julia Broadcasting across arrays in Julia How to Install Julia on Windows ? How to install NumPy package in Julia?
[ { "code": null, "e": 24023, "s": 23995, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24182, "s": 24023, "text": "The repeat() is an inbuilt function in julia which is used to construct an array by repeating the specified array elements with the specified number of times." }, { "code": null, "e": 24350, "s": 24182, "text": "Syntax:repeat(A::AbstractArray, counts::Integer...)orrepeat(A::AbstractArray; inner, outer)orrepeat(s::AbstractString, r::Integer)orrepeat(c::AbstractChar, r::Integer)" }, { "code": null, "e": 24362, "s": 24350, "text": "Parameters:" }, { "code": null, "e": 24397, "s": 24362, "text": "A::AbstractArray: Specified array." }, { "code": null, "e": 24467, "s": 24397, "text": "counts::Integer: Specified number of times each element get repeated." }, { "code": null, "e": 24520, "s": 24467, "text": "inner: It says the repetition of individual element." }, { "code": null, "e": 24566, "s": 24520, "text": "outer: It says the repetition of whole slice." }, { "code": null, "e": 24603, "s": 24566, "text": "s::AbstractString: Specified string." }, { "code": null, "e": 24668, "s": 24603, "text": "r::Integer: Specified number of times each element get repeated." }, { "code": null, "e": 24706, "s": 24668, "text": "c::AbstractChar: Specified character." }, { "code": null, "e": 24751, "s": 24706, "text": "Returns: It returns a new constructed array." }, { "code": null, "e": 24762, "s": 24751, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of Array repeat() method # Constructing an array by repeating# the specified 1D array with the # specified number of times.A = [1, 2, 3, 4];println(repeat(A, 1)) # Constructing an array by repeating# the specified 1D array with the # specified number of times.B = [1, 2, 3, 4];println(repeat(B, 1, 2)) # Constructing an array by repeating# the specified 2D array with the # specified number of times.C = [1 2; 3 4];println(repeat(C, 2)) # Constructing an array by repeating# the specified 2D array with the # specified number of times.D = [1 2; 3 4];println(repeat(D, 2, 2))", "e": 25381, "s": 24762, "text": null }, { "code": null, "e": 25389, "s": 25381, "text": "Output:" }, { "code": null, "e": 25400, "s": 25389, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of Array repeat() method # Constructing an array by repeating# the specified elements with the # specified inner valueprintln(repeat(1:3, inner = 2)) # Constructing an array by repeating# the specified elements with the # specified outer valueprintln(repeat(2:4, outer = 2)) # Constructing an array by repeating# the specified elements with the # specified inner and outer valueprintln(repeat([5 10; 15 20], inner =(2, 1), outer =(1, 3)))", "e": 25882, "s": 25400, "text": null }, { "code": null, "e": 25890, "s": 25882, "text": "Output:" }, { "code": null, "e": 25901, "s": 25890, "text": "Example 3:" }, { "code": "# Julia program to illustrate # the use of Array repeat() method # Getting new string after repetition of# specified string or characterprintln(repeat(\"GFG\", 3))println(repeat(\"GeeksforGeeks\", 2))println(repeat(\"a\", 4))println(repeat(\"A\", 5))", "e": 26145, "s": 25901, "text": null }, { "code": null, "e": 26153, "s": 26145, "text": "Output:" }, { "code": null, "e": 26201, "s": 26153, "text": "GFGGFGGFG\nGeeksforGeeksGeeksforGeeks\naaaa\nAAAAA" }, { "code": null, "e": 26207, "s": 26201, "text": "Julia" }, { "code": null, "e": 26305, "s": 26207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26314, "s": 26305, "text": "Comments" }, { "code": null, "e": 26327, "s": 26314, "text": "Old Comments" }, { "code": null, "e": 26363, "s": 26327, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 26433, "s": 26363, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 26452, "s": 26433, "text": "Functions in Julia" }, { "code": null, "e": 26525, "s": 26452, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 26587, "s": 26525, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 26615, "s": 26587, "text": "Julia Language Introduction" }, { "code": null, "e": 26644, "s": 26615, "text": "Regular Expressions in Julia" }, { "code": null, "e": 26680, "s": 26644, "text": "Broadcasting across arrays in Julia" }, { "code": null, "e": 26714, "s": 26680, "text": "How to Install Julia on Windows ?" } ]
Redis - Publish Subscribe
Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel. In Redis, a client can subscribe any number of channels. Following example explains how publish subscriber concept works. In the following example, one client subscribes a channel named ‘redisChat’. redis 127.0.0.1:6379> SUBSCRIBE redisChat Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "redisChat" 3) (integer) 1 Now, two clients are publishing the messages on the same channel named ‘redisChat’ and the above subscribed client is receiving messages. redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique" (integer) 1 redis 127.0.0.1:6379> PUBLISH redisChat "Learn redis by tutorials point" (integer) 1 1) "message" 2) "redisChat" 3) "Redis is a great caching technique" 1) "message" 2) "redisChat" 3) "Learn redis by tutorials point" Following table lists some basic commands related to Redis Pub/Sub. Subscribes to channels matching the given patterns. Tells the state of Pub/Sub system. For example, which clients are active on the server. Posts a message to a channel. Stops listening for messages posted to channels matching the given patterns. Listens for messages published to the given channels. Stops listening for messages posted to the given channels. 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2283, "s": 2045, "text": "Redis Pub/Sub implements the messaging system where the senders (in redis terminology called publishers) sends the messages while the receivers (subscribers) receive them. The link by which the messages are transferred is called channel." }, { "code": null, "e": 2340, "s": 2283, "text": "In Redis, a client can subscribe any number of channels." }, { "code": null, "e": 2482, "s": 2340, "text": "Following example explains how publish subscriber concept works. In the following example, one client subscribes a channel named ‘redisChat’." }, { "code": null, "e": 2619, "s": 2482, "text": "redis 127.0.0.1:6379> SUBSCRIBE redisChat \nReading messages... (press Ctrl-C to quit) \n1) \"subscribe\" \n2) \"redisChat\" \n3) (integer) 1 \n" }, { "code": null, "e": 2757, "s": 2619, "text": "Now, two clients are publishing the messages on the same channel named ‘redisChat’ and the above subscribed client is receiving messages." }, { "code": null, "e": 3079, "s": 2757, "text": "redis 127.0.0.1:6379> PUBLISH redisChat \"Redis is a great caching technique\" \n(integer) 1 \nredis 127.0.0.1:6379> PUBLISH redisChat \"Learn redis by tutorials point\" \n(integer) 1 \n1) \"message\" \n2) \"redisChat\" \n3) \"Redis is a great caching technique\" \n1) \"message\" \n2) \"redisChat\" \n3) \"Learn redis by tutorials point\" \n" }, { "code": null, "e": 3147, "s": 3079, "text": "Following table lists some basic commands related to Redis Pub/Sub." }, { "code": null, "e": 3199, "s": 3147, "text": "Subscribes to channels matching the given patterns." }, { "code": null, "e": 3287, "s": 3199, "text": "Tells the state of Pub/Sub system. For example, which clients are active on the server." }, { "code": null, "e": 3317, "s": 3287, "text": "Posts a message to a channel." }, { "code": null, "e": 3394, "s": 3317, "text": "Stops listening for messages posted to channels matching the given patterns." }, { "code": null, "e": 3448, "s": 3394, "text": "Listens for messages published to the given channels." }, { "code": null, "e": 3507, "s": 3448, "text": "Stops listening for messages posted to the given channels." }, { "code": null, "e": 3539, "s": 3507, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 3559, "s": 3539, "text": " Skillbakerystudios" }, { "code": null, "e": 3566, "s": 3559, "text": " Print" }, { "code": null, "e": 3577, "s": 3566, "text": " Add Notes" } ]
Solidity - Style Guide
Style Guide helps to maintain code layout consistent and make code more readable. Following are the best practices following while writing contracts with Solidity. Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs. Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs. Two Blank Lines Rule − Use 2 Blank lines between two contract definitions. Two Blank Lines Rule − Use 2 Blank lines between two contract definitions. pragma solidity ^0.5.0; contract LedgerBalance { //... } contract Updater { //... } One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines. One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines. pragma solidity ^0.5.0; contract A { function balance() public pure; function account() public pure; } contract B is A { function balance() public pure { // ... } function account() public pure { // ... } } Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code. Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code. Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one. Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one. function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); variable = function_with_a_long_name( longArgument1, longArgument2, longArgument3 ); event multipleArguments( address sender, address recipient, uint256 publicKey, uint256 amount, bytes32[] options ); MultipleArguments( sender, recipient, publicKey, amount, options ); Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably. Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably. Imports − Import statements should be placed at the top of the file just after pragma declaration. Imports − Import statements should be placed at the top of the file just after pragma declaration. Order of Functions − Functions should be grouped as per their visibility. Order of Functions − Functions should be grouped as per their visibility. pragma solidity ^0.5.0; contract A { constructor() public { // ... } function() external { // ... } // External functions // ... // External view functions // ... // External pure functions // ... // Public functions // ... // Internal functions // ... // Private functions // ... } Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace. Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace. pragma solidity ^0.5.0; contract Coin { struct Bank { address owner; uint balance; } } if (x < 3) { x += 1; } else if (x > 7) { x -= 1; } else { x = 5; } if (x < 3) x += 1; else x -= 1; Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. function kill() public onlyowner { selfdestruct(owner); } Mappings − Avoid whitespaces while declaring mapping variables. Mappings − Avoid whitespaces while declaring mapping variables. mapping(uint => uint) map; mapping(address => bool) registeredAddresses; mapping(uint => mapping(bool => Data[])) public data; mapping(uint => mapping(uint => s)) data; Variable declaration − Avoid whitespaces while declaring array variables. Variable declaration − Avoid whitespaces while declaring array variables. uint[] x; // not unit [] x; String declaration − Use double quotes to declare a string instead of single quote. String declaration − Use double quotes to declare a string instead of single quote. str = "foo"; str = "Hamlet says, 'To be or not to be...'"; Elements should be layout in following order. Pragma statements Pragma statements Import statements Import statements Interfaces Interfaces Libraries Libraries Contracts Contracts Within Interfaces, libraries or contracts the order should be as − Type declarations Type declarations State variables State variables Events Events Functions Functions Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc. Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc. Contract and Library name should match their file names. Contract and Library name should match their file names. In case of multiple contracts/libraries in a file, use name of core contract/library. In case of multiple contracts/libraries in a file, use name of core contract/library. Owned.sol pragma solidity ^0.5.0; // Owned.sol contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { //.... } function transferOwnership(address newOwner) public onlyOwner { //... } } Congress.sol pragma solidity ^0.5.0; // Congress.sol import "./Owned.sol"; contract Congress is Owned, TokenRecipient { //... } Struct Names − Use CapWords Style like SmartCoin. Struct Names Event Names − Use CapWords Style like Deposit, AfterTransfer. Event Names Function Names − Use mixedCase Style like initiateSupply. Function Names Local and State variables − Use mixedCase Style like creatorAddress, supply. Local and State variables Constants − Use all capital letters with underscore to seperate words like MAX_BLOCKS. Constants Modifier Names − Use mixCase Style like onlyAfter. Modifier Names Enum Names − Use CapWords Style like TokenGroup. Enum Names 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2719, "s": 2555, "text": "Style Guide helps to maintain code layout consistent and make code more readable. Following are the best practices following while writing contracts with Solidity." }, { "code": null, "e": 2823, "s": 2719, "text": "Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs." }, { "code": null, "e": 2927, "s": 2823, "text": "Indentation − Use 4 spaces instead of tab to maintain indentation level. Avoid mixing spaces with tabs." }, { "code": null, "e": 3002, "s": 2927, "text": "Two Blank Lines Rule − Use 2 Blank lines between two contract definitions." }, { "code": null, "e": 3077, "s": 3002, "text": "Two Blank Lines Rule − Use 2 Blank lines between two contract definitions." }, { "code": null, "e": 3168, "s": 3077, "text": "pragma solidity ^0.5.0;\n\ncontract LedgerBalance {\n //...\n}\ncontract Updater {\n //...\n}" }, { "code": null, "e": 3288, "s": 3168, "text": "One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines." }, { "code": null, "e": 3408, "s": 3288, "text": "One Blank Line Rule − Use 1 Blank line between two functions. In case of only declaration, no need to have blank lines." }, { "code": null, "e": 3646, "s": 3408, "text": "pragma solidity ^0.5.0;\n\ncontract A {\n function balance() public pure;\n function account() public pure;\n}\ncontract B is A {\n function balance() public pure {\n // ...\n }\n function account() public pure {\n // ...\n }\n}" }, { "code": null, "e": 3756, "s": 3646, "text": "Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code." }, { "code": null, "e": 3866, "s": 3756, "text": "Maximum Line Length − A single line should not cross 79 characters so that readers can easily parse the code." }, { "code": null, "e": 4021, "s": 3866, "text": "Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one." }, { "code": null, "e": 4176, "s": 4021, "text": "Wrapping rules − First argument be in new line without opening parenthesis. Use single indent per argument. Terminating element ); should be the last one." }, { "code": null, "e": 4567, "s": 4176, "text": "function_with_a_long_name(\n longArgument1,\n longArgument2,\n longArgument3\n);\nvariable = function_with_a_long_name(\n longArgument1,\n longArgument2,\n longArgument3\n);\nevent multipleArguments(\n address sender,\n address recipient,\n uint256 publicKey,\n uint256 amount,\n bytes32[] options\n);\nMultipleArguments(\n sender,\n recipient,\n publicKey,\n amount,\n options\n);" }, { "code": null, "e": 4640, "s": 4567, "text": "Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably." }, { "code": null, "e": 4713, "s": 4640, "text": "Source Code Encoding − UTF-8 or ASCII encoding is to be used preferably." }, { "code": null, "e": 4812, "s": 4713, "text": "Imports − Import statements should be placed at the top of the file just after pragma declaration." }, { "code": null, "e": 4911, "s": 4812, "text": "Imports − Import statements should be placed at the top of the file just after pragma declaration." }, { "code": null, "e": 4985, "s": 4911, "text": "Order of Functions − Functions should be grouped as per their visibility." }, { "code": null, "e": 5059, "s": 4985, "text": "Order of Functions − Functions should be grouped as per their visibility." }, { "code": null, "e": 5410, "s": 5059, "text": "pragma solidity ^0.5.0;\n\ncontract A {\n constructor() public {\n // ...\n }\n function() external {\n // ...\n }\n\n // External functions\n // ...\n\n // External view functions\n // ...\n\n // External pure functions \n // ...\n\n // Public functions\n // ...\n\n // Internal functions\n // ...\n\n // Private functions\n // ...\n}" }, { "code": null, "e": 5507, "s": 5410, "text": "Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. " }, { "code": null, "e": 5604, "s": 5507, "text": "Avoid extra whitespaces − Avoid whitespaces immediately inside parenthesis, brackets or braces. " }, { "code": null, "e": 5763, "s": 5604, "text": "Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace." }, { "code": null, "e": 5922, "s": 5763, "text": "Control structures − Braces should open on same line as declaration. Close on their own line maintaining the same indentation. Use a space with opening brace." }, { "code": null, "e": 6142, "s": 5922, "text": "pragma solidity ^0.5.0;\n\ncontract Coin {\n struct Bank {\n address owner;\n uint balance;\n }\n}\nif (x < 3) {\n x += 1;\n} else if (x > 7) {\n x -= 1;\n} else {\n x = 5;\n}\nif (x < 3)\n x += 1;\nelse\n x -= 1;" }, { "code": null, "e": 6291, "s": 6142, "text": "Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. " }, { "code": null, "e": 6440, "s": 6291, "text": "Function Declaration − Use the above rule for braces. Always add a visibility label. Visibility label should come first before any custom modifier. " }, { "code": null, "e": 6501, "s": 6440, "text": "function kill() public onlyowner {\n selfdestruct(owner);\n}" }, { "code": null, "e": 6565, "s": 6501, "text": "Mappings − Avoid whitespaces while declaring mapping variables." }, { "code": null, "e": 6629, "s": 6565, "text": "Mappings − Avoid whitespaces while declaring mapping variables." }, { "code": null, "e": 6798, "s": 6629, "text": "mapping(uint => uint) map;\nmapping(address => bool) registeredAddresses;\nmapping(uint => mapping(bool => Data[])) public data;\nmapping(uint => mapping(uint => s)) data;" }, { "code": null, "e": 6872, "s": 6798, "text": "Variable declaration − Avoid whitespaces while declaring array variables." }, { "code": null, "e": 6946, "s": 6872, "text": "Variable declaration − Avoid whitespaces while declaring array variables." }, { "code": null, "e": 6975, "s": 6946, "text": "uint[] x; // not unit [] x;" }, { "code": null, "e": 7059, "s": 6975, "text": "String declaration − Use double quotes to declare a string instead of single quote." }, { "code": null, "e": 7143, "s": 7059, "text": "String declaration − Use double quotes to declare a string instead of single quote." }, { "code": null, "e": 7202, "s": 7143, "text": "str = \"foo\";\nstr = \"Hamlet says, 'To be or not to be...'\";" }, { "code": null, "e": 7248, "s": 7202, "text": "Elements should be layout in following order." }, { "code": null, "e": 7266, "s": 7248, "text": "Pragma statements" }, { "code": null, "e": 7284, "s": 7266, "text": "Pragma statements" }, { "code": null, "e": 7302, "s": 7284, "text": "Import statements" }, { "code": null, "e": 7320, "s": 7302, "text": "Import statements" }, { "code": null, "e": 7331, "s": 7320, "text": "Interfaces" }, { "code": null, "e": 7342, "s": 7331, "text": "Interfaces" }, { "code": null, "e": 7352, "s": 7342, "text": "Libraries" }, { "code": null, "e": 7362, "s": 7352, "text": "Libraries" }, { "code": null, "e": 7372, "s": 7362, "text": "Contracts" }, { "code": null, "e": 7382, "s": 7372, "text": "Contracts" }, { "code": null, "e": 7449, "s": 7382, "text": "Within Interfaces, libraries or contracts the order should be as −" }, { "code": null, "e": 7467, "s": 7449, "text": "Type declarations" }, { "code": null, "e": 7485, "s": 7467, "text": "Type declarations" }, { "code": null, "e": 7501, "s": 7485, "text": "State variables" }, { "code": null, "e": 7517, "s": 7501, "text": "State variables" }, { "code": null, "e": 7524, "s": 7517, "text": "Events" }, { "code": null, "e": 7531, "s": 7524, "text": "Events" }, { "code": null, "e": 7541, "s": 7531, "text": "Functions" }, { "code": null, "e": 7551, "s": 7541, "text": "Functions" }, { "code": null, "e": 7649, "s": 7551, "text": "Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc." }, { "code": null, "e": 7747, "s": 7649, "text": "Contract and Library should be named using CapWords Style. For example, SmartContract, Owner etc." }, { "code": null, "e": 7804, "s": 7747, "text": "Contract and Library name should match their file names." }, { "code": null, "e": 7861, "s": 7804, "text": "Contract and Library name should match their file names." }, { "code": null, "e": 7947, "s": 7861, "text": "In case of multiple contracts/libraries in a file, use name of core contract/library." }, { "code": null, "e": 8033, "s": 7947, "text": "In case of multiple contracts/libraries in a file, use name of core contract/library." }, { "code": null, "e": 8043, "s": 8033, "text": "Owned.sol" }, { "code": null, "e": 8308, "s": 8043, "text": "pragma solidity ^0.5.0;\n\n// Owned.sol\ncontract Owned {\n address public owner;\n constructor() public {\n owner = msg.sender;\n }\n modifier onlyOwner {\n //....\n }\n function transferOwnership(address newOwner) public onlyOwner {\n //...\n }\n}" }, { "code": null, "e": 8321, "s": 8308, "text": "Congress.sol" }, { "code": null, "e": 8441, "s": 8321, "text": "pragma solidity ^0.5.0;\n\n// Congress.sol\nimport \"./Owned.sol\";\n\ncontract Congress is Owned, TokenRecipient {\n //...\n}" }, { "code": null, "e": 8491, "s": 8441, "text": "Struct Names − Use CapWords Style like SmartCoin." }, { "code": null, "e": 8504, "s": 8491, "text": "Struct Names" }, { "code": null, "e": 8566, "s": 8504, "text": "Event Names − Use CapWords Style like Deposit, AfterTransfer." }, { "code": null, "e": 8578, "s": 8566, "text": "Event Names" }, { "code": null, "e": 8636, "s": 8578, "text": "Function Names − Use mixedCase Style like initiateSupply." }, { "code": null, "e": 8651, "s": 8636, "text": "Function Names" }, { "code": null, "e": 8728, "s": 8651, "text": "Local and State variables − Use mixedCase Style like creatorAddress, supply." }, { "code": null, "e": 8754, "s": 8728, "text": "Local and State variables" }, { "code": null, "e": 8841, "s": 8754, "text": "Constants − Use all capital letters with underscore to seperate words like MAX_BLOCKS." }, { "code": null, "e": 8851, "s": 8841, "text": "Constants" }, { "code": null, "e": 8902, "s": 8851, "text": "Modifier Names − Use mixCase Style like onlyAfter." }, { "code": null, "e": 8917, "s": 8902, "text": "Modifier Names" }, { "code": null, "e": 8966, "s": 8917, "text": "Enum Names − Use CapWords Style like TokenGroup." }, { "code": null, "e": 8977, "s": 8966, "text": "Enum Names" }, { "code": null, "e": 9012, "s": 8977, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9029, "s": 9012, "text": " Abhilash Nelson" }, { "code": null, "e": 9064, "s": 9029, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 9081, "s": 9064, "text": " Frahaan Hussain" }, { "code": null, "e": 9116, "s": 9081, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9130, "s": 9116, "text": " Swapnil Kole" }, { "code": null, "e": 9137, "s": 9130, "text": " Print" }, { "code": null, "e": 9148, "s": 9137, "text": " Add Notes" } ]
Python 3 - os.open() Method
The method open() opens the file file and set various flags according to flags and possibly its mode according to mode.The default mode is 0777 (octal), and the current umask value is first masked out. Following is the syntax for open() method − os.open(file, flags[, mode]); file − File name to be opened. flags − The following constants are options for the flags. They can be combined using the bitwise OR operator |. Some of them are not available on all platforms. os.O_RDONLY − open for reading only os.O_RDONLY − open for reading only os.O_WRONLY − open for writing only os.O_WRONLY − open for writing only os.O_RDWR − open for reading and writing os.O_RDWR − open for reading and writing os.O_NONBLOCK − do not block on open os.O_NONBLOCK − do not block on open os.O_APPEND − append on each write os.O_APPEND − append on each write os.O_CREAT − create file if it does not exist os.O_CREAT − create file if it does not exist os.O_TRUNC − truncate size to 0 os.O_TRUNC − truncate size to 0 os.O_EXCL − error if create and file exists os.O_EXCL − error if create and file exists os.O_SHLOCK − atomically obtain a shared lock os.O_SHLOCK − atomically obtain a shared lock os.O_EXLOCK − atomically obtain an exclusive lock os.O_EXLOCK − atomically obtain an exclusive lock os.O_DIRECT − eliminate or reduce cache effects os.O_DIRECT − eliminate or reduce cache effects os.O_FSYNC − synchronous writes os.O_FSYNC − synchronous writes os.O_NOFOLLOW − do not follow symlinks os.O_NOFOLLOW − do not follow symlinks mode − This work in similar way as it works for chmod() method. This method returns the file descriptor for the newly opened file. The following example shows the usage of open() method. #!/usr/bin/python3 import os, sys # Open a file fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Write one string line = "this is test" # string needs to be converted byte object b = str.encode(line) os.write(fd, b) # Close opened file os.close( fd) print ("Closed the file successfully!!") This would create given file foo.txt and then would write given content in that file and would produce following result − Closed the file successfully!! 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2542, "s": 2340, "text": "The method open() opens the file file and set various flags according to flags and possibly its mode according to mode.The default mode is 0777 (octal), and the current umask value is first masked out." }, { "code": null, "e": 2586, "s": 2542, "text": "Following is the syntax for open() method −" }, { "code": null, "e": 2617, "s": 2586, "text": "os.open(file, flags[, mode]);\n" }, { "code": null, "e": 2648, "s": 2617, "text": "file − File name to be opened." }, { "code": null, "e": 2810, "s": 2648, "text": "flags − The following constants are options for the flags. They can be combined using the bitwise OR operator |. Some of them are not available on all platforms." }, { "code": null, "e": 2846, "s": 2810, "text": "os.O_RDONLY − open for reading only" }, { "code": null, "e": 2882, "s": 2846, "text": "os.O_RDONLY − open for reading only" }, { "code": null, "e": 2918, "s": 2882, "text": "os.O_WRONLY − open for writing only" }, { "code": null, "e": 2954, "s": 2918, "text": "os.O_WRONLY − open for writing only" }, { "code": null, "e": 2995, "s": 2954, "text": "os.O_RDWR − open for reading and writing" }, { "code": null, "e": 3036, "s": 2995, "text": "os.O_RDWR − open for reading and writing" }, { "code": null, "e": 3073, "s": 3036, "text": "os.O_NONBLOCK − do not block on open" }, { "code": null, "e": 3110, "s": 3073, "text": "os.O_NONBLOCK − do not block on open" }, { "code": null, "e": 3145, "s": 3110, "text": "os.O_APPEND − append on each write" }, { "code": null, "e": 3180, "s": 3145, "text": "os.O_APPEND − append on each write" }, { "code": null, "e": 3226, "s": 3180, "text": "os.O_CREAT − create file if it does not exist" }, { "code": null, "e": 3272, "s": 3226, "text": "os.O_CREAT − create file if it does not exist" }, { "code": null, "e": 3304, "s": 3272, "text": "os.O_TRUNC − truncate size to 0" }, { "code": null, "e": 3336, "s": 3304, "text": "os.O_TRUNC − truncate size to 0" }, { "code": null, "e": 3380, "s": 3336, "text": "os.O_EXCL − error if create and file exists" }, { "code": null, "e": 3424, "s": 3380, "text": "os.O_EXCL − error if create and file exists" }, { "code": null, "e": 3470, "s": 3424, "text": "os.O_SHLOCK − atomically obtain a shared lock" }, { "code": null, "e": 3516, "s": 3470, "text": "os.O_SHLOCK − atomically obtain a shared lock" }, { "code": null, "e": 3566, "s": 3516, "text": "os.O_EXLOCK − atomically obtain an exclusive lock" }, { "code": null, "e": 3616, "s": 3566, "text": "os.O_EXLOCK − atomically obtain an exclusive lock" }, { "code": null, "e": 3664, "s": 3616, "text": "os.O_DIRECT − eliminate or reduce cache effects" }, { "code": null, "e": 3712, "s": 3664, "text": "os.O_DIRECT − eliminate or reduce cache effects" }, { "code": null, "e": 3745, "s": 3712, "text": "os.O_FSYNC − synchronous writes" }, { "code": null, "e": 3778, "s": 3745, "text": "os.O_FSYNC − synchronous writes" }, { "code": null, "e": 3817, "s": 3778, "text": "os.O_NOFOLLOW − do not follow symlinks" }, { "code": null, "e": 3856, "s": 3817, "text": "os.O_NOFOLLOW − do not follow symlinks" }, { "code": null, "e": 3920, "s": 3856, "text": "mode − This work in similar way as it works for chmod() method." }, { "code": null, "e": 3987, "s": 3920, "text": "This method returns the file descriptor for the newly opened file." }, { "code": null, "e": 4043, "s": 3987, "text": "The following example shows the usage of open() method." }, { "code": null, "e": 4341, "s": 4043, "text": "#!/usr/bin/python3\nimport os, sys\n\n# Open a file\nfd = os.open( \"foo.txt\", os.O_RDWR|os.O_CREAT )\n\n# Write one string\n\nline = \"this is test\" \n# string needs to be converted byte object\nb = str.encode(line)\nos.write(fd, b)\n\n# Close opened file\nos.close( fd)\n\nprint (\"Closed the file successfully!!\")" }, { "code": null, "e": 4463, "s": 4341, "text": "This would create given file foo.txt and then would write given content in that file and would produce following result −" }, { "code": null, "e": 4495, "s": 4463, "text": "Closed the file successfully!!\n" }, { "code": null, "e": 4532, "s": 4495, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4548, "s": 4532, "text": " Malhar Lathkar" }, { "code": null, "e": 4581, "s": 4548, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4600, "s": 4581, "text": " Arnab Chakraborty" }, { "code": null, "e": 4635, "s": 4600, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4657, "s": 4635, "text": " In28Minutes Official" }, { "code": null, "e": 4691, "s": 4657, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4719, "s": 4691, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4754, "s": 4719, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4768, "s": 4754, "text": " Lets Kode It" }, { "code": null, "e": 4801, "s": 4768, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4818, "s": 4801, "text": " Abhilash Nelson" }, { "code": null, "e": 4825, "s": 4818, "text": " Print" }, { "code": null, "e": 4836, "s": 4825, "text": " Add Notes" } ]
Decision Tree Algorithm for Multiclass problems using Python | by Angel Das | Towards Data Science
Decision tree classifiers are supervised learning models that are useful when we care about interpretability. Think of it like, breaking down the data by making decisions based on multiple questions at each level. The biggest challenge with the decision tree involves understanding the back end algorithm using which a tree spans out into branches and sub-branches. In this article, we will take a broader look into how different impurity metrics are used to determine the decision variables at each node, how important features are determined, and more importantly how trees are pruned to prevent model overfitting. To get a better understanding of how the decision tree works, you can refer to the link below. towardsdatascience.com Decision trees consist of nodes and branches. The nodes can further be classified into a root node (starting node of the tree), decision nodes (sub-nodes that splits based on conditions), and leaf nodes (nodes that don’t branch out further). Since the decision tree follows an if-else structure, every node uses one and only one independent variable to split into two or more branches. The independent variable can be categorical or continuous. For categorical variables, the categories are used to decide the split of the node, for continuous variables the algorithm comes up with multiple threshold values that act as the decision-maker (Raschka, Julian and Hearty, 2016, pp.83, 88, 89). Say we are trying to develop a decision tree for the dataset below. The dataset consists of Student IDs, their gender information, their study method, and an attribute that identifies if they play cricket or not. We can demarcate between the predictor and dependent variables vs. the independent variables or attributes. The dependent variable being the “Plays Cricket” column and rest of the attributes other than the “Student ID” will form the independent variables set. Say we are trying to develop a decision tree for the dataset shown in Figure 1 below. The dataset consists of Student IDs, their gender information, their study method, and an attribute that identifies if they play cricket or not. We can demarcate between the predictor and dependent variables vs. the independent variables or attributes. The dependent variable being the “Plays Cricket” column and rest of the attributes other than the “Student ID” will form the independent variables set. As step 1 to this problem, we need to identify which independent variable can be used to split the root node. Let’s use Gini Impurity to decide the branching of students in cricketers and non-cricketers. We will be calculating the Gini Impurity using both “Gender” and “Study Method” and consider the one with the lowest impurity score. Note that decision trees algorithm tries to make every node as homogeneous as possible. This is in line with the outcome we are trying to achieve, predict students as cricketers and non-cricketers correctly. Homogeneity is a situation under which all students in a particular node belong to one of the categories, i.e. either they are cricketers (Plays Cricket = Y) or non-Cricketers (Plays Cricket = N). Since impurity is a measure of how homogeneous a node is, the algorithm with chose the independent variable with the lowest weighted average impurity score as the decision variable for the root node, in this case, “Gender” will be used to create the first split of the decision tree. Also, note the figures highlighted in yellow, they are used to calculate the information gain of the split. Information Gain can be defined as the change in impurity from the parent node to their respective child nodes, in this scenario we need to check if impurity in the root node is higher than Weighted Impurity of the Split. If the information gain is greater than 0, the algorithm will go ahead and split the node using the decision variable. Decision trees in general will continue to form branches till every node becomes homogeneous. As a result of this, the tree works well with the training data but fails to produce quality output for the test data. Hence the tree should be pruned to prevent overfitting. From the above example, we can fine-tune the decision tree using the factors outlined below. Criterion — Python works with Gini & Entropy. Other algorithm uses CHAID (Chi-square Automatic Interaction Detector), miss classification errors, etc.Information Gain or minimum impurity decrease from root node/parent node to child nodesNumber of samples in each node (minimum or maximum)Depth of the tree (how many branches should the algorithm form)Maximum number of leaves Criterion — Python works with Gini & Entropy. Other algorithm uses CHAID (Chi-square Automatic Interaction Detector), miss classification errors, etc. Information Gain or minimum impurity decrease from root node/parent node to child nodes Number of samples in each node (minimum or maximum) Depth of the tree (how many branches should the algorithm form) Maximum number of leaves The problem statement aims at developing a classification model to predict the quality of red wine. Details about the problem statement can be found here. This is a classic example of a multi-class classification problem. We won’t look into the codes, but rather try and interpret the output using DecisionTreeClassifier() from sklearn.tree in Python. Reference of the code Snippets below: Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77 #Reading the datawine_df = pd.read_csv('winequality-red.csv',sep=';')# splitting data into training and test set for independent attributesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test =train_test_split(wine_df.drop('quality',axis=1), wine_df['quality'], test_size=.3, random_state=22)X_train.shape,X_test.shape#developing a modelclf_pruned = DecisionTreeClassifier(criterion = "gini", random_state = 100, max_depth=3, min_samples_leaf=5)clf_pruned.fit(X_train, y_train)#visualizing the treeimport iofrom io import StringIOfrom sklearn.tree import export_graphviz# from sklearn.externals.six import StringIO from IPython.display import Image import pydotplusimport graphvizxvar = wine_df.drop('quality', axis=1)feature_cols = xvar.columnsdot_data = StringIO()export_graphviz(clf_pruned, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1','2'])from pydot import graph_from_dot_data(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png()) When we look at a multiclass algorithm, let’s not get confused about how to calculate the Gini Index. In the example before we had P and Q to represent students playing cricket and students not playing cricket. Where P is the probability of playing Cricket and Q is the probability of not playing cricket. In the case of a multiclass decision tree, for node alcohol <=0.25 we will perform the following calculation. P represents probability of the Wine being quality 5 which is (514/1119) = 0.46 Q represents probability of the Wine being quality 6 which is (448/1119) = 0.40 R represents probability of the Wine being quality 7 which is (157/1119) = 0.14 Gini Index = P2 + Q2 + R2 = (0.46)2 + (0.40)2 + (0.14)2 = 0.39 Gini Impurity = 1–0.39 = 0.61 (see it matches) The above tree is pruned so that we can visualize the model better. There is no statistical significance of using a depth 3 or maximum sample leaf as 5. Instead of using criterion = “gini” we can always use criterion= “entropy” to obtain the above tree diagram. Entropy is calculated as -P*log(P)-Q*log(Q). Feature importance refers to a class of techniques for assigning scores to input features of a predictive model that indicates the relative importance of each feature when making a prediction (Das, 2020). ## Calculating feature importancefeat_importance = clf_pruned.tree_.compute_feature_importances(normalize=False)feat_imp_dict = dict(zip(feature_cols, clf_pruned.feature_importances_))feat_imp = pd.DataFrame.from_dict(feat_imp_dict, orient='index')feat_imp.rename(columns = {0:'FeatureImportance'}, inplace = True)feat_imp.sort_values(by=['FeatureImportance'], ascending=False).head() Let us try and understand the following to get a better picture of how feature importance is decided. First split is based on alcohol <=10.25; This variable with this threshold ensures minimum impurity of all other variables hence in the above table (Figure 5) you see that the feature importance is highThe next split is based on sulphates <-0.555 and <=0.685, so sulphates come second in the orderWhen we look at the third level of the split, we see that there are three contenders, chlorides <=0.08, total sulfur dioxide <=88.5, volatile acidity <=0.87. First split is based on alcohol <=10.25; This variable with this threshold ensures minimum impurity of all other variables hence in the above table (Figure 5) you see that the feature importance is high The next split is based on sulphates <-0.555 and <=0.685, so sulphates come second in the order When we look at the third level of the split, we see that there are three contenders, chlorides <=0.08, total sulfur dioxide <=88.5, volatile acidity <=0.87. To decide which independent variable is important we need to understand the information gain by splitting these parent nodes into their respective child nodes. So, we see that the information gain by splitting Node “volatile acidity <=0.87” is higher than by splitting “total sulfur dioxide <=88.5” hence in the importance table “volatile acidity <=0.87” is placed above “total sulfur dioxide <=88.5”. The cost complexity refers to the complexity parameter that is used to define the cost complexity measure Ra(T) of a given tree T. Ra(T) is written as: Ra(T) = R(T) + a|T| where |T| is the number of terminal nodes, R(T) is the total misclassification rate of the terminal node, and a is the CCP parameter. To summarise, the subtree with the highest cost complexity that is smaller than ccp_alpha will be retained. It is always good to select a CCP parameter that produces the highest test accuracy (Scikit Learn, n.d.). Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89.‌Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html.Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py.Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77 [Accessed 18 Jul. 2020]. Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89. ‌Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011. Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html. Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py. Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77 [Accessed 18 Jul. 2020]. About the Author: Advanced analytics professional and management consultant helping companies find solutions for diverse problems through a mix of business, technology, and math on organizational data. A Data Science enthusiast, here to share, learn and contribute; You can connect with me on Linked and Twitter;
[ { "code": null, "e": 884, "s": 172, "text": "Decision tree classifiers are supervised learning models that are useful when we care about interpretability. Think of it like, breaking down the data by making decisions based on multiple questions at each level. The biggest challenge with the decision tree involves understanding the back end algorithm using which a tree spans out into branches and sub-branches. In this article, we will take a broader look into how different impurity metrics are used to determine the decision variables at each node, how important features are determined, and more importantly how trees are pruned to prevent model overfitting. To get a better understanding of how the decision tree works, you can refer to the link below." }, { "code": null, "e": 907, "s": 884, "text": "towardsdatascience.com" }, { "code": null, "e": 1597, "s": 907, "text": "Decision trees consist of nodes and branches. The nodes can further be classified into a root node (starting node of the tree), decision nodes (sub-nodes that splits based on conditions), and leaf nodes (nodes that don’t branch out further). Since the decision tree follows an if-else structure, every node uses one and only one independent variable to split into two or more branches. The independent variable can be categorical or continuous. For categorical variables, the categories are used to decide the split of the node, for continuous variables the algorithm comes up with multiple threshold values that act as the decision-maker (Raschka, Julian and Hearty, 2016, pp.83, 88, 89)." }, { "code": null, "e": 2070, "s": 1597, "text": "Say we are trying to develop a decision tree for the dataset below. The dataset consists of Student IDs, their gender information, their study method, and an attribute that identifies if they play cricket or not. We can demarcate between the predictor and dependent variables vs. the independent variables or attributes. The dependent variable being the “Plays Cricket” column and rest of the attributes other than the “Student ID” will form the independent variables set." }, { "code": null, "e": 2561, "s": 2070, "text": "Say we are trying to develop a decision tree for the dataset shown in Figure 1 below. The dataset consists of Student IDs, their gender information, their study method, and an attribute that identifies if they play cricket or not. We can demarcate between the predictor and dependent variables vs. the independent variables or attributes. The dependent variable being the “Plays Cricket” column and rest of the attributes other than the “Student ID” will form the independent variables set." }, { "code": null, "e": 3303, "s": 2561, "text": "As step 1 to this problem, we need to identify which independent variable can be used to split the root node. Let’s use Gini Impurity to decide the branching of students in cricketers and non-cricketers. We will be calculating the Gini Impurity using both “Gender” and “Study Method” and consider the one with the lowest impurity score. Note that decision trees algorithm tries to make every node as homogeneous as possible. This is in line with the outcome we are trying to achieve, predict students as cricketers and non-cricketers correctly. Homogeneity is a situation under which all students in a particular node belong to one of the categories, i.e. either they are cricketers (Plays Cricket = Y) or non-Cricketers (Plays Cricket = N)." }, { "code": null, "e": 4036, "s": 3303, "text": "Since impurity is a measure of how homogeneous a node is, the algorithm with chose the independent variable with the lowest weighted average impurity score as the decision variable for the root node, in this case, “Gender” will be used to create the first split of the decision tree. Also, note the figures highlighted in yellow, they are used to calculate the information gain of the split. Information Gain can be defined as the change in impurity from the parent node to their respective child nodes, in this scenario we need to check if impurity in the root node is higher than Weighted Impurity of the Split. If the information gain is greater than 0, the algorithm will go ahead and split the node using the decision variable." }, { "code": null, "e": 4398, "s": 4036, "text": "Decision trees in general will continue to form branches till every node becomes homogeneous. As a result of this, the tree works well with the training data but fails to produce quality output for the test data. Hence the tree should be pruned to prevent overfitting. From the above example, we can fine-tune the decision tree using the factors outlined below." }, { "code": null, "e": 4774, "s": 4398, "text": "Criterion — Python works with Gini & Entropy. Other algorithm uses CHAID (Chi-square Automatic Interaction Detector), miss classification errors, etc.Information Gain or minimum impurity decrease from root node/parent node to child nodesNumber of samples in each node (minimum or maximum)Depth of the tree (how many branches should the algorithm form)Maximum number of leaves" }, { "code": null, "e": 4925, "s": 4774, "text": "Criterion — Python works with Gini & Entropy. Other algorithm uses CHAID (Chi-square Automatic Interaction Detector), miss classification errors, etc." }, { "code": null, "e": 5013, "s": 4925, "text": "Information Gain or minimum impurity decrease from root node/parent node to child nodes" }, { "code": null, "e": 5065, "s": 5013, "text": "Number of samples in each node (minimum or maximum)" }, { "code": null, "e": 5129, "s": 5065, "text": "Depth of the tree (how many branches should the algorithm form)" }, { "code": null, "e": 5154, "s": 5129, "text": "Maximum number of leaves" }, { "code": null, "e": 5506, "s": 5154, "text": "The problem statement aims at developing a classification model to predict the quality of red wine. Details about the problem statement can be found here. This is a classic example of a multi-class classification problem. We won’t look into the codes, but rather try and interpret the output using DecisionTreeClassifier() from sklearn.tree in Python." }, { "code": null, "e": 5770, "s": 5506, "text": "Reference of the code Snippets below: Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77" }, { "code": null, "e": 6950, "s": 5770, "text": "#Reading the datawine_df = pd.read_csv('winequality-red.csv',sep=';')# splitting data into training and test set for independent attributesfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test =train_test_split(wine_df.drop('quality',axis=1), wine_df['quality'], test_size=.3, random_state=22)X_train.shape,X_test.shape#developing a modelclf_pruned = DecisionTreeClassifier(criterion = \"gini\", random_state = 100, max_depth=3, min_samples_leaf=5)clf_pruned.fit(X_train, y_train)#visualizing the treeimport iofrom io import StringIOfrom sklearn.tree import export_graphviz# from sklearn.externals.six import StringIO from IPython.display import Image import pydotplusimport graphvizxvar = wine_df.drop('quality', axis=1)feature_cols = xvar.columnsdot_data = StringIO()export_graphviz(clf_pruned, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1','2'])from pydot import graph_from_dot_data(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png())" }, { "code": null, "e": 7366, "s": 6950, "text": "When we look at a multiclass algorithm, let’s not get confused about how to calculate the Gini Index. In the example before we had P and Q to represent students playing cricket and students not playing cricket. Where P is the probability of playing Cricket and Q is the probability of not playing cricket. In the case of a multiclass decision tree, for node alcohol <=0.25 we will perform the following calculation." }, { "code": null, "e": 7446, "s": 7366, "text": "P represents probability of the Wine being quality 5 which is (514/1119) = 0.46" }, { "code": null, "e": 7526, "s": 7446, "text": "Q represents probability of the Wine being quality 6 which is (448/1119) = 0.40" }, { "code": null, "e": 7606, "s": 7526, "text": "R represents probability of the Wine being quality 7 which is (157/1119) = 0.14" }, { "code": null, "e": 7669, "s": 7606, "text": "Gini Index = P2 + Q2 + R2 = (0.46)2 + (0.40)2 + (0.14)2 = 0.39" }, { "code": null, "e": 7716, "s": 7669, "text": "Gini Impurity = 1–0.39 = 0.61 (see it matches)" }, { "code": null, "e": 7869, "s": 7716, "text": "The above tree is pruned so that we can visualize the model better. There is no statistical significance of using a depth 3 or maximum sample leaf as 5." }, { "code": null, "e": 8023, "s": 7869, "text": "Instead of using criterion = “gini” we can always use criterion= “entropy” to obtain the above tree diagram. Entropy is calculated as -P*log(P)-Q*log(Q)." }, { "code": null, "e": 8228, "s": 8023, "text": "Feature importance refers to a class of techniques for assigning scores to input features of a predictive model that indicates the relative importance of each feature when making a prediction (Das, 2020)." }, { "code": null, "e": 8613, "s": 8228, "text": "## Calculating feature importancefeat_importance = clf_pruned.tree_.compute_feature_importances(normalize=False)feat_imp_dict = dict(zip(feature_cols, clf_pruned.feature_importances_))feat_imp = pd.DataFrame.from_dict(feat_imp_dict, orient='index')feat_imp.rename(columns = {0:'FeatureImportance'}, inplace = True)feat_imp.sort_values(by=['FeatureImportance'], ascending=False).head()" }, { "code": null, "e": 8715, "s": 8613, "text": "Let us try and understand the following to get a better picture of how feature importance is decided." }, { "code": null, "e": 9170, "s": 8715, "text": "First split is based on alcohol <=10.25; This variable with this threshold ensures minimum impurity of all other variables hence in the above table (Figure 5) you see that the feature importance is highThe next split is based on sulphates <-0.555 and <=0.685, so sulphates come second in the orderWhen we look at the third level of the split, we see that there are three contenders, chlorides <=0.08, total sulfur dioxide <=88.5, volatile acidity <=0.87." }, { "code": null, "e": 9373, "s": 9170, "text": "First split is based on alcohol <=10.25; This variable with this threshold ensures minimum impurity of all other variables hence in the above table (Figure 5) you see that the feature importance is high" }, { "code": null, "e": 9469, "s": 9373, "text": "The next split is based on sulphates <-0.555 and <=0.685, so sulphates come second in the order" }, { "code": null, "e": 9627, "s": 9469, "text": "When we look at the third level of the split, we see that there are three contenders, chlorides <=0.08, total sulfur dioxide <=88.5, volatile acidity <=0.87." }, { "code": null, "e": 9787, "s": 9627, "text": "To decide which independent variable is important we need to understand the information gain by splitting these parent nodes into their respective child nodes." }, { "code": null, "e": 10029, "s": 9787, "text": "So, we see that the information gain by splitting Node “volatile acidity <=0.87” is higher than by splitting “total sulfur dioxide <=88.5” hence in the importance table “volatile acidity <=0.87” is placed above “total sulfur dioxide <=88.5”." }, { "code": null, "e": 10181, "s": 10029, "text": "The cost complexity refers to the complexity parameter that is used to define the cost complexity measure Ra(T) of a given tree T. Ra(T) is written as:" }, { "code": null, "e": 10201, "s": 10181, "text": "Ra(T) = R(T) + a|T|" }, { "code": null, "e": 10549, "s": 10201, "text": "where |T| is the number of terminal nodes, R(T) is the total misclassification rate of the terminal node, and a is the CCP parameter. To summarise, the subtree with the highest cost complexity that is smaller than ccp_alpha will be retained. It is always good to select a CCP parameter that produces the highest test accuracy (Scikit Learn, n.d.)." }, { "code": null, "e": 11598, "s": 10549, "text": "Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89.‌Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html.Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py.Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77 [Accessed 18 Jul. 2020]." }, { "code": null, "e": 11834, "s": 11598, "text": "Raschka, S., Julian, D. and Hearty, J. (2016). Python : deeper insights into machine learning : leverage benefits of machine learning techniques using Python : a course in three modules. Birmingham, Uk: Packt Publishing, pp.83, 88, 89." }, { "code": null, "e": 11925, "s": 11834, "text": "‌Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011." }, { "code": null, "e": 12152, "s": 11925, "text": "Scikit Learn (2019). sklearn.tree.DecisionTreeClassifier — scikit-learn 0.22.1 documentation. [online] Scikit-learn.org. Available at: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html." }, { "code": null, "e": 12400, "s": 12152, "text": "Scikit Learn (n.d.). Post pruning decision trees with cost complexity pruning. [online] Available at: https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py." }, { "code": null, "e": 12651, "s": 12400, "text": "Das, A. (2020). Decision Tree Classifier and Cost Computation Pruning using Python. [online] Medium. Available at: https://towardsdatascience.com/decision-tree-classifier-and-cost-computation-pruning-using-python-b93a0985ea77 [Accessed 18 Jul. 2020]." } ]
How MySQL use YEAR data type to store year value in a table?
MySQL permits to declare a column YEAR type, with the help of which we can store year values in that column. mysql> Create table year1 (Year_Copyright YEAR); Query OK, 0 rows affected (0.21 sec) mysql> Insert into year1(Year_Copyright) values (2017); Query OK, 1 row affected (0.08 sec) mysql> Select * from year1; +----------------+ | Year_Copyright | +----------------+ | 2017 | +----------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1171, "s": 1062, "text": "MySQL permits to declare a column YEAR type, with the help of which we can store year values in that column." }, { "code": null, "e": 1498, "s": 1171, "text": "mysql> Create table year1 (Year_Copyright YEAR);\nQuery OK, 0 rows affected (0.21 sec)\n\nmysql> Insert into year1(Year_Copyright) values (2017);\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> Select * from year1;\n+----------------+\n| Year_Copyright |\n+----------------+\n| 2017 |\n+----------------+\n1 row in set (0.00 sec)" } ]
Installing TensorFlow on the M1 Mac | by Wei-Meng Lee | Towards Data Science
If you are a Mac user, you probably have one of the latest machines running Apple Silicon. To utilize Apple’s ML Compute framework for native hardware acceleration on M1 Macs, you need to install Apple’s hardware-accelerated TensorFlow and TensorFlow Addons for macOS 11.0+. This article will show how how to prepare your M1 Mac for developing deep learning projects using TensorFlow. In addition, I will show you how to install Jupyter Notebook and the various additional libraries you need for your deep learning projects. Apple maintains a Github page at https://github.com/apple/tensorflow_macos/issues/153 detailing the instructions to install TensorFlow in a Conda enviroment. My article provides a step-by-step instructions to do that. Important note. Before proceeding with the following instructions, make sure that you do not have Anaconda installed on your Mac. If you have one installed, simply remove the Anaconda folder from your Mac to uninstall it. The first tool you need to install is Xcode, which is available from the Mac AppStore: When you install Xcode, it will also install the Command Line Tools. But if you have not installed it yet, the following command will do it: $ xcode-select --install Instead of using Anaconda, you will use MiniForge, a lightweight Python interpreter with full access to the Conda ecosystem. Conda is an open source package and environment management system that runs on Windows, Mac OS and Linux. You can download Miniforge from: https://github.com/conda-forge/miniforge. For the M1 Mac, click the Miniforge3-MacOSX-arm64 item (second last in the list above). Once it is downloaded, launch Terminal and go to the directory that contains the Miniforge3-MacOSX-arm64.sh file and then use the bash command, like the following, to install Miniforge: $ bash Miniforge3-MacOSX-arm64.sh You will be prompted to accept the licensing agreements. Just accept them and proceed with the installation. After the installation is done, close Terminal. In a new Terminal window, launch conda by typing: $ conda You will see the following: To install TensorFlow on Apple’s M1 machines, first download the environment.yml file from https://raw.githubusercontent.com/mwidjaja1/DSOnMacARM/main/environment.yml. This file contains the instructions to create a Python environment with the dependencies you need. To create a new environment for TensorFlow, change to the directory containing the environment.yml file: $ cd Downloads Then, type the following command: $ conda env create --file=environment.yml --name tf_m1 The tf_m1 is the new environment name that I have chosen. Feel free to change it to your own desired name. You can now activate the newly created environment: $ conda activate tf_m1 The list of Apple’s TensorFlow libraries are available at: https://github.com/apple/tensorflow_macos/releases: At the time of writing, there are currently three versions available: v0.1alpha3 v0.1alpha2 v0.1alpha1 Selecting the latest release (v0.1aplha3) will lead you this this page: https://github.com/apple/tensorflow_macos/releases/tag/v0.1alpha3: Observe and copy the links for the two files: tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl — https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl — https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl In the tf_m1 environment, you can now install the above two libraries using the following command: $ pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl Once the two libraries are installed, you can test out TensorFlow by launching Python and then importing TensorFlow and printing out its version number: If the above succeeds, your TensorFlow is now installed correctly on your M1 Mac. Besides installing the TensorFlow libraries, you would very likely need to install other libraries like matplotlib, sklearn, OpenCV, Pandas, etc. So go ahead and install them as follows: $ conda install -c conda-forge matplotlib -y$ conda install -c conda-forge scikit-learn -y$ conda install -c conda-forge opencv -y$ conda install -c conda-forge pandas -y The -y option saves you the trouble of answering the confirmation when installing the libraries. Finally, you would want to install Jupyter Notebook: $ conda install notebook -y That’s it! Test if Jupyter Notebook is installed correctly: $ jupyter notebook If you can see the following, you are all set! If you try to load a saved model: from tensorflow.keras.models import load_modelmodel = load_model('trained_model.h5') You may encounter the following error: AttributeError: 'str' object has no attribute 'decode' Turns out that internally the load_model() is using the newer version of the h5py module. To fix this, you can downgrade the version of h5py to version 2.10.0 using the following command: $ pip install 'h5py==2.10.0' --force-reinstall Have a great time with TensorFlow on the M1 Mac!
[ { "code": null, "e": 447, "s": 172, "text": "If you are a Mac user, you probably have one of the latest machines running Apple Silicon. To utilize Apple’s ML Compute framework for native hardware acceleration on M1 Macs, you need to install Apple’s hardware-accelerated TensorFlow and TensorFlow Addons for macOS 11.0+." }, { "code": null, "e": 697, "s": 447, "text": "This article will show how how to prepare your M1 Mac for developing deep learning projects using TensorFlow. In addition, I will show you how to install Jupyter Notebook and the various additional libraries you need for your deep learning projects." }, { "code": null, "e": 915, "s": 697, "text": "Apple maintains a Github page at https://github.com/apple/tensorflow_macos/issues/153 detailing the instructions to install TensorFlow in a Conda enviroment. My article provides a step-by-step instructions to do that." }, { "code": null, "e": 1137, "s": 915, "text": "Important note. Before proceeding with the following instructions, make sure that you do not have Anaconda installed on your Mac. If you have one installed, simply remove the Anaconda folder from your Mac to uninstall it." }, { "code": null, "e": 1224, "s": 1137, "text": "The first tool you need to install is Xcode, which is available from the Mac AppStore:" }, { "code": null, "e": 1365, "s": 1224, "text": "When you install Xcode, it will also install the Command Line Tools. But if you have not installed it yet, the following command will do it:" }, { "code": null, "e": 1390, "s": 1365, "text": "$ xcode-select --install" }, { "code": null, "e": 1515, "s": 1390, "text": "Instead of using Anaconda, you will use MiniForge, a lightweight Python interpreter with full access to the Conda ecosystem." }, { "code": null, "e": 1621, "s": 1515, "text": "Conda is an open source package and environment management system that runs on Windows, Mac OS and Linux." }, { "code": null, "e": 1696, "s": 1621, "text": "You can download Miniforge from: https://github.com/conda-forge/miniforge." }, { "code": null, "e": 1970, "s": 1696, "text": "For the M1 Mac, click the Miniforge3-MacOSX-arm64 item (second last in the list above). Once it is downloaded, launch Terminal and go to the directory that contains the Miniforge3-MacOSX-arm64.sh file and then use the bash command, like the following, to install Miniforge:" }, { "code": null, "e": 2004, "s": 1970, "text": "$ bash Miniforge3-MacOSX-arm64.sh" }, { "code": null, "e": 2161, "s": 2004, "text": "You will be prompted to accept the licensing agreements. Just accept them and proceed with the installation. After the installation is done, close Terminal." }, { "code": null, "e": 2211, "s": 2161, "text": "In a new Terminal window, launch conda by typing:" }, { "code": null, "e": 2219, "s": 2211, "text": "$ conda" }, { "code": null, "e": 2247, "s": 2219, "text": "You will see the following:" }, { "code": null, "e": 2415, "s": 2247, "text": "To install TensorFlow on Apple’s M1 machines, first download the environment.yml file from https://raw.githubusercontent.com/mwidjaja1/DSOnMacARM/main/environment.yml." }, { "code": null, "e": 2619, "s": 2415, "text": "This file contains the instructions to create a Python environment with the dependencies you need. To create a new environment for TensorFlow, change to the directory containing the environment.yml file:" }, { "code": null, "e": 2634, "s": 2619, "text": "$ cd Downloads" }, { "code": null, "e": 2668, "s": 2634, "text": "Then, type the following command:" }, { "code": null, "e": 2723, "s": 2668, "text": "$ conda env create --file=environment.yml --name tf_m1" }, { "code": null, "e": 2882, "s": 2723, "text": "The tf_m1 is the new environment name that I have chosen. Feel free to change it to your own desired name. You can now activate the newly created environment:" }, { "code": null, "e": 2905, "s": 2882, "text": "$ conda activate tf_m1" }, { "code": null, "e": 3016, "s": 2905, "text": "The list of Apple’s TensorFlow libraries are available at: https://github.com/apple/tensorflow_macos/releases:" }, { "code": null, "e": 3086, "s": 3016, "text": "At the time of writing, there are currently three versions available:" }, { "code": null, "e": 3097, "s": 3086, "text": "v0.1alpha3" }, { "code": null, "e": 3108, "s": 3097, "text": "v0.1alpha2" }, { "code": null, "e": 3119, "s": 3108, "text": "v0.1alpha1" }, { "code": null, "e": 3258, "s": 3119, "text": "Selecting the latest release (v0.1aplha3) will lead you this this page: https://github.com/apple/tensorflow_macos/releases/tag/v0.1alpha3:" }, { "code": null, "e": 3304, "s": 3258, "text": "Observe and copy the links for the two files:" }, { "code": null, "e": 3501, "s": 3304, "text": "tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl — https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl" }, { "code": null, "e": 3684, "s": 3501, "text": "tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl — https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl" }, { "code": null, "e": 3783, "s": 3684, "text": "In the tf_m1 environment, you can now install the above two libraries using the following command:" }, { "code": null, "e": 4092, "s": 3783, "text": "$ pip install --upgrade --force --no-dependencies https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha3/tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl" }, { "code": null, "e": 4245, "s": 4092, "text": "Once the two libraries are installed, you can test out TensorFlow by launching Python and then importing TensorFlow and printing out its version number:" }, { "code": null, "e": 4327, "s": 4245, "text": "If the above succeeds, your TensorFlow is now installed correctly on your M1 Mac." }, { "code": null, "e": 4514, "s": 4327, "text": "Besides installing the TensorFlow libraries, you would very likely need to install other libraries like matplotlib, sklearn, OpenCV, Pandas, etc. So go ahead and install them as follows:" }, { "code": null, "e": 4685, "s": 4514, "text": "$ conda install -c conda-forge matplotlib -y$ conda install -c conda-forge scikit-learn -y$ conda install -c conda-forge opencv -y$ conda install -c conda-forge pandas -y" }, { "code": null, "e": 4782, "s": 4685, "text": "The -y option saves you the trouble of answering the confirmation when installing the libraries." }, { "code": null, "e": 4835, "s": 4782, "text": "Finally, you would want to install Jupyter Notebook:" }, { "code": null, "e": 4863, "s": 4835, "text": "$ conda install notebook -y" }, { "code": null, "e": 4923, "s": 4863, "text": "That’s it! Test if Jupyter Notebook is installed correctly:" }, { "code": null, "e": 4942, "s": 4923, "text": "$ jupyter notebook" }, { "code": null, "e": 4989, "s": 4942, "text": "If you can see the following, you are all set!" }, { "code": null, "e": 5023, "s": 4989, "text": "If you try to load a saved model:" }, { "code": null, "e": 5108, "s": 5023, "text": "from tensorflow.keras.models import load_modelmodel = load_model('trained_model.h5')" }, { "code": null, "e": 5147, "s": 5108, "text": "You may encounter the following error:" }, { "code": null, "e": 5202, "s": 5147, "text": "AttributeError: 'str' object has no attribute 'decode'" }, { "code": null, "e": 5390, "s": 5202, "text": "Turns out that internally the load_model() is using the newer version of the h5py module. To fix this, you can downgrade the version of h5py to version 2.10.0 using the following command:" }, { "code": null, "e": 5437, "s": 5390, "text": "$ pip install 'h5py==2.10.0' --force-reinstall" } ]
NumPy - Indexing & Slicing
Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects. As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing. Basic slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array. import numpy as np a = np.arange(10) s = slice(2,7,2) print a[s] Its output is as follows − [2 4 6] In the above example, an ndarray object is prepared by arange() function. Then a slice object is defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced. The same result can also be obtained by giving the slicing parameters separated by a colon : (start:stop:step) directly to the ndarray object. import numpy as np a = np.arange(10) b = a[2:7:2] print b Here, we will get the same output − [2 4 6] If only one parameter is put, a single item corresponding to the index will be returned. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index) with default step one are sliced. # slice single item import numpy as np a = np.arange(10) b = a[5] print b Its output is as follows − 5 # slice items starting from index import numpy as np a = np.arange(10) print a[2:] Now, the output would be − [2 3 4 5 6 7 8 9] # slice items between indexes import numpy as np a = np.arange(10) print a[2:5] Here, the output would be − [2 3 4] The above description applies to multi-dimensional ndarray too. import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print a # slice items starting from index print 'Now we will slice the array from the index a[1:]' print a[1:] The output is as follows − [[1 2 3] [3 4 5] [4 5 6]] Now we will slice the array from the index a[1:] [[3 4 5] [4 5 6]] Slicing can also include ellipsis (...) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows. # array to begin with import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print 'Our array is:' print a print '\n' # this returns array of items in the second column print 'The items in the second column are:' print a[...,1] print '\n' # Now we will slice all items from the second row print 'The items in the second row are:' print a[1,...] print '\n' # Now we will slice all items from column 1 onwards print 'The items column 1 onwards are:' print a[...,1:] The output of this program is as follows − Our array is: [[1 2 3] [3 4 5] [4 5 6]] The items in the second column are: [2 4 5] The items in the second row are: [3 4 5] The items column 1 onwards are: [[2 3] [4 5] [5 6]] 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": 2370, "s": 2243, "text": "Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects." }, { "code": null, "e": 2541, "s": 2370, "text": "As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing." }, { "code": null, "e": 2806, "s": 2541, "text": "Basic slicing is an extension of Python's basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array." }, { "code": null, "e": 2874, "s": 2806, "text": "import numpy as np \na = np.arange(10) \ns = slice(2,7,2) \nprint a[s]" }, { "code": null, "e": 2901, "s": 2874, "text": "Its output is as follows −" }, { "code": null, "e": 2912, "s": 2901, "text": "[2 4 6]\n" }, { "code": null, "e": 3197, "s": 2912, "text": "In the above example, an ndarray object is prepared by arange() function. Then a slice object is defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced." }, { "code": null, "e": 3340, "s": 3197, "text": "The same result can also be obtained by giving the slicing parameters separated by a colon : (start:stop:step) directly to the ndarray object." }, { "code": null, "e": 3401, "s": 3340, "text": "import numpy as np \na = np.arange(10) \nb = a[2:7:2] \nprint b" }, { "code": null, "e": 3437, "s": 3401, "text": "Here, we will get the same output −" }, { "code": null, "e": 3448, "s": 3437, "text": "[2 4 6]\n" }, { "code": null, "e": 3769, "s": 3448, "text": "If only one parameter is put, a single item corresponding to the index will be returned. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index) with default step one are sliced." }, { "code": null, "e": 3848, "s": 3769, "text": "# slice single item \nimport numpy as np \n\na = np.arange(10) \nb = a[5] \nprint b" }, { "code": null, "e": 3875, "s": 3848, "text": "Its output is as follows −" }, { "code": null, "e": 3878, "s": 3875, "text": "5\n" }, { "code": null, "e": 3964, "s": 3878, "text": "# slice items starting from index \nimport numpy as np \na = np.arange(10) \nprint a[2:]" }, { "code": null, "e": 3991, "s": 3964, "text": "Now, the output would be −" }, { "code": null, "e": 4017, "s": 3991, "text": "[2 3 4 5 6 7 8 9]\n" }, { "code": null, "e": 4100, "s": 4017, "text": "# slice items between indexes \nimport numpy as np \na = np.arange(10) \nprint a[2:5]" }, { "code": null, "e": 4128, "s": 4100, "text": "Here, the output would be −" }, { "code": null, "e": 4140, "s": 4128, "text": "[2 3 4] \n" }, { "code": null, "e": 4204, "s": 4140, "text": "The above description applies to multi-dimensional ndarray too." }, { "code": null, "e": 4380, "s": 4204, "text": "import numpy as np \na = np.array([[1,2,3],[3,4,5],[4,5,6]]) \nprint a \n\n# slice items starting from index\nprint 'Now we will slice the array from the index a[1:]' \nprint a[1:]" }, { "code": null, "e": 4407, "s": 4380, "text": "The output is as follows −" }, { "code": null, "e": 4505, "s": 4407, "text": "[[1 2 3]\n [3 4 5]\n [4 5 6]]\n\nNow we will slice the array from the index a[1:]\n[[3 4 5]\n [4 5 6]]\n" }, { "code": null, "e": 4716, "s": 4505, "text": "Slicing can also include ellipsis (...) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows." }, { "code": null, "e": 5208, "s": 4716, "text": "# array to begin with \nimport numpy as np \na = np.array([[1,2,3],[3,4,5],[4,5,6]]) \n\nprint 'Our array is:' \nprint a \nprint '\\n' \n\n# this returns array of items in the second column \nprint 'The items in the second column are:' \nprint a[...,1] \nprint '\\n' \n\n# Now we will slice all items from the second row \nprint 'The items in the second row are:' \nprint a[1,...] \nprint '\\n' \n\n# Now we will slice all items from column 1 onwards \nprint 'The items column 1 onwards are:' \nprint a[...,1:]" }, { "code": null, "e": 5251, "s": 5208, "text": "The output of this program is as follows −" }, { "code": null, "e": 5441, "s": 5251, "text": "Our array is:\n[[1 2 3]\n [3 4 5]\n [4 5 6]] \n \nThe items in the second column are: \n[2 4 5] \n\nThe items in the second row are:\n[3 4 5]\n\nThe items column 1 onwards are:\n[[2 3]\n [4 5]\n [5 6]] \n" }, { "code": null, "e": 5474, "s": 5441, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5491, "s": 5474, "text": " Abhilash Nelson" }, { "code": null, "e": 5524, "s": 5491, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 5559, "s": 5524, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5592, "s": 5559, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 5627, "s": 5592, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5662, "s": 5627, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5674, "s": 5662, "text": " Akbar Khan" }, { "code": null, "e": 5707, "s": 5674, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5722, "s": 5707, "text": " Pruthviraja L" }, { "code": null, "e": 5755, "s": 5722, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5762, "s": 5755, "text": " Anmol" }, { "code": null, "e": 5769, "s": 5762, "text": " Print" }, { "code": null, "e": 5780, "s": 5769, "text": " Add Notes" } ]
GATE | GATE CS 2012 | Question 41 - GeeksforGeeks
28 Jun, 2021 Suppose (A, B) and (C,D) are two relation schemas. Let r1 and r2 be the corresponding relation instances. B is a foreign key that refers to C in r2. If data in r1 and r2 satisfy referential integrity constraints, which of the following is ALWAYS TRUE? (A) A(B) B(C) C(D) DAnswer: (A)Explanation: See Question 3 of https://www.geeksforgeeks.org/database-management-system-set-2/Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25621, "s": 25593, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25873, "s": 25621, "text": "Suppose (A, B) and (C,D) are two relation schemas. Let r1 and r2 be the corresponding relation instances. B is a foreign key that refers to C in r2. If data in r1 and r2 satisfy referential integrity constraints, which of the following is ALWAYS TRUE?" }, { "code": null, "e": 26020, "s": 25873, "text": "(A) A(B) B(C) C(D) DAnswer: (A)Explanation: See Question 3 of https://www.geeksforgeeks.org/database-management-system-set-2/Quiz of this Question" }, { "code": null, "e": 26033, "s": 26020, "text": "GATE-CS-2012" }, { "code": null, "e": 26051, "s": 26033, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 26056, "s": 26051, "text": "GATE" }, { "code": null, "e": 26154, "s": 26056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26188, "s": 26154, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26222, "s": 26188, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26256, "s": 26222, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26289, "s": 26256, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26325, "s": 26289, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26359, "s": 26325, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26395, "s": 26359, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26429, "s": 26395, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26463, "s": 26429, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Image Enhancement in PIL - GeeksforGeeks
04 May, 2022 The Python Imaging Library(PIL) adds powerful image processing capabilities. It provides immense file format support, an efficient representation, and fairly powerful image processing capabilities. The core image library is intended for fast access to data stored in very few basic pixel formats. It provides a firm foundation for a general image processing tool. Step-1: Import the Image module from the PIL library.e from PIL import Image This module provides a class with an identical name which is employed to represent a PIL image. And also provides various functionalities, including functions to load images from files, and to create new images. I’m not gonna explain the whole Image module here. But, here’s how you’ll be able to open an image file. image_variable_name = Image.open("lena.jpg") We are going to use a PNG image here. One thing to remember- the image file you’re using here must be present within the same directory where your program is. Else use the full path of the image file within the quotation marks. Now you can see the image in your image viewer with a line of code. image_variable_name.show() Step-2: Now It is time to Import the foremost important module- ‘ImageEnhance’ module from the PIL library from PIL import ImageEnhance The ImageEnhance module contains various classes which will be used for image enhancement. All enhancement classes implement a typical interface, containing one method which is named the ‘enhance(factor)’ method. PIL.ImageEnhance.[method](image_variable_name) The method can be brightness, color, contrast, sharpness. Parameter: The enhance() method takes just one parameter factor, i.e. a floating-point.Return Type: This method returns an enhanced image. Classes are as follows: Adjust image brightness. It’s accustomed to controlling the brightness of our resulting image. The code for brightness goes like below: Input: Python3 from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Brightnesscurr_bri = ImageEnhance.Brightness(image)new_bri = 2.5 # Brightness enhanced by a factor of 2.5img_brightened = curr_bri.enhance(new_bri) # shows updated image in image viewerimg_brightened.show() An enhancement factor of 0.0 results in a full black image and an enhancement factor of 1.0 results the same as the original image. Output: Adjust image color level. It’s accustomed to controlling the color level of our resulting image. The code for coloring goes like below: Input: Python3 from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Color Levelcurr_col = ImageEnhance.Color(image)new_col = 2.5 # Color level enhanced by a factor of 2.5img_colored = curr_col.enhance(new_col) # shows updated image in image viewerimg_colored.show() An enhancement factor of 0.0 results in a full black and white image and an enhancement factor of 1.0 results the same as the original image. Output: Adjust image Contrast. It is accustomed to controlling the contrast of our resulting image. The code for changing contrast goes like below: Input: Python3 from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Contrastcurr_con = ImageEnhance.Contrast(image)new_con = 0.3 # Contrast enhanced by a factor of 0.3img_contrasted = curr_con.enhance(new_con) # shows updated image in image viewerimg_contrasted.show() An enhancement factor of 0.0 results in a full grey image and an enhancement factor of 1.0 results the same as the original image. Output: Adjust image Sharpness. It’s accustomed to controlling the sharpness of our resulting image. The code for changing sharpness goes like below: Input: Python3 from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Sharpnesscurr_sharp = ImageEnhance.Sharpness(image)new_sharp = 8.3 # Sharpness enhanced by a factor of 8.3img_sharped = curr_sharp.enhance(new_sharp) # shows updated image in image viewerimg_sharped.show() An enhancement factor of 0.0 results in a blurred image and an enhancement factor of 1.0 results in the same as the original image and a factor > 1.0 results in a sharpened image. Output: These 4 classes are the most used, to enhance an image. A lot of other functionalities available there. Don’t stop your learning here, go and explore more by yourself. Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n04 May, 2022" }, { "code": null, "e": 25919, "s": 25555, "text": "The Python Imaging Library(PIL) adds powerful image processing capabilities. It provides immense file format support, an efficient representation, and fairly powerful image processing capabilities. The core image library is intended for fast access to data stored in very few basic pixel formats. It provides a firm foundation for a general image processing tool." }, { "code": null, "e": 25974, "s": 25919, "text": "Step-1: Import the Image module from the PIL library.e" }, { "code": null, "e": 25996, "s": 25974, "text": "from PIL import Image" }, { "code": null, "e": 26313, "s": 25996, "text": "This module provides a class with an identical name which is employed to represent a PIL image. And also provides various functionalities, including functions to load images from files, and to create new images. I’m not gonna explain the whole Image module here. But, here’s how you’ll be able to open an image file." }, { "code": null, "e": 26358, "s": 26313, "text": "image_variable_name = Image.open(\"lena.jpg\")" }, { "code": null, "e": 26587, "s": 26358, "text": "We are going to use a PNG image here. One thing to remember- the image file you’re using here must be present within the same directory where your program is. Else use the full path of the image file within the quotation marks. " }, { "code": null, "e": 26655, "s": 26587, "text": "Now you can see the image in your image viewer with a line of code." }, { "code": null, "e": 26682, "s": 26655, "text": "image_variable_name.show()" }, { "code": null, "e": 26789, "s": 26682, "text": "Step-2: Now It is time to Import the foremost important module- ‘ImageEnhance’ module from the PIL library" }, { "code": null, "e": 26818, "s": 26789, "text": "from PIL import ImageEnhance" }, { "code": null, "e": 26909, "s": 26818, "text": "The ImageEnhance module contains various classes which will be used for image enhancement." }, { "code": null, "e": 27031, "s": 26909, "text": "All enhancement classes implement a typical interface, containing one method which is named the ‘enhance(factor)’ method." }, { "code": null, "e": 27078, "s": 27031, "text": "PIL.ImageEnhance.[method](image_variable_name)" }, { "code": null, "e": 27136, "s": 27078, "text": "The method can be brightness, color, contrast, sharpness." }, { "code": null, "e": 27276, "s": 27136, "text": "Parameter: The enhance() method takes just one parameter factor, i.e. a floating-point.Return Type: This method returns an enhanced image. " }, { "code": null, "e": 27300, "s": 27276, "text": "Classes are as follows:" }, { "code": null, "e": 27436, "s": 27300, "text": "Adjust image brightness. It’s accustomed to controlling the brightness of our resulting image. The code for brightness goes like below:" }, { "code": null, "e": 27443, "s": 27436, "text": "Input:" }, { "code": null, "e": 27451, "s": 27443, "text": "Python3" }, { "code": "from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Brightnesscurr_bri = ImageEnhance.Brightness(image)new_bri = 2.5 # Brightness enhanced by a factor of 2.5img_brightened = curr_bri.enhance(new_bri) # shows updated image in image viewerimg_brightened.show() ", "e": 27825, "s": 27451, "text": null }, { "code": null, "e": 27957, "s": 27825, "text": "An enhancement factor of 0.0 results in a full black image and an enhancement factor of 1.0 results the same as the original image." }, { "code": null, "e": 27965, "s": 27957, "text": "Output:" }, { "code": null, "e": 28101, "s": 27965, "text": "Adjust image color level. It’s accustomed to controlling the color level of our resulting image. The code for coloring goes like below:" }, { "code": null, "e": 28108, "s": 28101, "text": "Input:" }, { "code": null, "e": 28116, "s": 28108, "text": "Python3" }, { "code": "from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Color Levelcurr_col = ImageEnhance.Color(image)new_col = 2.5 # Color level enhanced by a factor of 2.5img_colored = curr_col.enhance(new_col) # shows updated image in image viewerimg_colored.show()", "e": 28475, "s": 28116, "text": null }, { "code": null, "e": 28617, "s": 28475, "text": "An enhancement factor of 0.0 results in a full black and white image and an enhancement factor of 1.0 results the same as the original image." }, { "code": null, "e": 28625, "s": 28617, "text": "Output:" }, { "code": null, "e": 28765, "s": 28625, "text": "Adjust image Contrast. It is accustomed to controlling the contrast of our resulting image. The code for changing contrast goes like below:" }, { "code": null, "e": 28772, "s": 28765, "text": "Input:" }, { "code": null, "e": 28780, "s": 28772, "text": "Python3" }, { "code": "from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Contrastcurr_con = ImageEnhance.Contrast(image)new_con = 0.3 # Contrast enhanced by a factor of 0.3img_contrasted = curr_con.enhance(new_con) # shows updated image in image viewerimg_contrasted.show() ", "e": 29144, "s": 28780, "text": null }, { "code": null, "e": 29275, "s": 29144, "text": "An enhancement factor of 0.0 results in a full grey image and an enhancement factor of 1.0 results the same as the original image." }, { "code": null, "e": 29283, "s": 29275, "text": "Output:" }, { "code": null, "e": 29425, "s": 29283, "text": "Adjust image Sharpness. It’s accustomed to controlling the sharpness of our resulting image. The code for changing sharpness goes like below:" }, { "code": null, "e": 29432, "s": 29425, "text": "Input:" }, { "code": null, "e": 29440, "s": 29432, "text": "Python3" }, { "code": "from PIL import Imagefrom PIL import ImageEnhance # Opens the image fileimage = Image.open('gfg.png') # shows image in image viewerimage.show() # Enhance Sharpnesscurr_sharp = ImageEnhance.Sharpness(image)new_sharp = 8.3 # Sharpness enhanced by a factor of 8.3img_sharped = curr_sharp.enhance(new_sharp) # shows updated image in image viewerimg_sharped.show()", "e": 29805, "s": 29440, "text": null }, { "code": null, "e": 29985, "s": 29805, "text": "An enhancement factor of 0.0 results in a blurred image and an enhancement factor of 1.0 results in the same as the original image and a factor > 1.0 results in a sharpened image." }, { "code": null, "e": 29993, "s": 29985, "text": "Output:" }, { "code": null, "e": 30161, "s": 29993, "text": "These 4 classes are the most used, to enhance an image. A lot of other functionalities available there. Don’t stop your learning here, go and explore more by yourself." }, { "code": null, "e": 30168, "s": 30161, "text": "Picked" }, { "code": null, "e": 30179, "s": 30168, "text": "Python-pil" }, { "code": null, "e": 30186, "s": 30179, "text": "Python" }, { "code": null, "e": 30284, "s": 30186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30316, "s": 30284, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30358, "s": 30316, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30400, "s": 30358, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30456, "s": 30400, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30483, "s": 30456, "text": "Python Classes and Objects" }, { "code": null, "e": 30514, "s": 30483, "text": "Python | os.path.join() method" }, { "code": null, "e": 30553, "s": 30514, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30582, "s": 30553, "text": "Create a directory in Python" }, { "code": null, "e": 30604, "s": 30582, "text": "Defaultdict in Python" } ]